1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements semantic analysis for expressions. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "TreeTransform.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/ASTMutationListener.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/DeclObjC.h" 21 #include "clang/AST/DeclTemplate.h" 22 #include "clang/AST/EvaluatedExprVisitor.h" 23 #include "clang/AST/Expr.h" 24 #include "clang/AST/ExprCXX.h" 25 #include "clang/AST/ExprObjC.h" 26 #include "clang/AST/ExprOpenMP.h" 27 #include "clang/AST/RecursiveASTVisitor.h" 28 #include "clang/AST/TypeLoc.h" 29 #include "clang/Basic/PartialDiagnostic.h" 30 #include "clang/Basic/SourceManager.h" 31 #include "clang/Basic/TargetInfo.h" 32 #include "clang/Lex/LiteralSupport.h" 33 #include "clang/Lex/Preprocessor.h" 34 #include "clang/Sema/AnalysisBasedWarnings.h" 35 #include "clang/Sema/DeclSpec.h" 36 #include "clang/Sema/DelayedDiagnostic.h" 37 #include "clang/Sema/Designator.h" 38 #include "clang/Sema/Initialization.h" 39 #include "clang/Sema/Lookup.h" 40 #include "clang/Sema/Overload.h" 41 #include "clang/Sema/ParsedTemplate.h" 42 #include "clang/Sema/Scope.h" 43 #include "clang/Sema/ScopeInfo.h" 44 #include "clang/Sema/SemaFixItUtils.h" 45 #include "clang/Sema/SemaInternal.h" 46 #include "clang/Sema/Template.h" 47 #include "llvm/Support/ConvertUTF.h" 48 using namespace clang; 49 using namespace sema; 50 51 /// Determine whether the use of this declaration is valid, without 52 /// emitting diagnostics. 53 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 54 // See if this is an auto-typed variable whose initializer we are parsing. 55 if (ParsingInitForAutoVars.count(D)) 56 return false; 57 58 // See if this is a deleted function. 59 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 60 if (FD->isDeleted()) 61 return false; 62 63 // If the function has a deduced return type, and we can't deduce it, 64 // then we can't use it either. 65 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 66 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 67 return false; 68 } 69 70 // See if this function is unavailable. 71 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 72 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 73 return false; 74 75 return true; 76 } 77 78 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 79 // Warn if this is used but marked unused. 80 if (const auto *A = D->getAttr<UnusedAttr>()) { 81 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 82 // should diagnose them. 83 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 84 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 85 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 86 if (DC && !DC->hasAttr<UnusedAttr>()) 87 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 88 } 89 } 90 } 91 92 /// Emit a note explaining that this function is deleted. 93 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 94 assert(Decl->isDeleted()); 95 96 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 97 98 if (Method && Method->isDeleted() && Method->isDefaulted()) { 99 // If the method was explicitly defaulted, point at that declaration. 100 if (!Method->isImplicit()) 101 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 102 103 // Try to diagnose why this special member function was implicitly 104 // deleted. This might fail, if that reason no longer applies. 105 CXXSpecialMember CSM = getSpecialMember(Method); 106 if (CSM != CXXInvalid) 107 ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true); 108 109 return; 110 } 111 112 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 113 if (Ctor && Ctor->isInheritingConstructor()) 114 return NoteDeletedInheritingConstructor(Ctor); 115 116 Diag(Decl->getLocation(), diag::note_availability_specified_here) 117 << Decl << true; 118 } 119 120 /// Determine whether a FunctionDecl was ever declared with an 121 /// explicit storage class. 122 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 123 for (auto I : D->redecls()) { 124 if (I->getStorageClass() != SC_None) 125 return true; 126 } 127 return false; 128 } 129 130 /// Check whether we're in an extern inline function and referring to a 131 /// variable or function with internal linkage (C11 6.7.4p3). 132 /// 133 /// This is only a warning because we used to silently accept this code, but 134 /// in many cases it will not behave correctly. This is not enabled in C++ mode 135 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 136 /// and so while there may still be user mistakes, most of the time we can't 137 /// prove that there are errors. 138 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 139 const NamedDecl *D, 140 SourceLocation Loc) { 141 // This is disabled under C++; there are too many ways for this to fire in 142 // contexts where the warning is a false positive, or where it is technically 143 // correct but benign. 144 if (S.getLangOpts().CPlusPlus) 145 return; 146 147 // Check if this is an inlined function or method. 148 FunctionDecl *Current = S.getCurFunctionDecl(); 149 if (!Current) 150 return; 151 if (!Current->isInlined()) 152 return; 153 if (!Current->isExternallyVisible()) 154 return; 155 156 // Check if the decl has internal linkage. 157 if (D->getFormalLinkage() != InternalLinkage) 158 return; 159 160 // Downgrade from ExtWarn to Extension if 161 // (1) the supposedly external inline function is in the main file, 162 // and probably won't be included anywhere else. 163 // (2) the thing we're referencing is a pure function. 164 // (3) the thing we're referencing is another inline function. 165 // This last can give us false negatives, but it's better than warning on 166 // wrappers for simple C library functions. 167 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 168 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 169 if (!DowngradeWarning && UsedFn) 170 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 171 172 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 173 : diag::ext_internal_in_extern_inline) 174 << /*IsVar=*/!UsedFn << D; 175 176 S.MaybeSuggestAddingStaticToDecl(Current); 177 178 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 179 << D; 180 } 181 182 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 183 const FunctionDecl *First = Cur->getFirstDecl(); 184 185 // Suggest "static" on the function, if possible. 186 if (!hasAnyExplicitStorageClass(First)) { 187 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 188 Diag(DeclBegin, diag::note_convert_inline_to_static) 189 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 190 } 191 } 192 193 /// Determine whether the use of this declaration is valid, and 194 /// emit any corresponding diagnostics. 195 /// 196 /// This routine diagnoses various problems with referencing 197 /// declarations that can occur when using a declaration. For example, 198 /// it might warn if a deprecated or unavailable declaration is being 199 /// used, or produce an error (and return true) if a C++0x deleted 200 /// function is being used. 201 /// 202 /// \returns true if there was an error (this declaration cannot be 203 /// referenced), false otherwise. 204 /// 205 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 206 const ObjCInterfaceDecl *UnknownObjCClass, 207 bool ObjCPropertyAccess, 208 bool AvoidPartialAvailabilityChecks) { 209 SourceLocation Loc = Locs.front(); 210 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 211 // If there were any diagnostics suppressed by template argument deduction, 212 // emit them now. 213 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 214 if (Pos != SuppressedDiagnostics.end()) { 215 for (const PartialDiagnosticAt &Suppressed : Pos->second) 216 Diag(Suppressed.first, Suppressed.second); 217 218 // Clear out the list of suppressed diagnostics, so that we don't emit 219 // them again for this specialization. However, we don't obsolete this 220 // entry from the table, because we want to avoid ever emitting these 221 // diagnostics again. 222 Pos->second.clear(); 223 } 224 225 // C++ [basic.start.main]p3: 226 // The function 'main' shall not be used within a program. 227 if (cast<FunctionDecl>(D)->isMain()) 228 Diag(Loc, diag::ext_main_used); 229 } 230 231 // See if this is an auto-typed variable whose initializer we are parsing. 232 if (ParsingInitForAutoVars.count(D)) { 233 if (isa<BindingDecl>(D)) { 234 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 235 << D->getDeclName(); 236 } else { 237 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 238 << D->getDeclName() << cast<VarDecl>(D)->getType(); 239 } 240 return true; 241 } 242 243 // See if this is a deleted function. 244 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 245 if (FD->isDeleted()) { 246 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 247 if (Ctor && Ctor->isInheritingConstructor()) 248 Diag(Loc, diag::err_deleted_inherited_ctor_use) 249 << Ctor->getParent() 250 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 251 else 252 Diag(Loc, diag::err_deleted_function_use); 253 NoteDeletedFunction(FD); 254 return true; 255 } 256 257 // If the function has a deduced return type, and we can't deduce it, 258 // then we can't use it either. 259 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 260 DeduceReturnType(FD, Loc)) 261 return true; 262 263 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 264 return true; 265 } 266 267 auto getReferencedObjCProp = [](const NamedDecl *D) -> 268 const ObjCPropertyDecl * { 269 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 270 return MD->findPropertyDecl(); 271 return nullptr; 272 }; 273 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 274 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 275 return true; 276 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 277 return true; 278 } 279 280 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 281 // Only the variables omp_in and omp_out are allowed in the combiner. 282 // Only the variables omp_priv and omp_orig are allowed in the 283 // initializer-clause. 284 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 285 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 286 isa<VarDecl>(D)) { 287 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 288 << getCurFunction()->HasOMPDeclareReductionCombiner; 289 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 290 return true; 291 } 292 293 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 294 AvoidPartialAvailabilityChecks); 295 296 DiagnoseUnusedOfDecl(*this, D, Loc); 297 298 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 299 300 return false; 301 } 302 303 /// Retrieve the message suffix that should be added to a 304 /// diagnostic complaining about the given function being deleted or 305 /// unavailable. 306 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 307 std::string Message; 308 if (FD->getAvailability(&Message)) 309 return ": " + Message; 310 311 return std::string(); 312 } 313 314 /// DiagnoseSentinelCalls - This routine checks whether a call or 315 /// message-send is to a declaration with the sentinel attribute, and 316 /// if so, it checks that the requirements of the sentinel are 317 /// satisfied. 318 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 319 ArrayRef<Expr *> Args) { 320 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 321 if (!attr) 322 return; 323 324 // The number of formal parameters of the declaration. 325 unsigned numFormalParams; 326 327 // The kind of declaration. This is also an index into a %select in 328 // the diagnostic. 329 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 330 331 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 332 numFormalParams = MD->param_size(); 333 calleeType = CT_Method; 334 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 335 numFormalParams = FD->param_size(); 336 calleeType = CT_Function; 337 } else if (isa<VarDecl>(D)) { 338 QualType type = cast<ValueDecl>(D)->getType(); 339 const FunctionType *fn = nullptr; 340 if (const PointerType *ptr = type->getAs<PointerType>()) { 341 fn = ptr->getPointeeType()->getAs<FunctionType>(); 342 if (!fn) return; 343 calleeType = CT_Function; 344 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 345 fn = ptr->getPointeeType()->castAs<FunctionType>(); 346 calleeType = CT_Block; 347 } else { 348 return; 349 } 350 351 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 352 numFormalParams = proto->getNumParams(); 353 } else { 354 numFormalParams = 0; 355 } 356 } else { 357 return; 358 } 359 360 // "nullPos" is the number of formal parameters at the end which 361 // effectively count as part of the variadic arguments. This is 362 // useful if you would prefer to not have *any* formal parameters, 363 // but the language forces you to have at least one. 364 unsigned nullPos = attr->getNullPos(); 365 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 366 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 367 368 // The number of arguments which should follow the sentinel. 369 unsigned numArgsAfterSentinel = attr->getSentinel(); 370 371 // If there aren't enough arguments for all the formal parameters, 372 // the sentinel, and the args after the sentinel, complain. 373 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 374 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 375 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 376 return; 377 } 378 379 // Otherwise, find the sentinel expression. 380 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 381 if (!sentinelExpr) return; 382 if (sentinelExpr->isValueDependent()) return; 383 if (Context.isSentinelNullExpr(sentinelExpr)) return; 384 385 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 386 // or 'NULL' if those are actually defined in the context. Only use 387 // 'nil' for ObjC methods, where it's much more likely that the 388 // variadic arguments form a list of object pointers. 389 SourceLocation MissingNilLoc 390 = getLocForEndOfToken(sentinelExpr->getLocEnd()); 391 std::string NullValue; 392 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 393 NullValue = "nil"; 394 else if (getLangOpts().CPlusPlus11) 395 NullValue = "nullptr"; 396 else if (PP.isMacroDefined("NULL")) 397 NullValue = "NULL"; 398 else 399 NullValue = "(void*) 0"; 400 401 if (MissingNilLoc.isInvalid()) 402 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 403 else 404 Diag(MissingNilLoc, diag::warn_missing_sentinel) 405 << int(calleeType) 406 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 407 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 408 } 409 410 SourceRange Sema::getExprRange(Expr *E) const { 411 return E ? E->getSourceRange() : SourceRange(); 412 } 413 414 //===----------------------------------------------------------------------===// 415 // Standard Promotions and Conversions 416 //===----------------------------------------------------------------------===// 417 418 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 419 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 420 // Handle any placeholder expressions which made it here. 421 if (E->getType()->isPlaceholderType()) { 422 ExprResult result = CheckPlaceholderExpr(E); 423 if (result.isInvalid()) return ExprError(); 424 E = result.get(); 425 } 426 427 QualType Ty = E->getType(); 428 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 429 430 if (Ty->isFunctionType()) { 431 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 432 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 433 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 434 return ExprError(); 435 436 E = ImpCastExprToType(E, Context.getPointerType(Ty), 437 CK_FunctionToPointerDecay).get(); 438 } else if (Ty->isArrayType()) { 439 // In C90 mode, arrays only promote to pointers if the array expression is 440 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 441 // type 'array of type' is converted to an expression that has type 'pointer 442 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 443 // that has type 'array of type' ...". The relevant change is "an lvalue" 444 // (C90) to "an expression" (C99). 445 // 446 // C++ 4.2p1: 447 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 448 // T" can be converted to an rvalue of type "pointer to T". 449 // 450 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 451 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 452 CK_ArrayToPointerDecay).get(); 453 } 454 return E; 455 } 456 457 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 458 // Check to see if we are dereferencing a null pointer. If so, 459 // and if not volatile-qualified, this is undefined behavior that the 460 // optimizer will delete, so warn about it. People sometimes try to use this 461 // to get a deterministic trap and are surprised by clang's behavior. This 462 // only handles the pattern "*null", which is a very syntactic check. 463 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 464 if (UO->getOpcode() == UO_Deref && 465 UO->getSubExpr()->IgnoreParenCasts()-> 466 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 467 !UO->getType().isVolatileQualified()) { 468 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 469 S.PDiag(diag::warn_indirection_through_null) 470 << UO->getSubExpr()->getSourceRange()); 471 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 472 S.PDiag(diag::note_indirection_through_null)); 473 } 474 } 475 476 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 477 SourceLocation AssignLoc, 478 const Expr* RHS) { 479 const ObjCIvarDecl *IV = OIRE->getDecl(); 480 if (!IV) 481 return; 482 483 DeclarationName MemberName = IV->getDeclName(); 484 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 485 if (!Member || !Member->isStr("isa")) 486 return; 487 488 const Expr *Base = OIRE->getBase(); 489 QualType BaseType = Base->getType(); 490 if (OIRE->isArrow()) 491 BaseType = BaseType->getPointeeType(); 492 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 493 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 494 ObjCInterfaceDecl *ClassDeclared = nullptr; 495 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 496 if (!ClassDeclared->getSuperClass() 497 && (*ClassDeclared->ivar_begin()) == IV) { 498 if (RHS) { 499 NamedDecl *ObjectSetClass = 500 S.LookupSingleName(S.TUScope, 501 &S.Context.Idents.get("object_setClass"), 502 SourceLocation(), S.LookupOrdinaryName); 503 if (ObjectSetClass) { 504 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd()); 505 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 506 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 507 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 508 AssignLoc), ",") << 509 FixItHint::CreateInsertion(RHSLocEnd, ")"); 510 } 511 else 512 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 513 } else { 514 NamedDecl *ObjectGetClass = 515 S.LookupSingleName(S.TUScope, 516 &S.Context.Idents.get("object_getClass"), 517 SourceLocation(), S.LookupOrdinaryName); 518 if (ObjectGetClass) 519 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 520 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 521 FixItHint::CreateReplacement( 522 SourceRange(OIRE->getOpLoc(), 523 OIRE->getLocEnd()), ")"); 524 else 525 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 526 } 527 S.Diag(IV->getLocation(), diag::note_ivar_decl); 528 } 529 } 530 } 531 532 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 533 // Handle any placeholder expressions which made it here. 534 if (E->getType()->isPlaceholderType()) { 535 ExprResult result = CheckPlaceholderExpr(E); 536 if (result.isInvalid()) return ExprError(); 537 E = result.get(); 538 } 539 540 // C++ [conv.lval]p1: 541 // A glvalue of a non-function, non-array type T can be 542 // converted to a prvalue. 543 if (!E->isGLValue()) return E; 544 545 QualType T = E->getType(); 546 assert(!T.isNull() && "r-value conversion on typeless expression?"); 547 548 // We don't want to throw lvalue-to-rvalue casts on top of 549 // expressions of certain types in C++. 550 if (getLangOpts().CPlusPlus && 551 (E->getType() == Context.OverloadTy || 552 T->isDependentType() || 553 T->isRecordType())) 554 return E; 555 556 // The C standard is actually really unclear on this point, and 557 // DR106 tells us what the result should be but not why. It's 558 // generally best to say that void types just doesn't undergo 559 // lvalue-to-rvalue at all. Note that expressions of unqualified 560 // 'void' type are never l-values, but qualified void can be. 561 if (T->isVoidType()) 562 return E; 563 564 // OpenCL usually rejects direct accesses to values of 'half' type. 565 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 566 T->isHalfType()) { 567 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 568 << 0 << T; 569 return ExprError(); 570 } 571 572 CheckForNullPointerDereference(*this, E); 573 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 574 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 575 &Context.Idents.get("object_getClass"), 576 SourceLocation(), LookupOrdinaryName); 577 if (ObjectGetClass) 578 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 579 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 580 FixItHint::CreateReplacement( 581 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 582 else 583 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 584 } 585 else if (const ObjCIvarRefExpr *OIRE = 586 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 587 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 588 589 // C++ [conv.lval]p1: 590 // [...] If T is a non-class type, the type of the prvalue is the 591 // cv-unqualified version of T. Otherwise, the type of the 592 // rvalue is T. 593 // 594 // C99 6.3.2.1p2: 595 // If the lvalue has qualified type, the value has the unqualified 596 // version of the type of the lvalue; otherwise, the value has the 597 // type of the lvalue. 598 if (T.hasQualifiers()) 599 T = T.getUnqualifiedType(); 600 601 // Under the MS ABI, lock down the inheritance model now. 602 if (T->isMemberPointerType() && 603 Context.getTargetInfo().getCXXABI().isMicrosoft()) 604 (void)isCompleteType(E->getExprLoc(), T); 605 606 UpdateMarkingForLValueToRValue(E); 607 608 // Loading a __weak object implicitly retains the value, so we need a cleanup to 609 // balance that. 610 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 611 Cleanup.setExprNeedsCleanups(true); 612 613 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 614 nullptr, VK_RValue); 615 616 // C11 6.3.2.1p2: 617 // ... if the lvalue has atomic type, the value has the non-atomic version 618 // of the type of the lvalue ... 619 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 620 T = Atomic->getValueType().getUnqualifiedType(); 621 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 622 nullptr, VK_RValue); 623 } 624 625 return Res; 626 } 627 628 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 629 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 630 if (Res.isInvalid()) 631 return ExprError(); 632 Res = DefaultLvalueConversion(Res.get()); 633 if (Res.isInvalid()) 634 return ExprError(); 635 return Res; 636 } 637 638 /// CallExprUnaryConversions - a special case of an unary conversion 639 /// performed on a function designator of a call expression. 640 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 641 QualType Ty = E->getType(); 642 ExprResult Res = E; 643 // Only do implicit cast for a function type, but not for a pointer 644 // to function type. 645 if (Ty->isFunctionType()) { 646 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 647 CK_FunctionToPointerDecay).get(); 648 if (Res.isInvalid()) 649 return ExprError(); 650 } 651 Res = DefaultLvalueConversion(Res.get()); 652 if (Res.isInvalid()) 653 return ExprError(); 654 return Res.get(); 655 } 656 657 /// UsualUnaryConversions - Performs various conversions that are common to most 658 /// operators (C99 6.3). The conversions of array and function types are 659 /// sometimes suppressed. For example, the array->pointer conversion doesn't 660 /// apply if the array is an argument to the sizeof or address (&) operators. 661 /// In these instances, this routine should *not* be called. 662 ExprResult Sema::UsualUnaryConversions(Expr *E) { 663 // First, convert to an r-value. 664 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 665 if (Res.isInvalid()) 666 return ExprError(); 667 E = Res.get(); 668 669 QualType Ty = E->getType(); 670 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 671 672 // Half FP have to be promoted to float unless it is natively supported 673 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 674 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 675 676 // Try to perform integral promotions if the object has a theoretically 677 // promotable type. 678 if (Ty->isIntegralOrUnscopedEnumerationType()) { 679 // C99 6.3.1.1p2: 680 // 681 // The following may be used in an expression wherever an int or 682 // unsigned int may be used: 683 // - an object or expression with an integer type whose integer 684 // conversion rank is less than or equal to the rank of int 685 // and unsigned int. 686 // - A bit-field of type _Bool, int, signed int, or unsigned int. 687 // 688 // If an int can represent all values of the original type, the 689 // value is converted to an int; otherwise, it is converted to an 690 // unsigned int. These are called the integer promotions. All 691 // other types are unchanged by the integer promotions. 692 693 QualType PTy = Context.isPromotableBitField(E); 694 if (!PTy.isNull()) { 695 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 696 return E; 697 } 698 if (Ty->isPromotableIntegerType()) { 699 QualType PT = Context.getPromotedIntegerType(Ty); 700 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 701 return E; 702 } 703 } 704 return E; 705 } 706 707 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 708 /// do not have a prototype. Arguments that have type float or __fp16 709 /// are promoted to double. All other argument types are converted by 710 /// UsualUnaryConversions(). 711 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 712 QualType Ty = E->getType(); 713 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 714 715 ExprResult Res = UsualUnaryConversions(E); 716 if (Res.isInvalid()) 717 return ExprError(); 718 E = Res.get(); 719 720 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 721 // promote to double. 722 // Note that default argument promotion applies only to float (and 723 // half/fp16); it does not apply to _Float16. 724 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 725 if (BTy && (BTy->getKind() == BuiltinType::Half || 726 BTy->getKind() == BuiltinType::Float)) { 727 if (getLangOpts().OpenCL && 728 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 729 if (BTy->getKind() == BuiltinType::Half) { 730 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 731 } 732 } else { 733 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 734 } 735 } 736 737 // C++ performs lvalue-to-rvalue conversion as a default argument 738 // promotion, even on class types, but note: 739 // C++11 [conv.lval]p2: 740 // When an lvalue-to-rvalue conversion occurs in an unevaluated 741 // operand or a subexpression thereof the value contained in the 742 // referenced object is not accessed. Otherwise, if the glvalue 743 // has a class type, the conversion copy-initializes a temporary 744 // of type T from the glvalue and the result of the conversion 745 // is a prvalue for the temporary. 746 // FIXME: add some way to gate this entire thing for correctness in 747 // potentially potentially evaluated contexts. 748 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 749 ExprResult Temp = PerformCopyInitialization( 750 InitializedEntity::InitializeTemporary(E->getType()), 751 E->getExprLoc(), E); 752 if (Temp.isInvalid()) 753 return ExprError(); 754 E = Temp.get(); 755 } 756 757 return E; 758 } 759 760 /// Determine the degree of POD-ness for an expression. 761 /// Incomplete types are considered POD, since this check can be performed 762 /// when we're in an unevaluated context. 763 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 764 if (Ty->isIncompleteType()) { 765 // C++11 [expr.call]p7: 766 // After these conversions, if the argument does not have arithmetic, 767 // enumeration, pointer, pointer to member, or class type, the program 768 // is ill-formed. 769 // 770 // Since we've already performed array-to-pointer and function-to-pointer 771 // decay, the only such type in C++ is cv void. This also handles 772 // initializer lists as variadic arguments. 773 if (Ty->isVoidType()) 774 return VAK_Invalid; 775 776 if (Ty->isObjCObjectType()) 777 return VAK_Invalid; 778 return VAK_Valid; 779 } 780 781 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 782 return VAK_Invalid; 783 784 if (Ty.isCXX98PODType(Context)) 785 return VAK_Valid; 786 787 // C++11 [expr.call]p7: 788 // Passing a potentially-evaluated argument of class type (Clause 9) 789 // having a non-trivial copy constructor, a non-trivial move constructor, 790 // or a non-trivial destructor, with no corresponding parameter, 791 // is conditionally-supported with implementation-defined semantics. 792 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 793 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 794 if (!Record->hasNonTrivialCopyConstructor() && 795 !Record->hasNonTrivialMoveConstructor() && 796 !Record->hasNonTrivialDestructor()) 797 return VAK_ValidInCXX11; 798 799 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 800 return VAK_Valid; 801 802 if (Ty->isObjCObjectType()) 803 return VAK_Invalid; 804 805 if (getLangOpts().MSVCCompat) 806 return VAK_MSVCUndefined; 807 808 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 809 // permitted to reject them. We should consider doing so. 810 return VAK_Undefined; 811 } 812 813 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 814 // Don't allow one to pass an Objective-C interface to a vararg. 815 const QualType &Ty = E->getType(); 816 VarArgKind VAK = isValidVarArgType(Ty); 817 818 // Complain about passing non-POD types through varargs. 819 switch (VAK) { 820 case VAK_ValidInCXX11: 821 DiagRuntimeBehavior( 822 E->getLocStart(), nullptr, 823 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 824 << Ty << CT); 825 LLVM_FALLTHROUGH; 826 case VAK_Valid: 827 if (Ty->isRecordType()) { 828 // This is unlikely to be what the user intended. If the class has a 829 // 'c_str' member function, the user probably meant to call that. 830 DiagRuntimeBehavior(E->getLocStart(), nullptr, 831 PDiag(diag::warn_pass_class_arg_to_vararg) 832 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 833 } 834 break; 835 836 case VAK_Undefined: 837 case VAK_MSVCUndefined: 838 DiagRuntimeBehavior( 839 E->getLocStart(), nullptr, 840 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 841 << getLangOpts().CPlusPlus11 << Ty << CT); 842 break; 843 844 case VAK_Invalid: 845 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 846 Diag(E->getLocStart(), 847 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) << Ty << CT; 848 else if (Ty->isObjCObjectType()) 849 DiagRuntimeBehavior( 850 E->getLocStart(), nullptr, 851 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 852 << Ty << CT); 853 else 854 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg) 855 << isa<InitListExpr>(E) << Ty << CT; 856 break; 857 } 858 } 859 860 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 861 /// will create a trap if the resulting type is not a POD type. 862 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 863 FunctionDecl *FDecl) { 864 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 865 // Strip the unbridged-cast placeholder expression off, if applicable. 866 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 867 (CT == VariadicMethod || 868 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 869 E = stripARCUnbridgedCast(E); 870 871 // Otherwise, do normal placeholder checking. 872 } else { 873 ExprResult ExprRes = CheckPlaceholderExpr(E); 874 if (ExprRes.isInvalid()) 875 return ExprError(); 876 E = ExprRes.get(); 877 } 878 } 879 880 ExprResult ExprRes = DefaultArgumentPromotion(E); 881 if (ExprRes.isInvalid()) 882 return ExprError(); 883 E = ExprRes.get(); 884 885 // Diagnostics regarding non-POD argument types are 886 // emitted along with format string checking in Sema::CheckFunctionCall(). 887 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 888 // Turn this into a trap. 889 CXXScopeSpec SS; 890 SourceLocation TemplateKWLoc; 891 UnqualifiedId Name; 892 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 893 E->getLocStart()); 894 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 895 Name, true, false); 896 if (TrapFn.isInvalid()) 897 return ExprError(); 898 899 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 900 E->getLocStart(), None, 901 E->getLocEnd()); 902 if (Call.isInvalid()) 903 return ExprError(); 904 905 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 906 Call.get(), E); 907 if (Comma.isInvalid()) 908 return ExprError(); 909 return Comma.get(); 910 } 911 912 if (!getLangOpts().CPlusPlus && 913 RequireCompleteType(E->getExprLoc(), E->getType(), 914 diag::err_call_incomplete_argument)) 915 return ExprError(); 916 917 return E; 918 } 919 920 /// Converts an integer to complex float type. Helper function of 921 /// UsualArithmeticConversions() 922 /// 923 /// \return false if the integer expression is an integer type and is 924 /// successfully converted to the complex type. 925 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 926 ExprResult &ComplexExpr, 927 QualType IntTy, 928 QualType ComplexTy, 929 bool SkipCast) { 930 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 931 if (SkipCast) return false; 932 if (IntTy->isIntegerType()) { 933 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 934 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 935 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 936 CK_FloatingRealToComplex); 937 } else { 938 assert(IntTy->isComplexIntegerType()); 939 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 940 CK_IntegralComplexToFloatingComplex); 941 } 942 return false; 943 } 944 945 /// Handle arithmetic conversion with complex types. Helper function of 946 /// UsualArithmeticConversions() 947 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 948 ExprResult &RHS, QualType LHSType, 949 QualType RHSType, 950 bool IsCompAssign) { 951 // if we have an integer operand, the result is the complex type. 952 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 953 /*skipCast*/false)) 954 return LHSType; 955 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 956 /*skipCast*/IsCompAssign)) 957 return RHSType; 958 959 // This handles complex/complex, complex/float, or float/complex. 960 // When both operands are complex, the shorter operand is converted to the 961 // type of the longer, and that is the type of the result. This corresponds 962 // to what is done when combining two real floating-point operands. 963 // The fun begins when size promotion occur across type domains. 964 // From H&S 6.3.4: When one operand is complex and the other is a real 965 // floating-point type, the less precise type is converted, within it's 966 // real or complex domain, to the precision of the other type. For example, 967 // when combining a "long double" with a "double _Complex", the 968 // "double _Complex" is promoted to "long double _Complex". 969 970 // Compute the rank of the two types, regardless of whether they are complex. 971 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 972 973 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 974 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 975 QualType LHSElementType = 976 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 977 QualType RHSElementType = 978 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 979 980 QualType ResultType = S.Context.getComplexType(LHSElementType); 981 if (Order < 0) { 982 // Promote the precision of the LHS if not an assignment. 983 ResultType = S.Context.getComplexType(RHSElementType); 984 if (!IsCompAssign) { 985 if (LHSComplexType) 986 LHS = 987 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 988 else 989 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 990 } 991 } else if (Order > 0) { 992 // Promote the precision of the RHS. 993 if (RHSComplexType) 994 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 995 else 996 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 997 } 998 return ResultType; 999 } 1000 1001 /// Handle arithmetic conversion from integer to float. Helper function 1002 /// of UsualArithmeticConversions() 1003 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1004 ExprResult &IntExpr, 1005 QualType FloatTy, QualType IntTy, 1006 bool ConvertFloat, bool ConvertInt) { 1007 if (IntTy->isIntegerType()) { 1008 if (ConvertInt) 1009 // Convert intExpr to the lhs floating point type. 1010 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1011 CK_IntegralToFloating); 1012 return FloatTy; 1013 } 1014 1015 // Convert both sides to the appropriate complex float. 1016 assert(IntTy->isComplexIntegerType()); 1017 QualType result = S.Context.getComplexType(FloatTy); 1018 1019 // _Complex int -> _Complex float 1020 if (ConvertInt) 1021 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1022 CK_IntegralComplexToFloatingComplex); 1023 1024 // float -> _Complex float 1025 if (ConvertFloat) 1026 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1027 CK_FloatingRealToComplex); 1028 1029 return result; 1030 } 1031 1032 /// Handle arithmethic conversion with floating point types. Helper 1033 /// function of UsualArithmeticConversions() 1034 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1035 ExprResult &RHS, QualType LHSType, 1036 QualType RHSType, bool IsCompAssign) { 1037 bool LHSFloat = LHSType->isRealFloatingType(); 1038 bool RHSFloat = RHSType->isRealFloatingType(); 1039 1040 // If we have two real floating types, convert the smaller operand 1041 // to the bigger result. 1042 if (LHSFloat && RHSFloat) { 1043 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1044 if (order > 0) { 1045 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1046 return LHSType; 1047 } 1048 1049 assert(order < 0 && "illegal float comparison"); 1050 if (!IsCompAssign) 1051 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1052 return RHSType; 1053 } 1054 1055 if (LHSFloat) { 1056 // Half FP has to be promoted to float unless it is natively supported 1057 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1058 LHSType = S.Context.FloatTy; 1059 1060 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1061 /*convertFloat=*/!IsCompAssign, 1062 /*convertInt=*/ true); 1063 } 1064 assert(RHSFloat); 1065 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1066 /*convertInt=*/ true, 1067 /*convertFloat=*/!IsCompAssign); 1068 } 1069 1070 /// Diagnose attempts to convert between __float128 and long double if 1071 /// there is no support for such conversion. Helper function of 1072 /// UsualArithmeticConversions(). 1073 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1074 QualType RHSType) { 1075 /* No issue converting if at least one of the types is not a floating point 1076 type or the two types have the same rank. 1077 */ 1078 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1079 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1080 return false; 1081 1082 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1083 "The remaining types must be floating point types."); 1084 1085 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1086 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1087 1088 QualType LHSElemType = LHSComplex ? 1089 LHSComplex->getElementType() : LHSType; 1090 QualType RHSElemType = RHSComplex ? 1091 RHSComplex->getElementType() : RHSType; 1092 1093 // No issue if the two types have the same representation 1094 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1095 &S.Context.getFloatTypeSemantics(RHSElemType)) 1096 return false; 1097 1098 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1099 RHSElemType == S.Context.LongDoubleTy); 1100 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1101 RHSElemType == S.Context.Float128Ty); 1102 1103 // We've handled the situation where __float128 and long double have the same 1104 // representation. We allow all conversions for all possible long double types 1105 // except PPC's double double. 1106 return Float128AndLongDouble && 1107 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1108 &llvm::APFloat::PPCDoubleDouble()); 1109 } 1110 1111 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1112 1113 namespace { 1114 /// These helper callbacks are placed in an anonymous namespace to 1115 /// permit their use as function template parameters. 1116 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1117 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1118 } 1119 1120 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1121 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1122 CK_IntegralComplexCast); 1123 } 1124 } 1125 1126 /// Handle integer arithmetic conversions. Helper function of 1127 /// UsualArithmeticConversions() 1128 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1129 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1130 ExprResult &RHS, QualType LHSType, 1131 QualType RHSType, bool IsCompAssign) { 1132 // The rules for this case are in C99 6.3.1.8 1133 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1134 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1135 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1136 if (LHSSigned == RHSSigned) { 1137 // Same signedness; use the higher-ranked type 1138 if (order >= 0) { 1139 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1140 return LHSType; 1141 } else if (!IsCompAssign) 1142 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1143 return RHSType; 1144 } else if (order != (LHSSigned ? 1 : -1)) { 1145 // The unsigned type has greater than or equal rank to the 1146 // signed type, so use the unsigned type 1147 if (RHSSigned) { 1148 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1149 return LHSType; 1150 } else if (!IsCompAssign) 1151 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1152 return RHSType; 1153 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1154 // The two types are different widths; if we are here, that 1155 // means the signed type is larger than the unsigned type, so 1156 // use the signed type. 1157 if (LHSSigned) { 1158 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1159 return LHSType; 1160 } else if (!IsCompAssign) 1161 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1162 return RHSType; 1163 } else { 1164 // The signed type is higher-ranked than the unsigned type, 1165 // but isn't actually any bigger (like unsigned int and long 1166 // on most 32-bit systems). Use the unsigned type corresponding 1167 // to the signed type. 1168 QualType result = 1169 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1170 RHS = (*doRHSCast)(S, RHS.get(), result); 1171 if (!IsCompAssign) 1172 LHS = (*doLHSCast)(S, LHS.get(), result); 1173 return result; 1174 } 1175 } 1176 1177 /// Handle conversions with GCC complex int extension. Helper function 1178 /// of UsualArithmeticConversions() 1179 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1180 ExprResult &RHS, QualType LHSType, 1181 QualType RHSType, 1182 bool IsCompAssign) { 1183 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1184 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1185 1186 if (LHSComplexInt && RHSComplexInt) { 1187 QualType LHSEltType = LHSComplexInt->getElementType(); 1188 QualType RHSEltType = RHSComplexInt->getElementType(); 1189 QualType ScalarType = 1190 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1191 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1192 1193 return S.Context.getComplexType(ScalarType); 1194 } 1195 1196 if (LHSComplexInt) { 1197 QualType LHSEltType = LHSComplexInt->getElementType(); 1198 QualType ScalarType = 1199 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1200 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1201 QualType ComplexType = S.Context.getComplexType(ScalarType); 1202 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1203 CK_IntegralRealToComplex); 1204 1205 return ComplexType; 1206 } 1207 1208 assert(RHSComplexInt); 1209 1210 QualType RHSEltType = RHSComplexInt->getElementType(); 1211 QualType ScalarType = 1212 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1213 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1214 QualType ComplexType = S.Context.getComplexType(ScalarType); 1215 1216 if (!IsCompAssign) 1217 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1218 CK_IntegralRealToComplex); 1219 return ComplexType; 1220 } 1221 1222 /// UsualArithmeticConversions - Performs various conversions that are common to 1223 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1224 /// routine returns the first non-arithmetic type found. The client is 1225 /// responsible for emitting appropriate error diagnostics. 1226 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1227 bool IsCompAssign) { 1228 if (!IsCompAssign) { 1229 LHS = UsualUnaryConversions(LHS.get()); 1230 if (LHS.isInvalid()) 1231 return QualType(); 1232 } 1233 1234 RHS = UsualUnaryConversions(RHS.get()); 1235 if (RHS.isInvalid()) 1236 return QualType(); 1237 1238 // For conversion purposes, we ignore any qualifiers. 1239 // For example, "const float" and "float" are equivalent. 1240 QualType LHSType = 1241 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1242 QualType RHSType = 1243 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1244 1245 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1246 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1247 LHSType = AtomicLHS->getValueType(); 1248 1249 // If both types are identical, no conversion is needed. 1250 if (LHSType == RHSType) 1251 return LHSType; 1252 1253 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1254 // The caller can deal with this (e.g. pointer + int). 1255 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1256 return QualType(); 1257 1258 // Apply unary and bitfield promotions to the LHS's type. 1259 QualType LHSUnpromotedType = LHSType; 1260 if (LHSType->isPromotableIntegerType()) 1261 LHSType = Context.getPromotedIntegerType(LHSType); 1262 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1263 if (!LHSBitfieldPromoteTy.isNull()) 1264 LHSType = LHSBitfieldPromoteTy; 1265 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1266 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1267 1268 // If both types are identical, no conversion is needed. 1269 if (LHSType == RHSType) 1270 return LHSType; 1271 1272 // At this point, we have two different arithmetic types. 1273 1274 // Diagnose attempts to convert between __float128 and long double where 1275 // such conversions currently can't be handled. 1276 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1277 return QualType(); 1278 1279 // Handle complex types first (C99 6.3.1.8p1). 1280 if (LHSType->isComplexType() || RHSType->isComplexType()) 1281 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1282 IsCompAssign); 1283 1284 // Now handle "real" floating types (i.e. float, double, long double). 1285 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1286 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1287 IsCompAssign); 1288 1289 // Handle GCC complex int extension. 1290 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1291 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1292 IsCompAssign); 1293 1294 // Finally, we have two differing integer types. 1295 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1296 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1297 } 1298 1299 1300 //===----------------------------------------------------------------------===// 1301 // Semantic Analysis for various Expression Types 1302 //===----------------------------------------------------------------------===// 1303 1304 1305 ExprResult 1306 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1307 SourceLocation DefaultLoc, 1308 SourceLocation RParenLoc, 1309 Expr *ControllingExpr, 1310 ArrayRef<ParsedType> ArgTypes, 1311 ArrayRef<Expr *> ArgExprs) { 1312 unsigned NumAssocs = ArgTypes.size(); 1313 assert(NumAssocs == ArgExprs.size()); 1314 1315 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1316 for (unsigned i = 0; i < NumAssocs; ++i) { 1317 if (ArgTypes[i]) 1318 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1319 else 1320 Types[i] = nullptr; 1321 } 1322 1323 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1324 ControllingExpr, 1325 llvm::makeArrayRef(Types, NumAssocs), 1326 ArgExprs); 1327 delete [] Types; 1328 return ER; 1329 } 1330 1331 ExprResult 1332 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1333 SourceLocation DefaultLoc, 1334 SourceLocation RParenLoc, 1335 Expr *ControllingExpr, 1336 ArrayRef<TypeSourceInfo *> Types, 1337 ArrayRef<Expr *> Exprs) { 1338 unsigned NumAssocs = Types.size(); 1339 assert(NumAssocs == Exprs.size()); 1340 1341 // Decay and strip qualifiers for the controlling expression type, and handle 1342 // placeholder type replacement. See committee discussion from WG14 DR423. 1343 { 1344 EnterExpressionEvaluationContext Unevaluated( 1345 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1346 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1347 if (R.isInvalid()) 1348 return ExprError(); 1349 ControllingExpr = R.get(); 1350 } 1351 1352 // The controlling expression is an unevaluated operand, so side effects are 1353 // likely unintended. 1354 if (!inTemplateInstantiation() && 1355 ControllingExpr->HasSideEffects(Context, false)) 1356 Diag(ControllingExpr->getExprLoc(), 1357 diag::warn_side_effects_unevaluated_context); 1358 1359 bool TypeErrorFound = false, 1360 IsResultDependent = ControllingExpr->isTypeDependent(), 1361 ContainsUnexpandedParameterPack 1362 = ControllingExpr->containsUnexpandedParameterPack(); 1363 1364 for (unsigned i = 0; i < NumAssocs; ++i) { 1365 if (Exprs[i]->containsUnexpandedParameterPack()) 1366 ContainsUnexpandedParameterPack = true; 1367 1368 if (Types[i]) { 1369 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1370 ContainsUnexpandedParameterPack = true; 1371 1372 if (Types[i]->getType()->isDependentType()) { 1373 IsResultDependent = true; 1374 } else { 1375 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1376 // complete object type other than a variably modified type." 1377 unsigned D = 0; 1378 if (Types[i]->getType()->isIncompleteType()) 1379 D = diag::err_assoc_type_incomplete; 1380 else if (!Types[i]->getType()->isObjectType()) 1381 D = diag::err_assoc_type_nonobject; 1382 else if (Types[i]->getType()->isVariablyModifiedType()) 1383 D = diag::err_assoc_type_variably_modified; 1384 1385 if (D != 0) { 1386 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1387 << Types[i]->getTypeLoc().getSourceRange() 1388 << Types[i]->getType(); 1389 TypeErrorFound = true; 1390 } 1391 1392 // C11 6.5.1.1p2 "No two generic associations in the same generic 1393 // selection shall specify compatible types." 1394 for (unsigned j = i+1; j < NumAssocs; ++j) 1395 if (Types[j] && !Types[j]->getType()->isDependentType() && 1396 Context.typesAreCompatible(Types[i]->getType(), 1397 Types[j]->getType())) { 1398 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1399 diag::err_assoc_compatible_types) 1400 << Types[j]->getTypeLoc().getSourceRange() 1401 << Types[j]->getType() 1402 << Types[i]->getType(); 1403 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1404 diag::note_compat_assoc) 1405 << Types[i]->getTypeLoc().getSourceRange() 1406 << Types[i]->getType(); 1407 TypeErrorFound = true; 1408 } 1409 } 1410 } 1411 } 1412 if (TypeErrorFound) 1413 return ExprError(); 1414 1415 // If we determined that the generic selection is result-dependent, don't 1416 // try to compute the result expression. 1417 if (IsResultDependent) 1418 return new (Context) GenericSelectionExpr( 1419 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1420 ContainsUnexpandedParameterPack); 1421 1422 SmallVector<unsigned, 1> CompatIndices; 1423 unsigned DefaultIndex = -1U; 1424 for (unsigned i = 0; i < NumAssocs; ++i) { 1425 if (!Types[i]) 1426 DefaultIndex = i; 1427 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1428 Types[i]->getType())) 1429 CompatIndices.push_back(i); 1430 } 1431 1432 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1433 // type compatible with at most one of the types named in its generic 1434 // association list." 1435 if (CompatIndices.size() > 1) { 1436 // We strip parens here because the controlling expression is typically 1437 // parenthesized in macro definitions. 1438 ControllingExpr = ControllingExpr->IgnoreParens(); 1439 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1440 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1441 << (unsigned) CompatIndices.size(); 1442 for (unsigned I : CompatIndices) { 1443 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1444 diag::note_compat_assoc) 1445 << Types[I]->getTypeLoc().getSourceRange() 1446 << Types[I]->getType(); 1447 } 1448 return ExprError(); 1449 } 1450 1451 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1452 // its controlling expression shall have type compatible with exactly one of 1453 // the types named in its generic association list." 1454 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1455 // We strip parens here because the controlling expression is typically 1456 // parenthesized in macro definitions. 1457 ControllingExpr = ControllingExpr->IgnoreParens(); 1458 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1459 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1460 return ExprError(); 1461 } 1462 1463 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1464 // type name that is compatible with the type of the controlling expression, 1465 // then the result expression of the generic selection is the expression 1466 // in that generic association. Otherwise, the result expression of the 1467 // generic selection is the expression in the default generic association." 1468 unsigned ResultIndex = 1469 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1470 1471 return new (Context) GenericSelectionExpr( 1472 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1473 ContainsUnexpandedParameterPack, ResultIndex); 1474 } 1475 1476 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1477 /// location of the token and the offset of the ud-suffix within it. 1478 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1479 unsigned Offset) { 1480 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1481 S.getLangOpts()); 1482 } 1483 1484 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1485 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1486 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1487 IdentifierInfo *UDSuffix, 1488 SourceLocation UDSuffixLoc, 1489 ArrayRef<Expr*> Args, 1490 SourceLocation LitEndLoc) { 1491 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1492 1493 QualType ArgTy[2]; 1494 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1495 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1496 if (ArgTy[ArgIdx]->isArrayType()) 1497 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1498 } 1499 1500 DeclarationName OpName = 1501 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1502 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1503 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1504 1505 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1506 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1507 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1508 /*AllowStringTemplate*/ false, 1509 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1510 return ExprError(); 1511 1512 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1513 } 1514 1515 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1516 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1517 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1518 /// multiple tokens. However, the common case is that StringToks points to one 1519 /// string. 1520 /// 1521 ExprResult 1522 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1523 assert(!StringToks.empty() && "Must have at least one string!"); 1524 1525 StringLiteralParser Literal(StringToks, PP); 1526 if (Literal.hadError) 1527 return ExprError(); 1528 1529 SmallVector<SourceLocation, 4> StringTokLocs; 1530 for (const Token &Tok : StringToks) 1531 StringTokLocs.push_back(Tok.getLocation()); 1532 1533 QualType CharTy = Context.CharTy; 1534 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1535 if (Literal.isWide()) { 1536 CharTy = Context.getWideCharType(); 1537 Kind = StringLiteral::Wide; 1538 } else if (Literal.isUTF8()) { 1539 if (getLangOpts().Char8) 1540 CharTy = Context.Char8Ty; 1541 Kind = StringLiteral::UTF8; 1542 } else if (Literal.isUTF16()) { 1543 CharTy = Context.Char16Ty; 1544 Kind = StringLiteral::UTF16; 1545 } else if (Literal.isUTF32()) { 1546 CharTy = Context.Char32Ty; 1547 Kind = StringLiteral::UTF32; 1548 } else if (Literal.isPascal()) { 1549 CharTy = Context.UnsignedCharTy; 1550 } 1551 1552 QualType CharTyConst = CharTy; 1553 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1554 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1555 CharTyConst.addConst(); 1556 1557 CharTyConst = Context.adjustStringLiteralBaseType(CharTyConst); 1558 1559 // Get an array type for the string, according to C99 6.4.5. This includes 1560 // the nul terminator character as well as the string length for pascal 1561 // strings. 1562 QualType StrTy = Context.getConstantArrayType( 1563 CharTyConst, llvm::APInt(32, Literal.GetNumStringChars() + 1), 1564 ArrayType::Normal, 0); 1565 1566 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1567 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1568 Kind, Literal.Pascal, StrTy, 1569 &StringTokLocs[0], 1570 StringTokLocs.size()); 1571 if (Literal.getUDSuffix().empty()) 1572 return Lit; 1573 1574 // We're building a user-defined literal. 1575 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1576 SourceLocation UDSuffixLoc = 1577 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1578 Literal.getUDSuffixOffset()); 1579 1580 // Make sure we're allowed user-defined literals here. 1581 if (!UDLScope) 1582 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1583 1584 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1585 // operator "" X (str, len) 1586 QualType SizeType = Context.getSizeType(); 1587 1588 DeclarationName OpName = 1589 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1590 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1591 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1592 1593 QualType ArgTy[] = { 1594 Context.getArrayDecayedType(StrTy), SizeType 1595 }; 1596 1597 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1598 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1599 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1600 /*AllowStringTemplate*/ true, 1601 /*DiagnoseMissing*/ true)) { 1602 1603 case LOLR_Cooked: { 1604 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1605 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1606 StringTokLocs[0]); 1607 Expr *Args[] = { Lit, LenArg }; 1608 1609 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1610 } 1611 1612 case LOLR_StringTemplate: { 1613 TemplateArgumentListInfo ExplicitArgs; 1614 1615 unsigned CharBits = Context.getIntWidth(CharTy); 1616 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1617 llvm::APSInt Value(CharBits, CharIsUnsigned); 1618 1619 TemplateArgument TypeArg(CharTy); 1620 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1621 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1622 1623 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1624 Value = Lit->getCodeUnit(I); 1625 TemplateArgument Arg(Context, Value, CharTy); 1626 TemplateArgumentLocInfo ArgInfo; 1627 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1628 } 1629 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1630 &ExplicitArgs); 1631 } 1632 case LOLR_Raw: 1633 case LOLR_Template: 1634 case LOLR_ErrorNoDiagnostic: 1635 llvm_unreachable("unexpected literal operator lookup result"); 1636 case LOLR_Error: 1637 return ExprError(); 1638 } 1639 llvm_unreachable("unexpected literal operator lookup result"); 1640 } 1641 1642 ExprResult 1643 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1644 SourceLocation Loc, 1645 const CXXScopeSpec *SS) { 1646 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1647 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1648 } 1649 1650 /// BuildDeclRefExpr - Build an expression that references a 1651 /// declaration that does not require a closure capture. 1652 ExprResult 1653 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1654 const DeclarationNameInfo &NameInfo, 1655 const CXXScopeSpec *SS, NamedDecl *FoundD, 1656 const TemplateArgumentListInfo *TemplateArgs) { 1657 bool RefersToCapturedVariable = 1658 isa<VarDecl>(D) && 1659 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1660 1661 DeclRefExpr *E; 1662 if (isa<VarTemplateSpecializationDecl>(D)) { 1663 VarTemplateSpecializationDecl *VarSpec = 1664 cast<VarTemplateSpecializationDecl>(D); 1665 1666 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1667 : NestedNameSpecifierLoc(), 1668 VarSpec->getTemplateKeywordLoc(), D, 1669 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK, 1670 FoundD, TemplateArgs); 1671 } else { 1672 assert(!TemplateArgs && "No template arguments for non-variable" 1673 " template specialization references"); 1674 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1675 : NestedNameSpecifierLoc(), 1676 SourceLocation(), D, RefersToCapturedVariable, 1677 NameInfo, Ty, VK, FoundD); 1678 } 1679 1680 MarkDeclRefReferenced(E); 1681 1682 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1683 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 1684 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart())) 1685 getCurFunction()->recordUseOfWeak(E); 1686 1687 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1688 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 1689 FD = IFD->getAnonField(); 1690 if (FD) { 1691 UnusedPrivateFields.remove(FD); 1692 // Just in case we're building an illegal pointer-to-member. 1693 if (FD->isBitField()) 1694 E->setObjectKind(OK_BitField); 1695 } 1696 1697 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1698 // designates a bit-field. 1699 if (auto *BD = dyn_cast<BindingDecl>(D)) 1700 if (auto *BE = BD->getBinding()) 1701 E->setObjectKind(BE->getObjectKind()); 1702 1703 return E; 1704 } 1705 1706 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1707 /// possibly a list of template arguments. 1708 /// 1709 /// If this produces template arguments, it is permitted to call 1710 /// DecomposeTemplateName. 1711 /// 1712 /// This actually loses a lot of source location information for 1713 /// non-standard name kinds; we should consider preserving that in 1714 /// some way. 1715 void 1716 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1717 TemplateArgumentListInfo &Buffer, 1718 DeclarationNameInfo &NameInfo, 1719 const TemplateArgumentListInfo *&TemplateArgs) { 1720 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 1721 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1722 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1723 1724 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1725 Id.TemplateId->NumArgs); 1726 translateTemplateArguments(TemplateArgsPtr, Buffer); 1727 1728 TemplateName TName = Id.TemplateId->Template.get(); 1729 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1730 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1731 TemplateArgs = &Buffer; 1732 } else { 1733 NameInfo = GetNameFromUnqualifiedId(Id); 1734 TemplateArgs = nullptr; 1735 } 1736 } 1737 1738 static void emitEmptyLookupTypoDiagnostic( 1739 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1740 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1741 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1742 DeclContext *Ctx = 1743 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1744 if (!TC) { 1745 // Emit a special diagnostic for failed member lookups. 1746 // FIXME: computing the declaration context might fail here (?) 1747 if (Ctx) 1748 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1749 << SS.getRange(); 1750 else 1751 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1752 return; 1753 } 1754 1755 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1756 bool DroppedSpecifier = 1757 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1758 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1759 ? diag::note_implicit_param_decl 1760 : diag::note_previous_decl; 1761 if (!Ctx) 1762 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1763 SemaRef.PDiag(NoteID)); 1764 else 1765 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1766 << Typo << Ctx << DroppedSpecifier 1767 << SS.getRange(), 1768 SemaRef.PDiag(NoteID)); 1769 } 1770 1771 /// Diagnose an empty lookup. 1772 /// 1773 /// \return false if new lookup candidates were found 1774 bool 1775 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1776 std::unique_ptr<CorrectionCandidateCallback> CCC, 1777 TemplateArgumentListInfo *ExplicitTemplateArgs, 1778 ArrayRef<Expr *> Args, TypoExpr **Out) { 1779 DeclarationName Name = R.getLookupName(); 1780 1781 unsigned diagnostic = diag::err_undeclared_var_use; 1782 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1783 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1784 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1785 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1786 diagnostic = diag::err_undeclared_use; 1787 diagnostic_suggest = diag::err_undeclared_use_suggest; 1788 } 1789 1790 // If the original lookup was an unqualified lookup, fake an 1791 // unqualified lookup. This is useful when (for example) the 1792 // original lookup would not have found something because it was a 1793 // dependent name. 1794 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1795 while (DC) { 1796 if (isa<CXXRecordDecl>(DC)) { 1797 LookupQualifiedName(R, DC); 1798 1799 if (!R.empty()) { 1800 // Don't give errors about ambiguities in this lookup. 1801 R.suppressDiagnostics(); 1802 1803 // During a default argument instantiation the CurContext points 1804 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1805 // function parameter list, hence add an explicit check. 1806 bool isDefaultArgument = 1807 !CodeSynthesisContexts.empty() && 1808 CodeSynthesisContexts.back().Kind == 1809 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 1810 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1811 bool isInstance = CurMethod && 1812 CurMethod->isInstance() && 1813 DC == CurMethod->getParent() && !isDefaultArgument; 1814 1815 // Give a code modification hint to insert 'this->'. 1816 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1817 // Actually quite difficult! 1818 if (getLangOpts().MSVCCompat) 1819 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1820 if (isInstance) { 1821 Diag(R.getNameLoc(), diagnostic) << Name 1822 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1823 CheckCXXThisCapture(R.getNameLoc()); 1824 } else { 1825 Diag(R.getNameLoc(), diagnostic) << Name; 1826 } 1827 1828 // Do we really want to note all of these? 1829 for (NamedDecl *D : R) 1830 Diag(D->getLocation(), diag::note_dependent_var_use); 1831 1832 // Return true if we are inside a default argument instantiation 1833 // and the found name refers to an instance member function, otherwise 1834 // the function calling DiagnoseEmptyLookup will try to create an 1835 // implicit member call and this is wrong for default argument. 1836 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1837 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1838 return true; 1839 } 1840 1841 // Tell the callee to try to recover. 1842 return false; 1843 } 1844 1845 R.clear(); 1846 } 1847 1848 // In Microsoft mode, if we are performing lookup from within a friend 1849 // function definition declared at class scope then we must set 1850 // DC to the lexical parent to be able to search into the parent 1851 // class. 1852 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1853 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1854 DC->getLexicalParent()->isRecord()) 1855 DC = DC->getLexicalParent(); 1856 else 1857 DC = DC->getParent(); 1858 } 1859 1860 // We didn't find anything, so try to correct for a typo. 1861 TypoCorrection Corrected; 1862 if (S && Out) { 1863 SourceLocation TypoLoc = R.getNameLoc(); 1864 assert(!ExplicitTemplateArgs && 1865 "Diagnosing an empty lookup with explicit template args!"); 1866 *Out = CorrectTypoDelayed( 1867 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC), 1868 [=](const TypoCorrection &TC) { 1869 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 1870 diagnostic, diagnostic_suggest); 1871 }, 1872 nullptr, CTK_ErrorRecovery); 1873 if (*Out) 1874 return true; 1875 } else if (S && (Corrected = 1876 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, 1877 &SS, std::move(CCC), CTK_ErrorRecovery))) { 1878 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1879 bool DroppedSpecifier = 1880 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1881 R.setLookupName(Corrected.getCorrection()); 1882 1883 bool AcceptableWithRecovery = false; 1884 bool AcceptableWithoutRecovery = false; 1885 NamedDecl *ND = Corrected.getFoundDecl(); 1886 if (ND) { 1887 if (Corrected.isOverloaded()) { 1888 OverloadCandidateSet OCS(R.getNameLoc(), 1889 OverloadCandidateSet::CSK_Normal); 1890 OverloadCandidateSet::iterator Best; 1891 for (NamedDecl *CD : Corrected) { 1892 if (FunctionTemplateDecl *FTD = 1893 dyn_cast<FunctionTemplateDecl>(CD)) 1894 AddTemplateOverloadCandidate( 1895 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1896 Args, OCS); 1897 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 1898 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1899 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1900 Args, OCS); 1901 } 1902 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1903 case OR_Success: 1904 ND = Best->FoundDecl; 1905 Corrected.setCorrectionDecl(ND); 1906 break; 1907 default: 1908 // FIXME: Arbitrarily pick the first declaration for the note. 1909 Corrected.setCorrectionDecl(ND); 1910 break; 1911 } 1912 } 1913 R.addDecl(ND); 1914 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 1915 CXXRecordDecl *Record = nullptr; 1916 if (Corrected.getCorrectionSpecifier()) { 1917 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 1918 Record = Ty->getAsCXXRecordDecl(); 1919 } 1920 if (!Record) 1921 Record = cast<CXXRecordDecl>( 1922 ND->getDeclContext()->getRedeclContext()); 1923 R.setNamingClass(Record); 1924 } 1925 1926 auto *UnderlyingND = ND->getUnderlyingDecl(); 1927 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 1928 isa<FunctionTemplateDecl>(UnderlyingND); 1929 // FIXME: If we ended up with a typo for a type name or 1930 // Objective-C class name, we're in trouble because the parser 1931 // is in the wrong place to recover. Suggest the typo 1932 // correction, but don't make it a fix-it since we're not going 1933 // to recover well anyway. 1934 AcceptableWithoutRecovery = 1935 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND); 1936 } else { 1937 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1938 // because we aren't able to recover. 1939 AcceptableWithoutRecovery = true; 1940 } 1941 1942 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 1943 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 1944 ? diag::note_implicit_param_decl 1945 : diag::note_previous_decl; 1946 if (SS.isEmpty()) 1947 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 1948 PDiag(NoteID), AcceptableWithRecovery); 1949 else 1950 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 1951 << Name << computeDeclContext(SS, false) 1952 << DroppedSpecifier << SS.getRange(), 1953 PDiag(NoteID), AcceptableWithRecovery); 1954 1955 // Tell the callee whether to try to recover. 1956 return !AcceptableWithRecovery; 1957 } 1958 } 1959 R.clear(); 1960 1961 // Emit a special diagnostic for failed member lookups. 1962 // FIXME: computing the declaration context might fail here (?) 1963 if (!SS.isEmpty()) { 1964 Diag(R.getNameLoc(), diag::err_no_member) 1965 << Name << computeDeclContext(SS, false) 1966 << SS.getRange(); 1967 return true; 1968 } 1969 1970 // Give up, we can't recover. 1971 Diag(R.getNameLoc(), diagnostic) << Name; 1972 return true; 1973 } 1974 1975 /// In Microsoft mode, if we are inside a template class whose parent class has 1976 /// dependent base classes, and we can't resolve an unqualified identifier, then 1977 /// assume the identifier is a member of a dependent base class. We can only 1978 /// recover successfully in static methods, instance methods, and other contexts 1979 /// where 'this' is available. This doesn't precisely match MSVC's 1980 /// instantiation model, but it's close enough. 1981 static Expr * 1982 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 1983 DeclarationNameInfo &NameInfo, 1984 SourceLocation TemplateKWLoc, 1985 const TemplateArgumentListInfo *TemplateArgs) { 1986 // Only try to recover from lookup into dependent bases in static methods or 1987 // contexts where 'this' is available. 1988 QualType ThisType = S.getCurrentThisType(); 1989 const CXXRecordDecl *RD = nullptr; 1990 if (!ThisType.isNull()) 1991 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 1992 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 1993 RD = MD->getParent(); 1994 if (!RD || !RD->hasAnyDependentBases()) 1995 return nullptr; 1996 1997 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 1998 // is available, suggest inserting 'this->' as a fixit. 1999 SourceLocation Loc = NameInfo.getLoc(); 2000 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2001 DB << NameInfo.getName() << RD; 2002 2003 if (!ThisType.isNull()) { 2004 DB << FixItHint::CreateInsertion(Loc, "this->"); 2005 return CXXDependentScopeMemberExpr::Create( 2006 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2007 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2008 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 2009 } 2010 2011 // Synthesize a fake NNS that points to the derived class. This will 2012 // perform name lookup during template instantiation. 2013 CXXScopeSpec SS; 2014 auto *NNS = 2015 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2016 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2017 return DependentScopeDeclRefExpr::Create( 2018 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2019 TemplateArgs); 2020 } 2021 2022 ExprResult 2023 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2024 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2025 bool HasTrailingLParen, bool IsAddressOfOperand, 2026 std::unique_ptr<CorrectionCandidateCallback> CCC, 2027 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2028 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2029 "cannot be direct & operand and have a trailing lparen"); 2030 if (SS.isInvalid()) 2031 return ExprError(); 2032 2033 TemplateArgumentListInfo TemplateArgsBuffer; 2034 2035 // Decompose the UnqualifiedId into the following data. 2036 DeclarationNameInfo NameInfo; 2037 const TemplateArgumentListInfo *TemplateArgs; 2038 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2039 2040 DeclarationName Name = NameInfo.getName(); 2041 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2042 SourceLocation NameLoc = NameInfo.getLoc(); 2043 2044 if (II && II->isEditorPlaceholder()) { 2045 // FIXME: When typed placeholders are supported we can create a typed 2046 // placeholder expression node. 2047 return ExprError(); 2048 } 2049 2050 // C++ [temp.dep.expr]p3: 2051 // An id-expression is type-dependent if it contains: 2052 // -- an identifier that was declared with a dependent type, 2053 // (note: handled after lookup) 2054 // -- a template-id that is dependent, 2055 // (note: handled in BuildTemplateIdExpr) 2056 // -- a conversion-function-id that specifies a dependent type, 2057 // -- a nested-name-specifier that contains a class-name that 2058 // names a dependent type. 2059 // Determine whether this is a member of an unknown specialization; 2060 // we need to handle these differently. 2061 bool DependentID = false; 2062 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2063 Name.getCXXNameType()->isDependentType()) { 2064 DependentID = true; 2065 } else if (SS.isSet()) { 2066 if (DeclContext *DC = computeDeclContext(SS, false)) { 2067 if (RequireCompleteDeclContext(SS, DC)) 2068 return ExprError(); 2069 } else { 2070 DependentID = true; 2071 } 2072 } 2073 2074 if (DependentID) 2075 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2076 IsAddressOfOperand, TemplateArgs); 2077 2078 // Perform the required lookup. 2079 LookupResult R(*this, NameInfo, 2080 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2081 ? LookupObjCImplicitSelfParam 2082 : LookupOrdinaryName); 2083 if (TemplateKWLoc.isValid() || TemplateArgs) { 2084 // Lookup the template name again to correctly establish the context in 2085 // which it was found. This is really unfortunate as we already did the 2086 // lookup to determine that it was a template name in the first place. If 2087 // this becomes a performance hit, we can work harder to preserve those 2088 // results until we get here but it's likely not worth it. 2089 bool MemberOfUnknownSpecialization; 2090 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2091 MemberOfUnknownSpecialization, TemplateKWLoc)) 2092 return ExprError(); 2093 2094 if (MemberOfUnknownSpecialization || 2095 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2096 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2097 IsAddressOfOperand, TemplateArgs); 2098 } else { 2099 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2100 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2101 2102 // If the result might be in a dependent base class, this is a dependent 2103 // id-expression. 2104 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2105 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2106 IsAddressOfOperand, TemplateArgs); 2107 2108 // If this reference is in an Objective-C method, then we need to do 2109 // some special Objective-C lookup, too. 2110 if (IvarLookupFollowUp) { 2111 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2112 if (E.isInvalid()) 2113 return ExprError(); 2114 2115 if (Expr *Ex = E.getAs<Expr>()) 2116 return Ex; 2117 } 2118 } 2119 2120 if (R.isAmbiguous()) 2121 return ExprError(); 2122 2123 // This could be an implicitly declared function reference (legal in C90, 2124 // extension in C99, forbidden in C++). 2125 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2126 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2127 if (D) R.addDecl(D); 2128 } 2129 2130 // Determine whether this name might be a candidate for 2131 // argument-dependent lookup. 2132 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2133 2134 if (R.empty() && !ADL) { 2135 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2136 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2137 TemplateKWLoc, TemplateArgs)) 2138 return E; 2139 } 2140 2141 // Don't diagnose an empty lookup for inline assembly. 2142 if (IsInlineAsmIdentifier) 2143 return ExprError(); 2144 2145 // If this name wasn't predeclared and if this is not a function 2146 // call, diagnose the problem. 2147 TypoExpr *TE = nullptr; 2148 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2149 II, SS.isValid() ? SS.getScopeRep() : nullptr); 2150 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; 2151 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2152 "Typo correction callback misconfigured"); 2153 if (CCC) { 2154 // Make sure the callback knows what the typo being diagnosed is. 2155 CCC->setTypoName(II); 2156 if (SS.isValid()) 2157 CCC->setTypoNNS(SS.getScopeRep()); 2158 } 2159 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2160 // a template name, but we happen to have always already looked up the name 2161 // before we get here if it must be a template name. 2162 if (DiagnoseEmptyLookup(S, SS, R, 2163 CCC ? std::move(CCC) : std::move(DefaultValidator), 2164 nullptr, None, &TE)) { 2165 if (TE && KeywordReplacement) { 2166 auto &State = getTypoExprState(TE); 2167 auto BestTC = State.Consumer->getNextCorrection(); 2168 if (BestTC.isKeyword()) { 2169 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2170 if (State.DiagHandler) 2171 State.DiagHandler(BestTC); 2172 KeywordReplacement->startToken(); 2173 KeywordReplacement->setKind(II->getTokenID()); 2174 KeywordReplacement->setIdentifierInfo(II); 2175 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2176 // Clean up the state associated with the TypoExpr, since it has 2177 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2178 clearDelayedTypo(TE); 2179 // Signal that a correction to a keyword was performed by returning a 2180 // valid-but-null ExprResult. 2181 return (Expr*)nullptr; 2182 } 2183 State.Consumer->resetCorrectionStream(); 2184 } 2185 return TE ? TE : ExprError(); 2186 } 2187 2188 assert(!R.empty() && 2189 "DiagnoseEmptyLookup returned false but added no results"); 2190 2191 // If we found an Objective-C instance variable, let 2192 // LookupInObjCMethod build the appropriate expression to 2193 // reference the ivar. 2194 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2195 R.clear(); 2196 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2197 // In a hopelessly buggy code, Objective-C instance variable 2198 // lookup fails and no expression will be built to reference it. 2199 if (!E.isInvalid() && !E.get()) 2200 return ExprError(); 2201 return E; 2202 } 2203 } 2204 2205 // This is guaranteed from this point on. 2206 assert(!R.empty() || ADL); 2207 2208 // Check whether this might be a C++ implicit instance member access. 2209 // C++ [class.mfct.non-static]p3: 2210 // When an id-expression that is not part of a class member access 2211 // syntax and not used to form a pointer to member is used in the 2212 // body of a non-static member function of class X, if name lookup 2213 // resolves the name in the id-expression to a non-static non-type 2214 // member of some class C, the id-expression is transformed into a 2215 // class member access expression using (*this) as the 2216 // postfix-expression to the left of the . operator. 2217 // 2218 // But we don't actually need to do this for '&' operands if R 2219 // resolved to a function or overloaded function set, because the 2220 // expression is ill-formed if it actually works out to be a 2221 // non-static member function: 2222 // 2223 // C++ [expr.ref]p4: 2224 // Otherwise, if E1.E2 refers to a non-static member function. . . 2225 // [t]he expression can be used only as the left-hand operand of a 2226 // member function call. 2227 // 2228 // There are other safeguards against such uses, but it's important 2229 // to get this right here so that we don't end up making a 2230 // spuriously dependent expression if we're inside a dependent 2231 // instance method. 2232 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2233 bool MightBeImplicitMember; 2234 if (!IsAddressOfOperand) 2235 MightBeImplicitMember = true; 2236 else if (!SS.isEmpty()) 2237 MightBeImplicitMember = false; 2238 else if (R.isOverloadedResult()) 2239 MightBeImplicitMember = false; 2240 else if (R.isUnresolvableResult()) 2241 MightBeImplicitMember = true; 2242 else 2243 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2244 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2245 isa<MSPropertyDecl>(R.getFoundDecl()); 2246 2247 if (MightBeImplicitMember) 2248 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2249 R, TemplateArgs, S); 2250 } 2251 2252 if (TemplateArgs || TemplateKWLoc.isValid()) { 2253 2254 // In C++1y, if this is a variable template id, then check it 2255 // in BuildTemplateIdExpr(). 2256 // The single lookup result must be a variable template declaration. 2257 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2258 Id.TemplateId->Kind == TNK_Var_template) { 2259 assert(R.getAsSingle<VarTemplateDecl>() && 2260 "There should only be one declaration found."); 2261 } 2262 2263 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2264 } 2265 2266 return BuildDeclarationNameExpr(SS, R, ADL); 2267 } 2268 2269 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2270 /// declaration name, generally during template instantiation. 2271 /// There's a large number of things which don't need to be done along 2272 /// this path. 2273 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2274 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2275 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2276 DeclContext *DC = computeDeclContext(SS, false); 2277 if (!DC) 2278 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2279 NameInfo, /*TemplateArgs=*/nullptr); 2280 2281 if (RequireCompleteDeclContext(SS, DC)) 2282 return ExprError(); 2283 2284 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2285 LookupQualifiedName(R, DC); 2286 2287 if (R.isAmbiguous()) 2288 return ExprError(); 2289 2290 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2291 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2292 NameInfo, /*TemplateArgs=*/nullptr); 2293 2294 if (R.empty()) { 2295 Diag(NameInfo.getLoc(), diag::err_no_member) 2296 << NameInfo.getName() << DC << SS.getRange(); 2297 return ExprError(); 2298 } 2299 2300 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2301 // Diagnose a missing typename if this resolved unambiguously to a type in 2302 // a dependent context. If we can recover with a type, downgrade this to 2303 // a warning in Microsoft compatibility mode. 2304 unsigned DiagID = diag::err_typename_missing; 2305 if (RecoveryTSI && getLangOpts().MSVCCompat) 2306 DiagID = diag::ext_typename_missing; 2307 SourceLocation Loc = SS.getBeginLoc(); 2308 auto D = Diag(Loc, DiagID); 2309 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2310 << SourceRange(Loc, NameInfo.getEndLoc()); 2311 2312 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2313 // context. 2314 if (!RecoveryTSI) 2315 return ExprError(); 2316 2317 // Only issue the fixit if we're prepared to recover. 2318 D << FixItHint::CreateInsertion(Loc, "typename "); 2319 2320 // Recover by pretending this was an elaborated type. 2321 QualType Ty = Context.getTypeDeclType(TD); 2322 TypeLocBuilder TLB; 2323 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2324 2325 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2326 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2327 QTL.setElaboratedKeywordLoc(SourceLocation()); 2328 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2329 2330 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2331 2332 return ExprEmpty(); 2333 } 2334 2335 // Defend against this resolving to an implicit member access. We usually 2336 // won't get here if this might be a legitimate a class member (we end up in 2337 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2338 // a pointer-to-member or in an unevaluated context in C++11. 2339 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2340 return BuildPossibleImplicitMemberExpr(SS, 2341 /*TemplateKWLoc=*/SourceLocation(), 2342 R, /*TemplateArgs=*/nullptr, S); 2343 2344 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2345 } 2346 2347 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2348 /// detected that we're currently inside an ObjC method. Perform some 2349 /// additional lookup. 2350 /// 2351 /// Ideally, most of this would be done by lookup, but there's 2352 /// actually quite a lot of extra work involved. 2353 /// 2354 /// Returns a null sentinel to indicate trivial success. 2355 ExprResult 2356 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2357 IdentifierInfo *II, bool AllowBuiltinCreation) { 2358 SourceLocation Loc = Lookup.getNameLoc(); 2359 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2360 2361 // Check for error condition which is already reported. 2362 if (!CurMethod) 2363 return ExprError(); 2364 2365 // There are two cases to handle here. 1) scoped lookup could have failed, 2366 // in which case we should look for an ivar. 2) scoped lookup could have 2367 // found a decl, but that decl is outside the current instance method (i.e. 2368 // a global variable). In these two cases, we do a lookup for an ivar with 2369 // this name, if the lookup sucedes, we replace it our current decl. 2370 2371 // If we're in a class method, we don't normally want to look for 2372 // ivars. But if we don't find anything else, and there's an 2373 // ivar, that's an error. 2374 bool IsClassMethod = CurMethod->isClassMethod(); 2375 2376 bool LookForIvars; 2377 if (Lookup.empty()) 2378 LookForIvars = true; 2379 else if (IsClassMethod) 2380 LookForIvars = false; 2381 else 2382 LookForIvars = (Lookup.isSingleResult() && 2383 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2384 ObjCInterfaceDecl *IFace = nullptr; 2385 if (LookForIvars) { 2386 IFace = CurMethod->getClassInterface(); 2387 ObjCInterfaceDecl *ClassDeclared; 2388 ObjCIvarDecl *IV = nullptr; 2389 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2390 // Diagnose using an ivar in a class method. 2391 if (IsClassMethod) 2392 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2393 << IV->getDeclName()); 2394 2395 // If we're referencing an invalid decl, just return this as a silent 2396 // error node. The error diagnostic was already emitted on the decl. 2397 if (IV->isInvalidDecl()) 2398 return ExprError(); 2399 2400 // Check if referencing a field with __attribute__((deprecated)). 2401 if (DiagnoseUseOfDecl(IV, Loc)) 2402 return ExprError(); 2403 2404 // Diagnose the use of an ivar outside of the declaring class. 2405 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2406 !declaresSameEntity(ClassDeclared, IFace) && 2407 !getLangOpts().DebuggerSupport) 2408 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2409 2410 // FIXME: This should use a new expr for a direct reference, don't 2411 // turn this into Self->ivar, just return a BareIVarExpr or something. 2412 IdentifierInfo &II = Context.Idents.get("self"); 2413 UnqualifiedId SelfName; 2414 SelfName.setIdentifier(&II, SourceLocation()); 2415 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam); 2416 CXXScopeSpec SelfScopeSpec; 2417 SourceLocation TemplateKWLoc; 2418 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2419 SelfName, false, false); 2420 if (SelfExpr.isInvalid()) 2421 return ExprError(); 2422 2423 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2424 if (SelfExpr.isInvalid()) 2425 return ExprError(); 2426 2427 MarkAnyDeclReferenced(Loc, IV, true); 2428 2429 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2430 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2431 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2432 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2433 2434 ObjCIvarRefExpr *Result = new (Context) 2435 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2436 IV->getLocation(), SelfExpr.get(), true, true); 2437 2438 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2439 if (!isUnevaluatedContext() && 2440 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2441 getCurFunction()->recordUseOfWeak(Result); 2442 } 2443 if (getLangOpts().ObjCAutoRefCount) { 2444 if (CurContext->isClosure()) 2445 Diag(Loc, diag::warn_implicitly_retains_self) 2446 << FixItHint::CreateInsertion(Loc, "self->"); 2447 } 2448 2449 return Result; 2450 } 2451 } else if (CurMethod->isInstanceMethod()) { 2452 // We should warn if a local variable hides an ivar. 2453 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2454 ObjCInterfaceDecl *ClassDeclared; 2455 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2456 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2457 declaresSameEntity(IFace, ClassDeclared)) 2458 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2459 } 2460 } 2461 } else if (Lookup.isSingleResult() && 2462 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2463 // If accessing a stand-alone ivar in a class method, this is an error. 2464 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2465 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2466 << IV->getDeclName()); 2467 } 2468 2469 if (Lookup.empty() && II && AllowBuiltinCreation) { 2470 // FIXME. Consolidate this with similar code in LookupName. 2471 if (unsigned BuiltinID = II->getBuiltinID()) { 2472 if (!(getLangOpts().CPlusPlus && 2473 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2474 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2475 S, Lookup.isForRedeclaration(), 2476 Lookup.getNameLoc()); 2477 if (D) Lookup.addDecl(D); 2478 } 2479 } 2480 } 2481 // Sentinel value saying that we didn't do anything special. 2482 return ExprResult((Expr *)nullptr); 2483 } 2484 2485 /// Cast a base object to a member's actual type. 2486 /// 2487 /// Logically this happens in three phases: 2488 /// 2489 /// * First we cast from the base type to the naming class. 2490 /// The naming class is the class into which we were looking 2491 /// when we found the member; it's the qualifier type if a 2492 /// qualifier was provided, and otherwise it's the base type. 2493 /// 2494 /// * Next we cast from the naming class to the declaring class. 2495 /// If the member we found was brought into a class's scope by 2496 /// a using declaration, this is that class; otherwise it's 2497 /// the class declaring the member. 2498 /// 2499 /// * Finally we cast from the declaring class to the "true" 2500 /// declaring class of the member. This conversion does not 2501 /// obey access control. 2502 ExprResult 2503 Sema::PerformObjectMemberConversion(Expr *From, 2504 NestedNameSpecifier *Qualifier, 2505 NamedDecl *FoundDecl, 2506 NamedDecl *Member) { 2507 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2508 if (!RD) 2509 return From; 2510 2511 QualType DestRecordType; 2512 QualType DestType; 2513 QualType FromRecordType; 2514 QualType FromType = From->getType(); 2515 bool PointerConversions = false; 2516 if (isa<FieldDecl>(Member)) { 2517 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2518 2519 if (FromType->getAs<PointerType>()) { 2520 DestType = Context.getPointerType(DestRecordType); 2521 FromRecordType = FromType->getPointeeType(); 2522 PointerConversions = true; 2523 } else { 2524 DestType = DestRecordType; 2525 FromRecordType = FromType; 2526 } 2527 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2528 if (Method->isStatic()) 2529 return From; 2530 2531 DestType = Method->getThisType(Context); 2532 DestRecordType = DestType->getPointeeType(); 2533 2534 if (FromType->getAs<PointerType>()) { 2535 FromRecordType = FromType->getPointeeType(); 2536 PointerConversions = true; 2537 } else { 2538 FromRecordType = FromType; 2539 DestType = DestRecordType; 2540 } 2541 } else { 2542 // No conversion necessary. 2543 return From; 2544 } 2545 2546 if (DestType->isDependentType() || FromType->isDependentType()) 2547 return From; 2548 2549 // If the unqualified types are the same, no conversion is necessary. 2550 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2551 return From; 2552 2553 SourceRange FromRange = From->getSourceRange(); 2554 SourceLocation FromLoc = FromRange.getBegin(); 2555 2556 ExprValueKind VK = From->getValueKind(); 2557 2558 // C++ [class.member.lookup]p8: 2559 // [...] Ambiguities can often be resolved by qualifying a name with its 2560 // class name. 2561 // 2562 // If the member was a qualified name and the qualified referred to a 2563 // specific base subobject type, we'll cast to that intermediate type 2564 // first and then to the object in which the member is declared. That allows 2565 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2566 // 2567 // class Base { public: int x; }; 2568 // class Derived1 : public Base { }; 2569 // class Derived2 : public Base { }; 2570 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2571 // 2572 // void VeryDerived::f() { 2573 // x = 17; // error: ambiguous base subobjects 2574 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2575 // } 2576 if (Qualifier && Qualifier->getAsType()) { 2577 QualType QType = QualType(Qualifier->getAsType(), 0); 2578 assert(QType->isRecordType() && "lookup done with non-record type"); 2579 2580 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2581 2582 // In C++98, the qualifier type doesn't actually have to be a base 2583 // type of the object type, in which case we just ignore it. 2584 // Otherwise build the appropriate casts. 2585 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2586 CXXCastPath BasePath; 2587 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2588 FromLoc, FromRange, &BasePath)) 2589 return ExprError(); 2590 2591 if (PointerConversions) 2592 QType = Context.getPointerType(QType); 2593 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2594 VK, &BasePath).get(); 2595 2596 FromType = QType; 2597 FromRecordType = QRecordType; 2598 2599 // If the qualifier type was the same as the destination type, 2600 // we're done. 2601 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2602 return From; 2603 } 2604 } 2605 2606 bool IgnoreAccess = false; 2607 2608 // If we actually found the member through a using declaration, cast 2609 // down to the using declaration's type. 2610 // 2611 // Pointer equality is fine here because only one declaration of a 2612 // class ever has member declarations. 2613 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2614 assert(isa<UsingShadowDecl>(FoundDecl)); 2615 QualType URecordType = Context.getTypeDeclType( 2616 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2617 2618 // We only need to do this if the naming-class to declaring-class 2619 // conversion is non-trivial. 2620 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2621 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2622 CXXCastPath BasePath; 2623 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2624 FromLoc, FromRange, &BasePath)) 2625 return ExprError(); 2626 2627 QualType UType = URecordType; 2628 if (PointerConversions) 2629 UType = Context.getPointerType(UType); 2630 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2631 VK, &BasePath).get(); 2632 FromType = UType; 2633 FromRecordType = URecordType; 2634 } 2635 2636 // We don't do access control for the conversion from the 2637 // declaring class to the true declaring class. 2638 IgnoreAccess = true; 2639 } 2640 2641 CXXCastPath BasePath; 2642 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2643 FromLoc, FromRange, &BasePath, 2644 IgnoreAccess)) 2645 return ExprError(); 2646 2647 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2648 VK, &BasePath); 2649 } 2650 2651 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2652 const LookupResult &R, 2653 bool HasTrailingLParen) { 2654 // Only when used directly as the postfix-expression of a call. 2655 if (!HasTrailingLParen) 2656 return false; 2657 2658 // Never if a scope specifier was provided. 2659 if (SS.isSet()) 2660 return false; 2661 2662 // Only in C++ or ObjC++. 2663 if (!getLangOpts().CPlusPlus) 2664 return false; 2665 2666 // Turn off ADL when we find certain kinds of declarations during 2667 // normal lookup: 2668 for (NamedDecl *D : R) { 2669 // C++0x [basic.lookup.argdep]p3: 2670 // -- a declaration of a class member 2671 // Since using decls preserve this property, we check this on the 2672 // original decl. 2673 if (D->isCXXClassMember()) 2674 return false; 2675 2676 // C++0x [basic.lookup.argdep]p3: 2677 // -- a block-scope function declaration that is not a 2678 // using-declaration 2679 // NOTE: we also trigger this for function templates (in fact, we 2680 // don't check the decl type at all, since all other decl types 2681 // turn off ADL anyway). 2682 if (isa<UsingShadowDecl>(D)) 2683 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2684 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2685 return false; 2686 2687 // C++0x [basic.lookup.argdep]p3: 2688 // -- a declaration that is neither a function or a function 2689 // template 2690 // And also for builtin functions. 2691 if (isa<FunctionDecl>(D)) { 2692 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2693 2694 // But also builtin functions. 2695 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2696 return false; 2697 } else if (!isa<FunctionTemplateDecl>(D)) 2698 return false; 2699 } 2700 2701 return true; 2702 } 2703 2704 2705 /// Diagnoses obvious problems with the use of the given declaration 2706 /// as an expression. This is only actually called for lookups that 2707 /// were not overloaded, and it doesn't promise that the declaration 2708 /// will in fact be used. 2709 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2710 if (D->isInvalidDecl()) 2711 return true; 2712 2713 if (isa<TypedefNameDecl>(D)) { 2714 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2715 return true; 2716 } 2717 2718 if (isa<ObjCInterfaceDecl>(D)) { 2719 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2720 return true; 2721 } 2722 2723 if (isa<NamespaceDecl>(D)) { 2724 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2725 return true; 2726 } 2727 2728 return false; 2729 } 2730 2731 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2732 LookupResult &R, bool NeedsADL, 2733 bool AcceptInvalidDecl) { 2734 // If this is a single, fully-resolved result and we don't need ADL, 2735 // just build an ordinary singleton decl ref. 2736 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2737 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2738 R.getRepresentativeDecl(), nullptr, 2739 AcceptInvalidDecl); 2740 2741 // We only need to check the declaration if there's exactly one 2742 // result, because in the overloaded case the results can only be 2743 // functions and function templates. 2744 if (R.isSingleResult() && 2745 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2746 return ExprError(); 2747 2748 // Otherwise, just build an unresolved lookup expression. Suppress 2749 // any lookup-related diagnostics; we'll hash these out later, when 2750 // we've picked a target. 2751 R.suppressDiagnostics(); 2752 2753 UnresolvedLookupExpr *ULE 2754 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2755 SS.getWithLocInContext(Context), 2756 R.getLookupNameInfo(), 2757 NeedsADL, R.isOverloadedResult(), 2758 R.begin(), R.end()); 2759 2760 return ULE; 2761 } 2762 2763 static void 2764 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 2765 ValueDecl *var, DeclContext *DC); 2766 2767 /// Complete semantic analysis for a reference to the given declaration. 2768 ExprResult Sema::BuildDeclarationNameExpr( 2769 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2770 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2771 bool AcceptInvalidDecl) { 2772 assert(D && "Cannot refer to a NULL declaration"); 2773 assert(!isa<FunctionTemplateDecl>(D) && 2774 "Cannot refer unambiguously to a function template"); 2775 2776 SourceLocation Loc = NameInfo.getLoc(); 2777 if (CheckDeclInExpr(*this, Loc, D)) 2778 return ExprError(); 2779 2780 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2781 // Specifically diagnose references to class templates that are missing 2782 // a template argument list. 2783 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 2784 return ExprError(); 2785 } 2786 2787 // Make sure that we're referring to a value. 2788 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2789 if (!VD) { 2790 Diag(Loc, diag::err_ref_non_value) 2791 << D << SS.getRange(); 2792 Diag(D->getLocation(), diag::note_declared_at); 2793 return ExprError(); 2794 } 2795 2796 // Check whether this declaration can be used. Note that we suppress 2797 // this check when we're going to perform argument-dependent lookup 2798 // on this function name, because this might not be the function 2799 // that overload resolution actually selects. 2800 if (DiagnoseUseOfDecl(VD, Loc)) 2801 return ExprError(); 2802 2803 // Only create DeclRefExpr's for valid Decl's. 2804 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2805 return ExprError(); 2806 2807 // Handle members of anonymous structs and unions. If we got here, 2808 // and the reference is to a class member indirect field, then this 2809 // must be the subject of a pointer-to-member expression. 2810 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2811 if (!indirectField->isCXXClassMember()) 2812 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2813 indirectField); 2814 2815 { 2816 QualType type = VD->getType(); 2817 if (type.isNull()) 2818 return ExprError(); 2819 if (auto *FPT = type->getAs<FunctionProtoType>()) { 2820 // C++ [except.spec]p17: 2821 // An exception-specification is considered to be needed when: 2822 // - in an expression, the function is the unique lookup result or 2823 // the selected member of a set of overloaded functions. 2824 ResolveExceptionSpec(Loc, FPT); 2825 type = VD->getType(); 2826 } 2827 ExprValueKind valueKind = VK_RValue; 2828 2829 switch (D->getKind()) { 2830 // Ignore all the non-ValueDecl kinds. 2831 #define ABSTRACT_DECL(kind) 2832 #define VALUE(type, base) 2833 #define DECL(type, base) \ 2834 case Decl::type: 2835 #include "clang/AST/DeclNodes.inc" 2836 llvm_unreachable("invalid value decl kind"); 2837 2838 // These shouldn't make it here. 2839 case Decl::ObjCAtDefsField: 2840 case Decl::ObjCIvar: 2841 llvm_unreachable("forming non-member reference to ivar?"); 2842 2843 // Enum constants are always r-values and never references. 2844 // Unresolved using declarations are dependent. 2845 case Decl::EnumConstant: 2846 case Decl::UnresolvedUsingValue: 2847 case Decl::OMPDeclareReduction: 2848 valueKind = VK_RValue; 2849 break; 2850 2851 // Fields and indirect fields that got here must be for 2852 // pointer-to-member expressions; we just call them l-values for 2853 // internal consistency, because this subexpression doesn't really 2854 // exist in the high-level semantics. 2855 case Decl::Field: 2856 case Decl::IndirectField: 2857 assert(getLangOpts().CPlusPlus && 2858 "building reference to field in C?"); 2859 2860 // These can't have reference type in well-formed programs, but 2861 // for internal consistency we do this anyway. 2862 type = type.getNonReferenceType(); 2863 valueKind = VK_LValue; 2864 break; 2865 2866 // Non-type template parameters are either l-values or r-values 2867 // depending on the type. 2868 case Decl::NonTypeTemplateParm: { 2869 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2870 type = reftype->getPointeeType(); 2871 valueKind = VK_LValue; // even if the parameter is an r-value reference 2872 break; 2873 } 2874 2875 // For non-references, we need to strip qualifiers just in case 2876 // the template parameter was declared as 'const int' or whatever. 2877 valueKind = VK_RValue; 2878 type = type.getUnqualifiedType(); 2879 break; 2880 } 2881 2882 case Decl::Var: 2883 case Decl::VarTemplateSpecialization: 2884 case Decl::VarTemplatePartialSpecialization: 2885 case Decl::Decomposition: 2886 case Decl::OMPCapturedExpr: 2887 // In C, "extern void blah;" is valid and is an r-value. 2888 if (!getLangOpts().CPlusPlus && 2889 !type.hasQualifiers() && 2890 type->isVoidType()) { 2891 valueKind = VK_RValue; 2892 break; 2893 } 2894 LLVM_FALLTHROUGH; 2895 2896 case Decl::ImplicitParam: 2897 case Decl::ParmVar: { 2898 // These are always l-values. 2899 valueKind = VK_LValue; 2900 type = type.getNonReferenceType(); 2901 2902 // FIXME: Does the addition of const really only apply in 2903 // potentially-evaluated contexts? Since the variable isn't actually 2904 // captured in an unevaluated context, it seems that the answer is no. 2905 if (!isUnevaluatedContext()) { 2906 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2907 if (!CapturedType.isNull()) 2908 type = CapturedType; 2909 } 2910 2911 break; 2912 } 2913 2914 case Decl::Binding: { 2915 // These are always lvalues. 2916 valueKind = VK_LValue; 2917 type = type.getNonReferenceType(); 2918 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 2919 // decides how that's supposed to work. 2920 auto *BD = cast<BindingDecl>(VD); 2921 if (BD->getDeclContext()->isFunctionOrMethod() && 2922 BD->getDeclContext() != CurContext) 2923 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 2924 break; 2925 } 2926 2927 case Decl::Function: { 2928 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2929 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2930 type = Context.BuiltinFnTy; 2931 valueKind = VK_RValue; 2932 break; 2933 } 2934 } 2935 2936 const FunctionType *fty = type->castAs<FunctionType>(); 2937 2938 // If we're referring to a function with an __unknown_anytype 2939 // result type, make the entire expression __unknown_anytype. 2940 if (fty->getReturnType() == Context.UnknownAnyTy) { 2941 type = Context.UnknownAnyTy; 2942 valueKind = VK_RValue; 2943 break; 2944 } 2945 2946 // Functions are l-values in C++. 2947 if (getLangOpts().CPlusPlus) { 2948 valueKind = VK_LValue; 2949 break; 2950 } 2951 2952 // C99 DR 316 says that, if a function type comes from a 2953 // function definition (without a prototype), that type is only 2954 // used for checking compatibility. Therefore, when referencing 2955 // the function, we pretend that we don't have the full function 2956 // type. 2957 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2958 isa<FunctionProtoType>(fty)) 2959 type = Context.getFunctionNoProtoType(fty->getReturnType(), 2960 fty->getExtInfo()); 2961 2962 // Functions are r-values in C. 2963 valueKind = VK_RValue; 2964 break; 2965 } 2966 2967 case Decl::CXXDeductionGuide: 2968 llvm_unreachable("building reference to deduction guide"); 2969 2970 case Decl::MSProperty: 2971 valueKind = VK_LValue; 2972 break; 2973 2974 case Decl::CXXMethod: 2975 // If we're referring to a method with an __unknown_anytype 2976 // result type, make the entire expression __unknown_anytype. 2977 // This should only be possible with a type written directly. 2978 if (const FunctionProtoType *proto 2979 = dyn_cast<FunctionProtoType>(VD->getType())) 2980 if (proto->getReturnType() == Context.UnknownAnyTy) { 2981 type = Context.UnknownAnyTy; 2982 valueKind = VK_RValue; 2983 break; 2984 } 2985 2986 // C++ methods are l-values if static, r-values if non-static. 2987 if (cast<CXXMethodDecl>(VD)->isStatic()) { 2988 valueKind = VK_LValue; 2989 break; 2990 } 2991 LLVM_FALLTHROUGH; 2992 2993 case Decl::CXXConversion: 2994 case Decl::CXXDestructor: 2995 case Decl::CXXConstructor: 2996 valueKind = VK_RValue; 2997 break; 2998 } 2999 3000 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3001 TemplateArgs); 3002 } 3003 } 3004 3005 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3006 SmallString<32> &Target) { 3007 Target.resize(CharByteWidth * (Source.size() + 1)); 3008 char *ResultPtr = &Target[0]; 3009 const llvm::UTF8 *ErrorPtr; 3010 bool success = 3011 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3012 (void)success; 3013 assert(success); 3014 Target.resize(ResultPtr - &Target[0]); 3015 } 3016 3017 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3018 PredefinedExpr::IdentType IT) { 3019 // Pick the current block, lambda, captured statement or function. 3020 Decl *currentDecl = nullptr; 3021 if (const BlockScopeInfo *BSI = getCurBlock()) 3022 currentDecl = BSI->TheDecl; 3023 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3024 currentDecl = LSI->CallOperator; 3025 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3026 currentDecl = CSI->TheCapturedDecl; 3027 else 3028 currentDecl = getCurFunctionOrMethodDecl(); 3029 3030 if (!currentDecl) { 3031 Diag(Loc, diag::ext_predef_outside_function); 3032 currentDecl = Context.getTranslationUnitDecl(); 3033 } 3034 3035 QualType ResTy; 3036 StringLiteral *SL = nullptr; 3037 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3038 ResTy = Context.DependentTy; 3039 else { 3040 // Pre-defined identifiers are of type char[x], where x is the length of 3041 // the string. 3042 auto Str = PredefinedExpr::ComputeName(IT, currentDecl); 3043 unsigned Length = Str.length(); 3044 3045 llvm::APInt LengthI(32, Length + 1); 3046 if (IT == PredefinedExpr::LFunction) { 3047 ResTy = 3048 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3049 SmallString<32> RawChars; 3050 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3051 Str, RawChars); 3052 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3053 /*IndexTypeQuals*/ 0); 3054 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3055 /*Pascal*/ false, ResTy, Loc); 3056 } else { 3057 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3058 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3059 /*IndexTypeQuals*/ 0); 3060 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3061 /*Pascal*/ false, ResTy, Loc); 3062 } 3063 } 3064 3065 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL); 3066 } 3067 3068 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3069 PredefinedExpr::IdentType IT; 3070 3071 switch (Kind) { 3072 default: llvm_unreachable("Unknown simple primary expr!"); 3073 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3074 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 3075 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 3076 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS] 3077 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 3078 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 3079 } 3080 3081 return BuildPredefinedExpr(Loc, IT); 3082 } 3083 3084 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3085 SmallString<16> CharBuffer; 3086 bool Invalid = false; 3087 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3088 if (Invalid) 3089 return ExprError(); 3090 3091 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3092 PP, Tok.getKind()); 3093 if (Literal.hadError()) 3094 return ExprError(); 3095 3096 QualType Ty; 3097 if (Literal.isWide()) 3098 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3099 else if (Literal.isUTF8() && getLangOpts().Char8) 3100 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3101 else if (Literal.isUTF16()) 3102 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3103 else if (Literal.isUTF32()) 3104 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3105 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3106 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3107 else 3108 Ty = Context.CharTy; // 'x' -> char in C++ 3109 3110 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3111 if (Literal.isWide()) 3112 Kind = CharacterLiteral::Wide; 3113 else if (Literal.isUTF16()) 3114 Kind = CharacterLiteral::UTF16; 3115 else if (Literal.isUTF32()) 3116 Kind = CharacterLiteral::UTF32; 3117 else if (Literal.isUTF8()) 3118 Kind = CharacterLiteral::UTF8; 3119 3120 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3121 Tok.getLocation()); 3122 3123 if (Literal.getUDSuffix().empty()) 3124 return Lit; 3125 3126 // We're building a user-defined literal. 3127 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3128 SourceLocation UDSuffixLoc = 3129 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3130 3131 // Make sure we're allowed user-defined literals here. 3132 if (!UDLScope) 3133 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3134 3135 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3136 // operator "" X (ch) 3137 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3138 Lit, Tok.getLocation()); 3139 } 3140 3141 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3142 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3143 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3144 Context.IntTy, Loc); 3145 } 3146 3147 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3148 QualType Ty, SourceLocation Loc) { 3149 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3150 3151 using llvm::APFloat; 3152 APFloat Val(Format); 3153 3154 APFloat::opStatus result = Literal.GetFloatValue(Val); 3155 3156 // Overflow is always an error, but underflow is only an error if 3157 // we underflowed to zero (APFloat reports denormals as underflow). 3158 if ((result & APFloat::opOverflow) || 3159 ((result & APFloat::opUnderflow) && Val.isZero())) { 3160 unsigned diagnostic; 3161 SmallString<20> buffer; 3162 if (result & APFloat::opOverflow) { 3163 diagnostic = diag::warn_float_overflow; 3164 APFloat::getLargest(Format).toString(buffer); 3165 } else { 3166 diagnostic = diag::warn_float_underflow; 3167 APFloat::getSmallest(Format).toString(buffer); 3168 } 3169 3170 S.Diag(Loc, diagnostic) 3171 << Ty 3172 << StringRef(buffer.data(), buffer.size()); 3173 } 3174 3175 bool isExact = (result == APFloat::opOK); 3176 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3177 } 3178 3179 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3180 assert(E && "Invalid expression"); 3181 3182 if (E->isValueDependent()) 3183 return false; 3184 3185 QualType QT = E->getType(); 3186 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3187 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3188 return true; 3189 } 3190 3191 llvm::APSInt ValueAPS; 3192 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3193 3194 if (R.isInvalid()) 3195 return true; 3196 3197 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3198 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3199 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3200 << ValueAPS.toString(10) << ValueIsPositive; 3201 return true; 3202 } 3203 3204 return false; 3205 } 3206 3207 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3208 // Fast path for a single digit (which is quite common). A single digit 3209 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3210 if (Tok.getLength() == 1) { 3211 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3212 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3213 } 3214 3215 SmallString<128> SpellingBuffer; 3216 // NumericLiteralParser wants to overread by one character. Add padding to 3217 // the buffer in case the token is copied to the buffer. If getSpelling() 3218 // returns a StringRef to the memory buffer, it should have a null char at 3219 // the EOF, so it is also safe. 3220 SpellingBuffer.resize(Tok.getLength() + 1); 3221 3222 // Get the spelling of the token, which eliminates trigraphs, etc. 3223 bool Invalid = false; 3224 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3225 if (Invalid) 3226 return ExprError(); 3227 3228 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3229 if (Literal.hadError) 3230 return ExprError(); 3231 3232 if (Literal.hasUDSuffix()) { 3233 // We're building a user-defined literal. 3234 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3235 SourceLocation UDSuffixLoc = 3236 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3237 3238 // Make sure we're allowed user-defined literals here. 3239 if (!UDLScope) 3240 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3241 3242 QualType CookedTy; 3243 if (Literal.isFloatingLiteral()) { 3244 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3245 // long double, the literal is treated as a call of the form 3246 // operator "" X (f L) 3247 CookedTy = Context.LongDoubleTy; 3248 } else { 3249 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3250 // unsigned long long, the literal is treated as a call of the form 3251 // operator "" X (n ULL) 3252 CookedTy = Context.UnsignedLongLongTy; 3253 } 3254 3255 DeclarationName OpName = 3256 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3257 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3258 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3259 3260 SourceLocation TokLoc = Tok.getLocation(); 3261 3262 // Perform literal operator lookup to determine if we're building a raw 3263 // literal or a cooked one. 3264 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3265 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3266 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3267 /*AllowStringTemplate*/ false, 3268 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3269 case LOLR_ErrorNoDiagnostic: 3270 // Lookup failure for imaginary constants isn't fatal, there's still the 3271 // GNU extension producing _Complex types. 3272 break; 3273 case LOLR_Error: 3274 return ExprError(); 3275 case LOLR_Cooked: { 3276 Expr *Lit; 3277 if (Literal.isFloatingLiteral()) { 3278 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3279 } else { 3280 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3281 if (Literal.GetIntegerValue(ResultVal)) 3282 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3283 << /* Unsigned */ 1; 3284 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3285 Tok.getLocation()); 3286 } 3287 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3288 } 3289 3290 case LOLR_Raw: { 3291 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3292 // literal is treated as a call of the form 3293 // operator "" X ("n") 3294 unsigned Length = Literal.getUDSuffixOffset(); 3295 QualType StrTy = Context.getConstantArrayType( 3296 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3297 llvm::APInt(32, Length + 1), ArrayType::Normal, 0); 3298 Expr *Lit = StringLiteral::Create( 3299 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3300 /*Pascal*/false, StrTy, &TokLoc, 1); 3301 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3302 } 3303 3304 case LOLR_Template: { 3305 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3306 // template), L is treated as a call fo the form 3307 // operator "" X <'c1', 'c2', ... 'ck'>() 3308 // where n is the source character sequence c1 c2 ... ck. 3309 TemplateArgumentListInfo ExplicitArgs; 3310 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3311 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3312 llvm::APSInt Value(CharBits, CharIsUnsigned); 3313 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3314 Value = TokSpelling[I]; 3315 TemplateArgument Arg(Context, Value, Context.CharTy); 3316 TemplateArgumentLocInfo ArgInfo; 3317 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3318 } 3319 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3320 &ExplicitArgs); 3321 } 3322 case LOLR_StringTemplate: 3323 llvm_unreachable("unexpected literal operator lookup result"); 3324 } 3325 } 3326 3327 Expr *Res; 3328 3329 if (Literal.isFixedPointLiteral()) { 3330 QualType Ty; 3331 3332 if (Literal.isAccum) { 3333 if (Literal.isHalf) { 3334 Ty = Context.ShortAccumTy; 3335 } else if (Literal.isLong) { 3336 Ty = Context.LongAccumTy; 3337 } else { 3338 Ty = Context.AccumTy; 3339 } 3340 } else if (Literal.isFract) { 3341 if (Literal.isHalf) { 3342 Ty = Context.ShortFractTy; 3343 } else if (Literal.isLong) { 3344 Ty = Context.LongFractTy; 3345 } else { 3346 Ty = Context.FractTy; 3347 } 3348 } 3349 3350 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3351 3352 bool isSigned = !Literal.isUnsigned; 3353 unsigned scale = Context.getFixedPointScale(Ty); 3354 unsigned ibits = Context.getFixedPointIBits(Ty); 3355 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3356 3357 llvm::APInt Val(bit_width, 0, isSigned); 3358 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3359 3360 // Do not use bit_width since some types may have padding like _Fract or 3361 // unsigned _Accums if PaddingOnUnsignedFixedPoint is set. 3362 auto MaxVal = llvm::APInt::getMaxValue(ibits + scale).zextOrSelf(bit_width); 3363 if (Literal.isFract && Val == MaxVal + 1) 3364 // Clause 6.4.4 - The value of a constant shall be in the range of 3365 // representable values for its type, with exception for constants of a 3366 // fract type with a value of exactly 1; such a constant shall denote 3367 // the maximal value for the type. 3368 --Val; 3369 else if (Val.ugt(MaxVal) || Overflowed) 3370 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3371 3372 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3373 Tok.getLocation(), scale); 3374 } else if (Literal.isFloatingLiteral()) { 3375 QualType Ty; 3376 if (Literal.isHalf){ 3377 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3378 Ty = Context.HalfTy; 3379 else { 3380 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3381 return ExprError(); 3382 } 3383 } else if (Literal.isFloat) 3384 Ty = Context.FloatTy; 3385 else if (Literal.isLong) 3386 Ty = Context.LongDoubleTy; 3387 else if (Literal.isFloat16) 3388 Ty = Context.Float16Ty; 3389 else if (Literal.isFloat128) 3390 Ty = Context.Float128Ty; 3391 else 3392 Ty = Context.DoubleTy; 3393 3394 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3395 3396 if (Ty == Context.DoubleTy) { 3397 if (getLangOpts().SinglePrecisionConstants) { 3398 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3399 if (BTy->getKind() != BuiltinType::Float) { 3400 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3401 } 3402 } else if (getLangOpts().OpenCL && 3403 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3404 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3405 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3406 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3407 } 3408 } 3409 } else if (!Literal.isIntegerLiteral()) { 3410 return ExprError(); 3411 } else { 3412 QualType Ty; 3413 3414 // 'long long' is a C99 or C++11 feature. 3415 if (!getLangOpts().C99 && Literal.isLongLong) { 3416 if (getLangOpts().CPlusPlus) 3417 Diag(Tok.getLocation(), 3418 getLangOpts().CPlusPlus11 ? 3419 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3420 else 3421 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3422 } 3423 3424 // Get the value in the widest-possible width. 3425 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3426 llvm::APInt ResultVal(MaxWidth, 0); 3427 3428 if (Literal.GetIntegerValue(ResultVal)) { 3429 // If this value didn't fit into uintmax_t, error and force to ull. 3430 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3431 << /* Unsigned */ 1; 3432 Ty = Context.UnsignedLongLongTy; 3433 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3434 "long long is not intmax_t?"); 3435 } else { 3436 // If this value fits into a ULL, try to figure out what else it fits into 3437 // according to the rules of C99 6.4.4.1p5. 3438 3439 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3440 // be an unsigned int. 3441 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3442 3443 // Check from smallest to largest, picking the smallest type we can. 3444 unsigned Width = 0; 3445 3446 // Microsoft specific integer suffixes are explicitly sized. 3447 if (Literal.MicrosoftInteger) { 3448 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3449 Width = 8; 3450 Ty = Context.CharTy; 3451 } else { 3452 Width = Literal.MicrosoftInteger; 3453 Ty = Context.getIntTypeForBitwidth(Width, 3454 /*Signed=*/!Literal.isUnsigned); 3455 } 3456 } 3457 3458 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3459 // Are int/unsigned possibilities? 3460 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3461 3462 // Does it fit in a unsigned int? 3463 if (ResultVal.isIntN(IntSize)) { 3464 // Does it fit in a signed int? 3465 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3466 Ty = Context.IntTy; 3467 else if (AllowUnsigned) 3468 Ty = Context.UnsignedIntTy; 3469 Width = IntSize; 3470 } 3471 } 3472 3473 // Are long/unsigned long possibilities? 3474 if (Ty.isNull() && !Literal.isLongLong) { 3475 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3476 3477 // Does it fit in a unsigned long? 3478 if (ResultVal.isIntN(LongSize)) { 3479 // Does it fit in a signed long? 3480 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3481 Ty = Context.LongTy; 3482 else if (AllowUnsigned) 3483 Ty = Context.UnsignedLongTy; 3484 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3485 // is compatible. 3486 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3487 const unsigned LongLongSize = 3488 Context.getTargetInfo().getLongLongWidth(); 3489 Diag(Tok.getLocation(), 3490 getLangOpts().CPlusPlus 3491 ? Literal.isLong 3492 ? diag::warn_old_implicitly_unsigned_long_cxx 3493 : /*C++98 UB*/ diag:: 3494 ext_old_implicitly_unsigned_long_cxx 3495 : diag::warn_old_implicitly_unsigned_long) 3496 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3497 : /*will be ill-formed*/ 1); 3498 Ty = Context.UnsignedLongTy; 3499 } 3500 Width = LongSize; 3501 } 3502 } 3503 3504 // Check long long if needed. 3505 if (Ty.isNull()) { 3506 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3507 3508 // Does it fit in a unsigned long long? 3509 if (ResultVal.isIntN(LongLongSize)) { 3510 // Does it fit in a signed long long? 3511 // To be compatible with MSVC, hex integer literals ending with the 3512 // LL or i64 suffix are always signed in Microsoft mode. 3513 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3514 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3515 Ty = Context.LongLongTy; 3516 else if (AllowUnsigned) 3517 Ty = Context.UnsignedLongLongTy; 3518 Width = LongLongSize; 3519 } 3520 } 3521 3522 // If we still couldn't decide a type, we probably have something that 3523 // does not fit in a signed long long, but has no U suffix. 3524 if (Ty.isNull()) { 3525 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3526 Ty = Context.UnsignedLongLongTy; 3527 Width = Context.getTargetInfo().getLongLongWidth(); 3528 } 3529 3530 if (ResultVal.getBitWidth() != Width) 3531 ResultVal = ResultVal.trunc(Width); 3532 } 3533 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3534 } 3535 3536 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3537 if (Literal.isImaginary) { 3538 Res = new (Context) ImaginaryLiteral(Res, 3539 Context.getComplexType(Res->getType())); 3540 3541 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3542 } 3543 return Res; 3544 } 3545 3546 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3547 assert(E && "ActOnParenExpr() missing expr"); 3548 return new (Context) ParenExpr(L, R, E); 3549 } 3550 3551 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3552 SourceLocation Loc, 3553 SourceRange ArgRange) { 3554 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3555 // scalar or vector data type argument..." 3556 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3557 // type (C99 6.2.5p18) or void. 3558 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3559 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3560 << T << ArgRange; 3561 return true; 3562 } 3563 3564 assert((T->isVoidType() || !T->isIncompleteType()) && 3565 "Scalar types should always be complete"); 3566 return false; 3567 } 3568 3569 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3570 SourceLocation Loc, 3571 SourceRange ArgRange, 3572 UnaryExprOrTypeTrait TraitKind) { 3573 // Invalid types must be hard errors for SFINAE in C++. 3574 if (S.LangOpts.CPlusPlus) 3575 return true; 3576 3577 // C99 6.5.3.4p1: 3578 if (T->isFunctionType() && 3579 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3580 // sizeof(function)/alignof(function) is allowed as an extension. 3581 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3582 << TraitKind << ArgRange; 3583 return false; 3584 } 3585 3586 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3587 // this is an error (OpenCL v1.1 s6.3.k) 3588 if (T->isVoidType()) { 3589 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3590 : diag::ext_sizeof_alignof_void_type; 3591 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3592 return false; 3593 } 3594 3595 return true; 3596 } 3597 3598 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3599 SourceLocation Loc, 3600 SourceRange ArgRange, 3601 UnaryExprOrTypeTrait TraitKind) { 3602 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3603 // runtime doesn't allow it. 3604 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3605 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3606 << T << (TraitKind == UETT_SizeOf) 3607 << ArgRange; 3608 return true; 3609 } 3610 3611 return false; 3612 } 3613 3614 /// Check whether E is a pointer from a decayed array type (the decayed 3615 /// pointer type is equal to T) and emit a warning if it is. 3616 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3617 Expr *E) { 3618 // Don't warn if the operation changed the type. 3619 if (T != E->getType()) 3620 return; 3621 3622 // Now look for array decays. 3623 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3624 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3625 return; 3626 3627 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3628 << ICE->getType() 3629 << ICE->getSubExpr()->getType(); 3630 } 3631 3632 /// Check the constraints on expression operands to unary type expression 3633 /// and type traits. 3634 /// 3635 /// Completes any types necessary and validates the constraints on the operand 3636 /// expression. The logic mostly mirrors the type-based overload, but may modify 3637 /// the expression as it completes the type for that expression through template 3638 /// instantiation, etc. 3639 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3640 UnaryExprOrTypeTrait ExprKind) { 3641 QualType ExprTy = E->getType(); 3642 assert(!ExprTy->isReferenceType()); 3643 3644 if (ExprKind == UETT_VecStep) 3645 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3646 E->getSourceRange()); 3647 3648 // Whitelist some types as extensions 3649 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3650 E->getSourceRange(), ExprKind)) 3651 return false; 3652 3653 // 'alignof' applied to an expression only requires the base element type of 3654 // the expression to be complete. 'sizeof' requires the expression's type to 3655 // be complete (and will attempt to complete it if it's an array of unknown 3656 // bound). 3657 if (ExprKind == UETT_AlignOf) { 3658 if (RequireCompleteType(E->getExprLoc(), 3659 Context.getBaseElementType(E->getType()), 3660 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3661 E->getSourceRange())) 3662 return true; 3663 } else { 3664 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3665 ExprKind, E->getSourceRange())) 3666 return true; 3667 } 3668 3669 // Completing the expression's type may have changed it. 3670 ExprTy = E->getType(); 3671 assert(!ExprTy->isReferenceType()); 3672 3673 if (ExprTy->isFunctionType()) { 3674 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3675 << ExprKind << E->getSourceRange(); 3676 return true; 3677 } 3678 3679 // The operand for sizeof and alignof is in an unevaluated expression context, 3680 // so side effects could result in unintended consequences. 3681 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) && 3682 !inTemplateInstantiation() && E->HasSideEffects(Context, false)) 3683 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3684 3685 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3686 E->getSourceRange(), ExprKind)) 3687 return true; 3688 3689 if (ExprKind == UETT_SizeOf) { 3690 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3691 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3692 QualType OType = PVD->getOriginalType(); 3693 QualType Type = PVD->getType(); 3694 if (Type->isPointerType() && OType->isArrayType()) { 3695 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3696 << Type << OType; 3697 Diag(PVD->getLocation(), diag::note_declared_at); 3698 } 3699 } 3700 } 3701 3702 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3703 // decays into a pointer and returns an unintended result. This is most 3704 // likely a typo for "sizeof(array) op x". 3705 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3706 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3707 BO->getLHS()); 3708 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3709 BO->getRHS()); 3710 } 3711 } 3712 3713 return false; 3714 } 3715 3716 /// Check the constraints on operands to unary expression and type 3717 /// traits. 3718 /// 3719 /// This will complete any types necessary, and validate the various constraints 3720 /// on those operands. 3721 /// 3722 /// The UsualUnaryConversions() function is *not* called by this routine. 3723 /// C99 6.3.2.1p[2-4] all state: 3724 /// Except when it is the operand of the sizeof operator ... 3725 /// 3726 /// C++ [expr.sizeof]p4 3727 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3728 /// standard conversions are not applied to the operand of sizeof. 3729 /// 3730 /// This policy is followed for all of the unary trait expressions. 3731 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3732 SourceLocation OpLoc, 3733 SourceRange ExprRange, 3734 UnaryExprOrTypeTrait ExprKind) { 3735 if (ExprType->isDependentType()) 3736 return false; 3737 3738 // C++ [expr.sizeof]p2: 3739 // When applied to a reference or a reference type, the result 3740 // is the size of the referenced type. 3741 // C++11 [expr.alignof]p3: 3742 // When alignof is applied to a reference type, the result 3743 // shall be the alignment of the referenced type. 3744 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3745 ExprType = Ref->getPointeeType(); 3746 3747 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3748 // When alignof or _Alignof is applied to an array type, the result 3749 // is the alignment of the element type. 3750 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign) 3751 ExprType = Context.getBaseElementType(ExprType); 3752 3753 if (ExprKind == UETT_VecStep) 3754 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3755 3756 // Whitelist some types as extensions 3757 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3758 ExprKind)) 3759 return false; 3760 3761 if (RequireCompleteType(OpLoc, ExprType, 3762 diag::err_sizeof_alignof_incomplete_type, 3763 ExprKind, ExprRange)) 3764 return true; 3765 3766 if (ExprType->isFunctionType()) { 3767 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3768 << ExprKind << ExprRange; 3769 return true; 3770 } 3771 3772 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3773 ExprKind)) 3774 return true; 3775 3776 return false; 3777 } 3778 3779 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3780 E = E->IgnoreParens(); 3781 3782 // Cannot know anything else if the expression is dependent. 3783 if (E->isTypeDependent()) 3784 return false; 3785 3786 if (E->getObjectKind() == OK_BitField) { 3787 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3788 << 1 << E->getSourceRange(); 3789 return true; 3790 } 3791 3792 ValueDecl *D = nullptr; 3793 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3794 D = DRE->getDecl(); 3795 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3796 D = ME->getMemberDecl(); 3797 } 3798 3799 // If it's a field, require the containing struct to have a 3800 // complete definition so that we can compute the layout. 3801 // 3802 // This can happen in C++11 onwards, either by naming the member 3803 // in a way that is not transformed into a member access expression 3804 // (in an unevaluated operand, for instance), or by naming the member 3805 // in a trailing-return-type. 3806 // 3807 // For the record, since __alignof__ on expressions is a GCC 3808 // extension, GCC seems to permit this but always gives the 3809 // nonsensical answer 0. 3810 // 3811 // We don't really need the layout here --- we could instead just 3812 // directly check for all the appropriate alignment-lowing 3813 // attributes --- but that would require duplicating a lot of 3814 // logic that just isn't worth duplicating for such a marginal 3815 // use-case. 3816 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3817 // Fast path this check, since we at least know the record has a 3818 // definition if we can find a member of it. 3819 if (!FD->getParent()->isCompleteDefinition()) { 3820 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3821 << E->getSourceRange(); 3822 return true; 3823 } 3824 3825 // Otherwise, if it's a field, and the field doesn't have 3826 // reference type, then it must have a complete type (or be a 3827 // flexible array member, which we explicitly want to 3828 // white-list anyway), which makes the following checks trivial. 3829 if (!FD->getType()->isReferenceType()) 3830 return false; 3831 } 3832 3833 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3834 } 3835 3836 bool Sema::CheckVecStepExpr(Expr *E) { 3837 E = E->IgnoreParens(); 3838 3839 // Cannot know anything else if the expression is dependent. 3840 if (E->isTypeDependent()) 3841 return false; 3842 3843 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3844 } 3845 3846 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 3847 CapturingScopeInfo *CSI) { 3848 assert(T->isVariablyModifiedType()); 3849 assert(CSI != nullptr); 3850 3851 // We're going to walk down into the type and look for VLA expressions. 3852 do { 3853 const Type *Ty = T.getTypePtr(); 3854 switch (Ty->getTypeClass()) { 3855 #define TYPE(Class, Base) 3856 #define ABSTRACT_TYPE(Class, Base) 3857 #define NON_CANONICAL_TYPE(Class, Base) 3858 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 3859 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 3860 #include "clang/AST/TypeNodes.def" 3861 T = QualType(); 3862 break; 3863 // These types are never variably-modified. 3864 case Type::Builtin: 3865 case Type::Complex: 3866 case Type::Vector: 3867 case Type::ExtVector: 3868 case Type::Record: 3869 case Type::Enum: 3870 case Type::Elaborated: 3871 case Type::TemplateSpecialization: 3872 case Type::ObjCObject: 3873 case Type::ObjCInterface: 3874 case Type::ObjCObjectPointer: 3875 case Type::ObjCTypeParam: 3876 case Type::Pipe: 3877 llvm_unreachable("type class is never variably-modified!"); 3878 case Type::Adjusted: 3879 T = cast<AdjustedType>(Ty)->getOriginalType(); 3880 break; 3881 case Type::Decayed: 3882 T = cast<DecayedType>(Ty)->getPointeeType(); 3883 break; 3884 case Type::Pointer: 3885 T = cast<PointerType>(Ty)->getPointeeType(); 3886 break; 3887 case Type::BlockPointer: 3888 T = cast<BlockPointerType>(Ty)->getPointeeType(); 3889 break; 3890 case Type::LValueReference: 3891 case Type::RValueReference: 3892 T = cast<ReferenceType>(Ty)->getPointeeType(); 3893 break; 3894 case Type::MemberPointer: 3895 T = cast<MemberPointerType>(Ty)->getPointeeType(); 3896 break; 3897 case Type::ConstantArray: 3898 case Type::IncompleteArray: 3899 // Losing element qualification here is fine. 3900 T = cast<ArrayType>(Ty)->getElementType(); 3901 break; 3902 case Type::VariableArray: { 3903 // Losing element qualification here is fine. 3904 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 3905 3906 // Unknown size indication requires no size computation. 3907 // Otherwise, evaluate and record it. 3908 if (auto Size = VAT->getSizeExpr()) { 3909 if (!CSI->isVLATypeCaptured(VAT)) { 3910 RecordDecl *CapRecord = nullptr; 3911 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 3912 CapRecord = LSI->Lambda; 3913 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 3914 CapRecord = CRSI->TheRecordDecl; 3915 } 3916 if (CapRecord) { 3917 auto ExprLoc = Size->getExprLoc(); 3918 auto SizeType = Context.getSizeType(); 3919 // Build the non-static data member. 3920 auto Field = 3921 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc, 3922 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 3923 /*BW*/ nullptr, /*Mutable*/ false, 3924 /*InitStyle*/ ICIS_NoInit); 3925 Field->setImplicit(true); 3926 Field->setAccess(AS_private); 3927 Field->setCapturedVLAType(VAT); 3928 CapRecord->addDecl(Field); 3929 3930 CSI->addVLATypeCapture(ExprLoc, SizeType); 3931 } 3932 } 3933 } 3934 T = VAT->getElementType(); 3935 break; 3936 } 3937 case Type::FunctionProto: 3938 case Type::FunctionNoProto: 3939 T = cast<FunctionType>(Ty)->getReturnType(); 3940 break; 3941 case Type::Paren: 3942 case Type::TypeOf: 3943 case Type::UnaryTransform: 3944 case Type::Attributed: 3945 case Type::SubstTemplateTypeParm: 3946 case Type::PackExpansion: 3947 // Keep walking after single level desugaring. 3948 T = T.getSingleStepDesugaredType(Context); 3949 break; 3950 case Type::Typedef: 3951 T = cast<TypedefType>(Ty)->desugar(); 3952 break; 3953 case Type::Decltype: 3954 T = cast<DecltypeType>(Ty)->desugar(); 3955 break; 3956 case Type::Auto: 3957 case Type::DeducedTemplateSpecialization: 3958 T = cast<DeducedType>(Ty)->getDeducedType(); 3959 break; 3960 case Type::TypeOfExpr: 3961 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 3962 break; 3963 case Type::Atomic: 3964 T = cast<AtomicType>(Ty)->getValueType(); 3965 break; 3966 } 3967 } while (!T.isNull() && T->isVariablyModifiedType()); 3968 } 3969 3970 /// Build a sizeof or alignof expression given a type operand. 3971 ExprResult 3972 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3973 SourceLocation OpLoc, 3974 UnaryExprOrTypeTrait ExprKind, 3975 SourceRange R) { 3976 if (!TInfo) 3977 return ExprError(); 3978 3979 QualType T = TInfo->getType(); 3980 3981 if (!T->isDependentType() && 3982 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3983 return ExprError(); 3984 3985 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 3986 if (auto *TT = T->getAs<TypedefType>()) { 3987 for (auto I = FunctionScopes.rbegin(), 3988 E = std::prev(FunctionScopes.rend()); 3989 I != E; ++I) { 3990 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 3991 if (CSI == nullptr) 3992 break; 3993 DeclContext *DC = nullptr; 3994 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 3995 DC = LSI->CallOperator; 3996 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 3997 DC = CRSI->TheCapturedDecl; 3998 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 3999 DC = BSI->TheDecl; 4000 if (DC) { 4001 if (DC->containsDecl(TT->getDecl())) 4002 break; 4003 captureVariablyModifiedType(Context, T, CSI); 4004 } 4005 } 4006 } 4007 } 4008 4009 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4010 return new (Context) UnaryExprOrTypeTraitExpr( 4011 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4012 } 4013 4014 /// Build a sizeof or alignof expression given an expression 4015 /// operand. 4016 ExprResult 4017 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4018 UnaryExprOrTypeTrait ExprKind) { 4019 ExprResult PE = CheckPlaceholderExpr(E); 4020 if (PE.isInvalid()) 4021 return ExprError(); 4022 4023 E = PE.get(); 4024 4025 // Verify that the operand is valid. 4026 bool isInvalid = false; 4027 if (E->isTypeDependent()) { 4028 // Delay type-checking for type-dependent expressions. 4029 } else if (ExprKind == UETT_AlignOf) { 4030 isInvalid = CheckAlignOfExpr(*this, E); 4031 } else if (ExprKind == UETT_VecStep) { 4032 isInvalid = CheckVecStepExpr(E); 4033 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4034 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4035 isInvalid = true; 4036 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4037 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4038 isInvalid = true; 4039 } else { 4040 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4041 } 4042 4043 if (isInvalid) 4044 return ExprError(); 4045 4046 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4047 PE = TransformToPotentiallyEvaluated(E); 4048 if (PE.isInvalid()) return ExprError(); 4049 E = PE.get(); 4050 } 4051 4052 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4053 return new (Context) UnaryExprOrTypeTraitExpr( 4054 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4055 } 4056 4057 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4058 /// expr and the same for @c alignof and @c __alignof 4059 /// Note that the ArgRange is invalid if isType is false. 4060 ExprResult 4061 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4062 UnaryExprOrTypeTrait ExprKind, bool IsType, 4063 void *TyOrEx, SourceRange ArgRange) { 4064 // If error parsing type, ignore. 4065 if (!TyOrEx) return ExprError(); 4066 4067 if (IsType) { 4068 TypeSourceInfo *TInfo; 4069 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4070 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4071 } 4072 4073 Expr *ArgEx = (Expr *)TyOrEx; 4074 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4075 return Result; 4076 } 4077 4078 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4079 bool IsReal) { 4080 if (V.get()->isTypeDependent()) 4081 return S.Context.DependentTy; 4082 4083 // _Real and _Imag are only l-values for normal l-values. 4084 if (V.get()->getObjectKind() != OK_Ordinary) { 4085 V = S.DefaultLvalueConversion(V.get()); 4086 if (V.isInvalid()) 4087 return QualType(); 4088 } 4089 4090 // These operators return the element type of a complex type. 4091 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4092 return CT->getElementType(); 4093 4094 // Otherwise they pass through real integer and floating point types here. 4095 if (V.get()->getType()->isArithmeticType()) 4096 return V.get()->getType(); 4097 4098 // Test for placeholders. 4099 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4100 if (PR.isInvalid()) return QualType(); 4101 if (PR.get() != V.get()) { 4102 V = PR; 4103 return CheckRealImagOperand(S, V, Loc, IsReal); 4104 } 4105 4106 // Reject anything else. 4107 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4108 << (IsReal ? "__real" : "__imag"); 4109 return QualType(); 4110 } 4111 4112 4113 4114 ExprResult 4115 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4116 tok::TokenKind Kind, Expr *Input) { 4117 UnaryOperatorKind Opc; 4118 switch (Kind) { 4119 default: llvm_unreachable("Unknown unary op!"); 4120 case tok::plusplus: Opc = UO_PostInc; break; 4121 case tok::minusminus: Opc = UO_PostDec; break; 4122 } 4123 4124 // Since this might is a postfix expression, get rid of ParenListExprs. 4125 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4126 if (Result.isInvalid()) return ExprError(); 4127 Input = Result.get(); 4128 4129 return BuildUnaryOp(S, OpLoc, Opc, Input); 4130 } 4131 4132 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4133 /// 4134 /// \return true on error 4135 static bool checkArithmeticOnObjCPointer(Sema &S, 4136 SourceLocation opLoc, 4137 Expr *op) { 4138 assert(op->getType()->isObjCObjectPointerType()); 4139 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4140 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4141 return false; 4142 4143 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4144 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4145 << op->getSourceRange(); 4146 return true; 4147 } 4148 4149 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4150 auto *BaseNoParens = Base->IgnoreParens(); 4151 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4152 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4153 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4154 } 4155 4156 ExprResult 4157 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4158 Expr *idx, SourceLocation rbLoc) { 4159 if (base && !base->getType().isNull() && 4160 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4161 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4162 /*Length=*/nullptr, rbLoc); 4163 4164 // Since this might be a postfix expression, get rid of ParenListExprs. 4165 if (isa<ParenListExpr>(base)) { 4166 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4167 if (result.isInvalid()) return ExprError(); 4168 base = result.get(); 4169 } 4170 4171 // Handle any non-overload placeholder types in the base and index 4172 // expressions. We can't handle overloads here because the other 4173 // operand might be an overloadable type, in which case the overload 4174 // resolution for the operator overload should get the first crack 4175 // at the overload. 4176 bool IsMSPropertySubscript = false; 4177 if (base->getType()->isNonOverloadPlaceholderType()) { 4178 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4179 if (!IsMSPropertySubscript) { 4180 ExprResult result = CheckPlaceholderExpr(base); 4181 if (result.isInvalid()) 4182 return ExprError(); 4183 base = result.get(); 4184 } 4185 } 4186 if (idx->getType()->isNonOverloadPlaceholderType()) { 4187 ExprResult result = CheckPlaceholderExpr(idx); 4188 if (result.isInvalid()) return ExprError(); 4189 idx = result.get(); 4190 } 4191 4192 // Build an unanalyzed expression if either operand is type-dependent. 4193 if (getLangOpts().CPlusPlus && 4194 (base->isTypeDependent() || idx->isTypeDependent())) { 4195 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4196 VK_LValue, OK_Ordinary, rbLoc); 4197 } 4198 4199 // MSDN, property (C++) 4200 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4201 // This attribute can also be used in the declaration of an empty array in a 4202 // class or structure definition. For example: 4203 // __declspec(property(get=GetX, put=PutX)) int x[]; 4204 // The above statement indicates that x[] can be used with one or more array 4205 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4206 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4207 if (IsMSPropertySubscript) { 4208 // Build MS property subscript expression if base is MS property reference 4209 // or MS property subscript. 4210 return new (Context) MSPropertySubscriptExpr( 4211 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4212 } 4213 4214 // Use C++ overloaded-operator rules if either operand has record 4215 // type. The spec says to do this if either type is *overloadable*, 4216 // but enum types can't declare subscript operators or conversion 4217 // operators, so there's nothing interesting for overload resolution 4218 // to do if there aren't any record types involved. 4219 // 4220 // ObjC pointers have their own subscripting logic that is not tied 4221 // to overload resolution and so should not take this path. 4222 if (getLangOpts().CPlusPlus && 4223 (base->getType()->isRecordType() || 4224 (!base->getType()->isObjCObjectPointerType() && 4225 idx->getType()->isRecordType()))) { 4226 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4227 } 4228 4229 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4230 } 4231 4232 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4233 Expr *LowerBound, 4234 SourceLocation ColonLoc, Expr *Length, 4235 SourceLocation RBLoc) { 4236 if (Base->getType()->isPlaceholderType() && 4237 !Base->getType()->isSpecificPlaceholderType( 4238 BuiltinType::OMPArraySection)) { 4239 ExprResult Result = CheckPlaceholderExpr(Base); 4240 if (Result.isInvalid()) 4241 return ExprError(); 4242 Base = Result.get(); 4243 } 4244 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4245 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4246 if (Result.isInvalid()) 4247 return ExprError(); 4248 Result = DefaultLvalueConversion(Result.get()); 4249 if (Result.isInvalid()) 4250 return ExprError(); 4251 LowerBound = Result.get(); 4252 } 4253 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4254 ExprResult Result = CheckPlaceholderExpr(Length); 4255 if (Result.isInvalid()) 4256 return ExprError(); 4257 Result = DefaultLvalueConversion(Result.get()); 4258 if (Result.isInvalid()) 4259 return ExprError(); 4260 Length = Result.get(); 4261 } 4262 4263 // Build an unanalyzed expression if either operand is type-dependent. 4264 if (Base->isTypeDependent() || 4265 (LowerBound && 4266 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4267 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4268 return new (Context) 4269 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4270 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4271 } 4272 4273 // Perform default conversions. 4274 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4275 QualType ResultTy; 4276 if (OriginalTy->isAnyPointerType()) { 4277 ResultTy = OriginalTy->getPointeeType(); 4278 } else if (OriginalTy->isArrayType()) { 4279 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4280 } else { 4281 return ExprError( 4282 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4283 << Base->getSourceRange()); 4284 } 4285 // C99 6.5.2.1p1 4286 if (LowerBound) { 4287 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4288 LowerBound); 4289 if (Res.isInvalid()) 4290 return ExprError(Diag(LowerBound->getExprLoc(), 4291 diag::err_omp_typecheck_section_not_integer) 4292 << 0 << LowerBound->getSourceRange()); 4293 LowerBound = Res.get(); 4294 4295 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4296 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4297 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4298 << 0 << LowerBound->getSourceRange(); 4299 } 4300 if (Length) { 4301 auto Res = 4302 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4303 if (Res.isInvalid()) 4304 return ExprError(Diag(Length->getExprLoc(), 4305 diag::err_omp_typecheck_section_not_integer) 4306 << 1 << Length->getSourceRange()); 4307 Length = Res.get(); 4308 4309 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4310 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4311 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4312 << 1 << Length->getSourceRange(); 4313 } 4314 4315 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4316 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4317 // type. Note that functions are not objects, and that (in C99 parlance) 4318 // incomplete types are not object types. 4319 if (ResultTy->isFunctionType()) { 4320 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4321 << ResultTy << Base->getSourceRange(); 4322 return ExprError(); 4323 } 4324 4325 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4326 diag::err_omp_section_incomplete_type, Base)) 4327 return ExprError(); 4328 4329 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4330 llvm::APSInt LowerBoundValue; 4331 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) { 4332 // OpenMP 4.5, [2.4 Array Sections] 4333 // The array section must be a subset of the original array. 4334 if (LowerBoundValue.isNegative()) { 4335 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4336 << LowerBound->getSourceRange(); 4337 return ExprError(); 4338 } 4339 } 4340 } 4341 4342 if (Length) { 4343 llvm::APSInt LengthValue; 4344 if (Length->EvaluateAsInt(LengthValue, Context)) { 4345 // OpenMP 4.5, [2.4 Array Sections] 4346 // The length must evaluate to non-negative integers. 4347 if (LengthValue.isNegative()) { 4348 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4349 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4350 << Length->getSourceRange(); 4351 return ExprError(); 4352 } 4353 } 4354 } else if (ColonLoc.isValid() && 4355 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4356 !OriginalTy->isVariableArrayType()))) { 4357 // OpenMP 4.5, [2.4 Array Sections] 4358 // When the size of the array dimension is not known, the length must be 4359 // specified explicitly. 4360 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4361 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4362 return ExprError(); 4363 } 4364 4365 if (!Base->getType()->isSpecificPlaceholderType( 4366 BuiltinType::OMPArraySection)) { 4367 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4368 if (Result.isInvalid()) 4369 return ExprError(); 4370 Base = Result.get(); 4371 } 4372 return new (Context) 4373 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4374 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4375 } 4376 4377 ExprResult 4378 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4379 Expr *Idx, SourceLocation RLoc) { 4380 Expr *LHSExp = Base; 4381 Expr *RHSExp = Idx; 4382 4383 ExprValueKind VK = VK_LValue; 4384 ExprObjectKind OK = OK_Ordinary; 4385 4386 // Per C++ core issue 1213, the result is an xvalue if either operand is 4387 // a non-lvalue array, and an lvalue otherwise. 4388 if (getLangOpts().CPlusPlus11) { 4389 for (auto *Op : {LHSExp, RHSExp}) { 4390 Op = Op->IgnoreImplicit(); 4391 if (Op->getType()->isArrayType() && !Op->isLValue()) 4392 VK = VK_XValue; 4393 } 4394 } 4395 4396 // Perform default conversions. 4397 if (!LHSExp->getType()->getAs<VectorType>()) { 4398 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4399 if (Result.isInvalid()) 4400 return ExprError(); 4401 LHSExp = Result.get(); 4402 } 4403 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4404 if (Result.isInvalid()) 4405 return ExprError(); 4406 RHSExp = Result.get(); 4407 4408 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4409 4410 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4411 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4412 // in the subscript position. As a result, we need to derive the array base 4413 // and index from the expression types. 4414 Expr *BaseExpr, *IndexExpr; 4415 QualType ResultType; 4416 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4417 BaseExpr = LHSExp; 4418 IndexExpr = RHSExp; 4419 ResultType = Context.DependentTy; 4420 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4421 BaseExpr = LHSExp; 4422 IndexExpr = RHSExp; 4423 ResultType = PTy->getPointeeType(); 4424 } else if (const ObjCObjectPointerType *PTy = 4425 LHSTy->getAs<ObjCObjectPointerType>()) { 4426 BaseExpr = LHSExp; 4427 IndexExpr = RHSExp; 4428 4429 // Use custom logic if this should be the pseudo-object subscript 4430 // expression. 4431 if (!LangOpts.isSubscriptPointerArithmetic()) 4432 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4433 nullptr); 4434 4435 ResultType = PTy->getPointeeType(); 4436 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4437 // Handle the uncommon case of "123[Ptr]". 4438 BaseExpr = RHSExp; 4439 IndexExpr = LHSExp; 4440 ResultType = PTy->getPointeeType(); 4441 } else if (const ObjCObjectPointerType *PTy = 4442 RHSTy->getAs<ObjCObjectPointerType>()) { 4443 // Handle the uncommon case of "123[Ptr]". 4444 BaseExpr = RHSExp; 4445 IndexExpr = LHSExp; 4446 ResultType = PTy->getPointeeType(); 4447 if (!LangOpts.isSubscriptPointerArithmetic()) { 4448 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4449 << ResultType << BaseExpr->getSourceRange(); 4450 return ExprError(); 4451 } 4452 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4453 BaseExpr = LHSExp; // vectors: V[123] 4454 IndexExpr = RHSExp; 4455 // We apply C++ DR1213 to vector subscripting too. 4456 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { 4457 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 4458 if (Materialized.isInvalid()) 4459 return ExprError(); 4460 LHSExp = Materialized.get(); 4461 } 4462 VK = LHSExp->getValueKind(); 4463 if (VK != VK_RValue) 4464 OK = OK_VectorComponent; 4465 4466 ResultType = VTy->getElementType(); 4467 QualType BaseType = BaseExpr->getType(); 4468 Qualifiers BaseQuals = BaseType.getQualifiers(); 4469 Qualifiers MemberQuals = ResultType.getQualifiers(); 4470 Qualifiers Combined = BaseQuals + MemberQuals; 4471 if (Combined != MemberQuals) 4472 ResultType = Context.getQualifiedType(ResultType, Combined); 4473 } else if (LHSTy->isArrayType()) { 4474 // If we see an array that wasn't promoted by 4475 // DefaultFunctionArrayLvalueConversion, it must be an array that 4476 // wasn't promoted because of the C90 rule that doesn't 4477 // allow promoting non-lvalue arrays. Warn, then 4478 // force the promotion here. 4479 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4480 LHSExp->getSourceRange(); 4481 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4482 CK_ArrayToPointerDecay).get(); 4483 LHSTy = LHSExp->getType(); 4484 4485 BaseExpr = LHSExp; 4486 IndexExpr = RHSExp; 4487 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4488 } else if (RHSTy->isArrayType()) { 4489 // Same as previous, except for 123[f().a] case 4490 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4491 RHSExp->getSourceRange(); 4492 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4493 CK_ArrayToPointerDecay).get(); 4494 RHSTy = RHSExp->getType(); 4495 4496 BaseExpr = RHSExp; 4497 IndexExpr = LHSExp; 4498 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4499 } else { 4500 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4501 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4502 } 4503 // C99 6.5.2.1p1 4504 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4505 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4506 << IndexExpr->getSourceRange()); 4507 4508 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4509 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4510 && !IndexExpr->isTypeDependent()) 4511 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4512 4513 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4514 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4515 // type. Note that Functions are not objects, and that (in C99 parlance) 4516 // incomplete types are not object types. 4517 if (ResultType->isFunctionType()) { 4518 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 4519 << ResultType << BaseExpr->getSourceRange(); 4520 return ExprError(); 4521 } 4522 4523 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4524 // GNU extension: subscripting on pointer to void 4525 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4526 << BaseExpr->getSourceRange(); 4527 4528 // C forbids expressions of unqualified void type from being l-values. 4529 // See IsCForbiddenLValueType. 4530 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4531 } else if (!ResultType->isDependentType() && 4532 RequireCompleteType(LLoc, ResultType, 4533 diag::err_subscript_incomplete_type, BaseExpr)) 4534 return ExprError(); 4535 4536 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4537 !ResultType.isCForbiddenLValueType()); 4538 4539 return new (Context) 4540 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4541 } 4542 4543 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 4544 ParmVarDecl *Param) { 4545 if (Param->hasUnparsedDefaultArg()) { 4546 Diag(CallLoc, 4547 diag::err_use_of_default_argument_to_function_declared_later) << 4548 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4549 Diag(UnparsedDefaultArgLocs[Param], 4550 diag::note_default_argument_declared_here); 4551 return true; 4552 } 4553 4554 if (Param->hasUninstantiatedDefaultArg()) { 4555 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4556 4557 EnterExpressionEvaluationContext EvalContext( 4558 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 4559 4560 // Instantiate the expression. 4561 // 4562 // FIXME: Pass in a correct Pattern argument, otherwise 4563 // getTemplateInstantiationArgs uses the lexical context of FD, e.g. 4564 // 4565 // template<typename T> 4566 // struct A { 4567 // static int FooImpl(); 4568 // 4569 // template<typename Tp> 4570 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level 4571 // // template argument list [[T], [Tp]], should be [[Tp]]. 4572 // friend A<Tp> Foo(int a); 4573 // }; 4574 // 4575 // template<typename T> 4576 // A<T> Foo(int a = A<T>::FooImpl()); 4577 MultiLevelTemplateArgumentList MutiLevelArgList 4578 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4579 4580 InstantiatingTemplate Inst(*this, CallLoc, Param, 4581 MutiLevelArgList.getInnermost()); 4582 if (Inst.isInvalid()) 4583 return true; 4584 if (Inst.isAlreadyInstantiating()) { 4585 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4586 Param->setInvalidDecl(); 4587 return true; 4588 } 4589 4590 ExprResult Result; 4591 { 4592 // C++ [dcl.fct.default]p5: 4593 // The names in the [default argument] expression are bound, and 4594 // the semantic constraints are checked, at the point where the 4595 // default argument expression appears. 4596 ContextRAII SavedContext(*this, FD); 4597 LocalInstantiationScope Local(*this); 4598 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 4599 /*DirectInit*/false); 4600 } 4601 if (Result.isInvalid()) 4602 return true; 4603 4604 // Check the expression as an initializer for the parameter. 4605 InitializedEntity Entity 4606 = InitializedEntity::InitializeParameter(Context, Param); 4607 InitializationKind Kind 4608 = InitializationKind::CreateCopy(Param->getLocation(), 4609 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 4610 Expr *ResultE = Result.getAs<Expr>(); 4611 4612 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4613 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4614 if (Result.isInvalid()) 4615 return true; 4616 4617 Result = ActOnFinishFullExpr(Result.getAs<Expr>(), 4618 Param->getOuterLocStart()); 4619 if (Result.isInvalid()) 4620 return true; 4621 4622 // Remember the instantiated default argument. 4623 Param->setDefaultArg(Result.getAs<Expr>()); 4624 if (ASTMutationListener *L = getASTMutationListener()) { 4625 L->DefaultArgumentInstantiated(Param); 4626 } 4627 } 4628 4629 // If the default argument expression is not set yet, we are building it now. 4630 if (!Param->hasInit()) { 4631 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4632 Param->setInvalidDecl(); 4633 return true; 4634 } 4635 4636 // If the default expression creates temporaries, we need to 4637 // push them to the current stack of expression temporaries so they'll 4638 // be properly destroyed. 4639 // FIXME: We should really be rebuilding the default argument with new 4640 // bound temporaries; see the comment in PR5810. 4641 // We don't need to do that with block decls, though, because 4642 // blocks in default argument expression can never capture anything. 4643 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 4644 // Set the "needs cleanups" bit regardless of whether there are 4645 // any explicit objects. 4646 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 4647 4648 // Append all the objects to the cleanup list. Right now, this 4649 // should always be a no-op, because blocks in default argument 4650 // expressions should never be able to capture anything. 4651 assert(!Init->getNumObjects() && 4652 "default argument expression has capturing blocks?"); 4653 } 4654 4655 // We already type-checked the argument, so we know it works. 4656 // Just mark all of the declarations in this potentially-evaluated expression 4657 // as being "referenced". 4658 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4659 /*SkipLocalVariables=*/true); 4660 return false; 4661 } 4662 4663 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4664 FunctionDecl *FD, ParmVarDecl *Param) { 4665 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 4666 return ExprError(); 4667 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4668 } 4669 4670 Sema::VariadicCallType 4671 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4672 Expr *Fn) { 4673 if (Proto && Proto->isVariadic()) { 4674 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4675 return VariadicConstructor; 4676 else if (Fn && Fn->getType()->isBlockPointerType()) 4677 return VariadicBlock; 4678 else if (FDecl) { 4679 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4680 if (Method->isInstance()) 4681 return VariadicMethod; 4682 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4683 return VariadicMethod; 4684 return VariadicFunction; 4685 } 4686 return VariadicDoesNotApply; 4687 } 4688 4689 namespace { 4690 class FunctionCallCCC : public FunctionCallFilterCCC { 4691 public: 4692 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4693 unsigned NumArgs, MemberExpr *ME) 4694 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4695 FunctionName(FuncName) {} 4696 4697 bool ValidateCandidate(const TypoCorrection &candidate) override { 4698 if (!candidate.getCorrectionSpecifier() || 4699 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4700 return false; 4701 } 4702 4703 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4704 } 4705 4706 private: 4707 const IdentifierInfo *const FunctionName; 4708 }; 4709 } 4710 4711 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4712 FunctionDecl *FDecl, 4713 ArrayRef<Expr *> Args) { 4714 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4715 DeclarationName FuncName = FDecl->getDeclName(); 4716 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart(); 4717 4718 if (TypoCorrection Corrected = S.CorrectTypo( 4719 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4720 S.getScopeForContext(S.CurContext), nullptr, 4721 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4722 Args.size(), ME), 4723 Sema::CTK_ErrorRecovery)) { 4724 if (NamedDecl *ND = Corrected.getFoundDecl()) { 4725 if (Corrected.isOverloaded()) { 4726 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4727 OverloadCandidateSet::iterator Best; 4728 for (NamedDecl *CD : Corrected) { 4729 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 4730 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4731 OCS); 4732 } 4733 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4734 case OR_Success: 4735 ND = Best->FoundDecl; 4736 Corrected.setCorrectionDecl(ND); 4737 break; 4738 default: 4739 break; 4740 } 4741 } 4742 ND = ND->getUnderlyingDecl(); 4743 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 4744 return Corrected; 4745 } 4746 } 4747 return TypoCorrection(); 4748 } 4749 4750 /// ConvertArgumentsForCall - Converts the arguments specified in 4751 /// Args/NumArgs to the parameter types of the function FDecl with 4752 /// function prototype Proto. Call is the call expression itself, and 4753 /// Fn is the function expression. For a C++ member function, this 4754 /// routine does not attempt to convert the object argument. Returns 4755 /// true if the call is ill-formed. 4756 bool 4757 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4758 FunctionDecl *FDecl, 4759 const FunctionProtoType *Proto, 4760 ArrayRef<Expr *> Args, 4761 SourceLocation RParenLoc, 4762 bool IsExecConfig) { 4763 // Bail out early if calling a builtin with custom typechecking. 4764 if (FDecl) 4765 if (unsigned ID = FDecl->getBuiltinID()) 4766 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4767 return false; 4768 4769 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4770 // assignment, to the types of the corresponding parameter, ... 4771 unsigned NumParams = Proto->getNumParams(); 4772 bool Invalid = false; 4773 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4774 unsigned FnKind = Fn->getType()->isBlockPointerType() 4775 ? 1 /* block */ 4776 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4777 : 0 /* function */); 4778 4779 // If too few arguments are available (and we don't have default 4780 // arguments for the remaining parameters), don't make the call. 4781 if (Args.size() < NumParams) { 4782 if (Args.size() < MinArgs) { 4783 TypoCorrection TC; 4784 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4785 unsigned diag_id = 4786 MinArgs == NumParams && !Proto->isVariadic() 4787 ? diag::err_typecheck_call_too_few_args_suggest 4788 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4789 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4790 << static_cast<unsigned>(Args.size()) 4791 << TC.getCorrectionRange()); 4792 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4793 Diag(RParenLoc, 4794 MinArgs == NumParams && !Proto->isVariadic() 4795 ? diag::err_typecheck_call_too_few_args_one 4796 : diag::err_typecheck_call_too_few_args_at_least_one) 4797 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4798 else 4799 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4800 ? diag::err_typecheck_call_too_few_args 4801 : diag::err_typecheck_call_too_few_args_at_least) 4802 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4803 << Fn->getSourceRange(); 4804 4805 // Emit the location of the prototype. 4806 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4807 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4808 << FDecl; 4809 4810 return true; 4811 } 4812 Call->setNumArgs(Context, NumParams); 4813 } 4814 4815 // If too many are passed and not variadic, error on the extras and drop 4816 // them. 4817 if (Args.size() > NumParams) { 4818 if (!Proto->isVariadic()) { 4819 TypoCorrection TC; 4820 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4821 unsigned diag_id = 4822 MinArgs == NumParams && !Proto->isVariadic() 4823 ? diag::err_typecheck_call_too_many_args_suggest 4824 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4825 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4826 << static_cast<unsigned>(Args.size()) 4827 << TC.getCorrectionRange()); 4828 } else if (NumParams == 1 && FDecl && 4829 FDecl->getParamDecl(0)->getDeclName()) 4830 Diag(Args[NumParams]->getLocStart(), 4831 MinArgs == NumParams 4832 ? diag::err_typecheck_call_too_many_args_one 4833 : diag::err_typecheck_call_too_many_args_at_most_one) 4834 << FnKind << FDecl->getParamDecl(0) 4835 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4836 << SourceRange(Args[NumParams]->getLocStart(), 4837 Args.back()->getLocEnd()); 4838 else 4839 Diag(Args[NumParams]->getLocStart(), 4840 MinArgs == NumParams 4841 ? diag::err_typecheck_call_too_many_args 4842 : diag::err_typecheck_call_too_many_args_at_most) 4843 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4844 << Fn->getSourceRange() 4845 << SourceRange(Args[NumParams]->getLocStart(), 4846 Args.back()->getLocEnd()); 4847 4848 // Emit the location of the prototype. 4849 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4850 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4851 << FDecl; 4852 4853 // This deletes the extra arguments. 4854 Call->setNumArgs(Context, NumParams); 4855 return true; 4856 } 4857 } 4858 SmallVector<Expr *, 8> AllArgs; 4859 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4860 4861 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4862 Proto, 0, Args, AllArgs, CallType); 4863 if (Invalid) 4864 return true; 4865 unsigned TotalNumArgs = AllArgs.size(); 4866 for (unsigned i = 0; i < TotalNumArgs; ++i) 4867 Call->setArg(i, AllArgs[i]); 4868 4869 return false; 4870 } 4871 4872 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4873 const FunctionProtoType *Proto, 4874 unsigned FirstParam, ArrayRef<Expr *> Args, 4875 SmallVectorImpl<Expr *> &AllArgs, 4876 VariadicCallType CallType, bool AllowExplicit, 4877 bool IsListInitialization) { 4878 unsigned NumParams = Proto->getNumParams(); 4879 bool Invalid = false; 4880 size_t ArgIx = 0; 4881 // Continue to check argument types (even if we have too few/many args). 4882 for (unsigned i = FirstParam; i < NumParams; i++) { 4883 QualType ProtoArgType = Proto->getParamType(i); 4884 4885 Expr *Arg; 4886 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4887 if (ArgIx < Args.size()) { 4888 Arg = Args[ArgIx++]; 4889 4890 if (RequireCompleteType(Arg->getLocStart(), 4891 ProtoArgType, 4892 diag::err_call_incomplete_argument, Arg)) 4893 return true; 4894 4895 // Strip the unbridged-cast placeholder expression off, if applicable. 4896 bool CFAudited = false; 4897 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4898 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4899 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4900 Arg = stripARCUnbridgedCast(Arg); 4901 else if (getLangOpts().ObjCAutoRefCount && 4902 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4903 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4904 CFAudited = true; 4905 4906 if (Proto->getExtParameterInfo(i).isNoEscape()) 4907 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 4908 BE->getBlockDecl()->setDoesNotEscape(); 4909 4910 InitializedEntity Entity = 4911 Param ? InitializedEntity::InitializeParameter(Context, Param, 4912 ProtoArgType) 4913 : InitializedEntity::InitializeParameter( 4914 Context, ProtoArgType, Proto->isParamConsumed(i)); 4915 4916 // Remember that parameter belongs to a CF audited API. 4917 if (CFAudited) 4918 Entity.setParameterCFAudited(); 4919 4920 ExprResult ArgE = PerformCopyInitialization( 4921 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 4922 if (ArgE.isInvalid()) 4923 return true; 4924 4925 Arg = ArgE.getAs<Expr>(); 4926 } else { 4927 assert(Param && "can't use default arguments without a known callee"); 4928 4929 ExprResult ArgExpr = 4930 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4931 if (ArgExpr.isInvalid()) 4932 return true; 4933 4934 Arg = ArgExpr.getAs<Expr>(); 4935 } 4936 4937 // Check for array bounds violations for each argument to the call. This 4938 // check only triggers warnings when the argument isn't a more complex Expr 4939 // with its own checking, such as a BinaryOperator. 4940 CheckArrayAccess(Arg); 4941 4942 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4943 CheckStaticArrayArgument(CallLoc, Param, Arg); 4944 4945 AllArgs.push_back(Arg); 4946 } 4947 4948 // If this is a variadic call, handle args passed through "...". 4949 if (CallType != VariadicDoesNotApply) { 4950 // Assume that extern "C" functions with variadic arguments that 4951 // return __unknown_anytype aren't *really* variadic. 4952 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4953 FDecl->isExternC()) { 4954 for (Expr *A : Args.slice(ArgIx)) { 4955 QualType paramType; // ignored 4956 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 4957 Invalid |= arg.isInvalid(); 4958 AllArgs.push_back(arg.get()); 4959 } 4960 4961 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4962 } else { 4963 for (Expr *A : Args.slice(ArgIx)) { 4964 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 4965 Invalid |= Arg.isInvalid(); 4966 AllArgs.push_back(Arg.get()); 4967 } 4968 } 4969 4970 // Check for array bounds violations. 4971 for (Expr *A : Args.slice(ArgIx)) 4972 CheckArrayAccess(A); 4973 } 4974 return Invalid; 4975 } 4976 4977 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4978 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4979 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4980 TL = DTL.getOriginalLoc(); 4981 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4982 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4983 << ATL.getLocalSourceRange(); 4984 } 4985 4986 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4987 /// array parameter, check that it is non-null, and that if it is formed by 4988 /// array-to-pointer decay, the underlying array is sufficiently large. 4989 /// 4990 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4991 /// array type derivation, then for each call to the function, the value of the 4992 /// corresponding actual argument shall provide access to the first element of 4993 /// an array with at least as many elements as specified by the size expression. 4994 void 4995 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4996 ParmVarDecl *Param, 4997 const Expr *ArgExpr) { 4998 // Static array parameters are not supported in C++. 4999 if (!Param || getLangOpts().CPlusPlus) 5000 return; 5001 5002 QualType OrigTy = Param->getOriginalType(); 5003 5004 const ArrayType *AT = Context.getAsArrayType(OrigTy); 5005 if (!AT || AT->getSizeModifier() != ArrayType::Static) 5006 return; 5007 5008 if (ArgExpr->isNullPointerConstant(Context, 5009 Expr::NPC_NeverValueDependent)) { 5010 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 5011 DiagnoseCalleeStaticArrayParam(*this, Param); 5012 return; 5013 } 5014 5015 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 5016 if (!CAT) 5017 return; 5018 5019 const ConstantArrayType *ArgCAT = 5020 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 5021 if (!ArgCAT) 5022 return; 5023 5024 if (ArgCAT->getSize().ult(CAT->getSize())) { 5025 Diag(CallLoc, diag::warn_static_array_too_small) 5026 << ArgExpr->getSourceRange() 5027 << (unsigned) ArgCAT->getSize().getZExtValue() 5028 << (unsigned) CAT->getSize().getZExtValue(); 5029 DiagnoseCalleeStaticArrayParam(*this, Param); 5030 } 5031 } 5032 5033 /// Given a function expression of unknown-any type, try to rebuild it 5034 /// to have a function type. 5035 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 5036 5037 /// Is the given type a placeholder that we need to lower out 5038 /// immediately during argument processing? 5039 static bool isPlaceholderToRemoveAsArg(QualType type) { 5040 // Placeholders are never sugared. 5041 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 5042 if (!placeholder) return false; 5043 5044 switch (placeholder->getKind()) { 5045 // Ignore all the non-placeholder types. 5046 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 5047 case BuiltinType::Id: 5048 #include "clang/Basic/OpenCLImageTypes.def" 5049 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 5050 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 5051 #include "clang/AST/BuiltinTypes.def" 5052 return false; 5053 5054 // We cannot lower out overload sets; they might validly be resolved 5055 // by the call machinery. 5056 case BuiltinType::Overload: 5057 return false; 5058 5059 // Unbridged casts in ARC can be handled in some call positions and 5060 // should be left in place. 5061 case BuiltinType::ARCUnbridgedCast: 5062 return false; 5063 5064 // Pseudo-objects should be converted as soon as possible. 5065 case BuiltinType::PseudoObject: 5066 return true; 5067 5068 // The debugger mode could theoretically but currently does not try 5069 // to resolve unknown-typed arguments based on known parameter types. 5070 case BuiltinType::UnknownAny: 5071 return true; 5072 5073 // These are always invalid as call arguments and should be reported. 5074 case BuiltinType::BoundMember: 5075 case BuiltinType::BuiltinFn: 5076 case BuiltinType::OMPArraySection: 5077 return true; 5078 5079 } 5080 llvm_unreachable("bad builtin type kind"); 5081 } 5082 5083 /// Check an argument list for placeholders that we won't try to 5084 /// handle later. 5085 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5086 // Apply this processing to all the arguments at once instead of 5087 // dying at the first failure. 5088 bool hasInvalid = false; 5089 for (size_t i = 0, e = args.size(); i != e; i++) { 5090 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5091 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5092 if (result.isInvalid()) hasInvalid = true; 5093 else args[i] = result.get(); 5094 } else if (hasInvalid) { 5095 (void)S.CorrectDelayedTyposInExpr(args[i]); 5096 } 5097 } 5098 return hasInvalid; 5099 } 5100 5101 /// If a builtin function has a pointer argument with no explicit address 5102 /// space, then it should be able to accept a pointer to any address 5103 /// space as input. In order to do this, we need to replace the 5104 /// standard builtin declaration with one that uses the same address space 5105 /// as the call. 5106 /// 5107 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5108 /// it does not contain any pointer arguments without 5109 /// an address space qualifer. Otherwise the rewritten 5110 /// FunctionDecl is returned. 5111 /// TODO: Handle pointer return types. 5112 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5113 const FunctionDecl *FDecl, 5114 MultiExprArg ArgExprs) { 5115 5116 QualType DeclType = FDecl->getType(); 5117 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5118 5119 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 5120 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 5121 return nullptr; 5122 5123 bool NeedsNewDecl = false; 5124 unsigned i = 0; 5125 SmallVector<QualType, 8> OverloadParams; 5126 5127 for (QualType ParamType : FT->param_types()) { 5128 5129 // Convert array arguments to pointer to simplify type lookup. 5130 ExprResult ArgRes = 5131 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5132 if (ArgRes.isInvalid()) 5133 return nullptr; 5134 Expr *Arg = ArgRes.get(); 5135 QualType ArgType = Arg->getType(); 5136 if (!ParamType->isPointerType() || 5137 ParamType.getQualifiers().hasAddressSpace() || 5138 !ArgType->isPointerType() || 5139 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 5140 OverloadParams.push_back(ParamType); 5141 continue; 5142 } 5143 5144 NeedsNewDecl = true; 5145 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 5146 5147 QualType PointeeType = ParamType->getPointeeType(); 5148 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5149 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5150 } 5151 5152 if (!NeedsNewDecl) 5153 return nullptr; 5154 5155 FunctionProtoType::ExtProtoInfo EPI; 5156 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5157 OverloadParams, EPI); 5158 DeclContext *Parent = Context.getTranslationUnitDecl(); 5159 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5160 FDecl->getLocation(), 5161 FDecl->getLocation(), 5162 FDecl->getIdentifier(), 5163 OverloadTy, 5164 /*TInfo=*/nullptr, 5165 SC_Extern, false, 5166 /*hasPrototype=*/true); 5167 SmallVector<ParmVarDecl*, 16> Params; 5168 FT = cast<FunctionProtoType>(OverloadTy); 5169 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5170 QualType ParamType = FT->getParamType(i); 5171 ParmVarDecl *Parm = 5172 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5173 SourceLocation(), nullptr, ParamType, 5174 /*TInfo=*/nullptr, SC_None, nullptr); 5175 Parm->setScopeInfo(0, i); 5176 Params.push_back(Parm); 5177 } 5178 OverloadDecl->setParams(Params); 5179 return OverloadDecl; 5180 } 5181 5182 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 5183 FunctionDecl *Callee, 5184 MultiExprArg ArgExprs) { 5185 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 5186 // similar attributes) really don't like it when functions are called with an 5187 // invalid number of args. 5188 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 5189 /*PartialOverloading=*/false) && 5190 !Callee->isVariadic()) 5191 return; 5192 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 5193 return; 5194 5195 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) { 5196 S.Diag(Fn->getLocStart(), 5197 isa<CXXMethodDecl>(Callee) 5198 ? diag::err_ovl_no_viable_member_function_in_call 5199 : diag::err_ovl_no_viable_function_in_call) 5200 << Callee << Callee->getSourceRange(); 5201 S.Diag(Callee->getLocation(), 5202 diag::note_ovl_candidate_disabled_by_function_cond_attr) 5203 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5204 return; 5205 } 5206 } 5207 5208 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 5209 const UnresolvedMemberExpr *const UME, Sema &S) { 5210 5211 const auto GetFunctionLevelDCIfCXXClass = 5212 [](Sema &S) -> const CXXRecordDecl * { 5213 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 5214 if (!DC || !DC->getParent()) 5215 return nullptr; 5216 5217 // If the call to some member function was made from within a member 5218 // function body 'M' return return 'M's parent. 5219 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 5220 return MD->getParent()->getCanonicalDecl(); 5221 // else the call was made from within a default member initializer of a 5222 // class, so return the class. 5223 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 5224 return RD->getCanonicalDecl(); 5225 return nullptr; 5226 }; 5227 // If our DeclContext is neither a member function nor a class (in the 5228 // case of a lambda in a default member initializer), we can't have an 5229 // enclosing 'this'. 5230 5231 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 5232 if (!CurParentClass) 5233 return false; 5234 5235 // The naming class for implicit member functions call is the class in which 5236 // name lookup starts. 5237 const CXXRecordDecl *const NamingClass = 5238 UME->getNamingClass()->getCanonicalDecl(); 5239 assert(NamingClass && "Must have naming class even for implicit access"); 5240 5241 // If the unresolved member functions were found in a 'naming class' that is 5242 // related (either the same or derived from) to the class that contains the 5243 // member function that itself contained the implicit member access. 5244 5245 return CurParentClass == NamingClass || 5246 CurParentClass->isDerivedFrom(NamingClass); 5247 } 5248 5249 static void 5250 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5251 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 5252 5253 if (!UME) 5254 return; 5255 5256 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 5257 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 5258 // already been captured, or if this is an implicit member function call (if 5259 // it isn't, an attempt to capture 'this' should already have been made). 5260 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 5261 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 5262 return; 5263 5264 // Check if the naming class in which the unresolved members were found is 5265 // related (same as or is a base of) to the enclosing class. 5266 5267 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 5268 return; 5269 5270 5271 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 5272 // If the enclosing function is not dependent, then this lambda is 5273 // capture ready, so if we can capture this, do so. 5274 if (!EnclosingFunctionCtx->isDependentContext()) { 5275 // If the current lambda and all enclosing lambdas can capture 'this' - 5276 // then go ahead and capture 'this' (since our unresolved overload set 5277 // contains at least one non-static member function). 5278 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 5279 S.CheckCXXThisCapture(CallLoc); 5280 } else if (S.CurContext->isDependentContext()) { 5281 // ... since this is an implicit member reference, that might potentially 5282 // involve a 'this' capture, mark 'this' for potential capture in 5283 // enclosing lambdas. 5284 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 5285 CurLSI->addPotentialThisCapture(CallLoc); 5286 } 5287 } 5288 5289 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 5290 /// This provides the location of the left/right parens and a list of comma 5291 /// locations. 5292 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5293 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5294 Expr *ExecConfig, bool IsExecConfig) { 5295 // Since this might be a postfix expression, get rid of ParenListExprs. 5296 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 5297 if (Result.isInvalid()) return ExprError(); 5298 Fn = Result.get(); 5299 5300 if (checkArgsForPlaceholders(*this, ArgExprs)) 5301 return ExprError(); 5302 5303 if (getLangOpts().CPlusPlus) { 5304 // If this is a pseudo-destructor expression, build the call immediately. 5305 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5306 if (!ArgExprs.empty()) { 5307 // Pseudo-destructor calls should not have any arguments. 5308 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 5309 << FixItHint::CreateRemoval( 5310 SourceRange(ArgExprs.front()->getLocStart(), 5311 ArgExprs.back()->getLocEnd())); 5312 } 5313 5314 return new (Context) 5315 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc); 5316 } 5317 if (Fn->getType() == Context.PseudoObjectTy) { 5318 ExprResult result = CheckPlaceholderExpr(Fn); 5319 if (result.isInvalid()) return ExprError(); 5320 Fn = result.get(); 5321 } 5322 5323 // Determine whether this is a dependent call inside a C++ template, 5324 // in which case we won't do any semantic analysis now. 5325 bool Dependent = false; 5326 if (Fn->isTypeDependent()) 5327 Dependent = true; 5328 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5329 Dependent = true; 5330 5331 if (Dependent) { 5332 if (ExecConfig) { 5333 return new (Context) CUDAKernelCallExpr( 5334 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5335 Context.DependentTy, VK_RValue, RParenLoc); 5336 } else { 5337 5338 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5339 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 5340 Fn->getLocStart()); 5341 5342 return new (Context) CallExpr( 5343 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5344 } 5345 } 5346 5347 // Determine whether this is a call to an object (C++ [over.call.object]). 5348 if (Fn->getType()->isRecordType()) 5349 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 5350 RParenLoc); 5351 5352 if (Fn->getType() == Context.UnknownAnyTy) { 5353 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5354 if (result.isInvalid()) return ExprError(); 5355 Fn = result.get(); 5356 } 5357 5358 if (Fn->getType() == Context.BoundMemberTy) { 5359 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5360 RParenLoc); 5361 } 5362 } 5363 5364 // Check for overloaded calls. This can happen even in C due to extensions. 5365 if (Fn->getType() == Context.OverloadTy) { 5366 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5367 5368 // We aren't supposed to apply this logic if there's an '&' involved. 5369 if (!find.HasFormOfMemberPointer) { 5370 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5371 return new (Context) CallExpr( 5372 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5373 OverloadExpr *ovl = find.Expression; 5374 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5375 return BuildOverloadedCallExpr( 5376 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 5377 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 5378 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5379 RParenLoc); 5380 } 5381 } 5382 5383 // If we're directly calling a function, get the appropriate declaration. 5384 if (Fn->getType() == Context.UnknownAnyTy) { 5385 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5386 if (result.isInvalid()) return ExprError(); 5387 Fn = result.get(); 5388 } 5389 5390 Expr *NakedFn = Fn->IgnoreParens(); 5391 5392 bool CallingNDeclIndirectly = false; 5393 NamedDecl *NDecl = nullptr; 5394 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5395 if (UnOp->getOpcode() == UO_AddrOf) { 5396 CallingNDeclIndirectly = true; 5397 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5398 } 5399 } 5400 5401 if (isa<DeclRefExpr>(NakedFn)) { 5402 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 5403 5404 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5405 if (FDecl && FDecl->getBuiltinID()) { 5406 // Rewrite the function decl for this builtin by replacing parameters 5407 // with no explicit address space with the address space of the arguments 5408 // in ArgExprs. 5409 if ((FDecl = 5410 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5411 NDecl = FDecl; 5412 Fn = DeclRefExpr::Create( 5413 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 5414 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl); 5415 } 5416 } 5417 } else if (isa<MemberExpr>(NakedFn)) 5418 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5419 5420 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5421 if (CallingNDeclIndirectly && 5422 !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 5423 Fn->getLocStart())) 5424 return ExprError(); 5425 5426 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 5427 return ExprError(); 5428 5429 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 5430 } 5431 5432 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5433 ExecConfig, IsExecConfig); 5434 } 5435 5436 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5437 /// 5438 /// __builtin_astype( value, dst type ) 5439 /// 5440 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5441 SourceLocation BuiltinLoc, 5442 SourceLocation RParenLoc) { 5443 ExprValueKind VK = VK_RValue; 5444 ExprObjectKind OK = OK_Ordinary; 5445 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5446 QualType SrcTy = E->getType(); 5447 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5448 return ExprError(Diag(BuiltinLoc, 5449 diag::err_invalid_astype_of_different_size) 5450 << DstTy 5451 << SrcTy 5452 << E->getSourceRange()); 5453 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5454 } 5455 5456 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5457 /// provided arguments. 5458 /// 5459 /// __builtin_convertvector( value, dst type ) 5460 /// 5461 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5462 SourceLocation BuiltinLoc, 5463 SourceLocation RParenLoc) { 5464 TypeSourceInfo *TInfo; 5465 GetTypeFromParser(ParsedDestTy, &TInfo); 5466 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5467 } 5468 5469 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5470 /// i.e. an expression not of \p OverloadTy. The expression should 5471 /// unary-convert to an expression of function-pointer or 5472 /// block-pointer type. 5473 /// 5474 /// \param NDecl the declaration being called, if available 5475 ExprResult 5476 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5477 SourceLocation LParenLoc, 5478 ArrayRef<Expr *> Args, 5479 SourceLocation RParenLoc, 5480 Expr *Config, bool IsExecConfig) { 5481 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5482 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5483 5484 // Functions with 'interrupt' attribute cannot be called directly. 5485 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5486 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5487 return ExprError(); 5488 } 5489 5490 // Interrupt handlers don't save off the VFP regs automatically on ARM, 5491 // so there's some risk when calling out to non-interrupt handler functions 5492 // that the callee might not preserve them. This is easy to diagnose here, 5493 // but can be very challenging to debug. 5494 if (auto *Caller = getCurFunctionDecl()) 5495 if (Caller->hasAttr<ARMInterruptAttr>()) { 5496 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 5497 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) 5498 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 5499 } 5500 5501 // Promote the function operand. 5502 // We special-case function promotion here because we only allow promoting 5503 // builtin functions to function pointers in the callee of a call. 5504 ExprResult Result; 5505 if (BuiltinID && 5506 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5507 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 5508 CK_BuiltinFnToFnPtr).get(); 5509 } else { 5510 Result = CallExprUnaryConversions(Fn); 5511 } 5512 if (Result.isInvalid()) 5513 return ExprError(); 5514 Fn = Result.get(); 5515 5516 // Make the call expr early, before semantic checks. This guarantees cleanup 5517 // of arguments and function on error. 5518 CallExpr *TheCall; 5519 if (Config) 5520 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 5521 cast<CallExpr>(Config), Args, 5522 Context.BoolTy, VK_RValue, 5523 RParenLoc); 5524 else 5525 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 5526 VK_RValue, RParenLoc); 5527 5528 if (!getLangOpts().CPlusPlus) { 5529 // C cannot always handle TypoExpr nodes in builtin calls and direct 5530 // function calls as their argument checking don't necessarily handle 5531 // dependent types properly, so make sure any TypoExprs have been 5532 // dealt with. 5533 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5534 if (!Result.isUsable()) return ExprError(); 5535 TheCall = dyn_cast<CallExpr>(Result.get()); 5536 if (!TheCall) return Result; 5537 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5538 } 5539 5540 // Bail out early if calling a builtin with custom typechecking. 5541 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5542 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5543 5544 retry: 5545 const FunctionType *FuncT; 5546 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5547 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5548 // have type pointer to function". 5549 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5550 if (!FuncT) 5551 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5552 << Fn->getType() << Fn->getSourceRange()); 5553 } else if (const BlockPointerType *BPT = 5554 Fn->getType()->getAs<BlockPointerType>()) { 5555 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5556 } else { 5557 // Handle calls to expressions of unknown-any type. 5558 if (Fn->getType() == Context.UnknownAnyTy) { 5559 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5560 if (rewrite.isInvalid()) return ExprError(); 5561 Fn = rewrite.get(); 5562 TheCall->setCallee(Fn); 5563 goto retry; 5564 } 5565 5566 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5567 << Fn->getType() << Fn->getSourceRange()); 5568 } 5569 5570 if (getLangOpts().CUDA) { 5571 if (Config) { 5572 // CUDA: Kernel calls must be to global functions 5573 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5574 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5575 << FDecl << Fn->getSourceRange()); 5576 5577 // CUDA: Kernel function must have 'void' return type 5578 if (!FuncT->getReturnType()->isVoidType()) 5579 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5580 << Fn->getType() << Fn->getSourceRange()); 5581 } else { 5582 // CUDA: Calls to global functions must be configured 5583 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5584 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5585 << FDecl << Fn->getSourceRange()); 5586 } 5587 } 5588 5589 // Check for a valid return type 5590 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall, 5591 FDecl)) 5592 return ExprError(); 5593 5594 // We know the result type of the call, set it. 5595 TheCall->setType(FuncT->getCallResultType(Context)); 5596 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5597 5598 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 5599 if (Proto) { 5600 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5601 IsExecConfig)) 5602 return ExprError(); 5603 } else { 5604 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5605 5606 if (FDecl) { 5607 // Check if we have too few/too many template arguments, based 5608 // on our knowledge of the function definition. 5609 const FunctionDecl *Def = nullptr; 5610 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5611 Proto = Def->getType()->getAs<FunctionProtoType>(); 5612 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5613 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5614 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5615 } 5616 5617 // If the function we're calling isn't a function prototype, but we have 5618 // a function prototype from a prior declaratiom, use that prototype. 5619 if (!FDecl->hasPrototype()) 5620 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5621 } 5622 5623 // Promote the arguments (C99 6.5.2.2p6). 5624 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5625 Expr *Arg = Args[i]; 5626 5627 if (Proto && i < Proto->getNumParams()) { 5628 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5629 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5630 ExprResult ArgE = 5631 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5632 if (ArgE.isInvalid()) 5633 return true; 5634 5635 Arg = ArgE.getAs<Expr>(); 5636 5637 } else { 5638 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5639 5640 if (ArgE.isInvalid()) 5641 return true; 5642 5643 Arg = ArgE.getAs<Expr>(); 5644 } 5645 5646 if (RequireCompleteType(Arg->getLocStart(), 5647 Arg->getType(), 5648 diag::err_call_incomplete_argument, Arg)) 5649 return ExprError(); 5650 5651 TheCall->setArg(i, Arg); 5652 } 5653 } 5654 5655 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5656 if (!Method->isStatic()) 5657 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5658 << Fn->getSourceRange()); 5659 5660 // Check for sentinels 5661 if (NDecl) 5662 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5663 5664 // Do special checking on direct calls to functions. 5665 if (FDecl) { 5666 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5667 return ExprError(); 5668 5669 if (BuiltinID) 5670 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5671 } else if (NDecl) { 5672 if (CheckPointerCall(NDecl, TheCall, Proto)) 5673 return ExprError(); 5674 } else { 5675 if (CheckOtherCall(TheCall, Proto)) 5676 return ExprError(); 5677 } 5678 5679 return MaybeBindToTemporary(TheCall); 5680 } 5681 5682 ExprResult 5683 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5684 SourceLocation RParenLoc, Expr *InitExpr) { 5685 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5686 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 5687 5688 TypeSourceInfo *TInfo; 5689 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5690 if (!TInfo) 5691 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5692 5693 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5694 } 5695 5696 ExprResult 5697 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5698 SourceLocation RParenLoc, Expr *LiteralExpr) { 5699 QualType literalType = TInfo->getType(); 5700 5701 if (literalType->isArrayType()) { 5702 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5703 diag::err_illegal_decl_array_incomplete_type, 5704 SourceRange(LParenLoc, 5705 LiteralExpr->getSourceRange().getEnd()))) 5706 return ExprError(); 5707 if (literalType->isVariableArrayType()) 5708 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5709 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5710 } else if (!literalType->isDependentType() && 5711 RequireCompleteType(LParenLoc, literalType, 5712 diag::err_typecheck_decl_incomplete_type, 5713 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5714 return ExprError(); 5715 5716 InitializedEntity Entity 5717 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5718 InitializationKind Kind 5719 = InitializationKind::CreateCStyleCast(LParenLoc, 5720 SourceRange(LParenLoc, RParenLoc), 5721 /*InitList=*/true); 5722 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5723 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5724 &literalType); 5725 if (Result.isInvalid()) 5726 return ExprError(); 5727 LiteralExpr = Result.get(); 5728 5729 bool isFileScope = !CurContext->isFunctionOrMethod(); 5730 if (isFileScope && 5731 !LiteralExpr->isTypeDependent() && 5732 !LiteralExpr->isValueDependent() && 5733 !literalType->isDependentType()) { // 6.5.2.5p3 5734 if (CheckForConstantInitializer(LiteralExpr, literalType)) 5735 return ExprError(); 5736 } 5737 5738 // In C, compound literals are l-values for some reason. 5739 // For GCC compatibility, in C++, file-scope array compound literals with 5740 // constant initializers are also l-values, and compound literals are 5741 // otherwise prvalues. 5742 // 5743 // (GCC also treats C++ list-initialized file-scope array prvalues with 5744 // constant initializers as l-values, but that's non-conforming, so we don't 5745 // follow it there.) 5746 // 5747 // FIXME: It would be better to handle the lvalue cases as materializing and 5748 // lifetime-extending a temporary object, but our materialized temporaries 5749 // representation only supports lifetime extension from a variable, not "out 5750 // of thin air". 5751 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 5752 // is bound to the result of applying array-to-pointer decay to the compound 5753 // literal. 5754 // FIXME: GCC supports compound literals of reference type, which should 5755 // obviously have a value kind derived from the kind of reference involved. 5756 ExprValueKind VK = 5757 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 5758 ? VK_RValue 5759 : VK_LValue; 5760 5761 return MaybeBindToTemporary( 5762 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 5763 VK, LiteralExpr, isFileScope)); 5764 } 5765 5766 ExprResult 5767 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 5768 SourceLocation RBraceLoc) { 5769 // Immediately handle non-overload placeholders. Overloads can be 5770 // resolved contextually, but everything else here can't. 5771 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 5772 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 5773 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 5774 5775 // Ignore failures; dropping the entire initializer list because 5776 // of one failure would be terrible for indexing/etc. 5777 if (result.isInvalid()) continue; 5778 5779 InitArgList[I] = result.get(); 5780 } 5781 } 5782 5783 // Semantic analysis for initializers is done by ActOnDeclarator() and 5784 // CheckInitializer() - it requires knowledge of the object being initialized. 5785 5786 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 5787 RBraceLoc); 5788 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 5789 return E; 5790 } 5791 5792 /// Do an explicit extend of the given block pointer if we're in ARC. 5793 void Sema::maybeExtendBlockObject(ExprResult &E) { 5794 assert(E.get()->getType()->isBlockPointerType()); 5795 assert(E.get()->isRValue()); 5796 5797 // Only do this in an r-value context. 5798 if (!getLangOpts().ObjCAutoRefCount) return; 5799 5800 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 5801 CK_ARCExtendBlockObject, E.get(), 5802 /*base path*/ nullptr, VK_RValue); 5803 Cleanup.setExprNeedsCleanups(true); 5804 } 5805 5806 /// Prepare a conversion of the given expression to an ObjC object 5807 /// pointer type. 5808 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 5809 QualType type = E.get()->getType(); 5810 if (type->isObjCObjectPointerType()) { 5811 return CK_BitCast; 5812 } else if (type->isBlockPointerType()) { 5813 maybeExtendBlockObject(E); 5814 return CK_BlockPointerToObjCPointerCast; 5815 } else { 5816 assert(type->isPointerType()); 5817 return CK_CPointerToObjCPointerCast; 5818 } 5819 } 5820 5821 /// Prepares for a scalar cast, performing all the necessary stages 5822 /// except the final cast and returning the kind required. 5823 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 5824 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 5825 // Also, callers should have filtered out the invalid cases with 5826 // pointers. Everything else should be possible. 5827 5828 QualType SrcTy = Src.get()->getType(); 5829 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 5830 return CK_NoOp; 5831 5832 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 5833 case Type::STK_MemberPointer: 5834 llvm_unreachable("member pointer type in C"); 5835 5836 case Type::STK_CPointer: 5837 case Type::STK_BlockPointer: 5838 case Type::STK_ObjCObjectPointer: 5839 switch (DestTy->getScalarTypeKind()) { 5840 case Type::STK_CPointer: { 5841 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 5842 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 5843 if (SrcAS != DestAS) 5844 return CK_AddressSpaceConversion; 5845 return CK_BitCast; 5846 } 5847 case Type::STK_BlockPointer: 5848 return (SrcKind == Type::STK_BlockPointer 5849 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 5850 case Type::STK_ObjCObjectPointer: 5851 if (SrcKind == Type::STK_ObjCObjectPointer) 5852 return CK_BitCast; 5853 if (SrcKind == Type::STK_CPointer) 5854 return CK_CPointerToObjCPointerCast; 5855 maybeExtendBlockObject(Src); 5856 return CK_BlockPointerToObjCPointerCast; 5857 case Type::STK_Bool: 5858 return CK_PointerToBoolean; 5859 case Type::STK_Integral: 5860 return CK_PointerToIntegral; 5861 case Type::STK_Floating: 5862 case Type::STK_FloatingComplex: 5863 case Type::STK_IntegralComplex: 5864 case Type::STK_MemberPointer: 5865 llvm_unreachable("illegal cast from pointer"); 5866 } 5867 llvm_unreachable("Should have returned before this"); 5868 5869 case Type::STK_Bool: // casting from bool is like casting from an integer 5870 case Type::STK_Integral: 5871 switch (DestTy->getScalarTypeKind()) { 5872 case Type::STK_CPointer: 5873 case Type::STK_ObjCObjectPointer: 5874 case Type::STK_BlockPointer: 5875 if (Src.get()->isNullPointerConstant(Context, 5876 Expr::NPC_ValueDependentIsNull)) 5877 return CK_NullToPointer; 5878 return CK_IntegralToPointer; 5879 case Type::STK_Bool: 5880 return CK_IntegralToBoolean; 5881 case Type::STK_Integral: 5882 return CK_IntegralCast; 5883 case Type::STK_Floating: 5884 return CK_IntegralToFloating; 5885 case Type::STK_IntegralComplex: 5886 Src = ImpCastExprToType(Src.get(), 5887 DestTy->castAs<ComplexType>()->getElementType(), 5888 CK_IntegralCast); 5889 return CK_IntegralRealToComplex; 5890 case Type::STK_FloatingComplex: 5891 Src = ImpCastExprToType(Src.get(), 5892 DestTy->castAs<ComplexType>()->getElementType(), 5893 CK_IntegralToFloating); 5894 return CK_FloatingRealToComplex; 5895 case Type::STK_MemberPointer: 5896 llvm_unreachable("member pointer type in C"); 5897 } 5898 llvm_unreachable("Should have returned before this"); 5899 5900 case Type::STK_Floating: 5901 switch (DestTy->getScalarTypeKind()) { 5902 case Type::STK_Floating: 5903 return CK_FloatingCast; 5904 case Type::STK_Bool: 5905 return CK_FloatingToBoolean; 5906 case Type::STK_Integral: 5907 return CK_FloatingToIntegral; 5908 case Type::STK_FloatingComplex: 5909 Src = ImpCastExprToType(Src.get(), 5910 DestTy->castAs<ComplexType>()->getElementType(), 5911 CK_FloatingCast); 5912 return CK_FloatingRealToComplex; 5913 case Type::STK_IntegralComplex: 5914 Src = ImpCastExprToType(Src.get(), 5915 DestTy->castAs<ComplexType>()->getElementType(), 5916 CK_FloatingToIntegral); 5917 return CK_IntegralRealToComplex; 5918 case Type::STK_CPointer: 5919 case Type::STK_ObjCObjectPointer: 5920 case Type::STK_BlockPointer: 5921 llvm_unreachable("valid float->pointer cast?"); 5922 case Type::STK_MemberPointer: 5923 llvm_unreachable("member pointer type in C"); 5924 } 5925 llvm_unreachable("Should have returned before this"); 5926 5927 case Type::STK_FloatingComplex: 5928 switch (DestTy->getScalarTypeKind()) { 5929 case Type::STK_FloatingComplex: 5930 return CK_FloatingComplexCast; 5931 case Type::STK_IntegralComplex: 5932 return CK_FloatingComplexToIntegralComplex; 5933 case Type::STK_Floating: { 5934 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5935 if (Context.hasSameType(ET, DestTy)) 5936 return CK_FloatingComplexToReal; 5937 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 5938 return CK_FloatingCast; 5939 } 5940 case Type::STK_Bool: 5941 return CK_FloatingComplexToBoolean; 5942 case Type::STK_Integral: 5943 Src = ImpCastExprToType(Src.get(), 5944 SrcTy->castAs<ComplexType>()->getElementType(), 5945 CK_FloatingComplexToReal); 5946 return CK_FloatingToIntegral; 5947 case Type::STK_CPointer: 5948 case Type::STK_ObjCObjectPointer: 5949 case Type::STK_BlockPointer: 5950 llvm_unreachable("valid complex float->pointer cast?"); 5951 case Type::STK_MemberPointer: 5952 llvm_unreachable("member pointer type in C"); 5953 } 5954 llvm_unreachable("Should have returned before this"); 5955 5956 case Type::STK_IntegralComplex: 5957 switch (DestTy->getScalarTypeKind()) { 5958 case Type::STK_FloatingComplex: 5959 return CK_IntegralComplexToFloatingComplex; 5960 case Type::STK_IntegralComplex: 5961 return CK_IntegralComplexCast; 5962 case Type::STK_Integral: { 5963 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5964 if (Context.hasSameType(ET, DestTy)) 5965 return CK_IntegralComplexToReal; 5966 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 5967 return CK_IntegralCast; 5968 } 5969 case Type::STK_Bool: 5970 return CK_IntegralComplexToBoolean; 5971 case Type::STK_Floating: 5972 Src = ImpCastExprToType(Src.get(), 5973 SrcTy->castAs<ComplexType>()->getElementType(), 5974 CK_IntegralComplexToReal); 5975 return CK_IntegralToFloating; 5976 case Type::STK_CPointer: 5977 case Type::STK_ObjCObjectPointer: 5978 case Type::STK_BlockPointer: 5979 llvm_unreachable("valid complex int->pointer cast?"); 5980 case Type::STK_MemberPointer: 5981 llvm_unreachable("member pointer type in C"); 5982 } 5983 llvm_unreachable("Should have returned before this"); 5984 } 5985 5986 llvm_unreachable("Unhandled scalar cast"); 5987 } 5988 5989 static bool breakDownVectorType(QualType type, uint64_t &len, 5990 QualType &eltType) { 5991 // Vectors are simple. 5992 if (const VectorType *vecType = type->getAs<VectorType>()) { 5993 len = vecType->getNumElements(); 5994 eltType = vecType->getElementType(); 5995 assert(eltType->isScalarType()); 5996 return true; 5997 } 5998 5999 // We allow lax conversion to and from non-vector types, but only if 6000 // they're real types (i.e. non-complex, non-pointer scalar types). 6001 if (!type->isRealType()) return false; 6002 6003 len = 1; 6004 eltType = type; 6005 return true; 6006 } 6007 6008 /// Are the two types lax-compatible vector types? That is, given 6009 /// that one of them is a vector, do they have equal storage sizes, 6010 /// where the storage size is the number of elements times the element 6011 /// size? 6012 /// 6013 /// This will also return false if either of the types is neither a 6014 /// vector nor a real type. 6015 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 6016 assert(destTy->isVectorType() || srcTy->isVectorType()); 6017 6018 // Disallow lax conversions between scalars and ExtVectors (these 6019 // conversions are allowed for other vector types because common headers 6020 // depend on them). Most scalar OP ExtVector cases are handled by the 6021 // splat path anyway, which does what we want (convert, not bitcast). 6022 // What this rules out for ExtVectors is crazy things like char4*float. 6023 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 6024 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 6025 6026 uint64_t srcLen, destLen; 6027 QualType srcEltTy, destEltTy; 6028 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 6029 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 6030 6031 // ASTContext::getTypeSize will return the size rounded up to a 6032 // power of 2, so instead of using that, we need to use the raw 6033 // element size multiplied by the element count. 6034 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 6035 uint64_t destEltSize = Context.getTypeSize(destEltTy); 6036 6037 return (srcLen * srcEltSize == destLen * destEltSize); 6038 } 6039 6040 /// Is this a legal conversion between two types, one of which is 6041 /// known to be a vector type? 6042 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 6043 assert(destTy->isVectorType() || srcTy->isVectorType()); 6044 6045 if (!Context.getLangOpts().LaxVectorConversions) 6046 return false; 6047 return areLaxCompatibleVectorTypes(srcTy, destTy); 6048 } 6049 6050 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 6051 CastKind &Kind) { 6052 assert(VectorTy->isVectorType() && "Not a vector type!"); 6053 6054 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 6055 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 6056 return Diag(R.getBegin(), 6057 Ty->isVectorType() ? 6058 diag::err_invalid_conversion_between_vectors : 6059 diag::err_invalid_conversion_between_vector_and_integer) 6060 << VectorTy << Ty << R; 6061 } else 6062 return Diag(R.getBegin(), 6063 diag::err_invalid_conversion_between_vector_and_scalar) 6064 << VectorTy << Ty << R; 6065 6066 Kind = CK_BitCast; 6067 return false; 6068 } 6069 6070 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 6071 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 6072 6073 if (DestElemTy == SplattedExpr->getType()) 6074 return SplattedExpr; 6075 6076 assert(DestElemTy->isFloatingType() || 6077 DestElemTy->isIntegralOrEnumerationType()); 6078 6079 CastKind CK; 6080 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 6081 // OpenCL requires that we convert `true` boolean expressions to -1, but 6082 // only when splatting vectors. 6083 if (DestElemTy->isFloatingType()) { 6084 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 6085 // in two steps: boolean to signed integral, then to floating. 6086 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 6087 CK_BooleanToSignedIntegral); 6088 SplattedExpr = CastExprRes.get(); 6089 CK = CK_IntegralToFloating; 6090 } else { 6091 CK = CK_BooleanToSignedIntegral; 6092 } 6093 } else { 6094 ExprResult CastExprRes = SplattedExpr; 6095 CK = PrepareScalarCast(CastExprRes, DestElemTy); 6096 if (CastExprRes.isInvalid()) 6097 return ExprError(); 6098 SplattedExpr = CastExprRes.get(); 6099 } 6100 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 6101 } 6102 6103 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 6104 Expr *CastExpr, CastKind &Kind) { 6105 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 6106 6107 QualType SrcTy = CastExpr->getType(); 6108 6109 // If SrcTy is a VectorType, the total size must match to explicitly cast to 6110 // an ExtVectorType. 6111 // In OpenCL, casts between vectors of different types are not allowed. 6112 // (See OpenCL 6.2). 6113 if (SrcTy->isVectorType()) { 6114 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 6115 (getLangOpts().OpenCL && 6116 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 6117 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 6118 << DestTy << SrcTy << R; 6119 return ExprError(); 6120 } 6121 Kind = CK_BitCast; 6122 return CastExpr; 6123 } 6124 6125 // All non-pointer scalars can be cast to ExtVector type. The appropriate 6126 // conversion will take place first from scalar to elt type, and then 6127 // splat from elt type to vector. 6128 if (SrcTy->isPointerType()) 6129 return Diag(R.getBegin(), 6130 diag::err_invalid_conversion_between_vector_and_scalar) 6131 << DestTy << SrcTy << R; 6132 6133 Kind = CK_VectorSplat; 6134 return prepareVectorSplat(DestTy, CastExpr); 6135 } 6136 6137 ExprResult 6138 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 6139 Declarator &D, ParsedType &Ty, 6140 SourceLocation RParenLoc, Expr *CastExpr) { 6141 assert(!D.isInvalidType() && (CastExpr != nullptr) && 6142 "ActOnCastExpr(): missing type or expr"); 6143 6144 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 6145 if (D.isInvalidType()) 6146 return ExprError(); 6147 6148 if (getLangOpts().CPlusPlus) { 6149 // Check that there are no default arguments (C++ only). 6150 CheckExtraCXXDefaultArguments(D); 6151 } else { 6152 // Make sure any TypoExprs have been dealt with. 6153 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 6154 if (!Res.isUsable()) 6155 return ExprError(); 6156 CastExpr = Res.get(); 6157 } 6158 6159 checkUnusedDeclAttributes(D); 6160 6161 QualType castType = castTInfo->getType(); 6162 Ty = CreateParsedType(castType, castTInfo); 6163 6164 bool isVectorLiteral = false; 6165 6166 // Check for an altivec or OpenCL literal, 6167 // i.e. all the elements are integer constants. 6168 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 6169 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 6170 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 6171 && castType->isVectorType() && (PE || PLE)) { 6172 if (PLE && PLE->getNumExprs() == 0) { 6173 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 6174 return ExprError(); 6175 } 6176 if (PE || PLE->getNumExprs() == 1) { 6177 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 6178 if (!E->getType()->isVectorType()) 6179 isVectorLiteral = true; 6180 } 6181 else 6182 isVectorLiteral = true; 6183 } 6184 6185 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 6186 // then handle it as such. 6187 if (isVectorLiteral) 6188 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 6189 6190 // If the Expr being casted is a ParenListExpr, handle it specially. 6191 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 6192 // sequence of BinOp comma operators. 6193 if (isa<ParenListExpr>(CastExpr)) { 6194 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 6195 if (Result.isInvalid()) return ExprError(); 6196 CastExpr = Result.get(); 6197 } 6198 6199 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6200 !getSourceManager().isInSystemMacro(LParenLoc)) 6201 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6202 6203 CheckTollFreeBridgeCast(castType, CastExpr); 6204 6205 CheckObjCBridgeRelatedCast(castType, CastExpr); 6206 6207 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 6208 6209 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6210 } 6211 6212 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6213 SourceLocation RParenLoc, Expr *E, 6214 TypeSourceInfo *TInfo) { 6215 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6216 "Expected paren or paren list expression"); 6217 6218 Expr **exprs; 6219 unsigned numExprs; 6220 Expr *subExpr; 6221 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6222 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6223 LiteralLParenLoc = PE->getLParenLoc(); 6224 LiteralRParenLoc = PE->getRParenLoc(); 6225 exprs = PE->getExprs(); 6226 numExprs = PE->getNumExprs(); 6227 } else { // isa<ParenExpr> by assertion at function entrance 6228 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6229 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6230 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6231 exprs = &subExpr; 6232 numExprs = 1; 6233 } 6234 6235 QualType Ty = TInfo->getType(); 6236 assert(Ty->isVectorType() && "Expected vector type"); 6237 6238 SmallVector<Expr *, 8> initExprs; 6239 const VectorType *VTy = Ty->getAs<VectorType>(); 6240 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 6241 6242 // '(...)' form of vector initialization in AltiVec: the number of 6243 // initializers must be one or must match the size of the vector. 6244 // If a single value is specified in the initializer then it will be 6245 // replicated to all the components of the vector 6246 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6247 // The number of initializers must be one or must match the size of the 6248 // vector. If a single value is specified in the initializer then it will 6249 // be replicated to all the components of the vector 6250 if (numExprs == 1) { 6251 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6252 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6253 if (Literal.isInvalid()) 6254 return ExprError(); 6255 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6256 PrepareScalarCast(Literal, ElemTy)); 6257 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6258 } 6259 else if (numExprs < numElems) { 6260 Diag(E->getExprLoc(), 6261 diag::err_incorrect_number_of_vector_initializers); 6262 return ExprError(); 6263 } 6264 else 6265 initExprs.append(exprs, exprs + numExprs); 6266 } 6267 else { 6268 // For OpenCL, when the number of initializers is a single value, 6269 // it will be replicated to all components of the vector. 6270 if (getLangOpts().OpenCL && 6271 VTy->getVectorKind() == VectorType::GenericVector && 6272 numExprs == 1) { 6273 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6274 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6275 if (Literal.isInvalid()) 6276 return ExprError(); 6277 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6278 PrepareScalarCast(Literal, ElemTy)); 6279 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6280 } 6281 6282 initExprs.append(exprs, exprs + numExprs); 6283 } 6284 // FIXME: This means that pretty-printing the final AST will produce curly 6285 // braces instead of the original commas. 6286 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6287 initExprs, LiteralRParenLoc); 6288 initE->setType(Ty); 6289 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6290 } 6291 6292 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6293 /// the ParenListExpr into a sequence of comma binary operators. 6294 ExprResult 6295 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6296 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6297 if (!E) 6298 return OrigExpr; 6299 6300 ExprResult Result(E->getExpr(0)); 6301 6302 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6303 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6304 E->getExpr(i)); 6305 6306 if (Result.isInvalid()) return ExprError(); 6307 6308 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6309 } 6310 6311 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6312 SourceLocation R, 6313 MultiExprArg Val) { 6314 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 6315 return expr; 6316 } 6317 6318 /// Emit a specialized diagnostic when one expression is a null pointer 6319 /// constant and the other is not a pointer. Returns true if a diagnostic is 6320 /// emitted. 6321 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6322 SourceLocation QuestionLoc) { 6323 Expr *NullExpr = LHSExpr; 6324 Expr *NonPointerExpr = RHSExpr; 6325 Expr::NullPointerConstantKind NullKind = 6326 NullExpr->isNullPointerConstant(Context, 6327 Expr::NPC_ValueDependentIsNotNull); 6328 6329 if (NullKind == Expr::NPCK_NotNull) { 6330 NullExpr = RHSExpr; 6331 NonPointerExpr = LHSExpr; 6332 NullKind = 6333 NullExpr->isNullPointerConstant(Context, 6334 Expr::NPC_ValueDependentIsNotNull); 6335 } 6336 6337 if (NullKind == Expr::NPCK_NotNull) 6338 return false; 6339 6340 if (NullKind == Expr::NPCK_ZeroExpression) 6341 return false; 6342 6343 if (NullKind == Expr::NPCK_ZeroLiteral) { 6344 // In this case, check to make sure that we got here from a "NULL" 6345 // string in the source code. 6346 NullExpr = NullExpr->IgnoreParenImpCasts(); 6347 SourceLocation loc = NullExpr->getExprLoc(); 6348 if (!findMacroSpelling(loc, "NULL")) 6349 return false; 6350 } 6351 6352 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6353 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6354 << NonPointerExpr->getType() << DiagType 6355 << NonPointerExpr->getSourceRange(); 6356 return true; 6357 } 6358 6359 /// Return false if the condition expression is valid, true otherwise. 6360 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6361 QualType CondTy = Cond->getType(); 6362 6363 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6364 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6365 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6366 << CondTy << Cond->getSourceRange(); 6367 return true; 6368 } 6369 6370 // C99 6.5.15p2 6371 if (CondTy->isScalarType()) return false; 6372 6373 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6374 << CondTy << Cond->getSourceRange(); 6375 return true; 6376 } 6377 6378 /// Handle when one or both operands are void type. 6379 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6380 ExprResult &RHS) { 6381 Expr *LHSExpr = LHS.get(); 6382 Expr *RHSExpr = RHS.get(); 6383 6384 if (!LHSExpr->getType()->isVoidType()) 6385 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6386 << RHSExpr->getSourceRange(); 6387 if (!RHSExpr->getType()->isVoidType()) 6388 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6389 << LHSExpr->getSourceRange(); 6390 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6391 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6392 return S.Context.VoidTy; 6393 } 6394 6395 /// Return false if the NullExpr can be promoted to PointerTy, 6396 /// true otherwise. 6397 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6398 QualType PointerTy) { 6399 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6400 !NullExpr.get()->isNullPointerConstant(S.Context, 6401 Expr::NPC_ValueDependentIsNull)) 6402 return true; 6403 6404 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6405 return false; 6406 } 6407 6408 /// Checks compatibility between two pointers and return the resulting 6409 /// type. 6410 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6411 ExprResult &RHS, 6412 SourceLocation Loc) { 6413 QualType LHSTy = LHS.get()->getType(); 6414 QualType RHSTy = RHS.get()->getType(); 6415 6416 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6417 // Two identical pointers types are always compatible. 6418 return LHSTy; 6419 } 6420 6421 QualType lhptee, rhptee; 6422 6423 // Get the pointee types. 6424 bool IsBlockPointer = false; 6425 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6426 lhptee = LHSBTy->getPointeeType(); 6427 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6428 IsBlockPointer = true; 6429 } else { 6430 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6431 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6432 } 6433 6434 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6435 // differently qualified versions of compatible types, the result type is 6436 // a pointer to an appropriately qualified version of the composite 6437 // type. 6438 6439 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6440 // clause doesn't make sense for our extensions. E.g. address space 2 should 6441 // be incompatible with address space 3: they may live on different devices or 6442 // anything. 6443 Qualifiers lhQual = lhptee.getQualifiers(); 6444 Qualifiers rhQual = rhptee.getQualifiers(); 6445 6446 LangAS ResultAddrSpace = LangAS::Default; 6447 LangAS LAddrSpace = lhQual.getAddressSpace(); 6448 LangAS RAddrSpace = rhQual.getAddressSpace(); 6449 if (S.getLangOpts().OpenCL) { 6450 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 6451 // spaces is disallowed. 6452 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 6453 ResultAddrSpace = LAddrSpace; 6454 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 6455 ResultAddrSpace = RAddrSpace; 6456 else { 6457 S.Diag(Loc, 6458 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 6459 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 6460 << RHS.get()->getSourceRange(); 6461 return QualType(); 6462 } 6463 } 6464 6465 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6466 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 6467 lhQual.removeCVRQualifiers(); 6468 rhQual.removeCVRQualifiers(); 6469 6470 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 6471 // (C99 6.7.3) for address spaces. We assume that the check should behave in 6472 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 6473 // qual types are compatible iff 6474 // * corresponded types are compatible 6475 // * CVR qualifiers are equal 6476 // * address spaces are equal 6477 // Thus for conditional operator we merge CVR and address space unqualified 6478 // pointees and if there is a composite type we return a pointer to it with 6479 // merged qualifiers. 6480 if (S.getLangOpts().OpenCL) { 6481 LHSCastKind = LAddrSpace == ResultAddrSpace 6482 ? CK_BitCast 6483 : CK_AddressSpaceConversion; 6484 RHSCastKind = RAddrSpace == ResultAddrSpace 6485 ? CK_BitCast 6486 : CK_AddressSpaceConversion; 6487 lhQual.removeAddressSpace(); 6488 rhQual.removeAddressSpace(); 6489 } 6490 6491 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 6492 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 6493 6494 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 6495 6496 if (CompositeTy.isNull()) { 6497 // In this situation, we assume void* type. No especially good 6498 // reason, but this is what gcc does, and we do have to pick 6499 // to get a consistent AST. 6500 QualType incompatTy; 6501 incompatTy = S.Context.getPointerType( 6502 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 6503 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 6504 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 6505 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 6506 // for casts between types with incompatible address space qualifiers. 6507 // For the following code the compiler produces casts between global and 6508 // local address spaces of the corresponded innermost pointees: 6509 // local int *global *a; 6510 // global int *global *b; 6511 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 6512 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 6513 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6514 << RHS.get()->getSourceRange(); 6515 return incompatTy; 6516 } 6517 6518 // The pointer types are compatible. 6519 // In case of OpenCL ResultTy should have the address space qualifier 6520 // which is a superset of address spaces of both the 2nd and the 3rd 6521 // operands of the conditional operator. 6522 QualType ResultTy = [&, ResultAddrSpace]() { 6523 if (S.getLangOpts().OpenCL) { 6524 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 6525 CompositeQuals.setAddressSpace(ResultAddrSpace); 6526 return S.Context 6527 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 6528 .withCVRQualifiers(MergedCVRQual); 6529 } 6530 return CompositeTy.withCVRQualifiers(MergedCVRQual); 6531 }(); 6532 if (IsBlockPointer) 6533 ResultTy = S.Context.getBlockPointerType(ResultTy); 6534 else 6535 ResultTy = S.Context.getPointerType(ResultTy); 6536 6537 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 6538 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 6539 return ResultTy; 6540 } 6541 6542 /// Return the resulting type when the operands are both block pointers. 6543 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 6544 ExprResult &LHS, 6545 ExprResult &RHS, 6546 SourceLocation Loc) { 6547 QualType LHSTy = LHS.get()->getType(); 6548 QualType RHSTy = RHS.get()->getType(); 6549 6550 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 6551 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 6552 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 6553 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6554 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6555 return destType; 6556 } 6557 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 6558 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6559 << RHS.get()->getSourceRange(); 6560 return QualType(); 6561 } 6562 6563 // We have 2 block pointer types. 6564 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6565 } 6566 6567 /// Return the resulting type when the operands are both pointers. 6568 static QualType 6569 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 6570 ExprResult &RHS, 6571 SourceLocation Loc) { 6572 // get the pointer types 6573 QualType LHSTy = LHS.get()->getType(); 6574 QualType RHSTy = RHS.get()->getType(); 6575 6576 // get the "pointed to" types 6577 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6578 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6579 6580 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 6581 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 6582 // Figure out necessary qualifiers (C99 6.5.15p6) 6583 QualType destPointee 6584 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6585 QualType destType = S.Context.getPointerType(destPointee); 6586 // Add qualifiers if necessary. 6587 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6588 // Promote to void*. 6589 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6590 return destType; 6591 } 6592 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 6593 QualType destPointee 6594 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6595 QualType destType = S.Context.getPointerType(destPointee); 6596 // Add qualifiers if necessary. 6597 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6598 // Promote to void*. 6599 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6600 return destType; 6601 } 6602 6603 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6604 } 6605 6606 /// Return false if the first expression is not an integer and the second 6607 /// expression is not a pointer, true otherwise. 6608 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 6609 Expr* PointerExpr, SourceLocation Loc, 6610 bool IsIntFirstExpr) { 6611 if (!PointerExpr->getType()->isPointerType() || 6612 !Int.get()->getType()->isIntegerType()) 6613 return false; 6614 6615 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 6616 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 6617 6618 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 6619 << Expr1->getType() << Expr2->getType() 6620 << Expr1->getSourceRange() << Expr2->getSourceRange(); 6621 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 6622 CK_IntegralToPointer); 6623 return true; 6624 } 6625 6626 /// Simple conversion between integer and floating point types. 6627 /// 6628 /// Used when handling the OpenCL conditional operator where the 6629 /// condition is a vector while the other operands are scalar. 6630 /// 6631 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 6632 /// types are either integer or floating type. Between the two 6633 /// operands, the type with the higher rank is defined as the "result 6634 /// type". The other operand needs to be promoted to the same type. No 6635 /// other type promotion is allowed. We cannot use 6636 /// UsualArithmeticConversions() for this purpose, since it always 6637 /// promotes promotable types. 6638 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 6639 ExprResult &RHS, 6640 SourceLocation QuestionLoc) { 6641 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 6642 if (LHS.isInvalid()) 6643 return QualType(); 6644 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 6645 if (RHS.isInvalid()) 6646 return QualType(); 6647 6648 // For conversion purposes, we ignore any qualifiers. 6649 // For example, "const float" and "float" are equivalent. 6650 QualType LHSType = 6651 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6652 QualType RHSType = 6653 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6654 6655 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 6656 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6657 << LHSType << LHS.get()->getSourceRange(); 6658 return QualType(); 6659 } 6660 6661 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 6662 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6663 << RHSType << RHS.get()->getSourceRange(); 6664 return QualType(); 6665 } 6666 6667 // If both types are identical, no conversion is needed. 6668 if (LHSType == RHSType) 6669 return LHSType; 6670 6671 // Now handle "real" floating types (i.e. float, double, long double). 6672 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 6673 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 6674 /*IsCompAssign = */ false); 6675 6676 // Finally, we have two differing integer types. 6677 return handleIntegerConversion<doIntegralCast, doIntegralCast> 6678 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 6679 } 6680 6681 /// Convert scalar operands to a vector that matches the 6682 /// condition in length. 6683 /// 6684 /// Used when handling the OpenCL conditional operator where the 6685 /// condition is a vector while the other operands are scalar. 6686 /// 6687 /// We first compute the "result type" for the scalar operands 6688 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 6689 /// into a vector of that type where the length matches the condition 6690 /// vector type. s6.11.6 requires that the element types of the result 6691 /// and the condition must have the same number of bits. 6692 static QualType 6693 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 6694 QualType CondTy, SourceLocation QuestionLoc) { 6695 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 6696 if (ResTy.isNull()) return QualType(); 6697 6698 const VectorType *CV = CondTy->getAs<VectorType>(); 6699 assert(CV); 6700 6701 // Determine the vector result type 6702 unsigned NumElements = CV->getNumElements(); 6703 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 6704 6705 // Ensure that all types have the same number of bits 6706 if (S.Context.getTypeSize(CV->getElementType()) 6707 != S.Context.getTypeSize(ResTy)) { 6708 // Since VectorTy is created internally, it does not pretty print 6709 // with an OpenCL name. Instead, we just print a description. 6710 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 6711 SmallString<64> Str; 6712 llvm::raw_svector_ostream OS(Str); 6713 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 6714 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6715 << CondTy << OS.str(); 6716 return QualType(); 6717 } 6718 6719 // Convert operands to the vector result type 6720 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 6721 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 6722 6723 return VectorTy; 6724 } 6725 6726 /// Return false if this is a valid OpenCL condition vector 6727 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 6728 SourceLocation QuestionLoc) { 6729 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 6730 // integral type. 6731 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 6732 assert(CondTy); 6733 QualType EleTy = CondTy->getElementType(); 6734 if (EleTy->isIntegerType()) return false; 6735 6736 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6737 << Cond->getType() << Cond->getSourceRange(); 6738 return true; 6739 } 6740 6741 /// Return false if the vector condition type and the vector 6742 /// result type are compatible. 6743 /// 6744 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 6745 /// number of elements, and their element types have the same number 6746 /// of bits. 6747 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 6748 SourceLocation QuestionLoc) { 6749 const VectorType *CV = CondTy->getAs<VectorType>(); 6750 const VectorType *RV = VecResTy->getAs<VectorType>(); 6751 assert(CV && RV); 6752 6753 if (CV->getNumElements() != RV->getNumElements()) { 6754 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 6755 << CondTy << VecResTy; 6756 return true; 6757 } 6758 6759 QualType CVE = CV->getElementType(); 6760 QualType RVE = RV->getElementType(); 6761 6762 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 6763 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6764 << CondTy << VecResTy; 6765 return true; 6766 } 6767 6768 return false; 6769 } 6770 6771 /// Return the resulting type for the conditional operator in 6772 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 6773 /// s6.3.i) when the condition is a vector type. 6774 static QualType 6775 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 6776 ExprResult &LHS, ExprResult &RHS, 6777 SourceLocation QuestionLoc) { 6778 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 6779 if (Cond.isInvalid()) 6780 return QualType(); 6781 QualType CondTy = Cond.get()->getType(); 6782 6783 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 6784 return QualType(); 6785 6786 // If either operand is a vector then find the vector type of the 6787 // result as specified in OpenCL v1.1 s6.3.i. 6788 if (LHS.get()->getType()->isVectorType() || 6789 RHS.get()->getType()->isVectorType()) { 6790 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 6791 /*isCompAssign*/false, 6792 /*AllowBothBool*/true, 6793 /*AllowBoolConversions*/false); 6794 if (VecResTy.isNull()) return QualType(); 6795 // The result type must match the condition type as specified in 6796 // OpenCL v1.1 s6.11.6. 6797 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 6798 return QualType(); 6799 return VecResTy; 6800 } 6801 6802 // Both operands are scalar. 6803 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 6804 } 6805 6806 /// Return true if the Expr is block type 6807 static bool checkBlockType(Sema &S, const Expr *E) { 6808 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 6809 QualType Ty = CE->getCallee()->getType(); 6810 if (Ty->isBlockPointerType()) { 6811 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 6812 return true; 6813 } 6814 } 6815 return false; 6816 } 6817 6818 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 6819 /// In that case, LHS = cond. 6820 /// C99 6.5.15 6821 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 6822 ExprResult &RHS, ExprValueKind &VK, 6823 ExprObjectKind &OK, 6824 SourceLocation QuestionLoc) { 6825 6826 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 6827 if (!LHSResult.isUsable()) return QualType(); 6828 LHS = LHSResult; 6829 6830 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 6831 if (!RHSResult.isUsable()) return QualType(); 6832 RHS = RHSResult; 6833 6834 // C++ is sufficiently different to merit its own checker. 6835 if (getLangOpts().CPlusPlus) 6836 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 6837 6838 VK = VK_RValue; 6839 OK = OK_Ordinary; 6840 6841 // The OpenCL operator with a vector condition is sufficiently 6842 // different to merit its own checker. 6843 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 6844 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 6845 6846 // First, check the condition. 6847 Cond = UsualUnaryConversions(Cond.get()); 6848 if (Cond.isInvalid()) 6849 return QualType(); 6850 if (checkCondition(*this, Cond.get(), QuestionLoc)) 6851 return QualType(); 6852 6853 // Now check the two expressions. 6854 if (LHS.get()->getType()->isVectorType() || 6855 RHS.get()->getType()->isVectorType()) 6856 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 6857 /*AllowBothBool*/true, 6858 /*AllowBoolConversions*/false); 6859 6860 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 6861 if (LHS.isInvalid() || RHS.isInvalid()) 6862 return QualType(); 6863 6864 QualType LHSTy = LHS.get()->getType(); 6865 QualType RHSTy = RHS.get()->getType(); 6866 6867 // Diagnose attempts to convert between __float128 and long double where 6868 // such conversions currently can't be handled. 6869 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 6870 Diag(QuestionLoc, 6871 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 6872 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6873 return QualType(); 6874 } 6875 6876 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 6877 // selection operator (?:). 6878 if (getLangOpts().OpenCL && 6879 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 6880 return QualType(); 6881 } 6882 6883 // If both operands have arithmetic type, do the usual arithmetic conversions 6884 // to find a common type: C99 6.5.15p3,5. 6885 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 6886 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 6887 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 6888 6889 return ResTy; 6890 } 6891 6892 // If both operands are the same structure or union type, the result is that 6893 // type. 6894 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 6895 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 6896 if (LHSRT->getDecl() == RHSRT->getDecl()) 6897 // "If both the operands have structure or union type, the result has 6898 // that type." This implies that CV qualifiers are dropped. 6899 return LHSTy.getUnqualifiedType(); 6900 // FIXME: Type of conditional expression must be complete in C mode. 6901 } 6902 6903 // C99 6.5.15p5: "If both operands have void type, the result has void type." 6904 // The following || allows only one side to be void (a GCC-ism). 6905 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 6906 return checkConditionalVoidType(*this, LHS, RHS); 6907 } 6908 6909 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 6910 // the type of the other operand." 6911 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 6912 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 6913 6914 // All objective-c pointer type analysis is done here. 6915 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 6916 QuestionLoc); 6917 if (LHS.isInvalid() || RHS.isInvalid()) 6918 return QualType(); 6919 if (!compositeType.isNull()) 6920 return compositeType; 6921 6922 6923 // Handle block pointer types. 6924 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 6925 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 6926 QuestionLoc); 6927 6928 // Check constraints for C object pointers types (C99 6.5.15p3,6). 6929 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 6930 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 6931 QuestionLoc); 6932 6933 // GCC compatibility: soften pointer/integer mismatch. Note that 6934 // null pointers have been filtered out by this point. 6935 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 6936 /*isIntFirstExpr=*/true)) 6937 return RHSTy; 6938 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 6939 /*isIntFirstExpr=*/false)) 6940 return LHSTy; 6941 6942 // Emit a better diagnostic if one of the expressions is a null pointer 6943 // constant and the other is not a pointer type. In this case, the user most 6944 // likely forgot to take the address of the other expression. 6945 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 6946 return QualType(); 6947 6948 // Otherwise, the operands are not compatible. 6949 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 6950 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6951 << RHS.get()->getSourceRange(); 6952 return QualType(); 6953 } 6954 6955 /// FindCompositeObjCPointerType - Helper method to find composite type of 6956 /// two objective-c pointer types of the two input expressions. 6957 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 6958 SourceLocation QuestionLoc) { 6959 QualType LHSTy = LHS.get()->getType(); 6960 QualType RHSTy = RHS.get()->getType(); 6961 6962 // Handle things like Class and struct objc_class*. Here we case the result 6963 // to the pseudo-builtin, because that will be implicitly cast back to the 6964 // redefinition type if an attempt is made to access its fields. 6965 if (LHSTy->isObjCClassType() && 6966 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 6967 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6968 return LHSTy; 6969 } 6970 if (RHSTy->isObjCClassType() && 6971 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 6972 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6973 return RHSTy; 6974 } 6975 // And the same for struct objc_object* / id 6976 if (LHSTy->isObjCIdType() && 6977 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 6978 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6979 return LHSTy; 6980 } 6981 if (RHSTy->isObjCIdType() && 6982 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 6983 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6984 return RHSTy; 6985 } 6986 // And the same for struct objc_selector* / SEL 6987 if (Context.isObjCSelType(LHSTy) && 6988 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 6989 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 6990 return LHSTy; 6991 } 6992 if (Context.isObjCSelType(RHSTy) && 6993 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 6994 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 6995 return RHSTy; 6996 } 6997 // Check constraints for Objective-C object pointers types. 6998 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 6999 7000 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 7001 // Two identical object pointer types are always compatible. 7002 return LHSTy; 7003 } 7004 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 7005 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 7006 QualType compositeType = LHSTy; 7007 7008 // If both operands are interfaces and either operand can be 7009 // assigned to the other, use that type as the composite 7010 // type. This allows 7011 // xxx ? (A*) a : (B*) b 7012 // where B is a subclass of A. 7013 // 7014 // Additionally, as for assignment, if either type is 'id' 7015 // allow silent coercion. Finally, if the types are 7016 // incompatible then make sure to use 'id' as the composite 7017 // type so the result is acceptable for sending messages to. 7018 7019 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 7020 // It could return the composite type. 7021 if (!(compositeType = 7022 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 7023 // Nothing more to do. 7024 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 7025 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 7026 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 7027 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 7028 } else if ((LHSTy->isObjCQualifiedIdType() || 7029 RHSTy->isObjCQualifiedIdType()) && 7030 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 7031 // Need to handle "id<xx>" explicitly. 7032 // GCC allows qualified id and any Objective-C type to devolve to 7033 // id. Currently localizing to here until clear this should be 7034 // part of ObjCQualifiedIdTypesAreCompatible. 7035 compositeType = Context.getObjCIdType(); 7036 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 7037 compositeType = Context.getObjCIdType(); 7038 } else { 7039 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 7040 << LHSTy << RHSTy 7041 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7042 QualType incompatTy = Context.getObjCIdType(); 7043 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 7044 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 7045 return incompatTy; 7046 } 7047 // The object pointer types are compatible. 7048 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 7049 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 7050 return compositeType; 7051 } 7052 // Check Objective-C object pointer types and 'void *' 7053 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 7054 if (getLangOpts().ObjCAutoRefCount) { 7055 // ARC forbids the implicit conversion of object pointers to 'void *', 7056 // so these types are not compatible. 7057 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7058 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7059 LHS = RHS = true; 7060 return QualType(); 7061 } 7062 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 7063 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 7064 QualType destPointee 7065 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7066 QualType destType = Context.getPointerType(destPointee); 7067 // Add qualifiers if necessary. 7068 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7069 // Promote to void*. 7070 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7071 return destType; 7072 } 7073 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 7074 if (getLangOpts().ObjCAutoRefCount) { 7075 // ARC forbids the implicit conversion of object pointers to 'void *', 7076 // so these types are not compatible. 7077 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7078 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7079 LHS = RHS = true; 7080 return QualType(); 7081 } 7082 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 7083 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 7084 QualType destPointee 7085 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7086 QualType destType = Context.getPointerType(destPointee); 7087 // Add qualifiers if necessary. 7088 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7089 // Promote to void*. 7090 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7091 return destType; 7092 } 7093 return QualType(); 7094 } 7095 7096 /// SuggestParentheses - Emit a note with a fixit hint that wraps 7097 /// ParenRange in parentheses. 7098 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 7099 const PartialDiagnostic &Note, 7100 SourceRange ParenRange) { 7101 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 7102 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 7103 EndLoc.isValid()) { 7104 Self.Diag(Loc, Note) 7105 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 7106 << FixItHint::CreateInsertion(EndLoc, ")"); 7107 } else { 7108 // We can't display the parentheses, so just show the bare note. 7109 Self.Diag(Loc, Note) << ParenRange; 7110 } 7111 } 7112 7113 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 7114 return BinaryOperator::isAdditiveOp(Opc) || 7115 BinaryOperator::isMultiplicativeOp(Opc) || 7116 BinaryOperator::isShiftOp(Opc); 7117 } 7118 7119 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 7120 /// expression, either using a built-in or overloaded operator, 7121 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 7122 /// expression. 7123 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 7124 Expr **RHSExprs) { 7125 // Don't strip parenthesis: we should not warn if E is in parenthesis. 7126 E = E->IgnoreImpCasts(); 7127 E = E->IgnoreConversionOperator(); 7128 E = E->IgnoreImpCasts(); 7129 7130 // Built-in binary operator. 7131 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 7132 if (IsArithmeticOp(OP->getOpcode())) { 7133 *Opcode = OP->getOpcode(); 7134 *RHSExprs = OP->getRHS(); 7135 return true; 7136 } 7137 } 7138 7139 // Overloaded operator. 7140 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 7141 if (Call->getNumArgs() != 2) 7142 return false; 7143 7144 // Make sure this is really a binary operator that is safe to pass into 7145 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 7146 OverloadedOperatorKind OO = Call->getOperator(); 7147 if (OO < OO_Plus || OO > OO_Arrow || 7148 OO == OO_PlusPlus || OO == OO_MinusMinus) 7149 return false; 7150 7151 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 7152 if (IsArithmeticOp(OpKind)) { 7153 *Opcode = OpKind; 7154 *RHSExprs = Call->getArg(1); 7155 return true; 7156 } 7157 } 7158 7159 return false; 7160 } 7161 7162 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 7163 /// or is a logical expression such as (x==y) which has int type, but is 7164 /// commonly interpreted as boolean. 7165 static bool ExprLooksBoolean(Expr *E) { 7166 E = E->IgnoreParenImpCasts(); 7167 7168 if (E->getType()->isBooleanType()) 7169 return true; 7170 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 7171 return OP->isComparisonOp() || OP->isLogicalOp(); 7172 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 7173 return OP->getOpcode() == UO_LNot; 7174 if (E->getType()->isPointerType()) 7175 return true; 7176 7177 return false; 7178 } 7179 7180 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 7181 /// and binary operator are mixed in a way that suggests the programmer assumed 7182 /// the conditional operator has higher precedence, for example: 7183 /// "int x = a + someBinaryCondition ? 1 : 2". 7184 static void DiagnoseConditionalPrecedence(Sema &Self, 7185 SourceLocation OpLoc, 7186 Expr *Condition, 7187 Expr *LHSExpr, 7188 Expr *RHSExpr) { 7189 BinaryOperatorKind CondOpcode; 7190 Expr *CondRHS; 7191 7192 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 7193 return; 7194 if (!ExprLooksBoolean(CondRHS)) 7195 return; 7196 7197 // The condition is an arithmetic binary expression, with a right- 7198 // hand side that looks boolean, so warn. 7199 7200 Self.Diag(OpLoc, diag::warn_precedence_conditional) 7201 << Condition->getSourceRange() 7202 << BinaryOperator::getOpcodeStr(CondOpcode); 7203 7204 SuggestParentheses(Self, OpLoc, 7205 Self.PDiag(diag::note_precedence_silence) 7206 << BinaryOperator::getOpcodeStr(CondOpcode), 7207 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 7208 7209 SuggestParentheses(Self, OpLoc, 7210 Self.PDiag(diag::note_precedence_conditional_first), 7211 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 7212 } 7213 7214 /// Compute the nullability of a conditional expression. 7215 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 7216 QualType LHSTy, QualType RHSTy, 7217 ASTContext &Ctx) { 7218 if (!ResTy->isAnyPointerType()) 7219 return ResTy; 7220 7221 auto GetNullability = [&Ctx](QualType Ty) { 7222 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 7223 if (Kind) 7224 return *Kind; 7225 return NullabilityKind::Unspecified; 7226 }; 7227 7228 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 7229 NullabilityKind MergedKind; 7230 7231 // Compute nullability of a binary conditional expression. 7232 if (IsBin) { 7233 if (LHSKind == NullabilityKind::NonNull) 7234 MergedKind = NullabilityKind::NonNull; 7235 else 7236 MergedKind = RHSKind; 7237 // Compute nullability of a normal conditional expression. 7238 } else { 7239 if (LHSKind == NullabilityKind::Nullable || 7240 RHSKind == NullabilityKind::Nullable) 7241 MergedKind = NullabilityKind::Nullable; 7242 else if (LHSKind == NullabilityKind::NonNull) 7243 MergedKind = RHSKind; 7244 else if (RHSKind == NullabilityKind::NonNull) 7245 MergedKind = LHSKind; 7246 else 7247 MergedKind = NullabilityKind::Unspecified; 7248 } 7249 7250 // Return if ResTy already has the correct nullability. 7251 if (GetNullability(ResTy) == MergedKind) 7252 return ResTy; 7253 7254 // Strip all nullability from ResTy. 7255 while (ResTy->getNullability(Ctx)) 7256 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 7257 7258 // Create a new AttributedType with the new nullability kind. 7259 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 7260 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 7261 } 7262 7263 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7264 /// in the case of a the GNU conditional expr extension. 7265 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7266 SourceLocation ColonLoc, 7267 Expr *CondExpr, Expr *LHSExpr, 7268 Expr *RHSExpr) { 7269 if (!getLangOpts().CPlusPlus) { 7270 // C cannot handle TypoExpr nodes in the condition because it 7271 // doesn't handle dependent types properly, so make sure any TypoExprs have 7272 // been dealt with before checking the operands. 7273 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7274 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7275 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7276 7277 if (!CondResult.isUsable()) 7278 return ExprError(); 7279 7280 if (LHSExpr) { 7281 if (!LHSResult.isUsable()) 7282 return ExprError(); 7283 } 7284 7285 if (!RHSResult.isUsable()) 7286 return ExprError(); 7287 7288 CondExpr = CondResult.get(); 7289 LHSExpr = LHSResult.get(); 7290 RHSExpr = RHSResult.get(); 7291 } 7292 7293 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7294 // was the condition. 7295 OpaqueValueExpr *opaqueValue = nullptr; 7296 Expr *commonExpr = nullptr; 7297 if (!LHSExpr) { 7298 commonExpr = CondExpr; 7299 // Lower out placeholder types first. This is important so that we don't 7300 // try to capture a placeholder. This happens in few cases in C++; such 7301 // as Objective-C++'s dictionary subscripting syntax. 7302 if (commonExpr->hasPlaceholderType()) { 7303 ExprResult result = CheckPlaceholderExpr(commonExpr); 7304 if (!result.isUsable()) return ExprError(); 7305 commonExpr = result.get(); 7306 } 7307 // We usually want to apply unary conversions *before* saving, except 7308 // in the special case of a C++ l-value conditional. 7309 if (!(getLangOpts().CPlusPlus 7310 && !commonExpr->isTypeDependent() 7311 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7312 && commonExpr->isGLValue() 7313 && commonExpr->isOrdinaryOrBitFieldObject() 7314 && RHSExpr->isOrdinaryOrBitFieldObject() 7315 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7316 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7317 if (commonRes.isInvalid()) 7318 return ExprError(); 7319 commonExpr = commonRes.get(); 7320 } 7321 7322 // If the common expression is a class or array prvalue, materialize it 7323 // so that we can safely refer to it multiple times. 7324 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 7325 commonExpr->getType()->isArrayType())) { 7326 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 7327 if (MatExpr.isInvalid()) 7328 return ExprError(); 7329 commonExpr = MatExpr.get(); 7330 } 7331 7332 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7333 commonExpr->getType(), 7334 commonExpr->getValueKind(), 7335 commonExpr->getObjectKind(), 7336 commonExpr); 7337 LHSExpr = CondExpr = opaqueValue; 7338 } 7339 7340 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 7341 ExprValueKind VK = VK_RValue; 7342 ExprObjectKind OK = OK_Ordinary; 7343 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7344 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7345 VK, OK, QuestionLoc); 7346 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7347 RHS.isInvalid()) 7348 return ExprError(); 7349 7350 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7351 RHS.get()); 7352 7353 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 7354 7355 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 7356 Context); 7357 7358 if (!commonExpr) 7359 return new (Context) 7360 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 7361 RHS.get(), result, VK, OK); 7362 7363 return new (Context) BinaryConditionalOperator( 7364 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 7365 ColonLoc, result, VK, OK); 7366 } 7367 7368 // checkPointerTypesForAssignment - This is a very tricky routine (despite 7369 // being closely modeled after the C99 spec:-). The odd characteristic of this 7370 // routine is it effectively iqnores the qualifiers on the top level pointee. 7371 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 7372 // FIXME: add a couple examples in this comment. 7373 static Sema::AssignConvertType 7374 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 7375 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7376 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7377 7378 // get the "pointed to" type (ignoring qualifiers at the top level) 7379 const Type *lhptee, *rhptee; 7380 Qualifiers lhq, rhq; 7381 std::tie(lhptee, lhq) = 7382 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 7383 std::tie(rhptee, rhq) = 7384 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 7385 7386 Sema::AssignConvertType ConvTy = Sema::Compatible; 7387 7388 // C99 6.5.16.1p1: This following citation is common to constraints 7389 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 7390 // qualifiers of the type *pointed to* by the right; 7391 7392 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 7393 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 7394 lhq.compatiblyIncludesObjCLifetime(rhq)) { 7395 // Ignore lifetime for further calculation. 7396 lhq.removeObjCLifetime(); 7397 rhq.removeObjCLifetime(); 7398 } 7399 7400 if (!lhq.compatiblyIncludes(rhq)) { 7401 // Treat address-space mismatches as fatal. TODO: address subspaces 7402 if (!lhq.isAddressSpaceSupersetOf(rhq)) 7403 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7404 7405 // It's okay to add or remove GC or lifetime qualifiers when converting to 7406 // and from void*. 7407 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 7408 .compatiblyIncludes( 7409 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 7410 && (lhptee->isVoidType() || rhptee->isVoidType())) 7411 ; // keep old 7412 7413 // Treat lifetime mismatches as fatal. 7414 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 7415 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7416 7417 // For GCC/MS compatibility, other qualifier mismatches are treated 7418 // as still compatible in C. 7419 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7420 } 7421 7422 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 7423 // incomplete type and the other is a pointer to a qualified or unqualified 7424 // version of void... 7425 if (lhptee->isVoidType()) { 7426 if (rhptee->isIncompleteOrObjectType()) 7427 return ConvTy; 7428 7429 // As an extension, we allow cast to/from void* to function pointer. 7430 assert(rhptee->isFunctionType()); 7431 return Sema::FunctionVoidPointer; 7432 } 7433 7434 if (rhptee->isVoidType()) { 7435 if (lhptee->isIncompleteOrObjectType()) 7436 return ConvTy; 7437 7438 // As an extension, we allow cast to/from void* to function pointer. 7439 assert(lhptee->isFunctionType()); 7440 return Sema::FunctionVoidPointer; 7441 } 7442 7443 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7444 // unqualified versions of compatible types, ... 7445 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7446 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7447 // Check if the pointee types are compatible ignoring the sign. 7448 // We explicitly check for char so that we catch "char" vs 7449 // "unsigned char" on systems where "char" is unsigned. 7450 if (lhptee->isCharType()) 7451 ltrans = S.Context.UnsignedCharTy; 7452 else if (lhptee->hasSignedIntegerRepresentation()) 7453 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7454 7455 if (rhptee->isCharType()) 7456 rtrans = S.Context.UnsignedCharTy; 7457 else if (rhptee->hasSignedIntegerRepresentation()) 7458 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 7459 7460 if (ltrans == rtrans) { 7461 // Types are compatible ignoring the sign. Qualifier incompatibility 7462 // takes priority over sign incompatibility because the sign 7463 // warning can be disabled. 7464 if (ConvTy != Sema::Compatible) 7465 return ConvTy; 7466 7467 return Sema::IncompatiblePointerSign; 7468 } 7469 7470 // If we are a multi-level pointer, it's possible that our issue is simply 7471 // one of qualification - e.g. char ** -> const char ** is not allowed. If 7472 // the eventual target type is the same and the pointers have the same 7473 // level of indirection, this must be the issue. 7474 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 7475 do { 7476 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 7477 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 7478 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 7479 7480 if (lhptee == rhptee) 7481 return Sema::IncompatibleNestedPointerQualifiers; 7482 } 7483 7484 // General pointer incompatibility takes priority over qualifiers. 7485 return Sema::IncompatiblePointer; 7486 } 7487 if (!S.getLangOpts().CPlusPlus && 7488 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 7489 return Sema::IncompatiblePointer; 7490 return ConvTy; 7491 } 7492 7493 /// checkBlockPointerTypesForAssignment - This routine determines whether two 7494 /// block pointer types are compatible or whether a block and normal pointer 7495 /// are compatible. It is more restrict than comparing two function pointer 7496 // types. 7497 static Sema::AssignConvertType 7498 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 7499 QualType RHSType) { 7500 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7501 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7502 7503 QualType lhptee, rhptee; 7504 7505 // get the "pointed to" type (ignoring qualifiers at the top level) 7506 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 7507 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 7508 7509 // In C++, the types have to match exactly. 7510 if (S.getLangOpts().CPlusPlus) 7511 return Sema::IncompatibleBlockPointer; 7512 7513 Sema::AssignConvertType ConvTy = Sema::Compatible; 7514 7515 // For blocks we enforce that qualifiers are identical. 7516 Qualifiers LQuals = lhptee.getLocalQualifiers(); 7517 Qualifiers RQuals = rhptee.getLocalQualifiers(); 7518 if (S.getLangOpts().OpenCL) { 7519 LQuals.removeAddressSpace(); 7520 RQuals.removeAddressSpace(); 7521 } 7522 if (LQuals != RQuals) 7523 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7524 7525 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 7526 // assignment. 7527 // The current behavior is similar to C++ lambdas. A block might be 7528 // assigned to a variable iff its return type and parameters are compatible 7529 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 7530 // an assignment. Presumably it should behave in way that a function pointer 7531 // assignment does in C, so for each parameter and return type: 7532 // * CVR and address space of LHS should be a superset of CVR and address 7533 // space of RHS. 7534 // * unqualified types should be compatible. 7535 if (S.getLangOpts().OpenCL) { 7536 if (!S.Context.typesAreBlockPointerCompatible( 7537 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 7538 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 7539 return Sema::IncompatibleBlockPointer; 7540 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 7541 return Sema::IncompatibleBlockPointer; 7542 7543 return ConvTy; 7544 } 7545 7546 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 7547 /// for assignment compatibility. 7548 static Sema::AssignConvertType 7549 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 7550 QualType RHSType) { 7551 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 7552 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 7553 7554 if (LHSType->isObjCBuiltinType()) { 7555 // Class is not compatible with ObjC object pointers. 7556 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 7557 !RHSType->isObjCQualifiedClassType()) 7558 return Sema::IncompatiblePointer; 7559 return Sema::Compatible; 7560 } 7561 if (RHSType->isObjCBuiltinType()) { 7562 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 7563 !LHSType->isObjCQualifiedClassType()) 7564 return Sema::IncompatiblePointer; 7565 return Sema::Compatible; 7566 } 7567 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7568 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7569 7570 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 7571 // make an exception for id<P> 7572 !LHSType->isObjCQualifiedIdType()) 7573 return Sema::CompatiblePointerDiscardsQualifiers; 7574 7575 if (S.Context.typesAreCompatible(LHSType, RHSType)) 7576 return Sema::Compatible; 7577 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 7578 return Sema::IncompatibleObjCQualifiedId; 7579 return Sema::IncompatiblePointer; 7580 } 7581 7582 Sema::AssignConvertType 7583 Sema::CheckAssignmentConstraints(SourceLocation Loc, 7584 QualType LHSType, QualType RHSType) { 7585 // Fake up an opaque expression. We don't actually care about what 7586 // cast operations are required, so if CheckAssignmentConstraints 7587 // adds casts to this they'll be wasted, but fortunately that doesn't 7588 // usually happen on valid code. 7589 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 7590 ExprResult RHSPtr = &RHSExpr; 7591 CastKind K; 7592 7593 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 7594 } 7595 7596 /// This helper function returns true if QT is a vector type that has element 7597 /// type ElementType. 7598 static bool isVector(QualType QT, QualType ElementType) { 7599 if (const VectorType *VT = QT->getAs<VectorType>()) 7600 return VT->getElementType() == ElementType; 7601 return false; 7602 } 7603 7604 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 7605 /// has code to accommodate several GCC extensions when type checking 7606 /// pointers. Here are some objectionable examples that GCC considers warnings: 7607 /// 7608 /// int a, *pint; 7609 /// short *pshort; 7610 /// struct foo *pfoo; 7611 /// 7612 /// pint = pshort; // warning: assignment from incompatible pointer type 7613 /// a = pint; // warning: assignment makes integer from pointer without a cast 7614 /// pint = a; // warning: assignment makes pointer from integer without a cast 7615 /// pint = pfoo; // warning: assignment from incompatible pointer type 7616 /// 7617 /// As a result, the code for dealing with pointers is more complex than the 7618 /// C99 spec dictates. 7619 /// 7620 /// Sets 'Kind' for any result kind except Incompatible. 7621 Sema::AssignConvertType 7622 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 7623 CastKind &Kind, bool ConvertRHS) { 7624 QualType RHSType = RHS.get()->getType(); 7625 QualType OrigLHSType = LHSType; 7626 7627 // Get canonical types. We're not formatting these types, just comparing 7628 // them. 7629 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 7630 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 7631 7632 // Common case: no conversion required. 7633 if (LHSType == RHSType) { 7634 Kind = CK_NoOp; 7635 return Compatible; 7636 } 7637 7638 // If we have an atomic type, try a non-atomic assignment, then just add an 7639 // atomic qualification step. 7640 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 7641 Sema::AssignConvertType result = 7642 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 7643 if (result != Compatible) 7644 return result; 7645 if (Kind != CK_NoOp && ConvertRHS) 7646 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 7647 Kind = CK_NonAtomicToAtomic; 7648 return Compatible; 7649 } 7650 7651 // If the left-hand side is a reference type, then we are in a 7652 // (rare!) case where we've allowed the use of references in C, 7653 // e.g., as a parameter type in a built-in function. In this case, 7654 // just make sure that the type referenced is compatible with the 7655 // right-hand side type. The caller is responsible for adjusting 7656 // LHSType so that the resulting expression does not have reference 7657 // type. 7658 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 7659 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 7660 Kind = CK_LValueBitCast; 7661 return Compatible; 7662 } 7663 return Incompatible; 7664 } 7665 7666 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 7667 // to the same ExtVector type. 7668 if (LHSType->isExtVectorType()) { 7669 if (RHSType->isExtVectorType()) 7670 return Incompatible; 7671 if (RHSType->isArithmeticType()) { 7672 // CK_VectorSplat does T -> vector T, so first cast to the element type. 7673 if (ConvertRHS) 7674 RHS = prepareVectorSplat(LHSType, RHS.get()); 7675 Kind = CK_VectorSplat; 7676 return Compatible; 7677 } 7678 } 7679 7680 // Conversions to or from vector type. 7681 if (LHSType->isVectorType() || RHSType->isVectorType()) { 7682 if (LHSType->isVectorType() && RHSType->isVectorType()) { 7683 // Allow assignments of an AltiVec vector type to an equivalent GCC 7684 // vector type and vice versa 7685 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7686 Kind = CK_BitCast; 7687 return Compatible; 7688 } 7689 7690 // If we are allowing lax vector conversions, and LHS and RHS are both 7691 // vectors, the total size only needs to be the same. This is a bitcast; 7692 // no bits are changed but the result type is different. 7693 if (isLaxVectorConversion(RHSType, LHSType)) { 7694 Kind = CK_BitCast; 7695 return IncompatibleVectors; 7696 } 7697 } 7698 7699 // When the RHS comes from another lax conversion (e.g. binops between 7700 // scalars and vectors) the result is canonicalized as a vector. When the 7701 // LHS is also a vector, the lax is allowed by the condition above. Handle 7702 // the case where LHS is a scalar. 7703 if (LHSType->isScalarType()) { 7704 const VectorType *VecType = RHSType->getAs<VectorType>(); 7705 if (VecType && VecType->getNumElements() == 1 && 7706 isLaxVectorConversion(RHSType, LHSType)) { 7707 ExprResult *VecExpr = &RHS; 7708 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 7709 Kind = CK_BitCast; 7710 return Compatible; 7711 } 7712 } 7713 7714 return Incompatible; 7715 } 7716 7717 // Diagnose attempts to convert between __float128 and long double where 7718 // such conversions currently can't be handled. 7719 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 7720 return Incompatible; 7721 7722 // Disallow assigning a _Complex to a real type in C++ mode since it simply 7723 // discards the imaginary part. 7724 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 7725 !LHSType->getAs<ComplexType>()) 7726 return Incompatible; 7727 7728 // Arithmetic conversions. 7729 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 7730 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 7731 if (ConvertRHS) 7732 Kind = PrepareScalarCast(RHS, LHSType); 7733 return Compatible; 7734 } 7735 7736 // Conversions to normal pointers. 7737 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 7738 // U* -> T* 7739 if (isa<PointerType>(RHSType)) { 7740 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7741 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 7742 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7743 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 7744 } 7745 7746 // int -> T* 7747 if (RHSType->isIntegerType()) { 7748 Kind = CK_IntegralToPointer; // FIXME: null? 7749 return IntToPointer; 7750 } 7751 7752 // C pointers are not compatible with ObjC object pointers, 7753 // with two exceptions: 7754 if (isa<ObjCObjectPointerType>(RHSType)) { 7755 // - conversions to void* 7756 if (LHSPointer->getPointeeType()->isVoidType()) { 7757 Kind = CK_BitCast; 7758 return Compatible; 7759 } 7760 7761 // - conversions from 'Class' to the redefinition type 7762 if (RHSType->isObjCClassType() && 7763 Context.hasSameType(LHSType, 7764 Context.getObjCClassRedefinitionType())) { 7765 Kind = CK_BitCast; 7766 return Compatible; 7767 } 7768 7769 Kind = CK_BitCast; 7770 return IncompatiblePointer; 7771 } 7772 7773 // U^ -> void* 7774 if (RHSType->getAs<BlockPointerType>()) { 7775 if (LHSPointer->getPointeeType()->isVoidType()) { 7776 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7777 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 7778 ->getPointeeType() 7779 .getAddressSpace(); 7780 Kind = 7781 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7782 return Compatible; 7783 } 7784 } 7785 7786 return Incompatible; 7787 } 7788 7789 // Conversions to block pointers. 7790 if (isa<BlockPointerType>(LHSType)) { 7791 // U^ -> T^ 7792 if (RHSType->isBlockPointerType()) { 7793 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 7794 ->getPointeeType() 7795 .getAddressSpace(); 7796 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 7797 ->getPointeeType() 7798 .getAddressSpace(); 7799 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7800 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 7801 } 7802 7803 // int or null -> T^ 7804 if (RHSType->isIntegerType()) { 7805 Kind = CK_IntegralToPointer; // FIXME: null 7806 return IntToBlockPointer; 7807 } 7808 7809 // id -> T^ 7810 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 7811 Kind = CK_AnyPointerToBlockPointerCast; 7812 return Compatible; 7813 } 7814 7815 // void* -> T^ 7816 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 7817 if (RHSPT->getPointeeType()->isVoidType()) { 7818 Kind = CK_AnyPointerToBlockPointerCast; 7819 return Compatible; 7820 } 7821 7822 return Incompatible; 7823 } 7824 7825 // Conversions to Objective-C pointers. 7826 if (isa<ObjCObjectPointerType>(LHSType)) { 7827 // A* -> B* 7828 if (RHSType->isObjCObjectPointerType()) { 7829 Kind = CK_BitCast; 7830 Sema::AssignConvertType result = 7831 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 7832 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 7833 result == Compatible && 7834 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 7835 result = IncompatibleObjCWeakRef; 7836 return result; 7837 } 7838 7839 // int or null -> A* 7840 if (RHSType->isIntegerType()) { 7841 Kind = CK_IntegralToPointer; // FIXME: null 7842 return IntToPointer; 7843 } 7844 7845 // In general, C pointers are not compatible with ObjC object pointers, 7846 // with two exceptions: 7847 if (isa<PointerType>(RHSType)) { 7848 Kind = CK_CPointerToObjCPointerCast; 7849 7850 // - conversions from 'void*' 7851 if (RHSType->isVoidPointerType()) { 7852 return Compatible; 7853 } 7854 7855 // - conversions to 'Class' from its redefinition type 7856 if (LHSType->isObjCClassType() && 7857 Context.hasSameType(RHSType, 7858 Context.getObjCClassRedefinitionType())) { 7859 return Compatible; 7860 } 7861 7862 return IncompatiblePointer; 7863 } 7864 7865 // Only under strict condition T^ is compatible with an Objective-C pointer. 7866 if (RHSType->isBlockPointerType() && 7867 LHSType->isBlockCompatibleObjCPointerType(Context)) { 7868 if (ConvertRHS) 7869 maybeExtendBlockObject(RHS); 7870 Kind = CK_BlockPointerToObjCPointerCast; 7871 return Compatible; 7872 } 7873 7874 return Incompatible; 7875 } 7876 7877 // Conversions from pointers that are not covered by the above. 7878 if (isa<PointerType>(RHSType)) { 7879 // T* -> _Bool 7880 if (LHSType == Context.BoolTy) { 7881 Kind = CK_PointerToBoolean; 7882 return Compatible; 7883 } 7884 7885 // T* -> int 7886 if (LHSType->isIntegerType()) { 7887 Kind = CK_PointerToIntegral; 7888 return PointerToInt; 7889 } 7890 7891 return Incompatible; 7892 } 7893 7894 // Conversions from Objective-C pointers that are not covered by the above. 7895 if (isa<ObjCObjectPointerType>(RHSType)) { 7896 // T* -> _Bool 7897 if (LHSType == Context.BoolTy) { 7898 Kind = CK_PointerToBoolean; 7899 return Compatible; 7900 } 7901 7902 // T* -> int 7903 if (LHSType->isIntegerType()) { 7904 Kind = CK_PointerToIntegral; 7905 return PointerToInt; 7906 } 7907 7908 return Incompatible; 7909 } 7910 7911 // struct A -> struct B 7912 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 7913 if (Context.typesAreCompatible(LHSType, RHSType)) { 7914 Kind = CK_NoOp; 7915 return Compatible; 7916 } 7917 } 7918 7919 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 7920 Kind = CK_IntToOCLSampler; 7921 return Compatible; 7922 } 7923 7924 return Incompatible; 7925 } 7926 7927 /// Constructs a transparent union from an expression that is 7928 /// used to initialize the transparent union. 7929 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 7930 ExprResult &EResult, QualType UnionType, 7931 FieldDecl *Field) { 7932 // Build an initializer list that designates the appropriate member 7933 // of the transparent union. 7934 Expr *E = EResult.get(); 7935 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 7936 E, SourceLocation()); 7937 Initializer->setType(UnionType); 7938 Initializer->setInitializedFieldInUnion(Field); 7939 7940 // Build a compound literal constructing a value of the transparent 7941 // union type from this initializer list. 7942 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 7943 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 7944 VK_RValue, Initializer, false); 7945 } 7946 7947 Sema::AssignConvertType 7948 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 7949 ExprResult &RHS) { 7950 QualType RHSType = RHS.get()->getType(); 7951 7952 // If the ArgType is a Union type, we want to handle a potential 7953 // transparent_union GCC extension. 7954 const RecordType *UT = ArgType->getAsUnionType(); 7955 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 7956 return Incompatible; 7957 7958 // The field to initialize within the transparent union. 7959 RecordDecl *UD = UT->getDecl(); 7960 FieldDecl *InitField = nullptr; 7961 // It's compatible if the expression matches any of the fields. 7962 for (auto *it : UD->fields()) { 7963 if (it->getType()->isPointerType()) { 7964 // If the transparent union contains a pointer type, we allow: 7965 // 1) void pointer 7966 // 2) null pointer constant 7967 if (RHSType->isPointerType()) 7968 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 7969 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 7970 InitField = it; 7971 break; 7972 } 7973 7974 if (RHS.get()->isNullPointerConstant(Context, 7975 Expr::NPC_ValueDependentIsNull)) { 7976 RHS = ImpCastExprToType(RHS.get(), it->getType(), 7977 CK_NullToPointer); 7978 InitField = it; 7979 break; 7980 } 7981 } 7982 7983 CastKind Kind; 7984 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 7985 == Compatible) { 7986 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 7987 InitField = it; 7988 break; 7989 } 7990 } 7991 7992 if (!InitField) 7993 return Incompatible; 7994 7995 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 7996 return Compatible; 7997 } 7998 7999 Sema::AssignConvertType 8000 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 8001 bool Diagnose, 8002 bool DiagnoseCFAudited, 8003 bool ConvertRHS) { 8004 // We need to be able to tell the caller whether we diagnosed a problem, if 8005 // they ask us to issue diagnostics. 8006 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 8007 8008 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 8009 // we can't avoid *all* modifications at the moment, so we need some somewhere 8010 // to put the updated value. 8011 ExprResult LocalRHS = CallerRHS; 8012 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 8013 8014 if (getLangOpts().CPlusPlus) { 8015 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 8016 // C++ 5.17p3: If the left operand is not of class type, the 8017 // expression is implicitly converted (C++ 4) to the 8018 // cv-unqualified type of the left operand. 8019 QualType RHSType = RHS.get()->getType(); 8020 if (Diagnose) { 8021 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8022 AA_Assigning); 8023 } else { 8024 ImplicitConversionSequence ICS = 8025 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8026 /*SuppressUserConversions=*/false, 8027 /*AllowExplicit=*/false, 8028 /*InOverloadResolution=*/false, 8029 /*CStyle=*/false, 8030 /*AllowObjCWritebackConversion=*/false); 8031 if (ICS.isFailure()) 8032 return Incompatible; 8033 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8034 ICS, AA_Assigning); 8035 } 8036 if (RHS.isInvalid()) 8037 return Incompatible; 8038 Sema::AssignConvertType result = Compatible; 8039 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8040 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 8041 result = IncompatibleObjCWeakRef; 8042 return result; 8043 } 8044 8045 // FIXME: Currently, we fall through and treat C++ classes like C 8046 // structures. 8047 // FIXME: We also fall through for atomics; not sure what should 8048 // happen there, though. 8049 } else if (RHS.get()->getType() == Context.OverloadTy) { 8050 // As a set of extensions to C, we support overloading on functions. These 8051 // functions need to be resolved here. 8052 DeclAccessPair DAP; 8053 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 8054 RHS.get(), LHSType, /*Complain=*/false, DAP)) 8055 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 8056 else 8057 return Incompatible; 8058 } 8059 8060 // C99 6.5.16.1p1: the left operand is a pointer and the right is 8061 // a null pointer constant. 8062 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 8063 LHSType->isBlockPointerType()) && 8064 RHS.get()->isNullPointerConstant(Context, 8065 Expr::NPC_ValueDependentIsNull)) { 8066 if (Diagnose || ConvertRHS) { 8067 CastKind Kind; 8068 CXXCastPath Path; 8069 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 8070 /*IgnoreBaseAccess=*/false, Diagnose); 8071 if (ConvertRHS) 8072 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 8073 } 8074 return Compatible; 8075 } 8076 8077 // This check seems unnatural, however it is necessary to ensure the proper 8078 // conversion of functions/arrays. If the conversion were done for all 8079 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 8080 // expressions that suppress this implicit conversion (&, sizeof). 8081 // 8082 // Suppress this for references: C++ 8.5.3p5. 8083 if (!LHSType->isReferenceType()) { 8084 // FIXME: We potentially allocate here even if ConvertRHS is false. 8085 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 8086 if (RHS.isInvalid()) 8087 return Incompatible; 8088 } 8089 8090 Expr *PRE = RHS.get()->IgnoreParenCasts(); 8091 if (Diagnose && isa<ObjCProtocolExpr>(PRE)) { 8092 ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol(); 8093 if (PDecl && !PDecl->hasDefinition()) { 8094 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl; 8095 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl; 8096 } 8097 } 8098 8099 CastKind Kind; 8100 Sema::AssignConvertType result = 8101 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 8102 8103 // C99 6.5.16.1p2: The value of the right operand is converted to the 8104 // type of the assignment expression. 8105 // CheckAssignmentConstraints allows the left-hand side to be a reference, 8106 // so that we can use references in built-in functions even in C. 8107 // The getNonReferenceType() call makes sure that the resulting expression 8108 // does not have reference type. 8109 if (result != Incompatible && RHS.get()->getType() != LHSType) { 8110 QualType Ty = LHSType.getNonLValueExprType(Context); 8111 Expr *E = RHS.get(); 8112 8113 // Check for various Objective-C errors. If we are not reporting 8114 // diagnostics and just checking for errors, e.g., during overload 8115 // resolution, return Incompatible to indicate the failure. 8116 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8117 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 8118 Diagnose, DiagnoseCFAudited) != ACR_okay) { 8119 if (!Diagnose) 8120 return Incompatible; 8121 } 8122 if (getLangOpts().ObjC1 && 8123 (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType, 8124 E->getType(), E, Diagnose) || 8125 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 8126 if (!Diagnose) 8127 return Incompatible; 8128 // Replace the expression with a corrected version and continue so we 8129 // can find further errors. 8130 RHS = E; 8131 return Compatible; 8132 } 8133 8134 if (ConvertRHS) 8135 RHS = ImpCastExprToType(E, Ty, Kind); 8136 } 8137 return result; 8138 } 8139 8140 namespace { 8141 /// The original operand to an operator, prior to the application of the usual 8142 /// arithmetic conversions and converting the arguments of a builtin operator 8143 /// candidate. 8144 struct OriginalOperand { 8145 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 8146 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 8147 Op = MTE->GetTemporaryExpr(); 8148 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 8149 Op = BTE->getSubExpr(); 8150 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 8151 Orig = ICE->getSubExprAsWritten(); 8152 Conversion = ICE->getConversionFunction(); 8153 } 8154 } 8155 8156 QualType getType() const { return Orig->getType(); } 8157 8158 Expr *Orig; 8159 NamedDecl *Conversion; 8160 }; 8161 } 8162 8163 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 8164 ExprResult &RHS) { 8165 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 8166 8167 Diag(Loc, diag::err_typecheck_invalid_operands) 8168 << OrigLHS.getType() << OrigRHS.getType() 8169 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8170 8171 // If a user-defined conversion was applied to either of the operands prior 8172 // to applying the built-in operator rules, tell the user about it. 8173 if (OrigLHS.Conversion) { 8174 Diag(OrigLHS.Conversion->getLocation(), 8175 diag::note_typecheck_invalid_operands_converted) 8176 << 0 << LHS.get()->getType(); 8177 } 8178 if (OrigRHS.Conversion) { 8179 Diag(OrigRHS.Conversion->getLocation(), 8180 diag::note_typecheck_invalid_operands_converted) 8181 << 1 << RHS.get()->getType(); 8182 } 8183 8184 return QualType(); 8185 } 8186 8187 // Diagnose cases where a scalar was implicitly converted to a vector and 8188 // diagnose the underlying types. Otherwise, diagnose the error 8189 // as invalid vector logical operands for non-C++ cases. 8190 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 8191 ExprResult &RHS) { 8192 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 8193 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 8194 8195 bool LHSNatVec = LHSType->isVectorType(); 8196 bool RHSNatVec = RHSType->isVectorType(); 8197 8198 if (!(LHSNatVec && RHSNatVec)) { 8199 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 8200 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 8201 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8202 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 8203 << Vector->getSourceRange(); 8204 return QualType(); 8205 } 8206 8207 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8208 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 8209 << RHS.get()->getSourceRange(); 8210 8211 return QualType(); 8212 } 8213 8214 /// Try to convert a value of non-vector type to a vector type by converting 8215 /// the type to the element type of the vector and then performing a splat. 8216 /// If the language is OpenCL, we only use conversions that promote scalar 8217 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 8218 /// for float->int. 8219 /// 8220 /// OpenCL V2.0 6.2.6.p2: 8221 /// An error shall occur if any scalar operand type has greater rank 8222 /// than the type of the vector element. 8223 /// 8224 /// \param scalar - if non-null, actually perform the conversions 8225 /// \return true if the operation fails (but without diagnosing the failure) 8226 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 8227 QualType scalarTy, 8228 QualType vectorEltTy, 8229 QualType vectorTy, 8230 unsigned &DiagID) { 8231 // The conversion to apply to the scalar before splatting it, 8232 // if necessary. 8233 CastKind scalarCast = CK_NoOp; 8234 8235 if (vectorEltTy->isIntegralType(S.Context)) { 8236 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 8237 (scalarTy->isIntegerType() && 8238 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 8239 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8240 return true; 8241 } 8242 if (!scalarTy->isIntegralType(S.Context)) 8243 return true; 8244 scalarCast = CK_IntegralCast; 8245 } else if (vectorEltTy->isRealFloatingType()) { 8246 if (scalarTy->isRealFloatingType()) { 8247 if (S.getLangOpts().OpenCL && 8248 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 8249 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8250 return true; 8251 } 8252 scalarCast = CK_FloatingCast; 8253 } 8254 else if (scalarTy->isIntegralType(S.Context)) 8255 scalarCast = CK_IntegralToFloating; 8256 else 8257 return true; 8258 } else { 8259 return true; 8260 } 8261 8262 // Adjust scalar if desired. 8263 if (scalar) { 8264 if (scalarCast != CK_NoOp) 8265 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 8266 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 8267 } 8268 return false; 8269 } 8270 8271 /// Convert vector E to a vector with the same number of elements but different 8272 /// element type. 8273 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 8274 const auto *VecTy = E->getType()->getAs<VectorType>(); 8275 assert(VecTy && "Expression E must be a vector"); 8276 QualType NewVecTy = S.Context.getVectorType(ElementType, 8277 VecTy->getNumElements(), 8278 VecTy->getVectorKind()); 8279 8280 // Look through the implicit cast. Return the subexpression if its type is 8281 // NewVecTy. 8282 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 8283 if (ICE->getSubExpr()->getType() == NewVecTy) 8284 return ICE->getSubExpr(); 8285 8286 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 8287 return S.ImpCastExprToType(E, NewVecTy, Cast); 8288 } 8289 8290 /// Test if a (constant) integer Int can be casted to another integer type 8291 /// IntTy without losing precision. 8292 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 8293 QualType OtherIntTy) { 8294 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8295 8296 // Reject cases where the value of the Int is unknown as that would 8297 // possibly cause truncation, but accept cases where the scalar can be 8298 // demoted without loss of precision. 8299 llvm::APSInt Result; 8300 bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context); 8301 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 8302 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 8303 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 8304 8305 if (CstInt) { 8306 // If the scalar is constant and is of a higher order and has more active 8307 // bits that the vector element type, reject it. 8308 unsigned NumBits = IntSigned 8309 ? (Result.isNegative() ? Result.getMinSignedBits() 8310 : Result.getActiveBits()) 8311 : Result.getActiveBits(); 8312 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 8313 return true; 8314 8315 // If the signedness of the scalar type and the vector element type 8316 // differs and the number of bits is greater than that of the vector 8317 // element reject it. 8318 return (IntSigned != OtherIntSigned && 8319 NumBits > S.Context.getIntWidth(OtherIntTy)); 8320 } 8321 8322 // Reject cases where the value of the scalar is not constant and it's 8323 // order is greater than that of the vector element type. 8324 return (Order < 0); 8325 } 8326 8327 /// Test if a (constant) integer Int can be casted to floating point type 8328 /// FloatTy without losing precision. 8329 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 8330 QualType FloatTy) { 8331 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8332 8333 // Determine if the integer constant can be expressed as a floating point 8334 // number of the appropriate type. 8335 llvm::APSInt Result; 8336 bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context); 8337 uint64_t Bits = 0; 8338 if (CstInt) { 8339 // Reject constants that would be truncated if they were converted to 8340 // the floating point type. Test by simple to/from conversion. 8341 // FIXME: Ideally the conversion to an APFloat and from an APFloat 8342 // could be avoided if there was a convertFromAPInt method 8343 // which could signal back if implicit truncation occurred. 8344 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 8345 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 8346 llvm::APFloat::rmTowardZero); 8347 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 8348 !IntTy->hasSignedIntegerRepresentation()); 8349 bool Ignored = false; 8350 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 8351 &Ignored); 8352 if (Result != ConvertBack) 8353 return true; 8354 } else { 8355 // Reject types that cannot be fully encoded into the mantissa of 8356 // the float. 8357 Bits = S.Context.getTypeSize(IntTy); 8358 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 8359 S.Context.getFloatTypeSemantics(FloatTy)); 8360 if (Bits > FloatPrec) 8361 return true; 8362 } 8363 8364 return false; 8365 } 8366 8367 /// Attempt to convert and splat Scalar into a vector whose types matches 8368 /// Vector following GCC conversion rules. The rule is that implicit 8369 /// conversion can occur when Scalar can be casted to match Vector's element 8370 /// type without causing truncation of Scalar. 8371 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 8372 ExprResult *Vector) { 8373 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 8374 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 8375 const VectorType *VT = VectorTy->getAs<VectorType>(); 8376 8377 assert(!isa<ExtVectorType>(VT) && 8378 "ExtVectorTypes should not be handled here!"); 8379 8380 QualType VectorEltTy = VT->getElementType(); 8381 8382 // Reject cases where the vector element type or the scalar element type are 8383 // not integral or floating point types. 8384 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 8385 return true; 8386 8387 // The conversion to apply to the scalar before splatting it, 8388 // if necessary. 8389 CastKind ScalarCast = CK_NoOp; 8390 8391 // Accept cases where the vector elements are integers and the scalar is 8392 // an integer. 8393 // FIXME: Notionally if the scalar was a floating point value with a precise 8394 // integral representation, we could cast it to an appropriate integer 8395 // type and then perform the rest of the checks here. GCC will perform 8396 // this conversion in some cases as determined by the input language. 8397 // We should accept it on a language independent basis. 8398 if (VectorEltTy->isIntegralType(S.Context) && 8399 ScalarTy->isIntegralType(S.Context) && 8400 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 8401 8402 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 8403 return true; 8404 8405 ScalarCast = CK_IntegralCast; 8406 } else if (VectorEltTy->isRealFloatingType()) { 8407 if (ScalarTy->isRealFloatingType()) { 8408 8409 // Reject cases where the scalar type is not a constant and has a higher 8410 // Order than the vector element type. 8411 llvm::APFloat Result(0.0); 8412 bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context); 8413 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 8414 if (!CstScalar && Order < 0) 8415 return true; 8416 8417 // If the scalar cannot be safely casted to the vector element type, 8418 // reject it. 8419 if (CstScalar) { 8420 bool Truncated = false; 8421 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 8422 llvm::APFloat::rmNearestTiesToEven, &Truncated); 8423 if (Truncated) 8424 return true; 8425 } 8426 8427 ScalarCast = CK_FloatingCast; 8428 } else if (ScalarTy->isIntegralType(S.Context)) { 8429 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 8430 return true; 8431 8432 ScalarCast = CK_IntegralToFloating; 8433 } else 8434 return true; 8435 } 8436 8437 // Adjust scalar if desired. 8438 if (Scalar) { 8439 if (ScalarCast != CK_NoOp) 8440 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 8441 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 8442 } 8443 return false; 8444 } 8445 8446 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 8447 SourceLocation Loc, bool IsCompAssign, 8448 bool AllowBothBool, 8449 bool AllowBoolConversions) { 8450 if (!IsCompAssign) { 8451 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 8452 if (LHS.isInvalid()) 8453 return QualType(); 8454 } 8455 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 8456 if (RHS.isInvalid()) 8457 return QualType(); 8458 8459 // For conversion purposes, we ignore any qualifiers. 8460 // For example, "const float" and "float" are equivalent. 8461 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 8462 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 8463 8464 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 8465 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 8466 assert(LHSVecType || RHSVecType); 8467 8468 // AltiVec-style "vector bool op vector bool" combinations are allowed 8469 // for some operators but not others. 8470 if (!AllowBothBool && 8471 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8472 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8473 return InvalidOperands(Loc, LHS, RHS); 8474 8475 // If the vector types are identical, return. 8476 if (Context.hasSameType(LHSType, RHSType)) 8477 return LHSType; 8478 8479 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 8480 if (LHSVecType && RHSVecType && 8481 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8482 if (isa<ExtVectorType>(LHSVecType)) { 8483 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8484 return LHSType; 8485 } 8486 8487 if (!IsCompAssign) 8488 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8489 return RHSType; 8490 } 8491 8492 // AllowBoolConversions says that bool and non-bool AltiVec vectors 8493 // can be mixed, with the result being the non-bool type. The non-bool 8494 // operand must have integer element type. 8495 if (AllowBoolConversions && LHSVecType && RHSVecType && 8496 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 8497 (Context.getTypeSize(LHSVecType->getElementType()) == 8498 Context.getTypeSize(RHSVecType->getElementType()))) { 8499 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 8500 LHSVecType->getElementType()->isIntegerType() && 8501 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 8502 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8503 return LHSType; 8504 } 8505 if (!IsCompAssign && 8506 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8507 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 8508 RHSVecType->getElementType()->isIntegerType()) { 8509 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8510 return RHSType; 8511 } 8512 } 8513 8514 // If there's a vector type and a scalar, try to convert the scalar to 8515 // the vector element type and splat. 8516 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 8517 if (!RHSVecType) { 8518 if (isa<ExtVectorType>(LHSVecType)) { 8519 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 8520 LHSVecType->getElementType(), LHSType, 8521 DiagID)) 8522 return LHSType; 8523 } else { 8524 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 8525 return LHSType; 8526 } 8527 } 8528 if (!LHSVecType) { 8529 if (isa<ExtVectorType>(RHSVecType)) { 8530 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 8531 LHSType, RHSVecType->getElementType(), 8532 RHSType, DiagID)) 8533 return RHSType; 8534 } else { 8535 if (LHS.get()->getValueKind() == VK_LValue || 8536 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 8537 return RHSType; 8538 } 8539 } 8540 8541 // FIXME: The code below also handles conversion between vectors and 8542 // non-scalars, we should break this down into fine grained specific checks 8543 // and emit proper diagnostics. 8544 QualType VecType = LHSVecType ? LHSType : RHSType; 8545 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 8546 QualType OtherType = LHSVecType ? RHSType : LHSType; 8547 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 8548 if (isLaxVectorConversion(OtherType, VecType)) { 8549 // If we're allowing lax vector conversions, only the total (data) size 8550 // needs to be the same. For non compound assignment, if one of the types is 8551 // scalar, the result is always the vector type. 8552 if (!IsCompAssign) { 8553 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 8554 return VecType; 8555 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 8556 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 8557 // type. Note that this is already done by non-compound assignments in 8558 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 8559 // <1 x T> -> T. The result is also a vector type. 8560 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 8561 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 8562 ExprResult *RHSExpr = &RHS; 8563 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 8564 return VecType; 8565 } 8566 } 8567 8568 // Okay, the expression is invalid. 8569 8570 // If there's a non-vector, non-real operand, diagnose that. 8571 if ((!RHSVecType && !RHSType->isRealType()) || 8572 (!LHSVecType && !LHSType->isRealType())) { 8573 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 8574 << LHSType << RHSType 8575 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8576 return QualType(); 8577 } 8578 8579 // OpenCL V1.1 6.2.6.p1: 8580 // If the operands are of more than one vector type, then an error shall 8581 // occur. Implicit conversions between vector types are not permitted, per 8582 // section 6.2.1. 8583 if (getLangOpts().OpenCL && 8584 RHSVecType && isa<ExtVectorType>(RHSVecType) && 8585 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 8586 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 8587 << RHSType; 8588 return QualType(); 8589 } 8590 8591 8592 // If there is a vector type that is not a ExtVector and a scalar, we reach 8593 // this point if scalar could not be converted to the vector's element type 8594 // without truncation. 8595 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 8596 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 8597 QualType Scalar = LHSVecType ? RHSType : LHSType; 8598 QualType Vector = LHSVecType ? LHSType : RHSType; 8599 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 8600 Diag(Loc, 8601 diag::err_typecheck_vector_not_convertable_implict_truncation) 8602 << ScalarOrVector << Scalar << Vector; 8603 8604 return QualType(); 8605 } 8606 8607 // Otherwise, use the generic diagnostic. 8608 Diag(Loc, DiagID) 8609 << LHSType << RHSType 8610 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8611 return QualType(); 8612 } 8613 8614 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 8615 // expression. These are mainly cases where the null pointer is used as an 8616 // integer instead of a pointer. 8617 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 8618 SourceLocation Loc, bool IsCompare) { 8619 // The canonical way to check for a GNU null is with isNullPointerConstant, 8620 // but we use a bit of a hack here for speed; this is a relatively 8621 // hot path, and isNullPointerConstant is slow. 8622 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 8623 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 8624 8625 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 8626 8627 // Avoid analyzing cases where the result will either be invalid (and 8628 // diagnosed as such) or entirely valid and not something to warn about. 8629 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 8630 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 8631 return; 8632 8633 // Comparison operations would not make sense with a null pointer no matter 8634 // what the other expression is. 8635 if (!IsCompare) { 8636 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 8637 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 8638 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 8639 return; 8640 } 8641 8642 // The rest of the operations only make sense with a null pointer 8643 // if the other expression is a pointer. 8644 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 8645 NonNullType->canDecayToPointerType()) 8646 return; 8647 8648 S.Diag(Loc, diag::warn_null_in_comparison_operation) 8649 << LHSNull /* LHS is NULL */ << NonNullType 8650 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8651 } 8652 8653 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 8654 ExprResult &RHS, 8655 SourceLocation Loc, bool IsDiv) { 8656 // Check for division/remainder by zero. 8657 llvm::APSInt RHSValue; 8658 if (!RHS.get()->isValueDependent() && 8659 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0) 8660 S.DiagRuntimeBehavior(Loc, RHS.get(), 8661 S.PDiag(diag::warn_remainder_division_by_zero) 8662 << IsDiv << RHS.get()->getSourceRange()); 8663 } 8664 8665 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 8666 SourceLocation Loc, 8667 bool IsCompAssign, bool IsDiv) { 8668 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8669 8670 if (LHS.get()->getType()->isVectorType() || 8671 RHS.get()->getType()->isVectorType()) 8672 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8673 /*AllowBothBool*/getLangOpts().AltiVec, 8674 /*AllowBoolConversions*/false); 8675 8676 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8677 if (LHS.isInvalid() || RHS.isInvalid()) 8678 return QualType(); 8679 8680 8681 if (compType.isNull() || !compType->isArithmeticType()) 8682 return InvalidOperands(Loc, LHS, RHS); 8683 if (IsDiv) 8684 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 8685 return compType; 8686 } 8687 8688 QualType Sema::CheckRemainderOperands( 8689 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 8690 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8691 8692 if (LHS.get()->getType()->isVectorType() || 8693 RHS.get()->getType()->isVectorType()) { 8694 if (LHS.get()->getType()->hasIntegerRepresentation() && 8695 RHS.get()->getType()->hasIntegerRepresentation()) 8696 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8697 /*AllowBothBool*/getLangOpts().AltiVec, 8698 /*AllowBoolConversions*/false); 8699 return InvalidOperands(Loc, LHS, RHS); 8700 } 8701 8702 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8703 if (LHS.isInvalid() || RHS.isInvalid()) 8704 return QualType(); 8705 8706 if (compType.isNull() || !compType->isIntegerType()) 8707 return InvalidOperands(Loc, LHS, RHS); 8708 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 8709 return compType; 8710 } 8711 8712 /// Diagnose invalid arithmetic on two void pointers. 8713 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 8714 Expr *LHSExpr, Expr *RHSExpr) { 8715 S.Diag(Loc, S.getLangOpts().CPlusPlus 8716 ? diag::err_typecheck_pointer_arith_void_type 8717 : diag::ext_gnu_void_ptr) 8718 << 1 /* two pointers */ << LHSExpr->getSourceRange() 8719 << RHSExpr->getSourceRange(); 8720 } 8721 8722 /// Diagnose invalid arithmetic on a void pointer. 8723 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 8724 Expr *Pointer) { 8725 S.Diag(Loc, S.getLangOpts().CPlusPlus 8726 ? diag::err_typecheck_pointer_arith_void_type 8727 : diag::ext_gnu_void_ptr) 8728 << 0 /* one pointer */ << Pointer->getSourceRange(); 8729 } 8730 8731 /// Diagnose invalid arithmetic on a null pointer. 8732 /// 8733 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 8734 /// idiom, which we recognize as a GNU extension. 8735 /// 8736 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 8737 Expr *Pointer, bool IsGNUIdiom) { 8738 if (IsGNUIdiom) 8739 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 8740 << Pointer->getSourceRange(); 8741 else 8742 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 8743 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 8744 } 8745 8746 /// Diagnose invalid arithmetic on two function pointers. 8747 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 8748 Expr *LHS, Expr *RHS) { 8749 assert(LHS->getType()->isAnyPointerType()); 8750 assert(RHS->getType()->isAnyPointerType()); 8751 S.Diag(Loc, S.getLangOpts().CPlusPlus 8752 ? diag::err_typecheck_pointer_arith_function_type 8753 : diag::ext_gnu_ptr_func_arith) 8754 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 8755 // We only show the second type if it differs from the first. 8756 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 8757 RHS->getType()) 8758 << RHS->getType()->getPointeeType() 8759 << LHS->getSourceRange() << RHS->getSourceRange(); 8760 } 8761 8762 /// Diagnose invalid arithmetic on a function pointer. 8763 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 8764 Expr *Pointer) { 8765 assert(Pointer->getType()->isAnyPointerType()); 8766 S.Diag(Loc, S.getLangOpts().CPlusPlus 8767 ? diag::err_typecheck_pointer_arith_function_type 8768 : diag::ext_gnu_ptr_func_arith) 8769 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 8770 << 0 /* one pointer, so only one type */ 8771 << Pointer->getSourceRange(); 8772 } 8773 8774 /// Emit error if Operand is incomplete pointer type 8775 /// 8776 /// \returns True if pointer has incomplete type 8777 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 8778 Expr *Operand) { 8779 QualType ResType = Operand->getType(); 8780 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8781 ResType = ResAtomicType->getValueType(); 8782 8783 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 8784 QualType PointeeTy = ResType->getPointeeType(); 8785 return S.RequireCompleteType(Loc, PointeeTy, 8786 diag::err_typecheck_arithmetic_incomplete_type, 8787 PointeeTy, Operand->getSourceRange()); 8788 } 8789 8790 /// Check the validity of an arithmetic pointer operand. 8791 /// 8792 /// If the operand has pointer type, this code will check for pointer types 8793 /// which are invalid in arithmetic operations. These will be diagnosed 8794 /// appropriately, including whether or not the use is supported as an 8795 /// extension. 8796 /// 8797 /// \returns True when the operand is valid to use (even if as an extension). 8798 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 8799 Expr *Operand) { 8800 QualType ResType = Operand->getType(); 8801 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8802 ResType = ResAtomicType->getValueType(); 8803 8804 if (!ResType->isAnyPointerType()) return true; 8805 8806 QualType PointeeTy = ResType->getPointeeType(); 8807 if (PointeeTy->isVoidType()) { 8808 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 8809 return !S.getLangOpts().CPlusPlus; 8810 } 8811 if (PointeeTy->isFunctionType()) { 8812 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 8813 return !S.getLangOpts().CPlusPlus; 8814 } 8815 8816 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 8817 8818 return true; 8819 } 8820 8821 /// Check the validity of a binary arithmetic operation w.r.t. pointer 8822 /// operands. 8823 /// 8824 /// This routine will diagnose any invalid arithmetic on pointer operands much 8825 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 8826 /// for emitting a single diagnostic even for operations where both LHS and RHS 8827 /// are (potentially problematic) pointers. 8828 /// 8829 /// \returns True when the operand is valid to use (even if as an extension). 8830 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 8831 Expr *LHSExpr, Expr *RHSExpr) { 8832 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 8833 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 8834 if (!isLHSPointer && !isRHSPointer) return true; 8835 8836 QualType LHSPointeeTy, RHSPointeeTy; 8837 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 8838 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 8839 8840 // if both are pointers check if operation is valid wrt address spaces 8841 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 8842 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 8843 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 8844 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 8845 S.Diag(Loc, 8846 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8847 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 8848 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 8849 return false; 8850 } 8851 } 8852 8853 // Check for arithmetic on pointers to incomplete types. 8854 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 8855 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 8856 if (isLHSVoidPtr || isRHSVoidPtr) { 8857 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 8858 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 8859 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 8860 8861 return !S.getLangOpts().CPlusPlus; 8862 } 8863 8864 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 8865 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 8866 if (isLHSFuncPtr || isRHSFuncPtr) { 8867 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 8868 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 8869 RHSExpr); 8870 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 8871 8872 return !S.getLangOpts().CPlusPlus; 8873 } 8874 8875 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 8876 return false; 8877 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 8878 return false; 8879 8880 return true; 8881 } 8882 8883 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 8884 /// literal. 8885 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 8886 Expr *LHSExpr, Expr *RHSExpr) { 8887 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 8888 Expr* IndexExpr = RHSExpr; 8889 if (!StrExpr) { 8890 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 8891 IndexExpr = LHSExpr; 8892 } 8893 8894 bool IsStringPlusInt = StrExpr && 8895 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 8896 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 8897 return; 8898 8899 llvm::APSInt index; 8900 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 8901 unsigned StrLenWithNull = StrExpr->getLength() + 1; 8902 if (index.isNonNegative() && 8903 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 8904 index.isUnsigned())) 8905 return; 8906 } 8907 8908 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8909 Self.Diag(OpLoc, diag::warn_string_plus_int) 8910 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 8911 8912 // Only print a fixit for "str" + int, not for int + "str". 8913 if (IndexExpr == RHSExpr) { 8914 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8915 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8916 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8917 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8918 << FixItHint::CreateInsertion(EndLoc, "]"); 8919 } else 8920 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8921 } 8922 8923 /// Emit a warning when adding a char literal to a string. 8924 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 8925 Expr *LHSExpr, Expr *RHSExpr) { 8926 const Expr *StringRefExpr = LHSExpr; 8927 const CharacterLiteral *CharExpr = 8928 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 8929 8930 if (!CharExpr) { 8931 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 8932 StringRefExpr = RHSExpr; 8933 } 8934 8935 if (!CharExpr || !StringRefExpr) 8936 return; 8937 8938 const QualType StringType = StringRefExpr->getType(); 8939 8940 // Return if not a PointerType. 8941 if (!StringType->isAnyPointerType()) 8942 return; 8943 8944 // Return if not a CharacterType. 8945 if (!StringType->getPointeeType()->isAnyCharacterType()) 8946 return; 8947 8948 ASTContext &Ctx = Self.getASTContext(); 8949 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8950 8951 const QualType CharType = CharExpr->getType(); 8952 if (!CharType->isAnyCharacterType() && 8953 CharType->isIntegerType() && 8954 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 8955 Self.Diag(OpLoc, diag::warn_string_plus_char) 8956 << DiagRange << Ctx.CharTy; 8957 } else { 8958 Self.Diag(OpLoc, diag::warn_string_plus_char) 8959 << DiagRange << CharExpr->getType(); 8960 } 8961 8962 // Only print a fixit for str + char, not for char + str. 8963 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 8964 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8965 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8966 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8967 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8968 << FixItHint::CreateInsertion(EndLoc, "]"); 8969 } else { 8970 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8971 } 8972 } 8973 8974 /// Emit error when two pointers are incompatible. 8975 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 8976 Expr *LHSExpr, Expr *RHSExpr) { 8977 assert(LHSExpr->getType()->isAnyPointerType()); 8978 assert(RHSExpr->getType()->isAnyPointerType()); 8979 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 8980 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 8981 << RHSExpr->getSourceRange(); 8982 } 8983 8984 // C99 6.5.6 8985 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 8986 SourceLocation Loc, BinaryOperatorKind Opc, 8987 QualType* CompLHSTy) { 8988 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8989 8990 if (LHS.get()->getType()->isVectorType() || 8991 RHS.get()->getType()->isVectorType()) { 8992 QualType compType = CheckVectorOperands( 8993 LHS, RHS, Loc, CompLHSTy, 8994 /*AllowBothBool*/getLangOpts().AltiVec, 8995 /*AllowBoolConversions*/getLangOpts().ZVector); 8996 if (CompLHSTy) *CompLHSTy = compType; 8997 return compType; 8998 } 8999 9000 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 9001 if (LHS.isInvalid() || RHS.isInvalid()) 9002 return QualType(); 9003 9004 // Diagnose "string literal" '+' int and string '+' "char literal". 9005 if (Opc == BO_Add) { 9006 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 9007 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 9008 } 9009 9010 // handle the common case first (both operands are arithmetic). 9011 if (!compType.isNull() && compType->isArithmeticType()) { 9012 if (CompLHSTy) *CompLHSTy = compType; 9013 return compType; 9014 } 9015 9016 // Type-checking. Ultimately the pointer's going to be in PExp; 9017 // note that we bias towards the LHS being the pointer. 9018 Expr *PExp = LHS.get(), *IExp = RHS.get(); 9019 9020 bool isObjCPointer; 9021 if (PExp->getType()->isPointerType()) { 9022 isObjCPointer = false; 9023 } else if (PExp->getType()->isObjCObjectPointerType()) { 9024 isObjCPointer = true; 9025 } else { 9026 std::swap(PExp, IExp); 9027 if (PExp->getType()->isPointerType()) { 9028 isObjCPointer = false; 9029 } else if (PExp->getType()->isObjCObjectPointerType()) { 9030 isObjCPointer = true; 9031 } else { 9032 return InvalidOperands(Loc, LHS, RHS); 9033 } 9034 } 9035 assert(PExp->getType()->isAnyPointerType()); 9036 9037 if (!IExp->getType()->isIntegerType()) 9038 return InvalidOperands(Loc, LHS, RHS); 9039 9040 // Adding to a null pointer results in undefined behavior. 9041 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 9042 Context, Expr::NPC_ValueDependentIsNotNull)) { 9043 // In C++ adding zero to a null pointer is defined. 9044 llvm::APSInt KnownVal; 9045 if (!getLangOpts().CPlusPlus || 9046 (!IExp->isValueDependent() && 9047 (!IExp->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) { 9048 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 9049 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 9050 Context, BO_Add, PExp, IExp); 9051 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 9052 } 9053 } 9054 9055 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 9056 return QualType(); 9057 9058 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 9059 return QualType(); 9060 9061 // Check array bounds for pointer arithemtic 9062 CheckArrayAccess(PExp, IExp); 9063 9064 if (CompLHSTy) { 9065 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 9066 if (LHSTy.isNull()) { 9067 LHSTy = LHS.get()->getType(); 9068 if (LHSTy->isPromotableIntegerType()) 9069 LHSTy = Context.getPromotedIntegerType(LHSTy); 9070 } 9071 *CompLHSTy = LHSTy; 9072 } 9073 9074 return PExp->getType(); 9075 } 9076 9077 // C99 6.5.6 9078 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 9079 SourceLocation Loc, 9080 QualType* CompLHSTy) { 9081 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9082 9083 if (LHS.get()->getType()->isVectorType() || 9084 RHS.get()->getType()->isVectorType()) { 9085 QualType compType = CheckVectorOperands( 9086 LHS, RHS, Loc, CompLHSTy, 9087 /*AllowBothBool*/getLangOpts().AltiVec, 9088 /*AllowBoolConversions*/getLangOpts().ZVector); 9089 if (CompLHSTy) *CompLHSTy = compType; 9090 return compType; 9091 } 9092 9093 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 9094 if (LHS.isInvalid() || RHS.isInvalid()) 9095 return QualType(); 9096 9097 // Enforce type constraints: C99 6.5.6p3. 9098 9099 // Handle the common case first (both operands are arithmetic). 9100 if (!compType.isNull() && compType->isArithmeticType()) { 9101 if (CompLHSTy) *CompLHSTy = compType; 9102 return compType; 9103 } 9104 9105 // Either ptr - int or ptr - ptr. 9106 if (LHS.get()->getType()->isAnyPointerType()) { 9107 QualType lpointee = LHS.get()->getType()->getPointeeType(); 9108 9109 // Diagnose bad cases where we step over interface counts. 9110 if (LHS.get()->getType()->isObjCObjectPointerType() && 9111 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 9112 return QualType(); 9113 9114 // The result type of a pointer-int computation is the pointer type. 9115 if (RHS.get()->getType()->isIntegerType()) { 9116 // Subtracting from a null pointer should produce a warning. 9117 // The last argument to the diagnose call says this doesn't match the 9118 // GNU int-to-pointer idiom. 9119 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 9120 Expr::NPC_ValueDependentIsNotNull)) { 9121 // In C++ adding zero to a null pointer is defined. 9122 llvm::APSInt KnownVal; 9123 if (!getLangOpts().CPlusPlus || 9124 (!RHS.get()->isValueDependent() && 9125 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) { 9126 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 9127 } 9128 } 9129 9130 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 9131 return QualType(); 9132 9133 // Check array bounds for pointer arithemtic 9134 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 9135 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 9136 9137 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9138 return LHS.get()->getType(); 9139 } 9140 9141 // Handle pointer-pointer subtractions. 9142 if (const PointerType *RHSPTy 9143 = RHS.get()->getType()->getAs<PointerType>()) { 9144 QualType rpointee = RHSPTy->getPointeeType(); 9145 9146 if (getLangOpts().CPlusPlus) { 9147 // Pointee types must be the same: C++ [expr.add] 9148 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 9149 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9150 } 9151 } else { 9152 // Pointee types must be compatible C99 6.5.6p3 9153 if (!Context.typesAreCompatible( 9154 Context.getCanonicalType(lpointee).getUnqualifiedType(), 9155 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 9156 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9157 return QualType(); 9158 } 9159 } 9160 9161 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 9162 LHS.get(), RHS.get())) 9163 return QualType(); 9164 9165 // FIXME: Add warnings for nullptr - ptr. 9166 9167 // The pointee type may have zero size. As an extension, a structure or 9168 // union may have zero size or an array may have zero length. In this 9169 // case subtraction does not make sense. 9170 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 9171 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 9172 if (ElementSize.isZero()) { 9173 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 9174 << rpointee.getUnqualifiedType() 9175 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9176 } 9177 } 9178 9179 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9180 return Context.getPointerDiffType(); 9181 } 9182 } 9183 9184 return InvalidOperands(Loc, LHS, RHS); 9185 } 9186 9187 static bool isScopedEnumerationType(QualType T) { 9188 if (const EnumType *ET = T->getAs<EnumType>()) 9189 return ET->getDecl()->isScoped(); 9190 return false; 9191 } 9192 9193 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 9194 SourceLocation Loc, BinaryOperatorKind Opc, 9195 QualType LHSType) { 9196 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 9197 // so skip remaining warnings as we don't want to modify values within Sema. 9198 if (S.getLangOpts().OpenCL) 9199 return; 9200 9201 llvm::APSInt Right; 9202 // Check right/shifter operand 9203 if (RHS.get()->isValueDependent() || 9204 !RHS.get()->EvaluateAsInt(Right, S.Context)) 9205 return; 9206 9207 if (Right.isNegative()) { 9208 S.DiagRuntimeBehavior(Loc, RHS.get(), 9209 S.PDiag(diag::warn_shift_negative) 9210 << RHS.get()->getSourceRange()); 9211 return; 9212 } 9213 llvm::APInt LeftBits(Right.getBitWidth(), 9214 S.Context.getTypeSize(LHS.get()->getType())); 9215 if (Right.uge(LeftBits)) { 9216 S.DiagRuntimeBehavior(Loc, RHS.get(), 9217 S.PDiag(diag::warn_shift_gt_typewidth) 9218 << RHS.get()->getSourceRange()); 9219 return; 9220 } 9221 if (Opc != BO_Shl) 9222 return; 9223 9224 // When left shifting an ICE which is signed, we can check for overflow which 9225 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 9226 // integers have defined behavior modulo one more than the maximum value 9227 // representable in the result type, so never warn for those. 9228 llvm::APSInt Left; 9229 if (LHS.get()->isValueDependent() || 9230 LHSType->hasUnsignedIntegerRepresentation() || 9231 !LHS.get()->EvaluateAsInt(Left, S.Context)) 9232 return; 9233 9234 // If LHS does not have a signed type and non-negative value 9235 // then, the behavior is undefined. Warn about it. 9236 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) { 9237 S.DiagRuntimeBehavior(Loc, LHS.get(), 9238 S.PDiag(diag::warn_shift_lhs_negative) 9239 << LHS.get()->getSourceRange()); 9240 return; 9241 } 9242 9243 llvm::APInt ResultBits = 9244 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 9245 if (LeftBits.uge(ResultBits)) 9246 return; 9247 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 9248 Result = Result.shl(Right); 9249 9250 // Print the bit representation of the signed integer as an unsigned 9251 // hexadecimal number. 9252 SmallString<40> HexResult; 9253 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 9254 9255 // If we are only missing a sign bit, this is less likely to result in actual 9256 // bugs -- if the result is cast back to an unsigned type, it will have the 9257 // expected value. Thus we place this behind a different warning that can be 9258 // turned off separately if needed. 9259 if (LeftBits == ResultBits - 1) { 9260 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 9261 << HexResult << LHSType 9262 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9263 return; 9264 } 9265 9266 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 9267 << HexResult.str() << Result.getMinSignedBits() << LHSType 9268 << Left.getBitWidth() << LHS.get()->getSourceRange() 9269 << RHS.get()->getSourceRange(); 9270 } 9271 9272 /// Return the resulting type when a vector is shifted 9273 /// by a scalar or vector shift amount. 9274 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 9275 SourceLocation Loc, bool IsCompAssign) { 9276 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 9277 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 9278 !LHS.get()->getType()->isVectorType()) { 9279 S.Diag(Loc, diag::err_shift_rhs_only_vector) 9280 << RHS.get()->getType() << LHS.get()->getType() 9281 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9282 return QualType(); 9283 } 9284 9285 if (!IsCompAssign) { 9286 LHS = S.UsualUnaryConversions(LHS.get()); 9287 if (LHS.isInvalid()) return QualType(); 9288 } 9289 9290 RHS = S.UsualUnaryConversions(RHS.get()); 9291 if (RHS.isInvalid()) return QualType(); 9292 9293 QualType LHSType = LHS.get()->getType(); 9294 // Note that LHS might be a scalar because the routine calls not only in 9295 // OpenCL case. 9296 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 9297 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 9298 9299 // Note that RHS might not be a vector. 9300 QualType RHSType = RHS.get()->getType(); 9301 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 9302 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 9303 9304 // The operands need to be integers. 9305 if (!LHSEleType->isIntegerType()) { 9306 S.Diag(Loc, diag::err_typecheck_expect_int) 9307 << LHS.get()->getType() << LHS.get()->getSourceRange(); 9308 return QualType(); 9309 } 9310 9311 if (!RHSEleType->isIntegerType()) { 9312 S.Diag(Loc, diag::err_typecheck_expect_int) 9313 << RHS.get()->getType() << RHS.get()->getSourceRange(); 9314 return QualType(); 9315 } 9316 9317 if (!LHSVecTy) { 9318 assert(RHSVecTy); 9319 if (IsCompAssign) 9320 return RHSType; 9321 if (LHSEleType != RHSEleType) { 9322 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 9323 LHSEleType = RHSEleType; 9324 } 9325 QualType VecTy = 9326 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 9327 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 9328 LHSType = VecTy; 9329 } else if (RHSVecTy) { 9330 // OpenCL v1.1 s6.3.j says that for vector types, the operators 9331 // are applied component-wise. So if RHS is a vector, then ensure 9332 // that the number of elements is the same as LHS... 9333 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 9334 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 9335 << LHS.get()->getType() << RHS.get()->getType() 9336 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9337 return QualType(); 9338 } 9339 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 9340 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 9341 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 9342 if (LHSBT != RHSBT && 9343 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 9344 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 9345 << LHS.get()->getType() << RHS.get()->getType() 9346 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9347 } 9348 } 9349 } else { 9350 // ...else expand RHS to match the number of elements in LHS. 9351 QualType VecTy = 9352 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 9353 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 9354 } 9355 9356 return LHSType; 9357 } 9358 9359 // C99 6.5.7 9360 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 9361 SourceLocation Loc, BinaryOperatorKind Opc, 9362 bool IsCompAssign) { 9363 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9364 9365 // Vector shifts promote their scalar inputs to vector type. 9366 if (LHS.get()->getType()->isVectorType() || 9367 RHS.get()->getType()->isVectorType()) { 9368 if (LangOpts.ZVector) { 9369 // The shift operators for the z vector extensions work basically 9370 // like general shifts, except that neither the LHS nor the RHS is 9371 // allowed to be a "vector bool". 9372 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 9373 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 9374 return InvalidOperands(Loc, LHS, RHS); 9375 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 9376 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9377 return InvalidOperands(Loc, LHS, RHS); 9378 } 9379 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 9380 } 9381 9382 // Shifts don't perform usual arithmetic conversions, they just do integer 9383 // promotions on each operand. C99 6.5.7p3 9384 9385 // For the LHS, do usual unary conversions, but then reset them away 9386 // if this is a compound assignment. 9387 ExprResult OldLHS = LHS; 9388 LHS = UsualUnaryConversions(LHS.get()); 9389 if (LHS.isInvalid()) 9390 return QualType(); 9391 QualType LHSType = LHS.get()->getType(); 9392 if (IsCompAssign) LHS = OldLHS; 9393 9394 // The RHS is simpler. 9395 RHS = UsualUnaryConversions(RHS.get()); 9396 if (RHS.isInvalid()) 9397 return QualType(); 9398 QualType RHSType = RHS.get()->getType(); 9399 9400 // C99 6.5.7p2: Each of the operands shall have integer type. 9401 if (!LHSType->hasIntegerRepresentation() || 9402 !RHSType->hasIntegerRepresentation()) 9403 return InvalidOperands(Loc, LHS, RHS); 9404 9405 // C++0x: Don't allow scoped enums. FIXME: Use something better than 9406 // hasIntegerRepresentation() above instead of this. 9407 if (isScopedEnumerationType(LHSType) || 9408 isScopedEnumerationType(RHSType)) { 9409 return InvalidOperands(Loc, LHS, RHS); 9410 } 9411 // Sanity-check shift operands 9412 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 9413 9414 // "The type of the result is that of the promoted left operand." 9415 return LHSType; 9416 } 9417 9418 /// If two different enums are compared, raise a warning. 9419 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 9420 Expr *RHS) { 9421 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 9422 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 9423 9424 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 9425 if (!LHSEnumType) 9426 return; 9427 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 9428 if (!RHSEnumType) 9429 return; 9430 9431 // Ignore anonymous enums. 9432 if (!LHSEnumType->getDecl()->getIdentifier() && 9433 !LHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 9434 return; 9435 if (!RHSEnumType->getDecl()->getIdentifier() && 9436 !RHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 9437 return; 9438 9439 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 9440 return; 9441 9442 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 9443 << LHSStrippedType << RHSStrippedType 9444 << LHS->getSourceRange() << RHS->getSourceRange(); 9445 } 9446 9447 /// Diagnose bad pointer comparisons. 9448 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 9449 ExprResult &LHS, ExprResult &RHS, 9450 bool IsError) { 9451 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 9452 : diag::ext_typecheck_comparison_of_distinct_pointers) 9453 << LHS.get()->getType() << RHS.get()->getType() 9454 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9455 } 9456 9457 /// Returns false if the pointers are converted to a composite type, 9458 /// true otherwise. 9459 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 9460 ExprResult &LHS, ExprResult &RHS) { 9461 // C++ [expr.rel]p2: 9462 // [...] Pointer conversions (4.10) and qualification 9463 // conversions (4.4) are performed on pointer operands (or on 9464 // a pointer operand and a null pointer constant) to bring 9465 // them to their composite pointer type. [...] 9466 // 9467 // C++ [expr.eq]p1 uses the same notion for (in)equality 9468 // comparisons of pointers. 9469 9470 QualType LHSType = LHS.get()->getType(); 9471 QualType RHSType = RHS.get()->getType(); 9472 assert(LHSType->isPointerType() || RHSType->isPointerType() || 9473 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 9474 9475 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 9476 if (T.isNull()) { 9477 if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) && 9478 (RHSType->isPointerType() || RHSType->isMemberPointerType())) 9479 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 9480 else 9481 S.InvalidOperands(Loc, LHS, RHS); 9482 return true; 9483 } 9484 9485 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 9486 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 9487 return false; 9488 } 9489 9490 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 9491 ExprResult &LHS, 9492 ExprResult &RHS, 9493 bool IsError) { 9494 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 9495 : diag::ext_typecheck_comparison_of_fptr_to_void) 9496 << LHS.get()->getType() << RHS.get()->getType() 9497 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9498 } 9499 9500 static bool isObjCObjectLiteral(ExprResult &E) { 9501 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 9502 case Stmt::ObjCArrayLiteralClass: 9503 case Stmt::ObjCDictionaryLiteralClass: 9504 case Stmt::ObjCStringLiteralClass: 9505 case Stmt::ObjCBoxedExprClass: 9506 return true; 9507 default: 9508 // Note that ObjCBoolLiteral is NOT an object literal! 9509 return false; 9510 } 9511 } 9512 9513 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 9514 const ObjCObjectPointerType *Type = 9515 LHS->getType()->getAs<ObjCObjectPointerType>(); 9516 9517 // If this is not actually an Objective-C object, bail out. 9518 if (!Type) 9519 return false; 9520 9521 // Get the LHS object's interface type. 9522 QualType InterfaceType = Type->getPointeeType(); 9523 9524 // If the RHS isn't an Objective-C object, bail out. 9525 if (!RHS->getType()->isObjCObjectPointerType()) 9526 return false; 9527 9528 // Try to find the -isEqual: method. 9529 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 9530 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 9531 InterfaceType, 9532 /*instance=*/true); 9533 if (!Method) { 9534 if (Type->isObjCIdType()) { 9535 // For 'id', just check the global pool. 9536 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 9537 /*receiverId=*/true); 9538 } else { 9539 // Check protocols. 9540 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 9541 /*instance=*/true); 9542 } 9543 } 9544 9545 if (!Method) 9546 return false; 9547 9548 QualType T = Method->parameters()[0]->getType(); 9549 if (!T->isObjCObjectPointerType()) 9550 return false; 9551 9552 QualType R = Method->getReturnType(); 9553 if (!R->isScalarType()) 9554 return false; 9555 9556 return true; 9557 } 9558 9559 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 9560 FromE = FromE->IgnoreParenImpCasts(); 9561 switch (FromE->getStmtClass()) { 9562 default: 9563 break; 9564 case Stmt::ObjCStringLiteralClass: 9565 // "string literal" 9566 return LK_String; 9567 case Stmt::ObjCArrayLiteralClass: 9568 // "array literal" 9569 return LK_Array; 9570 case Stmt::ObjCDictionaryLiteralClass: 9571 // "dictionary literal" 9572 return LK_Dictionary; 9573 case Stmt::BlockExprClass: 9574 return LK_Block; 9575 case Stmt::ObjCBoxedExprClass: { 9576 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 9577 switch (Inner->getStmtClass()) { 9578 case Stmt::IntegerLiteralClass: 9579 case Stmt::FloatingLiteralClass: 9580 case Stmt::CharacterLiteralClass: 9581 case Stmt::ObjCBoolLiteralExprClass: 9582 case Stmt::CXXBoolLiteralExprClass: 9583 // "numeric literal" 9584 return LK_Numeric; 9585 case Stmt::ImplicitCastExprClass: { 9586 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 9587 // Boolean literals can be represented by implicit casts. 9588 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 9589 return LK_Numeric; 9590 break; 9591 } 9592 default: 9593 break; 9594 } 9595 return LK_Boxed; 9596 } 9597 } 9598 return LK_None; 9599 } 9600 9601 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 9602 ExprResult &LHS, ExprResult &RHS, 9603 BinaryOperator::Opcode Opc){ 9604 Expr *Literal; 9605 Expr *Other; 9606 if (isObjCObjectLiteral(LHS)) { 9607 Literal = LHS.get(); 9608 Other = RHS.get(); 9609 } else { 9610 Literal = RHS.get(); 9611 Other = LHS.get(); 9612 } 9613 9614 // Don't warn on comparisons against nil. 9615 Other = Other->IgnoreParenCasts(); 9616 if (Other->isNullPointerConstant(S.getASTContext(), 9617 Expr::NPC_ValueDependentIsNotNull)) 9618 return; 9619 9620 // This should be kept in sync with warn_objc_literal_comparison. 9621 // LK_String should always be after the other literals, since it has its own 9622 // warning flag. 9623 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 9624 assert(LiteralKind != Sema::LK_Block); 9625 if (LiteralKind == Sema::LK_None) { 9626 llvm_unreachable("Unknown Objective-C object literal kind"); 9627 } 9628 9629 if (LiteralKind == Sema::LK_String) 9630 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 9631 << Literal->getSourceRange(); 9632 else 9633 S.Diag(Loc, diag::warn_objc_literal_comparison) 9634 << LiteralKind << Literal->getSourceRange(); 9635 9636 if (BinaryOperator::isEqualityOp(Opc) && 9637 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 9638 SourceLocation Start = LHS.get()->getLocStart(); 9639 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd()); 9640 CharSourceRange OpRange = 9641 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 9642 9643 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 9644 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 9645 << FixItHint::CreateReplacement(OpRange, " isEqual:") 9646 << FixItHint::CreateInsertion(End, "]"); 9647 } 9648 } 9649 9650 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 9651 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 9652 ExprResult &RHS, SourceLocation Loc, 9653 BinaryOperatorKind Opc) { 9654 // Check that left hand side is !something. 9655 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 9656 if (!UO || UO->getOpcode() != UO_LNot) return; 9657 9658 // Only check if the right hand side is non-bool arithmetic type. 9659 if (RHS.get()->isKnownToHaveBooleanValue()) return; 9660 9661 // Make sure that the something in !something is not bool. 9662 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 9663 if (SubExpr->isKnownToHaveBooleanValue()) return; 9664 9665 // Emit warning. 9666 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 9667 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 9668 << Loc << IsBitwiseOp; 9669 9670 // First note suggest !(x < y) 9671 SourceLocation FirstOpen = SubExpr->getLocStart(); 9672 SourceLocation FirstClose = RHS.get()->getLocEnd(); 9673 FirstClose = S.getLocForEndOfToken(FirstClose); 9674 if (FirstClose.isInvalid()) 9675 FirstOpen = SourceLocation(); 9676 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 9677 << IsBitwiseOp 9678 << FixItHint::CreateInsertion(FirstOpen, "(") 9679 << FixItHint::CreateInsertion(FirstClose, ")"); 9680 9681 // Second note suggests (!x) < y 9682 SourceLocation SecondOpen = LHS.get()->getLocStart(); 9683 SourceLocation SecondClose = LHS.get()->getLocEnd(); 9684 SecondClose = S.getLocForEndOfToken(SecondClose); 9685 if (SecondClose.isInvalid()) 9686 SecondOpen = SourceLocation(); 9687 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 9688 << FixItHint::CreateInsertion(SecondOpen, "(") 9689 << FixItHint::CreateInsertion(SecondClose, ")"); 9690 } 9691 9692 // Get the decl for a simple expression: a reference to a variable, 9693 // an implicit C++ field reference, or an implicit ObjC ivar reference. 9694 static ValueDecl *getCompareDecl(Expr *E) { 9695 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) 9696 return DR->getDecl(); 9697 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 9698 if (Ivar->isFreeIvar()) 9699 return Ivar->getDecl(); 9700 } 9701 if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 9702 if (Mem->isImplicitAccess()) 9703 return Mem->getMemberDecl(); 9704 } 9705 return nullptr; 9706 } 9707 9708 /// Diagnose some forms of syntactically-obvious tautological comparison. 9709 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 9710 Expr *LHS, Expr *RHS, 9711 BinaryOperatorKind Opc) { 9712 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 9713 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 9714 9715 QualType LHSType = LHS->getType(); 9716 QualType RHSType = RHS->getType(); 9717 if (LHSType->hasFloatingRepresentation() || 9718 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 9719 LHS->getLocStart().isMacroID() || RHS->getLocStart().isMacroID() || 9720 S.inTemplateInstantiation()) 9721 return; 9722 9723 // Comparisons between two array types are ill-formed for operator<=>, so 9724 // we shouldn't emit any additional warnings about it. 9725 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 9726 return; 9727 9728 // For non-floating point types, check for self-comparisons of the form 9729 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9730 // often indicate logic errors in the program. 9731 // 9732 // NOTE: Don't warn about comparison expressions resulting from macro 9733 // expansion. Also don't warn about comparisons which are only self 9734 // comparisons within a template instantiation. The warnings should catch 9735 // obvious cases in the definition of the template anyways. The idea is to 9736 // warn when the typed comparison operator will always evaluate to the same 9737 // result. 9738 ValueDecl *DL = getCompareDecl(LHSStripped); 9739 ValueDecl *DR = getCompareDecl(RHSStripped); 9740 if (DL && DR && declaresSameEntity(DL, DR)) { 9741 StringRef Result; 9742 switch (Opc) { 9743 case BO_EQ: case BO_LE: case BO_GE: 9744 Result = "true"; 9745 break; 9746 case BO_NE: case BO_LT: case BO_GT: 9747 Result = "false"; 9748 break; 9749 case BO_Cmp: 9750 Result = "'std::strong_ordering::equal'"; 9751 break; 9752 default: 9753 break; 9754 } 9755 S.DiagRuntimeBehavior(Loc, nullptr, 9756 S.PDiag(diag::warn_comparison_always) 9757 << 0 /*self-comparison*/ << !Result.empty() 9758 << Result); 9759 } else if (DL && DR && 9760 DL->getType()->isArrayType() && DR->getType()->isArrayType() && 9761 !DL->isWeak() && !DR->isWeak()) { 9762 // What is it always going to evaluate to? 9763 StringRef Result; 9764 switch(Opc) { 9765 case BO_EQ: // e.g. array1 == array2 9766 Result = "false"; 9767 break; 9768 case BO_NE: // e.g. array1 != array2 9769 Result = "true"; 9770 break; 9771 default: // e.g. array1 <= array2 9772 // The best we can say is 'a constant' 9773 break; 9774 } 9775 S.DiagRuntimeBehavior(Loc, nullptr, 9776 S.PDiag(diag::warn_comparison_always) 9777 << 1 /*array comparison*/ 9778 << !Result.empty() << Result); 9779 } 9780 9781 if (isa<CastExpr>(LHSStripped)) 9782 LHSStripped = LHSStripped->IgnoreParenCasts(); 9783 if (isa<CastExpr>(RHSStripped)) 9784 RHSStripped = RHSStripped->IgnoreParenCasts(); 9785 9786 // Warn about comparisons against a string constant (unless the other 9787 // operand is null); the user probably wants strcmp. 9788 Expr *LiteralString = nullptr; 9789 Expr *LiteralStringStripped = nullptr; 9790 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 9791 !RHSStripped->isNullPointerConstant(S.Context, 9792 Expr::NPC_ValueDependentIsNull)) { 9793 LiteralString = LHS; 9794 LiteralStringStripped = LHSStripped; 9795 } else if ((isa<StringLiteral>(RHSStripped) || 9796 isa<ObjCEncodeExpr>(RHSStripped)) && 9797 !LHSStripped->isNullPointerConstant(S.Context, 9798 Expr::NPC_ValueDependentIsNull)) { 9799 LiteralString = RHS; 9800 LiteralStringStripped = RHSStripped; 9801 } 9802 9803 if (LiteralString) { 9804 S.DiagRuntimeBehavior(Loc, nullptr, 9805 S.PDiag(diag::warn_stringcompare) 9806 << isa<ObjCEncodeExpr>(LiteralStringStripped) 9807 << LiteralString->getSourceRange()); 9808 } 9809 } 9810 9811 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 9812 switch (CK) { 9813 default: { 9814 #ifndef NDEBUG 9815 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 9816 << "\n"; 9817 #endif 9818 llvm_unreachable("unhandled cast kind"); 9819 } 9820 case CK_UserDefinedConversion: 9821 return ICK_Identity; 9822 case CK_LValueToRValue: 9823 return ICK_Lvalue_To_Rvalue; 9824 case CK_ArrayToPointerDecay: 9825 return ICK_Array_To_Pointer; 9826 case CK_FunctionToPointerDecay: 9827 return ICK_Function_To_Pointer; 9828 case CK_IntegralCast: 9829 return ICK_Integral_Conversion; 9830 case CK_FloatingCast: 9831 return ICK_Floating_Conversion; 9832 case CK_IntegralToFloating: 9833 case CK_FloatingToIntegral: 9834 return ICK_Floating_Integral; 9835 case CK_IntegralComplexCast: 9836 case CK_FloatingComplexCast: 9837 case CK_FloatingComplexToIntegralComplex: 9838 case CK_IntegralComplexToFloatingComplex: 9839 return ICK_Complex_Conversion; 9840 case CK_FloatingComplexToReal: 9841 case CK_FloatingRealToComplex: 9842 case CK_IntegralComplexToReal: 9843 case CK_IntegralRealToComplex: 9844 return ICK_Complex_Real; 9845 } 9846 } 9847 9848 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 9849 QualType FromType, 9850 SourceLocation Loc) { 9851 // Check for a narrowing implicit conversion. 9852 StandardConversionSequence SCS; 9853 SCS.setAsIdentityConversion(); 9854 SCS.setToType(0, FromType); 9855 SCS.setToType(1, ToType); 9856 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 9857 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 9858 9859 APValue PreNarrowingValue; 9860 QualType PreNarrowingType; 9861 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 9862 PreNarrowingType, 9863 /*IgnoreFloatToIntegralConversion*/ true)) { 9864 case NK_Dependent_Narrowing: 9865 // Implicit conversion to a narrower type, but the expression is 9866 // value-dependent so we can't tell whether it's actually narrowing. 9867 case NK_Not_Narrowing: 9868 return false; 9869 9870 case NK_Constant_Narrowing: 9871 // Implicit conversion to a narrower type, and the value is not a constant 9872 // expression. 9873 S.Diag(E->getLocStart(), diag::err_spaceship_argument_narrowing) 9874 << /*Constant*/ 1 9875 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 9876 return true; 9877 9878 case NK_Variable_Narrowing: 9879 // Implicit conversion to a narrower type, and the value is not a constant 9880 // expression. 9881 case NK_Type_Narrowing: 9882 S.Diag(E->getLocStart(), diag::err_spaceship_argument_narrowing) 9883 << /*Constant*/ 0 << FromType << ToType; 9884 // TODO: It's not a constant expression, but what if the user intended it 9885 // to be? Can we produce notes to help them figure out why it isn't? 9886 return true; 9887 } 9888 llvm_unreachable("unhandled case in switch"); 9889 } 9890 9891 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 9892 ExprResult &LHS, 9893 ExprResult &RHS, 9894 SourceLocation Loc) { 9895 using CCT = ComparisonCategoryType; 9896 9897 QualType LHSType = LHS.get()->getType(); 9898 QualType RHSType = RHS.get()->getType(); 9899 // Dig out the original argument type and expression before implicit casts 9900 // were applied. These are the types/expressions we need to check the 9901 // [expr.spaceship] requirements against. 9902 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 9903 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 9904 QualType LHSStrippedType = LHSStripped.get()->getType(); 9905 QualType RHSStrippedType = RHSStripped.get()->getType(); 9906 9907 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 9908 // other is not, the program is ill-formed. 9909 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 9910 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 9911 return QualType(); 9912 } 9913 9914 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 9915 RHSStrippedType->isEnumeralType(); 9916 if (NumEnumArgs == 1) { 9917 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 9918 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 9919 if (OtherTy->hasFloatingRepresentation()) { 9920 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 9921 return QualType(); 9922 } 9923 } 9924 if (NumEnumArgs == 2) { 9925 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 9926 // type E, the operator yields the result of converting the operands 9927 // to the underlying type of E and applying <=> to the converted operands. 9928 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 9929 S.InvalidOperands(Loc, LHS, RHS); 9930 return QualType(); 9931 } 9932 QualType IntType = 9933 LHSStrippedType->getAs<EnumType>()->getDecl()->getIntegerType(); 9934 assert(IntType->isArithmeticType()); 9935 9936 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 9937 // promote the boolean type, and all other promotable integer types, to 9938 // avoid this. 9939 if (IntType->isPromotableIntegerType()) 9940 IntType = S.Context.getPromotedIntegerType(IntType); 9941 9942 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 9943 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 9944 LHSType = RHSType = IntType; 9945 } 9946 9947 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 9948 // usual arithmetic conversions are applied to the operands. 9949 QualType Type = S.UsualArithmeticConversions(LHS, RHS); 9950 if (LHS.isInvalid() || RHS.isInvalid()) 9951 return QualType(); 9952 if (Type.isNull()) 9953 return S.InvalidOperands(Loc, LHS, RHS); 9954 assert(Type->isArithmeticType() || Type->isEnumeralType()); 9955 9956 bool HasNarrowing = checkThreeWayNarrowingConversion( 9957 S, Type, LHS.get(), LHSType, LHS.get()->getLocStart()); 9958 HasNarrowing |= checkThreeWayNarrowingConversion( 9959 S, Type, RHS.get(), RHSType, RHS.get()->getLocStart()); 9960 if (HasNarrowing) 9961 return QualType(); 9962 9963 assert(!Type.isNull() && "composite type for <=> has not been set"); 9964 9965 auto TypeKind = [&]() { 9966 if (const ComplexType *CT = Type->getAs<ComplexType>()) { 9967 if (CT->getElementType()->hasFloatingRepresentation()) 9968 return CCT::WeakEquality; 9969 return CCT::StrongEquality; 9970 } 9971 if (Type->isIntegralOrEnumerationType()) 9972 return CCT::StrongOrdering; 9973 if (Type->hasFloatingRepresentation()) 9974 return CCT::PartialOrdering; 9975 llvm_unreachable("other types are unimplemented"); 9976 }(); 9977 9978 return S.CheckComparisonCategoryType(TypeKind, Loc); 9979 } 9980 9981 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 9982 ExprResult &RHS, 9983 SourceLocation Loc, 9984 BinaryOperatorKind Opc) { 9985 if (Opc == BO_Cmp) 9986 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 9987 9988 // C99 6.5.8p3 / C99 6.5.9p4 9989 QualType Type = S.UsualArithmeticConversions(LHS, RHS); 9990 if (LHS.isInvalid() || RHS.isInvalid()) 9991 return QualType(); 9992 if (Type.isNull()) 9993 return S.InvalidOperands(Loc, LHS, RHS); 9994 assert(Type->isArithmeticType() || Type->isEnumeralType()); 9995 9996 checkEnumComparison(S, Loc, LHS.get(), RHS.get()); 9997 9998 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 9999 return S.InvalidOperands(Loc, LHS, RHS); 10000 10001 // Check for comparisons of floating point operands using != and ==. 10002 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 10003 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 10004 10005 // The result of comparisons is 'bool' in C++, 'int' in C. 10006 return S.Context.getLogicalOperationType(); 10007 } 10008 10009 // C99 6.5.8, C++ [expr.rel] 10010 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 10011 SourceLocation Loc, 10012 BinaryOperatorKind Opc) { 10013 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 10014 bool IsThreeWay = Opc == BO_Cmp; 10015 auto IsAnyPointerType = [](ExprResult E) { 10016 QualType Ty = E.get()->getType(); 10017 return Ty->isPointerType() || Ty->isMemberPointerType(); 10018 }; 10019 10020 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 10021 // type, array-to-pointer, ..., conversions are performed on both operands to 10022 // bring them to their composite type. 10023 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 10024 // any type-related checks. 10025 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 10026 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10027 if (LHS.isInvalid()) 10028 return QualType(); 10029 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10030 if (RHS.isInvalid()) 10031 return QualType(); 10032 } else { 10033 LHS = DefaultLvalueConversion(LHS.get()); 10034 if (LHS.isInvalid()) 10035 return QualType(); 10036 RHS = DefaultLvalueConversion(RHS.get()); 10037 if (RHS.isInvalid()) 10038 return QualType(); 10039 } 10040 10041 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 10042 10043 // Handle vector comparisons separately. 10044 if (LHS.get()->getType()->isVectorType() || 10045 RHS.get()->getType()->isVectorType()) 10046 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 10047 10048 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 10049 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 10050 10051 QualType LHSType = LHS.get()->getType(); 10052 QualType RHSType = RHS.get()->getType(); 10053 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 10054 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 10055 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 10056 10057 const Expr::NullPointerConstantKind LHSNullKind = 10058 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 10059 const Expr::NullPointerConstantKind RHSNullKind = 10060 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 10061 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 10062 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 10063 10064 auto computeResultTy = [&]() { 10065 if (Opc != BO_Cmp) 10066 return Context.getLogicalOperationType(); 10067 assert(getLangOpts().CPlusPlus); 10068 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 10069 10070 QualType CompositeTy = LHS.get()->getType(); 10071 assert(!CompositeTy->isReferenceType()); 10072 10073 auto buildResultTy = [&](ComparisonCategoryType Kind) { 10074 return CheckComparisonCategoryType(Kind, Loc); 10075 }; 10076 10077 // C++2a [expr.spaceship]p7: If the composite pointer type is a function 10078 // pointer type, a pointer-to-member type, or std::nullptr_t, the 10079 // result is of type std::strong_equality 10080 if (CompositeTy->isFunctionPointerType() || 10081 CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType()) 10082 // FIXME: consider making the function pointer case produce 10083 // strong_ordering not strong_equality, per P0946R0-Jax18 discussion 10084 // and direction polls 10085 return buildResultTy(ComparisonCategoryType::StrongEquality); 10086 10087 // C++2a [expr.spaceship]p8: If the composite pointer type is an object 10088 // pointer type, p <=> q is of type std::strong_ordering. 10089 if (CompositeTy->isPointerType()) { 10090 // P0946R0: Comparisons between a null pointer constant and an object 10091 // pointer result in std::strong_equality 10092 if (LHSIsNull != RHSIsNull) 10093 return buildResultTy(ComparisonCategoryType::StrongEquality); 10094 return buildResultTy(ComparisonCategoryType::StrongOrdering); 10095 } 10096 // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed. 10097 // TODO: Extend support for operator<=> to ObjC types. 10098 return InvalidOperands(Loc, LHS, RHS); 10099 }; 10100 10101 10102 if (!IsRelational && LHSIsNull != RHSIsNull) { 10103 bool IsEquality = Opc == BO_EQ; 10104 if (RHSIsNull) 10105 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 10106 RHS.get()->getSourceRange()); 10107 else 10108 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 10109 LHS.get()->getSourceRange()); 10110 } 10111 10112 if ((LHSType->isIntegerType() && !LHSIsNull) || 10113 (RHSType->isIntegerType() && !RHSIsNull)) { 10114 // Skip normal pointer conversion checks in this case; we have better 10115 // diagnostics for this below. 10116 } else if (getLangOpts().CPlusPlus) { 10117 // Equality comparison of a function pointer to a void pointer is invalid, 10118 // but we allow it as an extension. 10119 // FIXME: If we really want to allow this, should it be part of composite 10120 // pointer type computation so it works in conditionals too? 10121 if (!IsRelational && 10122 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 10123 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 10124 // This is a gcc extension compatibility comparison. 10125 // In a SFINAE context, we treat this as a hard error to maintain 10126 // conformance with the C++ standard. 10127 diagnoseFunctionPointerToVoidComparison( 10128 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 10129 10130 if (isSFINAEContext()) 10131 return QualType(); 10132 10133 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10134 return computeResultTy(); 10135 } 10136 10137 // C++ [expr.eq]p2: 10138 // If at least one operand is a pointer [...] bring them to their 10139 // composite pointer type. 10140 // C++ [expr.spaceship]p6 10141 // If at least one of the operands is of pointer type, [...] bring them 10142 // to their composite pointer type. 10143 // C++ [expr.rel]p2: 10144 // If both operands are pointers, [...] bring them to their composite 10145 // pointer type. 10146 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 10147 (IsRelational ? 2 : 1) && 10148 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 10149 RHSType->isObjCObjectPointerType()))) { 10150 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 10151 return QualType(); 10152 return computeResultTy(); 10153 } 10154 } else if (LHSType->isPointerType() && 10155 RHSType->isPointerType()) { // C99 6.5.8p2 10156 // All of the following pointer-related warnings are GCC extensions, except 10157 // when handling null pointer constants. 10158 QualType LCanPointeeTy = 10159 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 10160 QualType RCanPointeeTy = 10161 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 10162 10163 // C99 6.5.9p2 and C99 6.5.8p2 10164 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 10165 RCanPointeeTy.getUnqualifiedType())) { 10166 // Valid unless a relational comparison of function pointers 10167 if (IsRelational && LCanPointeeTy->isFunctionType()) { 10168 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 10169 << LHSType << RHSType << LHS.get()->getSourceRange() 10170 << RHS.get()->getSourceRange(); 10171 } 10172 } else if (!IsRelational && 10173 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 10174 // Valid unless comparison between non-null pointer and function pointer 10175 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 10176 && !LHSIsNull && !RHSIsNull) 10177 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 10178 /*isError*/false); 10179 } else { 10180 // Invalid 10181 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 10182 } 10183 if (LCanPointeeTy != RCanPointeeTy) { 10184 // Treat NULL constant as a special case in OpenCL. 10185 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 10186 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 10187 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 10188 Diag(Loc, 10189 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10190 << LHSType << RHSType << 0 /* comparison */ 10191 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10192 } 10193 } 10194 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 10195 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 10196 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 10197 : CK_BitCast; 10198 if (LHSIsNull && !RHSIsNull) 10199 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 10200 else 10201 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 10202 } 10203 return computeResultTy(); 10204 } 10205 10206 if (getLangOpts().CPlusPlus) { 10207 // C++ [expr.eq]p4: 10208 // Two operands of type std::nullptr_t or one operand of type 10209 // std::nullptr_t and the other a null pointer constant compare equal. 10210 if (!IsRelational && LHSIsNull && RHSIsNull) { 10211 if (LHSType->isNullPtrType()) { 10212 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10213 return computeResultTy(); 10214 } 10215 if (RHSType->isNullPtrType()) { 10216 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10217 return computeResultTy(); 10218 } 10219 } 10220 10221 // Comparison of Objective-C pointers and block pointers against nullptr_t. 10222 // These aren't covered by the composite pointer type rules. 10223 if (!IsRelational && RHSType->isNullPtrType() && 10224 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 10225 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10226 return computeResultTy(); 10227 } 10228 if (!IsRelational && LHSType->isNullPtrType() && 10229 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 10230 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10231 return computeResultTy(); 10232 } 10233 10234 if (IsRelational && 10235 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 10236 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 10237 // HACK: Relational comparison of nullptr_t against a pointer type is 10238 // invalid per DR583, but we allow it within std::less<> and friends, 10239 // since otherwise common uses of it break. 10240 // FIXME: Consider removing this hack once LWG fixes std::less<> and 10241 // friends to have std::nullptr_t overload candidates. 10242 DeclContext *DC = CurContext; 10243 if (isa<FunctionDecl>(DC)) 10244 DC = DC->getParent(); 10245 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 10246 if (CTSD->isInStdNamespace() && 10247 llvm::StringSwitch<bool>(CTSD->getName()) 10248 .Cases("less", "less_equal", "greater", "greater_equal", true) 10249 .Default(false)) { 10250 if (RHSType->isNullPtrType()) 10251 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10252 else 10253 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10254 return computeResultTy(); 10255 } 10256 } 10257 } 10258 10259 // C++ [expr.eq]p2: 10260 // If at least one operand is a pointer to member, [...] bring them to 10261 // their composite pointer type. 10262 if (!IsRelational && 10263 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 10264 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 10265 return QualType(); 10266 else 10267 return computeResultTy(); 10268 } 10269 } 10270 10271 // Handle block pointer types. 10272 if (!IsRelational && LHSType->isBlockPointerType() && 10273 RHSType->isBlockPointerType()) { 10274 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 10275 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 10276 10277 if (!LHSIsNull && !RHSIsNull && 10278 !Context.typesAreCompatible(lpointee, rpointee)) { 10279 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 10280 << LHSType << RHSType << LHS.get()->getSourceRange() 10281 << RHS.get()->getSourceRange(); 10282 } 10283 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10284 return computeResultTy(); 10285 } 10286 10287 // Allow block pointers to be compared with null pointer constants. 10288 if (!IsRelational 10289 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 10290 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 10291 if (!LHSIsNull && !RHSIsNull) { 10292 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 10293 ->getPointeeType()->isVoidType()) 10294 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 10295 ->getPointeeType()->isVoidType()))) 10296 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 10297 << LHSType << RHSType << LHS.get()->getSourceRange() 10298 << RHS.get()->getSourceRange(); 10299 } 10300 if (LHSIsNull && !RHSIsNull) 10301 LHS = ImpCastExprToType(LHS.get(), RHSType, 10302 RHSType->isPointerType() ? CK_BitCast 10303 : CK_AnyPointerToBlockPointerCast); 10304 else 10305 RHS = ImpCastExprToType(RHS.get(), LHSType, 10306 LHSType->isPointerType() ? CK_BitCast 10307 : CK_AnyPointerToBlockPointerCast); 10308 return computeResultTy(); 10309 } 10310 10311 if (LHSType->isObjCObjectPointerType() || 10312 RHSType->isObjCObjectPointerType()) { 10313 const PointerType *LPT = LHSType->getAs<PointerType>(); 10314 const PointerType *RPT = RHSType->getAs<PointerType>(); 10315 if (LPT || RPT) { 10316 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 10317 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 10318 10319 if (!LPtrToVoid && !RPtrToVoid && 10320 !Context.typesAreCompatible(LHSType, RHSType)) { 10321 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 10322 /*isError*/false); 10323 } 10324 if (LHSIsNull && !RHSIsNull) { 10325 Expr *E = LHS.get(); 10326 if (getLangOpts().ObjCAutoRefCount) 10327 CheckObjCConversion(SourceRange(), RHSType, E, 10328 CCK_ImplicitConversion); 10329 LHS = ImpCastExprToType(E, RHSType, 10330 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 10331 } 10332 else { 10333 Expr *E = RHS.get(); 10334 if (getLangOpts().ObjCAutoRefCount) 10335 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 10336 /*Diagnose=*/true, 10337 /*DiagnoseCFAudited=*/false, Opc); 10338 RHS = ImpCastExprToType(E, LHSType, 10339 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 10340 } 10341 return computeResultTy(); 10342 } 10343 if (LHSType->isObjCObjectPointerType() && 10344 RHSType->isObjCObjectPointerType()) { 10345 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 10346 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 10347 /*isError*/false); 10348 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 10349 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 10350 10351 if (LHSIsNull && !RHSIsNull) 10352 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10353 else 10354 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10355 return computeResultTy(); 10356 } 10357 10358 if (!IsRelational && LHSType->isBlockPointerType() && 10359 RHSType->isBlockCompatibleObjCPointerType(Context)) { 10360 LHS = ImpCastExprToType(LHS.get(), RHSType, 10361 CK_BlockPointerToObjCPointerCast); 10362 return computeResultTy(); 10363 } else if (!IsRelational && 10364 LHSType->isBlockCompatibleObjCPointerType(Context) && 10365 RHSType->isBlockPointerType()) { 10366 RHS = ImpCastExprToType(RHS.get(), LHSType, 10367 CK_BlockPointerToObjCPointerCast); 10368 return computeResultTy(); 10369 } 10370 } 10371 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 10372 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 10373 unsigned DiagID = 0; 10374 bool isError = false; 10375 if (LangOpts.DebuggerSupport) { 10376 // Under a debugger, allow the comparison of pointers to integers, 10377 // since users tend to want to compare addresses. 10378 } else if ((LHSIsNull && LHSType->isIntegerType()) || 10379 (RHSIsNull && RHSType->isIntegerType())) { 10380 if (IsRelational) { 10381 isError = getLangOpts().CPlusPlus; 10382 DiagID = 10383 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 10384 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 10385 } 10386 } else if (getLangOpts().CPlusPlus) { 10387 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 10388 isError = true; 10389 } else if (IsRelational) 10390 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 10391 else 10392 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 10393 10394 if (DiagID) { 10395 Diag(Loc, DiagID) 10396 << LHSType << RHSType << LHS.get()->getSourceRange() 10397 << RHS.get()->getSourceRange(); 10398 if (isError) 10399 return QualType(); 10400 } 10401 10402 if (LHSType->isIntegerType()) 10403 LHS = ImpCastExprToType(LHS.get(), RHSType, 10404 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 10405 else 10406 RHS = ImpCastExprToType(RHS.get(), LHSType, 10407 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 10408 return computeResultTy(); 10409 } 10410 10411 // Handle block pointers. 10412 if (!IsRelational && RHSIsNull 10413 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 10414 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10415 return computeResultTy(); 10416 } 10417 if (!IsRelational && LHSIsNull 10418 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 10419 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10420 return computeResultTy(); 10421 } 10422 10423 if (getLangOpts().OpenCLVersion >= 200) { 10424 if (LHSIsNull && RHSType->isQueueT()) { 10425 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10426 return computeResultTy(); 10427 } 10428 10429 if (LHSType->isQueueT() && RHSIsNull) { 10430 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10431 return computeResultTy(); 10432 } 10433 } 10434 10435 return InvalidOperands(Loc, LHS, RHS); 10436 } 10437 10438 // Return a signed ext_vector_type that is of identical size and number of 10439 // elements. For floating point vectors, return an integer type of identical 10440 // size and number of elements. In the non ext_vector_type case, search from 10441 // the largest type to the smallest type to avoid cases where long long == long, 10442 // where long gets picked over long long. 10443 QualType Sema::GetSignedVectorType(QualType V) { 10444 const VectorType *VTy = V->getAs<VectorType>(); 10445 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 10446 10447 if (isa<ExtVectorType>(VTy)) { 10448 if (TypeSize == Context.getTypeSize(Context.CharTy)) 10449 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 10450 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 10451 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 10452 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 10453 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 10454 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 10455 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 10456 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 10457 "Unhandled vector element size in vector compare"); 10458 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 10459 } 10460 10461 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 10462 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 10463 VectorType::GenericVector); 10464 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 10465 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 10466 VectorType::GenericVector); 10467 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 10468 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 10469 VectorType::GenericVector); 10470 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 10471 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 10472 VectorType::GenericVector); 10473 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 10474 "Unhandled vector element size in vector compare"); 10475 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 10476 VectorType::GenericVector); 10477 } 10478 10479 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 10480 /// operates on extended vector types. Instead of producing an IntTy result, 10481 /// like a scalar comparison, a vector comparison produces a vector of integer 10482 /// types. 10483 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 10484 SourceLocation Loc, 10485 BinaryOperatorKind Opc) { 10486 // Check to make sure we're operating on vectors of the same type and width, 10487 // Allowing one side to be a scalar of element type. 10488 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 10489 /*AllowBothBool*/true, 10490 /*AllowBoolConversions*/getLangOpts().ZVector); 10491 if (vType.isNull()) 10492 return vType; 10493 10494 QualType LHSType = LHS.get()->getType(); 10495 10496 // If AltiVec, the comparison results in a numeric type, i.e. 10497 // bool for C++, int for C 10498 if (getLangOpts().AltiVec && 10499 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 10500 return Context.getLogicalOperationType(); 10501 10502 // For non-floating point types, check for self-comparisons of the form 10503 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 10504 // often indicate logic errors in the program. 10505 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 10506 10507 // Check for comparisons of floating point operands using != and ==. 10508 if (BinaryOperator::isEqualityOp(Opc) && 10509 LHSType->hasFloatingRepresentation()) { 10510 assert(RHS.get()->getType()->hasFloatingRepresentation()); 10511 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 10512 } 10513 10514 // Return a signed type for the vector. 10515 return GetSignedVectorType(vType); 10516 } 10517 10518 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 10519 SourceLocation Loc) { 10520 // Ensure that either both operands are of the same vector type, or 10521 // one operand is of a vector type and the other is of its element type. 10522 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 10523 /*AllowBothBool*/true, 10524 /*AllowBoolConversions*/false); 10525 if (vType.isNull()) 10526 return InvalidOperands(Loc, LHS, RHS); 10527 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 10528 vType->hasFloatingRepresentation()) 10529 return InvalidOperands(Loc, LHS, RHS); 10530 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 10531 // usage of the logical operators && and || with vectors in C. This 10532 // check could be notionally dropped. 10533 if (!getLangOpts().CPlusPlus && 10534 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 10535 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 10536 10537 return GetSignedVectorType(LHS.get()->getType()); 10538 } 10539 10540 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 10541 SourceLocation Loc, 10542 BinaryOperatorKind Opc) { 10543 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 10544 10545 bool IsCompAssign = 10546 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 10547 10548 if (LHS.get()->getType()->isVectorType() || 10549 RHS.get()->getType()->isVectorType()) { 10550 if (LHS.get()->getType()->hasIntegerRepresentation() && 10551 RHS.get()->getType()->hasIntegerRepresentation()) 10552 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10553 /*AllowBothBool*/true, 10554 /*AllowBoolConversions*/getLangOpts().ZVector); 10555 return InvalidOperands(Loc, LHS, RHS); 10556 } 10557 10558 if (Opc == BO_And) 10559 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 10560 10561 ExprResult LHSResult = LHS, RHSResult = RHS; 10562 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 10563 IsCompAssign); 10564 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 10565 return QualType(); 10566 LHS = LHSResult.get(); 10567 RHS = RHSResult.get(); 10568 10569 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 10570 return compType; 10571 return InvalidOperands(Loc, LHS, RHS); 10572 } 10573 10574 // C99 6.5.[13,14] 10575 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 10576 SourceLocation Loc, 10577 BinaryOperatorKind Opc) { 10578 // Check vector operands differently. 10579 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 10580 return CheckVectorLogicalOperands(LHS, RHS, Loc); 10581 10582 // Diagnose cases where the user write a logical and/or but probably meant a 10583 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 10584 // is a constant. 10585 if (LHS.get()->getType()->isIntegerType() && 10586 !LHS.get()->getType()->isBooleanType() && 10587 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 10588 // Don't warn in macros or template instantiations. 10589 !Loc.isMacroID() && !inTemplateInstantiation()) { 10590 // If the RHS can be constant folded, and if it constant folds to something 10591 // that isn't 0 or 1 (which indicate a potential logical operation that 10592 // happened to fold to true/false) then warn. 10593 // Parens on the RHS are ignored. 10594 llvm::APSInt Result; 10595 if (RHS.get()->EvaluateAsInt(Result, Context)) 10596 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 10597 !RHS.get()->getExprLoc().isMacroID()) || 10598 (Result != 0 && Result != 1)) { 10599 Diag(Loc, diag::warn_logical_instead_of_bitwise) 10600 << RHS.get()->getSourceRange() 10601 << (Opc == BO_LAnd ? "&&" : "||"); 10602 // Suggest replacing the logical operator with the bitwise version 10603 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 10604 << (Opc == BO_LAnd ? "&" : "|") 10605 << FixItHint::CreateReplacement(SourceRange( 10606 Loc, getLocForEndOfToken(Loc)), 10607 Opc == BO_LAnd ? "&" : "|"); 10608 if (Opc == BO_LAnd) 10609 // Suggest replacing "Foo() && kNonZero" with "Foo()" 10610 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 10611 << FixItHint::CreateRemoval( 10612 SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()), 10613 RHS.get()->getLocEnd())); 10614 } 10615 } 10616 10617 if (!Context.getLangOpts().CPlusPlus) { 10618 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 10619 // not operate on the built-in scalar and vector float types. 10620 if (Context.getLangOpts().OpenCL && 10621 Context.getLangOpts().OpenCLVersion < 120) { 10622 if (LHS.get()->getType()->isFloatingType() || 10623 RHS.get()->getType()->isFloatingType()) 10624 return InvalidOperands(Loc, LHS, RHS); 10625 } 10626 10627 LHS = UsualUnaryConversions(LHS.get()); 10628 if (LHS.isInvalid()) 10629 return QualType(); 10630 10631 RHS = UsualUnaryConversions(RHS.get()); 10632 if (RHS.isInvalid()) 10633 return QualType(); 10634 10635 if (!LHS.get()->getType()->isScalarType() || 10636 !RHS.get()->getType()->isScalarType()) 10637 return InvalidOperands(Loc, LHS, RHS); 10638 10639 return Context.IntTy; 10640 } 10641 10642 // The following is safe because we only use this method for 10643 // non-overloadable operands. 10644 10645 // C++ [expr.log.and]p1 10646 // C++ [expr.log.or]p1 10647 // The operands are both contextually converted to type bool. 10648 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 10649 if (LHSRes.isInvalid()) 10650 return InvalidOperands(Loc, LHS, RHS); 10651 LHS = LHSRes; 10652 10653 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 10654 if (RHSRes.isInvalid()) 10655 return InvalidOperands(Loc, LHS, RHS); 10656 RHS = RHSRes; 10657 10658 // C++ [expr.log.and]p2 10659 // C++ [expr.log.or]p2 10660 // The result is a bool. 10661 return Context.BoolTy; 10662 } 10663 10664 static bool IsReadonlyMessage(Expr *E, Sema &S) { 10665 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 10666 if (!ME) return false; 10667 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 10668 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 10669 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 10670 if (!Base) return false; 10671 return Base->getMethodDecl() != nullptr; 10672 } 10673 10674 /// Is the given expression (which must be 'const') a reference to a 10675 /// variable which was originally non-const, but which has become 10676 /// 'const' due to being captured within a block? 10677 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 10678 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 10679 assert(E->isLValue() && E->getType().isConstQualified()); 10680 E = E->IgnoreParens(); 10681 10682 // Must be a reference to a declaration from an enclosing scope. 10683 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 10684 if (!DRE) return NCCK_None; 10685 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 10686 10687 // The declaration must be a variable which is not declared 'const'. 10688 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 10689 if (!var) return NCCK_None; 10690 if (var->getType().isConstQualified()) return NCCK_None; 10691 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 10692 10693 // Decide whether the first capture was for a block or a lambda. 10694 DeclContext *DC = S.CurContext, *Prev = nullptr; 10695 // Decide whether the first capture was for a block or a lambda. 10696 while (DC) { 10697 // For init-capture, it is possible that the variable belongs to the 10698 // template pattern of the current context. 10699 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 10700 if (var->isInitCapture() && 10701 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 10702 break; 10703 if (DC == var->getDeclContext()) 10704 break; 10705 Prev = DC; 10706 DC = DC->getParent(); 10707 } 10708 // Unless we have an init-capture, we've gone one step too far. 10709 if (!var->isInitCapture()) 10710 DC = Prev; 10711 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 10712 } 10713 10714 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 10715 Ty = Ty.getNonReferenceType(); 10716 if (IsDereference && Ty->isPointerType()) 10717 Ty = Ty->getPointeeType(); 10718 return !Ty.isConstQualified(); 10719 } 10720 10721 // Update err_typecheck_assign_const and note_typecheck_assign_const 10722 // when this enum is changed. 10723 enum { 10724 ConstFunction, 10725 ConstVariable, 10726 ConstMember, 10727 ConstMethod, 10728 NestedConstMember, 10729 ConstUnknown, // Keep as last element 10730 }; 10731 10732 /// Emit the "read-only variable not assignable" error and print notes to give 10733 /// more information about why the variable is not assignable, such as pointing 10734 /// to the declaration of a const variable, showing that a method is const, or 10735 /// that the function is returning a const reference. 10736 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 10737 SourceLocation Loc) { 10738 SourceRange ExprRange = E->getSourceRange(); 10739 10740 // Only emit one error on the first const found. All other consts will emit 10741 // a note to the error. 10742 bool DiagnosticEmitted = false; 10743 10744 // Track if the current expression is the result of a dereference, and if the 10745 // next checked expression is the result of a dereference. 10746 bool IsDereference = false; 10747 bool NextIsDereference = false; 10748 10749 // Loop to process MemberExpr chains. 10750 while (true) { 10751 IsDereference = NextIsDereference; 10752 10753 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 10754 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 10755 NextIsDereference = ME->isArrow(); 10756 const ValueDecl *VD = ME->getMemberDecl(); 10757 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 10758 // Mutable fields can be modified even if the class is const. 10759 if (Field->isMutable()) { 10760 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 10761 break; 10762 } 10763 10764 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 10765 if (!DiagnosticEmitted) { 10766 S.Diag(Loc, diag::err_typecheck_assign_const) 10767 << ExprRange << ConstMember << false /*static*/ << Field 10768 << Field->getType(); 10769 DiagnosticEmitted = true; 10770 } 10771 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10772 << ConstMember << false /*static*/ << Field << Field->getType() 10773 << Field->getSourceRange(); 10774 } 10775 E = ME->getBase(); 10776 continue; 10777 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 10778 if (VDecl->getType().isConstQualified()) { 10779 if (!DiagnosticEmitted) { 10780 S.Diag(Loc, diag::err_typecheck_assign_const) 10781 << ExprRange << ConstMember << true /*static*/ << VDecl 10782 << VDecl->getType(); 10783 DiagnosticEmitted = true; 10784 } 10785 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10786 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 10787 << VDecl->getSourceRange(); 10788 } 10789 // Static fields do not inherit constness from parents. 10790 break; 10791 } 10792 break; // End MemberExpr 10793 } else if (const ArraySubscriptExpr *ASE = 10794 dyn_cast<ArraySubscriptExpr>(E)) { 10795 E = ASE->getBase()->IgnoreParenImpCasts(); 10796 continue; 10797 } else if (const ExtVectorElementExpr *EVE = 10798 dyn_cast<ExtVectorElementExpr>(E)) { 10799 E = EVE->getBase()->IgnoreParenImpCasts(); 10800 continue; 10801 } 10802 break; 10803 } 10804 10805 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 10806 // Function calls 10807 const FunctionDecl *FD = CE->getDirectCallee(); 10808 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 10809 if (!DiagnosticEmitted) { 10810 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 10811 << ConstFunction << FD; 10812 DiagnosticEmitted = true; 10813 } 10814 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 10815 diag::note_typecheck_assign_const) 10816 << ConstFunction << FD << FD->getReturnType() 10817 << FD->getReturnTypeSourceRange(); 10818 } 10819 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 10820 // Point to variable declaration. 10821 if (const ValueDecl *VD = DRE->getDecl()) { 10822 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 10823 if (!DiagnosticEmitted) { 10824 S.Diag(Loc, diag::err_typecheck_assign_const) 10825 << ExprRange << ConstVariable << VD << VD->getType(); 10826 DiagnosticEmitted = true; 10827 } 10828 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10829 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 10830 } 10831 } 10832 } else if (isa<CXXThisExpr>(E)) { 10833 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 10834 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 10835 if (MD->isConst()) { 10836 if (!DiagnosticEmitted) { 10837 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 10838 << ConstMethod << MD; 10839 DiagnosticEmitted = true; 10840 } 10841 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 10842 << ConstMethod << MD << MD->getSourceRange(); 10843 } 10844 } 10845 } 10846 } 10847 10848 if (DiagnosticEmitted) 10849 return; 10850 10851 // Can't determine a more specific message, so display the generic error. 10852 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 10853 } 10854 10855 enum OriginalExprKind { 10856 OEK_Variable, 10857 OEK_Member, 10858 OEK_LValue 10859 }; 10860 10861 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 10862 const RecordType *Ty, 10863 SourceLocation Loc, SourceRange Range, 10864 OriginalExprKind OEK, 10865 bool &DiagnosticEmitted, 10866 bool IsNested = false) { 10867 // We walk the record hierarchy breadth-first to ensure that we print 10868 // diagnostics in field nesting order. 10869 // First, check every field for constness. 10870 for (const FieldDecl *Field : Ty->getDecl()->fields()) { 10871 if (Field->getType().isConstQualified()) { 10872 if (!DiagnosticEmitted) { 10873 S.Diag(Loc, diag::err_typecheck_assign_const) 10874 << Range << NestedConstMember << OEK << VD 10875 << IsNested << Field; 10876 DiagnosticEmitted = true; 10877 } 10878 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 10879 << NestedConstMember << IsNested << Field 10880 << Field->getType() << Field->getSourceRange(); 10881 } 10882 } 10883 // Then, recurse. 10884 for (const FieldDecl *Field : Ty->getDecl()->fields()) { 10885 QualType FTy = Field->getType(); 10886 if (const RecordType *FieldRecTy = FTy->getAs<RecordType>()) 10887 DiagnoseRecursiveConstFields(S, VD, FieldRecTy, Loc, Range, 10888 OEK, DiagnosticEmitted, true); 10889 } 10890 } 10891 10892 /// Emit an error for the case where a record we are trying to assign to has a 10893 /// const-qualified field somewhere in its hierarchy. 10894 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 10895 SourceLocation Loc) { 10896 QualType Ty = E->getType(); 10897 assert(Ty->isRecordType() && "lvalue was not record?"); 10898 SourceRange Range = E->getSourceRange(); 10899 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 10900 bool DiagEmitted = false; 10901 10902 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 10903 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 10904 Range, OEK_Member, DiagEmitted); 10905 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 10906 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 10907 Range, OEK_Variable, DiagEmitted); 10908 else 10909 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 10910 Range, OEK_LValue, DiagEmitted); 10911 if (!DiagEmitted) 10912 DiagnoseConstAssignment(S, E, Loc); 10913 } 10914 10915 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 10916 /// emit an error and return true. If so, return false. 10917 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 10918 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 10919 10920 S.CheckShadowingDeclModification(E, Loc); 10921 10922 SourceLocation OrigLoc = Loc; 10923 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 10924 &Loc); 10925 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 10926 IsLV = Expr::MLV_InvalidMessageExpression; 10927 if (IsLV == Expr::MLV_Valid) 10928 return false; 10929 10930 unsigned DiagID = 0; 10931 bool NeedType = false; 10932 switch (IsLV) { // C99 6.5.16p2 10933 case Expr::MLV_ConstQualified: 10934 // Use a specialized diagnostic when we're assigning to an object 10935 // from an enclosing function or block. 10936 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 10937 if (NCCK == NCCK_Block) 10938 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 10939 else 10940 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 10941 break; 10942 } 10943 10944 // In ARC, use some specialized diagnostics for occasions where we 10945 // infer 'const'. These are always pseudo-strong variables. 10946 if (S.getLangOpts().ObjCAutoRefCount) { 10947 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 10948 if (declRef && isa<VarDecl>(declRef->getDecl())) { 10949 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 10950 10951 // Use the normal diagnostic if it's pseudo-__strong but the 10952 // user actually wrote 'const'. 10953 if (var->isARCPseudoStrong() && 10954 (!var->getTypeSourceInfo() || 10955 !var->getTypeSourceInfo()->getType().isConstQualified())) { 10956 // There are two pseudo-strong cases: 10957 // - self 10958 ObjCMethodDecl *method = S.getCurMethodDecl(); 10959 if (method && var == method->getSelfDecl()) 10960 DiagID = method->isClassMethod() 10961 ? diag::err_typecheck_arc_assign_self_class_method 10962 : diag::err_typecheck_arc_assign_self; 10963 10964 // - fast enumeration variables 10965 else 10966 DiagID = diag::err_typecheck_arr_assign_enumeration; 10967 10968 SourceRange Assign; 10969 if (Loc != OrigLoc) 10970 Assign = SourceRange(OrigLoc, OrigLoc); 10971 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10972 // We need to preserve the AST regardless, so migration tool 10973 // can do its job. 10974 return false; 10975 } 10976 } 10977 } 10978 10979 // If none of the special cases above are triggered, then this is a 10980 // simple const assignment. 10981 if (DiagID == 0) { 10982 DiagnoseConstAssignment(S, E, Loc); 10983 return true; 10984 } 10985 10986 break; 10987 case Expr::MLV_ConstAddrSpace: 10988 DiagnoseConstAssignment(S, E, Loc); 10989 return true; 10990 case Expr::MLV_ConstQualifiedField: 10991 DiagnoseRecursiveConstFields(S, E, Loc); 10992 return true; 10993 case Expr::MLV_ArrayType: 10994 case Expr::MLV_ArrayTemporary: 10995 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 10996 NeedType = true; 10997 break; 10998 case Expr::MLV_NotObjectType: 10999 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 11000 NeedType = true; 11001 break; 11002 case Expr::MLV_LValueCast: 11003 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 11004 break; 11005 case Expr::MLV_Valid: 11006 llvm_unreachable("did not take early return for MLV_Valid"); 11007 case Expr::MLV_InvalidExpression: 11008 case Expr::MLV_MemberFunction: 11009 case Expr::MLV_ClassTemporary: 11010 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 11011 break; 11012 case Expr::MLV_IncompleteType: 11013 case Expr::MLV_IncompleteVoidType: 11014 return S.RequireCompleteType(Loc, E->getType(), 11015 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 11016 case Expr::MLV_DuplicateVectorComponents: 11017 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 11018 break; 11019 case Expr::MLV_NoSetterProperty: 11020 llvm_unreachable("readonly properties should be processed differently"); 11021 case Expr::MLV_InvalidMessageExpression: 11022 DiagID = diag::err_readonly_message_assignment; 11023 break; 11024 case Expr::MLV_SubObjCPropertySetting: 11025 DiagID = diag::err_no_subobject_property_setting; 11026 break; 11027 } 11028 11029 SourceRange Assign; 11030 if (Loc != OrigLoc) 11031 Assign = SourceRange(OrigLoc, OrigLoc); 11032 if (NeedType) 11033 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 11034 else 11035 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 11036 return true; 11037 } 11038 11039 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 11040 SourceLocation Loc, 11041 Sema &Sema) { 11042 if (Sema.inTemplateInstantiation()) 11043 return; 11044 if (Sema.isUnevaluatedContext()) 11045 return; 11046 if (Loc.isInvalid() || Loc.isMacroID()) 11047 return; 11048 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 11049 return; 11050 11051 // C / C++ fields 11052 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 11053 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 11054 if (ML && MR) { 11055 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 11056 return; 11057 const ValueDecl *LHSDecl = 11058 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 11059 const ValueDecl *RHSDecl = 11060 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 11061 if (LHSDecl != RHSDecl) 11062 return; 11063 if (LHSDecl->getType().isVolatileQualified()) 11064 return; 11065 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 11066 if (RefTy->getPointeeType().isVolatileQualified()) 11067 return; 11068 11069 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 11070 } 11071 11072 // Objective-C instance variables 11073 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 11074 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 11075 if (OL && OR && OL->getDecl() == OR->getDecl()) { 11076 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 11077 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 11078 if (RL && RR && RL->getDecl() == RR->getDecl()) 11079 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 11080 } 11081 } 11082 11083 // C99 6.5.16.1 11084 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 11085 SourceLocation Loc, 11086 QualType CompoundType) { 11087 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 11088 11089 // Verify that LHS is a modifiable lvalue, and emit error if not. 11090 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 11091 return QualType(); 11092 11093 QualType LHSType = LHSExpr->getType(); 11094 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 11095 CompoundType; 11096 // OpenCL v1.2 s6.1.1.1 p2: 11097 // The half data type can only be used to declare a pointer to a buffer that 11098 // contains half values 11099 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 11100 LHSType->isHalfType()) { 11101 Diag(Loc, diag::err_opencl_half_load_store) << 1 11102 << LHSType.getUnqualifiedType(); 11103 return QualType(); 11104 } 11105 11106 AssignConvertType ConvTy; 11107 if (CompoundType.isNull()) { 11108 Expr *RHSCheck = RHS.get(); 11109 11110 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 11111 11112 QualType LHSTy(LHSType); 11113 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 11114 if (RHS.isInvalid()) 11115 return QualType(); 11116 // Special case of NSObject attributes on c-style pointer types. 11117 if (ConvTy == IncompatiblePointer && 11118 ((Context.isObjCNSObjectType(LHSType) && 11119 RHSType->isObjCObjectPointerType()) || 11120 (Context.isObjCNSObjectType(RHSType) && 11121 LHSType->isObjCObjectPointerType()))) 11122 ConvTy = Compatible; 11123 11124 if (ConvTy == Compatible && 11125 LHSType->isObjCObjectType()) 11126 Diag(Loc, diag::err_objc_object_assignment) 11127 << LHSType; 11128 11129 // If the RHS is a unary plus or minus, check to see if they = and + are 11130 // right next to each other. If so, the user may have typo'd "x =+ 4" 11131 // instead of "x += 4". 11132 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 11133 RHSCheck = ICE->getSubExpr(); 11134 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 11135 if ((UO->getOpcode() == UO_Plus || 11136 UO->getOpcode() == UO_Minus) && 11137 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 11138 // Only if the two operators are exactly adjacent. 11139 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 11140 // And there is a space or other character before the subexpr of the 11141 // unary +/-. We don't want to warn on "x=-1". 11142 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 11143 UO->getSubExpr()->getLocStart().isFileID()) { 11144 Diag(Loc, diag::warn_not_compound_assign) 11145 << (UO->getOpcode() == UO_Plus ? "+" : "-") 11146 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 11147 } 11148 } 11149 11150 if (ConvTy == Compatible) { 11151 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 11152 // Warn about retain cycles where a block captures the LHS, but 11153 // not if the LHS is a simple variable into which the block is 11154 // being stored...unless that variable can be captured by reference! 11155 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 11156 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 11157 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 11158 checkRetainCycles(LHSExpr, RHS.get()); 11159 } 11160 11161 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 11162 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 11163 // It is safe to assign a weak reference into a strong variable. 11164 // Although this code can still have problems: 11165 // id x = self.weakProp; 11166 // id y = self.weakProp; 11167 // we do not warn to warn spuriously when 'x' and 'y' are on separate 11168 // paths through the function. This should be revisited if 11169 // -Wrepeated-use-of-weak is made flow-sensitive. 11170 // For ObjCWeak only, we do not warn if the assign is to a non-weak 11171 // variable, which will be valid for the current autorelease scope. 11172 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 11173 RHS.get()->getLocStart())) 11174 getCurFunction()->markSafeWeakUse(RHS.get()); 11175 11176 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 11177 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 11178 } 11179 } 11180 } else { 11181 // Compound assignment "x += y" 11182 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 11183 } 11184 11185 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 11186 RHS.get(), AA_Assigning)) 11187 return QualType(); 11188 11189 CheckForNullPointerDereference(*this, LHSExpr); 11190 11191 // C99 6.5.16p3: The type of an assignment expression is the type of the 11192 // left operand unless the left operand has qualified type, in which case 11193 // it is the unqualified version of the type of the left operand. 11194 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 11195 // is converted to the type of the assignment expression (above). 11196 // C++ 5.17p1: the type of the assignment expression is that of its left 11197 // operand. 11198 return (getLangOpts().CPlusPlus 11199 ? LHSType : LHSType.getUnqualifiedType()); 11200 } 11201 11202 // Only ignore explicit casts to void. 11203 static bool IgnoreCommaOperand(const Expr *E) { 11204 E = E->IgnoreParens(); 11205 11206 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 11207 if (CE->getCastKind() == CK_ToVoid) { 11208 return true; 11209 } 11210 } 11211 11212 return false; 11213 } 11214 11215 // Look for instances where it is likely the comma operator is confused with 11216 // another operator. There is a whitelist of acceptable expressions for the 11217 // left hand side of the comma operator, otherwise emit a warning. 11218 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 11219 // No warnings in macros 11220 if (Loc.isMacroID()) 11221 return; 11222 11223 // Don't warn in template instantiations. 11224 if (inTemplateInstantiation()) 11225 return; 11226 11227 // Scope isn't fine-grained enough to whitelist the specific cases, so 11228 // instead, skip more than needed, then call back into here with the 11229 // CommaVisitor in SemaStmt.cpp. 11230 // The whitelisted locations are the initialization and increment portions 11231 // of a for loop. The additional checks are on the condition of 11232 // if statements, do/while loops, and for loops. 11233 const unsigned ForIncrementFlags = 11234 Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope; 11235 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 11236 const unsigned ScopeFlags = getCurScope()->getFlags(); 11237 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 11238 (ScopeFlags & ForInitFlags) == ForInitFlags) 11239 return; 11240 11241 // If there are multiple comma operators used together, get the RHS of the 11242 // of the comma operator as the LHS. 11243 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 11244 if (BO->getOpcode() != BO_Comma) 11245 break; 11246 LHS = BO->getRHS(); 11247 } 11248 11249 // Only allow some expressions on LHS to not warn. 11250 if (IgnoreCommaOperand(LHS)) 11251 return; 11252 11253 Diag(Loc, diag::warn_comma_operator); 11254 Diag(LHS->getLocStart(), diag::note_cast_to_void) 11255 << LHS->getSourceRange() 11256 << FixItHint::CreateInsertion(LHS->getLocStart(), 11257 LangOpts.CPlusPlus ? "static_cast<void>(" 11258 : "(void)(") 11259 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()), 11260 ")"); 11261 } 11262 11263 // C99 6.5.17 11264 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 11265 SourceLocation Loc) { 11266 LHS = S.CheckPlaceholderExpr(LHS.get()); 11267 RHS = S.CheckPlaceholderExpr(RHS.get()); 11268 if (LHS.isInvalid() || RHS.isInvalid()) 11269 return QualType(); 11270 11271 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 11272 // operands, but not unary promotions. 11273 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 11274 11275 // So we treat the LHS as a ignored value, and in C++ we allow the 11276 // containing site to determine what should be done with the RHS. 11277 LHS = S.IgnoredValueConversions(LHS.get()); 11278 if (LHS.isInvalid()) 11279 return QualType(); 11280 11281 S.DiagnoseUnusedExprResult(LHS.get()); 11282 11283 if (!S.getLangOpts().CPlusPlus) { 11284 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 11285 if (RHS.isInvalid()) 11286 return QualType(); 11287 if (!RHS.get()->getType()->isVoidType()) 11288 S.RequireCompleteType(Loc, RHS.get()->getType(), 11289 diag::err_incomplete_type); 11290 } 11291 11292 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 11293 S.DiagnoseCommaOperator(LHS.get(), Loc); 11294 11295 return RHS.get()->getType(); 11296 } 11297 11298 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 11299 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 11300 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 11301 ExprValueKind &VK, 11302 ExprObjectKind &OK, 11303 SourceLocation OpLoc, 11304 bool IsInc, bool IsPrefix) { 11305 if (Op->isTypeDependent()) 11306 return S.Context.DependentTy; 11307 11308 QualType ResType = Op->getType(); 11309 // Atomic types can be used for increment / decrement where the non-atomic 11310 // versions can, so ignore the _Atomic() specifier for the purpose of 11311 // checking. 11312 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 11313 ResType = ResAtomicType->getValueType(); 11314 11315 assert(!ResType.isNull() && "no type for increment/decrement expression"); 11316 11317 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 11318 // Decrement of bool is not allowed. 11319 if (!IsInc) { 11320 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 11321 return QualType(); 11322 } 11323 // Increment of bool sets it to true, but is deprecated. 11324 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 11325 : diag::warn_increment_bool) 11326 << Op->getSourceRange(); 11327 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 11328 // Error on enum increments and decrements in C++ mode 11329 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 11330 return QualType(); 11331 } else if (ResType->isRealType()) { 11332 // OK! 11333 } else if (ResType->isPointerType()) { 11334 // C99 6.5.2.4p2, 6.5.6p2 11335 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 11336 return QualType(); 11337 } else if (ResType->isObjCObjectPointerType()) { 11338 // On modern runtimes, ObjC pointer arithmetic is forbidden. 11339 // Otherwise, we just need a complete type. 11340 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 11341 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 11342 return QualType(); 11343 } else if (ResType->isAnyComplexType()) { 11344 // C99 does not support ++/-- on complex types, we allow as an extension. 11345 S.Diag(OpLoc, diag::ext_integer_increment_complex) 11346 << ResType << Op->getSourceRange(); 11347 } else if (ResType->isPlaceholderType()) { 11348 ExprResult PR = S.CheckPlaceholderExpr(Op); 11349 if (PR.isInvalid()) return QualType(); 11350 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 11351 IsInc, IsPrefix); 11352 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 11353 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 11354 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 11355 (ResType->getAs<VectorType>()->getVectorKind() != 11356 VectorType::AltiVecBool)) { 11357 // The z vector extensions allow ++ and -- for non-bool vectors. 11358 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 11359 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 11360 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 11361 } else { 11362 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 11363 << ResType << int(IsInc) << Op->getSourceRange(); 11364 return QualType(); 11365 } 11366 // At this point, we know we have a real, complex or pointer type. 11367 // Now make sure the operand is a modifiable lvalue. 11368 if (CheckForModifiableLvalue(Op, OpLoc, S)) 11369 return QualType(); 11370 // In C++, a prefix increment is the same type as the operand. Otherwise 11371 // (in C or with postfix), the increment is the unqualified type of the 11372 // operand. 11373 if (IsPrefix && S.getLangOpts().CPlusPlus) { 11374 VK = VK_LValue; 11375 OK = Op->getObjectKind(); 11376 return ResType; 11377 } else { 11378 VK = VK_RValue; 11379 return ResType.getUnqualifiedType(); 11380 } 11381 } 11382 11383 11384 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 11385 /// This routine allows us to typecheck complex/recursive expressions 11386 /// where the declaration is needed for type checking. We only need to 11387 /// handle cases when the expression references a function designator 11388 /// or is an lvalue. Here are some examples: 11389 /// - &(x) => x 11390 /// - &*****f => f for f a function designator. 11391 /// - &s.xx => s 11392 /// - &s.zz[1].yy -> s, if zz is an array 11393 /// - *(x + 1) -> x, if x is an array 11394 /// - &"123"[2] -> 0 11395 /// - & __real__ x -> x 11396 static ValueDecl *getPrimaryDecl(Expr *E) { 11397 switch (E->getStmtClass()) { 11398 case Stmt::DeclRefExprClass: 11399 return cast<DeclRefExpr>(E)->getDecl(); 11400 case Stmt::MemberExprClass: 11401 // If this is an arrow operator, the address is an offset from 11402 // the base's value, so the object the base refers to is 11403 // irrelevant. 11404 if (cast<MemberExpr>(E)->isArrow()) 11405 return nullptr; 11406 // Otherwise, the expression refers to a part of the base 11407 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 11408 case Stmt::ArraySubscriptExprClass: { 11409 // FIXME: This code shouldn't be necessary! We should catch the implicit 11410 // promotion of register arrays earlier. 11411 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 11412 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 11413 if (ICE->getSubExpr()->getType()->isArrayType()) 11414 return getPrimaryDecl(ICE->getSubExpr()); 11415 } 11416 return nullptr; 11417 } 11418 case Stmt::UnaryOperatorClass: { 11419 UnaryOperator *UO = cast<UnaryOperator>(E); 11420 11421 switch(UO->getOpcode()) { 11422 case UO_Real: 11423 case UO_Imag: 11424 case UO_Extension: 11425 return getPrimaryDecl(UO->getSubExpr()); 11426 default: 11427 return nullptr; 11428 } 11429 } 11430 case Stmt::ParenExprClass: 11431 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 11432 case Stmt::ImplicitCastExprClass: 11433 // If the result of an implicit cast is an l-value, we care about 11434 // the sub-expression; otherwise, the result here doesn't matter. 11435 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 11436 default: 11437 return nullptr; 11438 } 11439 } 11440 11441 namespace { 11442 enum { 11443 AO_Bit_Field = 0, 11444 AO_Vector_Element = 1, 11445 AO_Property_Expansion = 2, 11446 AO_Register_Variable = 3, 11447 AO_No_Error = 4 11448 }; 11449 } 11450 /// Diagnose invalid operand for address of operations. 11451 /// 11452 /// \param Type The type of operand which cannot have its address taken. 11453 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 11454 Expr *E, unsigned Type) { 11455 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 11456 } 11457 11458 /// CheckAddressOfOperand - The operand of & must be either a function 11459 /// designator or an lvalue designating an object. If it is an lvalue, the 11460 /// object cannot be declared with storage class register or be a bit field. 11461 /// Note: The usual conversions are *not* applied to the operand of the & 11462 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 11463 /// In C++, the operand might be an overloaded function name, in which case 11464 /// we allow the '&' but retain the overloaded-function type. 11465 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 11466 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 11467 if (PTy->getKind() == BuiltinType::Overload) { 11468 Expr *E = OrigOp.get()->IgnoreParens(); 11469 if (!isa<OverloadExpr>(E)) { 11470 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 11471 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 11472 << OrigOp.get()->getSourceRange(); 11473 return QualType(); 11474 } 11475 11476 OverloadExpr *Ovl = cast<OverloadExpr>(E); 11477 if (isa<UnresolvedMemberExpr>(Ovl)) 11478 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 11479 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11480 << OrigOp.get()->getSourceRange(); 11481 return QualType(); 11482 } 11483 11484 return Context.OverloadTy; 11485 } 11486 11487 if (PTy->getKind() == BuiltinType::UnknownAny) 11488 return Context.UnknownAnyTy; 11489 11490 if (PTy->getKind() == BuiltinType::BoundMember) { 11491 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11492 << OrigOp.get()->getSourceRange(); 11493 return QualType(); 11494 } 11495 11496 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 11497 if (OrigOp.isInvalid()) return QualType(); 11498 } 11499 11500 if (OrigOp.get()->isTypeDependent()) 11501 return Context.DependentTy; 11502 11503 assert(!OrigOp.get()->getType()->isPlaceholderType()); 11504 11505 // Make sure to ignore parentheses in subsequent checks 11506 Expr *op = OrigOp.get()->IgnoreParens(); 11507 11508 // In OpenCL captures for blocks called as lambda functions 11509 // are located in the private address space. Blocks used in 11510 // enqueue_kernel can be located in a different address space 11511 // depending on a vendor implementation. Thus preventing 11512 // taking an address of the capture to avoid invalid AS casts. 11513 if (LangOpts.OpenCL) { 11514 auto* VarRef = dyn_cast<DeclRefExpr>(op); 11515 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 11516 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 11517 return QualType(); 11518 } 11519 } 11520 11521 if (getLangOpts().C99) { 11522 // Implement C99-only parts of addressof rules. 11523 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 11524 if (uOp->getOpcode() == UO_Deref) 11525 // Per C99 6.5.3.2, the address of a deref always returns a valid result 11526 // (assuming the deref expression is valid). 11527 return uOp->getSubExpr()->getType(); 11528 } 11529 // Technically, there should be a check for array subscript 11530 // expressions here, but the result of one is always an lvalue anyway. 11531 } 11532 ValueDecl *dcl = getPrimaryDecl(op); 11533 11534 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 11535 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 11536 op->getLocStart())) 11537 return QualType(); 11538 11539 Expr::LValueClassification lval = op->ClassifyLValue(Context); 11540 unsigned AddressOfError = AO_No_Error; 11541 11542 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 11543 bool sfinae = (bool)isSFINAEContext(); 11544 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 11545 : diag::ext_typecheck_addrof_temporary) 11546 << op->getType() << op->getSourceRange(); 11547 if (sfinae) 11548 return QualType(); 11549 // Materialize the temporary as an lvalue so that we can take its address. 11550 OrigOp = op = 11551 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 11552 } else if (isa<ObjCSelectorExpr>(op)) { 11553 return Context.getPointerType(op->getType()); 11554 } else if (lval == Expr::LV_MemberFunction) { 11555 // If it's an instance method, make a member pointer. 11556 // The expression must have exactly the form &A::foo. 11557 11558 // If the underlying expression isn't a decl ref, give up. 11559 if (!isa<DeclRefExpr>(op)) { 11560 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11561 << OrigOp.get()->getSourceRange(); 11562 return QualType(); 11563 } 11564 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 11565 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 11566 11567 // The id-expression was parenthesized. 11568 if (OrigOp.get() != DRE) { 11569 Diag(OpLoc, diag::err_parens_pointer_member_function) 11570 << OrigOp.get()->getSourceRange(); 11571 11572 // The method was named without a qualifier. 11573 } else if (!DRE->getQualifier()) { 11574 if (MD->getParent()->getName().empty()) 11575 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 11576 << op->getSourceRange(); 11577 else { 11578 SmallString<32> Str; 11579 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 11580 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 11581 << op->getSourceRange() 11582 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 11583 } 11584 } 11585 11586 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 11587 if (isa<CXXDestructorDecl>(MD)) 11588 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 11589 11590 QualType MPTy = Context.getMemberPointerType( 11591 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 11592 // Under the MS ABI, lock down the inheritance model now. 11593 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11594 (void)isCompleteType(OpLoc, MPTy); 11595 return MPTy; 11596 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 11597 // C99 6.5.3.2p1 11598 // The operand must be either an l-value or a function designator 11599 if (!op->getType()->isFunctionType()) { 11600 // Use a special diagnostic for loads from property references. 11601 if (isa<PseudoObjectExpr>(op)) { 11602 AddressOfError = AO_Property_Expansion; 11603 } else { 11604 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 11605 << op->getType() << op->getSourceRange(); 11606 return QualType(); 11607 } 11608 } 11609 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 11610 // The operand cannot be a bit-field 11611 AddressOfError = AO_Bit_Field; 11612 } else if (op->getObjectKind() == OK_VectorComponent) { 11613 // The operand cannot be an element of a vector 11614 AddressOfError = AO_Vector_Element; 11615 } else if (dcl) { // C99 6.5.3.2p1 11616 // We have an lvalue with a decl. Make sure the decl is not declared 11617 // with the register storage-class specifier. 11618 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 11619 // in C++ it is not error to take address of a register 11620 // variable (c++03 7.1.1P3) 11621 if (vd->getStorageClass() == SC_Register && 11622 !getLangOpts().CPlusPlus) { 11623 AddressOfError = AO_Register_Variable; 11624 } 11625 } else if (isa<MSPropertyDecl>(dcl)) { 11626 AddressOfError = AO_Property_Expansion; 11627 } else if (isa<FunctionTemplateDecl>(dcl)) { 11628 return Context.OverloadTy; 11629 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 11630 // Okay: we can take the address of a field. 11631 // Could be a pointer to member, though, if there is an explicit 11632 // scope qualifier for the class. 11633 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 11634 DeclContext *Ctx = dcl->getDeclContext(); 11635 if (Ctx && Ctx->isRecord()) { 11636 if (dcl->getType()->isReferenceType()) { 11637 Diag(OpLoc, 11638 diag::err_cannot_form_pointer_to_member_of_reference_type) 11639 << dcl->getDeclName() << dcl->getType(); 11640 return QualType(); 11641 } 11642 11643 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 11644 Ctx = Ctx->getParent(); 11645 11646 QualType MPTy = Context.getMemberPointerType( 11647 op->getType(), 11648 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 11649 // Under the MS ABI, lock down the inheritance model now. 11650 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11651 (void)isCompleteType(OpLoc, MPTy); 11652 return MPTy; 11653 } 11654 } 11655 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 11656 !isa<BindingDecl>(dcl)) 11657 llvm_unreachable("Unknown/unexpected decl type"); 11658 } 11659 11660 if (AddressOfError != AO_No_Error) { 11661 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 11662 return QualType(); 11663 } 11664 11665 if (lval == Expr::LV_IncompleteVoidType) { 11666 // Taking the address of a void variable is technically illegal, but we 11667 // allow it in cases which are otherwise valid. 11668 // Example: "extern void x; void* y = &x;". 11669 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 11670 } 11671 11672 // If the operand has type "type", the result has type "pointer to type". 11673 if (op->getType()->isObjCObjectType()) 11674 return Context.getObjCObjectPointerType(op->getType()); 11675 11676 CheckAddressOfPackedMember(op); 11677 11678 return Context.getPointerType(op->getType()); 11679 } 11680 11681 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 11682 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 11683 if (!DRE) 11684 return; 11685 const Decl *D = DRE->getDecl(); 11686 if (!D) 11687 return; 11688 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 11689 if (!Param) 11690 return; 11691 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 11692 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 11693 return; 11694 if (FunctionScopeInfo *FD = S.getCurFunction()) 11695 if (!FD->ModifiedNonNullParams.count(Param)) 11696 FD->ModifiedNonNullParams.insert(Param); 11697 } 11698 11699 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 11700 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 11701 SourceLocation OpLoc) { 11702 if (Op->isTypeDependent()) 11703 return S.Context.DependentTy; 11704 11705 ExprResult ConvResult = S.UsualUnaryConversions(Op); 11706 if (ConvResult.isInvalid()) 11707 return QualType(); 11708 Op = ConvResult.get(); 11709 QualType OpTy = Op->getType(); 11710 QualType Result; 11711 11712 if (isa<CXXReinterpretCastExpr>(Op)) { 11713 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 11714 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 11715 Op->getSourceRange()); 11716 } 11717 11718 if (const PointerType *PT = OpTy->getAs<PointerType>()) 11719 { 11720 Result = PT->getPointeeType(); 11721 } 11722 else if (const ObjCObjectPointerType *OPT = 11723 OpTy->getAs<ObjCObjectPointerType>()) 11724 Result = OPT->getPointeeType(); 11725 else { 11726 ExprResult PR = S.CheckPlaceholderExpr(Op); 11727 if (PR.isInvalid()) return QualType(); 11728 if (PR.get() != Op) 11729 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 11730 } 11731 11732 if (Result.isNull()) { 11733 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 11734 << OpTy << Op->getSourceRange(); 11735 return QualType(); 11736 } 11737 11738 // Note that per both C89 and C99, indirection is always legal, even if Result 11739 // is an incomplete type or void. It would be possible to warn about 11740 // dereferencing a void pointer, but it's completely well-defined, and such a 11741 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 11742 // for pointers to 'void' but is fine for any other pointer type: 11743 // 11744 // C++ [expr.unary.op]p1: 11745 // [...] the expression to which [the unary * operator] is applied shall 11746 // be a pointer to an object type, or a pointer to a function type 11747 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 11748 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 11749 << OpTy << Op->getSourceRange(); 11750 11751 // Dereferences are usually l-values... 11752 VK = VK_LValue; 11753 11754 // ...except that certain expressions are never l-values in C. 11755 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 11756 VK = VK_RValue; 11757 11758 return Result; 11759 } 11760 11761 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 11762 BinaryOperatorKind Opc; 11763 switch (Kind) { 11764 default: llvm_unreachable("Unknown binop!"); 11765 case tok::periodstar: Opc = BO_PtrMemD; break; 11766 case tok::arrowstar: Opc = BO_PtrMemI; break; 11767 case tok::star: Opc = BO_Mul; break; 11768 case tok::slash: Opc = BO_Div; break; 11769 case tok::percent: Opc = BO_Rem; break; 11770 case tok::plus: Opc = BO_Add; break; 11771 case tok::minus: Opc = BO_Sub; break; 11772 case tok::lessless: Opc = BO_Shl; break; 11773 case tok::greatergreater: Opc = BO_Shr; break; 11774 case tok::lessequal: Opc = BO_LE; break; 11775 case tok::less: Opc = BO_LT; break; 11776 case tok::greaterequal: Opc = BO_GE; break; 11777 case tok::greater: Opc = BO_GT; break; 11778 case tok::exclaimequal: Opc = BO_NE; break; 11779 case tok::equalequal: Opc = BO_EQ; break; 11780 case tok::spaceship: Opc = BO_Cmp; break; 11781 case tok::amp: Opc = BO_And; break; 11782 case tok::caret: Opc = BO_Xor; break; 11783 case tok::pipe: Opc = BO_Or; break; 11784 case tok::ampamp: Opc = BO_LAnd; break; 11785 case tok::pipepipe: Opc = BO_LOr; break; 11786 case tok::equal: Opc = BO_Assign; break; 11787 case tok::starequal: Opc = BO_MulAssign; break; 11788 case tok::slashequal: Opc = BO_DivAssign; break; 11789 case tok::percentequal: Opc = BO_RemAssign; break; 11790 case tok::plusequal: Opc = BO_AddAssign; break; 11791 case tok::minusequal: Opc = BO_SubAssign; break; 11792 case tok::lesslessequal: Opc = BO_ShlAssign; break; 11793 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 11794 case tok::ampequal: Opc = BO_AndAssign; break; 11795 case tok::caretequal: Opc = BO_XorAssign; break; 11796 case tok::pipeequal: Opc = BO_OrAssign; break; 11797 case tok::comma: Opc = BO_Comma; break; 11798 } 11799 return Opc; 11800 } 11801 11802 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 11803 tok::TokenKind Kind) { 11804 UnaryOperatorKind Opc; 11805 switch (Kind) { 11806 default: llvm_unreachable("Unknown unary op!"); 11807 case tok::plusplus: Opc = UO_PreInc; break; 11808 case tok::minusminus: Opc = UO_PreDec; break; 11809 case tok::amp: Opc = UO_AddrOf; break; 11810 case tok::star: Opc = UO_Deref; break; 11811 case tok::plus: Opc = UO_Plus; break; 11812 case tok::minus: Opc = UO_Minus; break; 11813 case tok::tilde: Opc = UO_Not; break; 11814 case tok::exclaim: Opc = UO_LNot; break; 11815 case tok::kw___real: Opc = UO_Real; break; 11816 case tok::kw___imag: Opc = UO_Imag; break; 11817 case tok::kw___extension__: Opc = UO_Extension; break; 11818 } 11819 return Opc; 11820 } 11821 11822 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 11823 /// This warning suppressed in the event of macro expansions. 11824 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 11825 SourceLocation OpLoc, bool IsBuiltin) { 11826 if (S.inTemplateInstantiation()) 11827 return; 11828 if (S.isUnevaluatedContext()) 11829 return; 11830 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 11831 return; 11832 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 11833 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 11834 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 11835 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 11836 if (!LHSDeclRef || !RHSDeclRef || 11837 LHSDeclRef->getLocation().isMacroID() || 11838 RHSDeclRef->getLocation().isMacroID()) 11839 return; 11840 const ValueDecl *LHSDecl = 11841 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 11842 const ValueDecl *RHSDecl = 11843 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 11844 if (LHSDecl != RHSDecl) 11845 return; 11846 if (LHSDecl->getType().isVolatileQualified()) 11847 return; 11848 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 11849 if (RefTy->getPointeeType().isVolatileQualified()) 11850 return; 11851 11852 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 11853 : diag::warn_self_assignment_overloaded) 11854 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 11855 << RHSExpr->getSourceRange(); 11856 } 11857 11858 /// Check if a bitwise-& is performed on an Objective-C pointer. This 11859 /// is usually indicative of introspection within the Objective-C pointer. 11860 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 11861 SourceLocation OpLoc) { 11862 if (!S.getLangOpts().ObjC1) 11863 return; 11864 11865 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 11866 const Expr *LHS = L.get(); 11867 const Expr *RHS = R.get(); 11868 11869 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 11870 ObjCPointerExpr = LHS; 11871 OtherExpr = RHS; 11872 } 11873 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 11874 ObjCPointerExpr = RHS; 11875 OtherExpr = LHS; 11876 } 11877 11878 // This warning is deliberately made very specific to reduce false 11879 // positives with logic that uses '&' for hashing. This logic mainly 11880 // looks for code trying to introspect into tagged pointers, which 11881 // code should generally never do. 11882 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 11883 unsigned Diag = diag::warn_objc_pointer_masking; 11884 // Determine if we are introspecting the result of performSelectorXXX. 11885 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 11886 // Special case messages to -performSelector and friends, which 11887 // can return non-pointer values boxed in a pointer value. 11888 // Some clients may wish to silence warnings in this subcase. 11889 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 11890 Selector S = ME->getSelector(); 11891 StringRef SelArg0 = S.getNameForSlot(0); 11892 if (SelArg0.startswith("performSelector")) 11893 Diag = diag::warn_objc_pointer_masking_performSelector; 11894 } 11895 11896 S.Diag(OpLoc, Diag) 11897 << ObjCPointerExpr->getSourceRange(); 11898 } 11899 } 11900 11901 static NamedDecl *getDeclFromExpr(Expr *E) { 11902 if (!E) 11903 return nullptr; 11904 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 11905 return DRE->getDecl(); 11906 if (auto *ME = dyn_cast<MemberExpr>(E)) 11907 return ME->getMemberDecl(); 11908 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 11909 return IRE->getDecl(); 11910 return nullptr; 11911 } 11912 11913 // This helper function promotes a binary operator's operands (which are of a 11914 // half vector type) to a vector of floats and then truncates the result to 11915 // a vector of either half or short. 11916 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 11917 BinaryOperatorKind Opc, QualType ResultTy, 11918 ExprValueKind VK, ExprObjectKind OK, 11919 bool IsCompAssign, SourceLocation OpLoc, 11920 FPOptions FPFeatures) { 11921 auto &Context = S.getASTContext(); 11922 assert((isVector(ResultTy, Context.HalfTy) || 11923 isVector(ResultTy, Context.ShortTy)) && 11924 "Result must be a vector of half or short"); 11925 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 11926 isVector(RHS.get()->getType(), Context.HalfTy) && 11927 "both operands expected to be a half vector"); 11928 11929 RHS = convertVector(RHS.get(), Context.FloatTy, S); 11930 QualType BinOpResTy = RHS.get()->getType(); 11931 11932 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 11933 // change BinOpResTy to a vector of ints. 11934 if (isVector(ResultTy, Context.ShortTy)) 11935 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 11936 11937 if (IsCompAssign) 11938 return new (Context) CompoundAssignOperator( 11939 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy, 11940 OpLoc, FPFeatures); 11941 11942 LHS = convertVector(LHS.get(), Context.FloatTy, S); 11943 auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy, 11944 VK, OK, OpLoc, FPFeatures); 11945 return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S); 11946 } 11947 11948 static std::pair<ExprResult, ExprResult> 11949 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 11950 Expr *RHSExpr) { 11951 ExprResult LHS = LHSExpr, RHS = RHSExpr; 11952 if (!S.getLangOpts().CPlusPlus) { 11953 // C cannot handle TypoExpr nodes on either side of a binop because it 11954 // doesn't handle dependent types properly, so make sure any TypoExprs have 11955 // been dealt with before checking the operands. 11956 LHS = S.CorrectDelayedTyposInExpr(LHS); 11957 RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) { 11958 if (Opc != BO_Assign) 11959 return ExprResult(E); 11960 // Avoid correcting the RHS to the same Expr as the LHS. 11961 Decl *D = getDeclFromExpr(E); 11962 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 11963 }); 11964 } 11965 return std::make_pair(LHS, RHS); 11966 } 11967 11968 /// Returns true if conversion between vectors of halfs and vectors of floats 11969 /// is needed. 11970 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 11971 QualType SrcType) { 11972 return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType && 11973 !Ctx.getTargetInfo().useFP16ConversionIntrinsics() && 11974 isVector(SrcType, Ctx.HalfTy); 11975 } 11976 11977 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 11978 /// operator @p Opc at location @c TokLoc. This routine only supports 11979 /// built-in operations; ActOnBinOp handles overloaded operators. 11980 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 11981 BinaryOperatorKind Opc, 11982 Expr *LHSExpr, Expr *RHSExpr) { 11983 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 11984 // The syntax only allows initializer lists on the RHS of assignment, 11985 // so we don't need to worry about accepting invalid code for 11986 // non-assignment operators. 11987 // C++11 5.17p9: 11988 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 11989 // of x = {} is x = T(). 11990 InitializationKind Kind = InitializationKind::CreateDirectList( 11991 RHSExpr->getLocStart(), RHSExpr->getLocStart(), RHSExpr->getLocEnd()); 11992 InitializedEntity Entity = 11993 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 11994 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 11995 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 11996 if (Init.isInvalid()) 11997 return Init; 11998 RHSExpr = Init.get(); 11999 } 12000 12001 ExprResult LHS = LHSExpr, RHS = RHSExpr; 12002 QualType ResultTy; // Result type of the binary operator. 12003 // The following two variables are used for compound assignment operators 12004 QualType CompLHSTy; // Type of LHS after promotions for computation 12005 QualType CompResultTy; // Type of computation result 12006 ExprValueKind VK = VK_RValue; 12007 ExprObjectKind OK = OK_Ordinary; 12008 bool ConvertHalfVec = false; 12009 12010 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 12011 if (!LHS.isUsable() || !RHS.isUsable()) 12012 return ExprError(); 12013 12014 if (getLangOpts().OpenCL) { 12015 QualType LHSTy = LHSExpr->getType(); 12016 QualType RHSTy = RHSExpr->getType(); 12017 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 12018 // the ATOMIC_VAR_INIT macro. 12019 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 12020 SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 12021 if (BO_Assign == Opc) 12022 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 12023 else 12024 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 12025 return ExprError(); 12026 } 12027 12028 // OpenCL special types - image, sampler, pipe, and blocks are to be used 12029 // only with a builtin functions and therefore should be disallowed here. 12030 if (LHSTy->isImageType() || RHSTy->isImageType() || 12031 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 12032 LHSTy->isPipeType() || RHSTy->isPipeType() || 12033 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 12034 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 12035 return ExprError(); 12036 } 12037 } 12038 12039 switch (Opc) { 12040 case BO_Assign: 12041 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 12042 if (getLangOpts().CPlusPlus && 12043 LHS.get()->getObjectKind() != OK_ObjCProperty) { 12044 VK = LHS.get()->getValueKind(); 12045 OK = LHS.get()->getObjectKind(); 12046 } 12047 if (!ResultTy.isNull()) { 12048 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 12049 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 12050 } 12051 RecordModifiableNonNullParam(*this, LHS.get()); 12052 break; 12053 case BO_PtrMemD: 12054 case BO_PtrMemI: 12055 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 12056 Opc == BO_PtrMemI); 12057 break; 12058 case BO_Mul: 12059 case BO_Div: 12060 ConvertHalfVec = true; 12061 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 12062 Opc == BO_Div); 12063 break; 12064 case BO_Rem: 12065 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 12066 break; 12067 case BO_Add: 12068 ConvertHalfVec = true; 12069 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 12070 break; 12071 case BO_Sub: 12072 ConvertHalfVec = true; 12073 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 12074 break; 12075 case BO_Shl: 12076 case BO_Shr: 12077 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 12078 break; 12079 case BO_LE: 12080 case BO_LT: 12081 case BO_GE: 12082 case BO_GT: 12083 ConvertHalfVec = true; 12084 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12085 break; 12086 case BO_EQ: 12087 case BO_NE: 12088 ConvertHalfVec = true; 12089 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12090 break; 12091 case BO_Cmp: 12092 ConvertHalfVec = true; 12093 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12094 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 12095 break; 12096 case BO_And: 12097 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 12098 LLVM_FALLTHROUGH; 12099 case BO_Xor: 12100 case BO_Or: 12101 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 12102 break; 12103 case BO_LAnd: 12104 case BO_LOr: 12105 ConvertHalfVec = true; 12106 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 12107 break; 12108 case BO_MulAssign: 12109 case BO_DivAssign: 12110 ConvertHalfVec = true; 12111 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 12112 Opc == BO_DivAssign); 12113 CompLHSTy = CompResultTy; 12114 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12115 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12116 break; 12117 case BO_RemAssign: 12118 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 12119 CompLHSTy = CompResultTy; 12120 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12121 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12122 break; 12123 case BO_AddAssign: 12124 ConvertHalfVec = true; 12125 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 12126 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12127 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12128 break; 12129 case BO_SubAssign: 12130 ConvertHalfVec = true; 12131 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 12132 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12133 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12134 break; 12135 case BO_ShlAssign: 12136 case BO_ShrAssign: 12137 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 12138 CompLHSTy = CompResultTy; 12139 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12140 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12141 break; 12142 case BO_AndAssign: 12143 case BO_OrAssign: // fallthrough 12144 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 12145 LLVM_FALLTHROUGH; 12146 case BO_XorAssign: 12147 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 12148 CompLHSTy = CompResultTy; 12149 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12150 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12151 break; 12152 case BO_Comma: 12153 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 12154 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 12155 VK = RHS.get()->getValueKind(); 12156 OK = RHS.get()->getObjectKind(); 12157 } 12158 break; 12159 } 12160 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 12161 return ExprError(); 12162 12163 // Some of the binary operations require promoting operands of half vector to 12164 // float vectors and truncating the result back to half vector. For now, we do 12165 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 12166 // arm64). 12167 assert(isVector(RHS.get()->getType(), Context.HalfTy) == 12168 isVector(LHS.get()->getType(), Context.HalfTy) && 12169 "both sides are half vectors or neither sides are"); 12170 ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context, 12171 LHS.get()->getType()); 12172 12173 // Check for array bounds violations for both sides of the BinaryOperator 12174 CheckArrayAccess(LHS.get()); 12175 CheckArrayAccess(RHS.get()); 12176 12177 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 12178 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 12179 &Context.Idents.get("object_setClass"), 12180 SourceLocation(), LookupOrdinaryName); 12181 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 12182 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd()); 12183 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 12184 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 12185 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 12186 FixItHint::CreateInsertion(RHSLocEnd, ")"); 12187 } 12188 else 12189 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 12190 } 12191 else if (const ObjCIvarRefExpr *OIRE = 12192 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 12193 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 12194 12195 // Opc is not a compound assignment if CompResultTy is null. 12196 if (CompResultTy.isNull()) { 12197 if (ConvertHalfVec) 12198 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 12199 OpLoc, FPFeatures); 12200 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 12201 OK, OpLoc, FPFeatures); 12202 } 12203 12204 // Handle compound assignments. 12205 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 12206 OK_ObjCProperty) { 12207 VK = VK_LValue; 12208 OK = LHS.get()->getObjectKind(); 12209 } 12210 12211 if (ConvertHalfVec) 12212 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 12213 OpLoc, FPFeatures); 12214 12215 return new (Context) CompoundAssignOperator( 12216 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 12217 OpLoc, FPFeatures); 12218 } 12219 12220 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 12221 /// operators are mixed in a way that suggests that the programmer forgot that 12222 /// comparison operators have higher precedence. The most typical example of 12223 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 12224 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 12225 SourceLocation OpLoc, Expr *LHSExpr, 12226 Expr *RHSExpr) { 12227 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 12228 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 12229 12230 // Check that one of the sides is a comparison operator and the other isn't. 12231 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 12232 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 12233 if (isLeftComp == isRightComp) 12234 return; 12235 12236 // Bitwise operations are sometimes used as eager logical ops. 12237 // Don't diagnose this. 12238 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 12239 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 12240 if (isLeftBitwise || isRightBitwise) 12241 return; 12242 12243 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 12244 OpLoc) 12245 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 12246 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 12247 SourceRange ParensRange = isLeftComp ? 12248 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 12249 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd()); 12250 12251 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 12252 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 12253 SuggestParentheses(Self, OpLoc, 12254 Self.PDiag(diag::note_precedence_silence) << OpStr, 12255 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 12256 SuggestParentheses(Self, OpLoc, 12257 Self.PDiag(diag::note_precedence_bitwise_first) 12258 << BinaryOperator::getOpcodeStr(Opc), 12259 ParensRange); 12260 } 12261 12262 /// It accepts a '&&' expr that is inside a '||' one. 12263 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 12264 /// in parentheses. 12265 static void 12266 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 12267 BinaryOperator *Bop) { 12268 assert(Bop->getOpcode() == BO_LAnd); 12269 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 12270 << Bop->getSourceRange() << OpLoc; 12271 SuggestParentheses(Self, Bop->getOperatorLoc(), 12272 Self.PDiag(diag::note_precedence_silence) 12273 << Bop->getOpcodeStr(), 12274 Bop->getSourceRange()); 12275 } 12276 12277 /// Returns true if the given expression can be evaluated as a constant 12278 /// 'true'. 12279 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 12280 bool Res; 12281 return !E->isValueDependent() && 12282 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 12283 } 12284 12285 /// Returns true if the given expression can be evaluated as a constant 12286 /// 'false'. 12287 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 12288 bool Res; 12289 return !E->isValueDependent() && 12290 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 12291 } 12292 12293 /// Look for '&&' in the left hand of a '||' expr. 12294 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 12295 Expr *LHSExpr, Expr *RHSExpr) { 12296 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 12297 if (Bop->getOpcode() == BO_LAnd) { 12298 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 12299 if (EvaluatesAsFalse(S, RHSExpr)) 12300 return; 12301 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 12302 if (!EvaluatesAsTrue(S, Bop->getLHS())) 12303 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 12304 } else if (Bop->getOpcode() == BO_LOr) { 12305 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 12306 // If it's "a || b && 1 || c" we didn't warn earlier for 12307 // "a || b && 1", but warn now. 12308 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 12309 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 12310 } 12311 } 12312 } 12313 } 12314 12315 /// Look for '&&' in the right hand of a '||' expr. 12316 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 12317 Expr *LHSExpr, Expr *RHSExpr) { 12318 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 12319 if (Bop->getOpcode() == BO_LAnd) { 12320 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 12321 if (EvaluatesAsFalse(S, LHSExpr)) 12322 return; 12323 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 12324 if (!EvaluatesAsTrue(S, Bop->getRHS())) 12325 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 12326 } 12327 } 12328 } 12329 12330 /// Look for bitwise op in the left or right hand of a bitwise op with 12331 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 12332 /// the '&' expression in parentheses. 12333 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 12334 SourceLocation OpLoc, Expr *SubExpr) { 12335 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 12336 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 12337 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 12338 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 12339 << Bop->getSourceRange() << OpLoc; 12340 SuggestParentheses(S, Bop->getOperatorLoc(), 12341 S.PDiag(diag::note_precedence_silence) 12342 << Bop->getOpcodeStr(), 12343 Bop->getSourceRange()); 12344 } 12345 } 12346 } 12347 12348 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 12349 Expr *SubExpr, StringRef Shift) { 12350 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 12351 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 12352 StringRef Op = Bop->getOpcodeStr(); 12353 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 12354 << Bop->getSourceRange() << OpLoc << Shift << Op; 12355 SuggestParentheses(S, Bop->getOperatorLoc(), 12356 S.PDiag(diag::note_precedence_silence) << Op, 12357 Bop->getSourceRange()); 12358 } 12359 } 12360 } 12361 12362 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 12363 Expr *LHSExpr, Expr *RHSExpr) { 12364 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 12365 if (!OCE) 12366 return; 12367 12368 FunctionDecl *FD = OCE->getDirectCallee(); 12369 if (!FD || !FD->isOverloadedOperator()) 12370 return; 12371 12372 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 12373 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 12374 return; 12375 12376 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 12377 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 12378 << (Kind == OO_LessLess); 12379 SuggestParentheses(S, OCE->getOperatorLoc(), 12380 S.PDiag(diag::note_precedence_silence) 12381 << (Kind == OO_LessLess ? "<<" : ">>"), 12382 OCE->getSourceRange()); 12383 SuggestParentheses(S, OpLoc, 12384 S.PDiag(diag::note_evaluate_comparison_first), 12385 SourceRange(OCE->getArg(1)->getLocStart(), 12386 RHSExpr->getLocEnd())); 12387 } 12388 12389 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 12390 /// precedence. 12391 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 12392 SourceLocation OpLoc, Expr *LHSExpr, 12393 Expr *RHSExpr){ 12394 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 12395 if (BinaryOperator::isBitwiseOp(Opc)) 12396 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 12397 12398 // Diagnose "arg1 & arg2 | arg3" 12399 if ((Opc == BO_Or || Opc == BO_Xor) && 12400 !OpLoc.isMacroID()/* Don't warn in macros. */) { 12401 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 12402 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 12403 } 12404 12405 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 12406 // We don't warn for 'assert(a || b && "bad")' since this is safe. 12407 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 12408 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 12409 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 12410 } 12411 12412 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 12413 || Opc == BO_Shr) { 12414 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 12415 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 12416 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 12417 } 12418 12419 // Warn on overloaded shift operators and comparisons, such as: 12420 // cout << 5 == 4; 12421 if (BinaryOperator::isComparisonOp(Opc)) 12422 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 12423 } 12424 12425 // Binary Operators. 'Tok' is the token for the operator. 12426 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 12427 tok::TokenKind Kind, 12428 Expr *LHSExpr, Expr *RHSExpr) { 12429 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 12430 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 12431 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 12432 12433 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 12434 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 12435 12436 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 12437 } 12438 12439 /// Build an overloaded binary operator expression in the given scope. 12440 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 12441 BinaryOperatorKind Opc, 12442 Expr *LHS, Expr *RHS) { 12443 switch (Opc) { 12444 case BO_Assign: 12445 case BO_DivAssign: 12446 case BO_RemAssign: 12447 case BO_SubAssign: 12448 case BO_AndAssign: 12449 case BO_OrAssign: 12450 case BO_XorAssign: 12451 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 12452 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 12453 break; 12454 default: 12455 break; 12456 } 12457 12458 // Find all of the overloaded operators visible from this 12459 // point. We perform both an operator-name lookup from the local 12460 // scope and an argument-dependent lookup based on the types of 12461 // the arguments. 12462 UnresolvedSet<16> Functions; 12463 OverloadedOperatorKind OverOp 12464 = BinaryOperator::getOverloadedOperator(Opc); 12465 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 12466 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 12467 RHS->getType(), Functions); 12468 12469 // Build the (potentially-overloaded, potentially-dependent) 12470 // binary operation. 12471 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 12472 } 12473 12474 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 12475 BinaryOperatorKind Opc, 12476 Expr *LHSExpr, Expr *RHSExpr) { 12477 ExprResult LHS, RHS; 12478 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 12479 if (!LHS.isUsable() || !RHS.isUsable()) 12480 return ExprError(); 12481 LHSExpr = LHS.get(); 12482 RHSExpr = RHS.get(); 12483 12484 // We want to end up calling one of checkPseudoObjectAssignment 12485 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 12486 // both expressions are overloadable or either is type-dependent), 12487 // or CreateBuiltinBinOp (in any other case). We also want to get 12488 // any placeholder types out of the way. 12489 12490 // Handle pseudo-objects in the LHS. 12491 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 12492 // Assignments with a pseudo-object l-value need special analysis. 12493 if (pty->getKind() == BuiltinType::PseudoObject && 12494 BinaryOperator::isAssignmentOp(Opc)) 12495 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 12496 12497 // Don't resolve overloads if the other type is overloadable. 12498 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 12499 // We can't actually test that if we still have a placeholder, 12500 // though. Fortunately, none of the exceptions we see in that 12501 // code below are valid when the LHS is an overload set. Note 12502 // that an overload set can be dependently-typed, but it never 12503 // instantiates to having an overloadable type. 12504 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 12505 if (resolvedRHS.isInvalid()) return ExprError(); 12506 RHSExpr = resolvedRHS.get(); 12507 12508 if (RHSExpr->isTypeDependent() || 12509 RHSExpr->getType()->isOverloadableType()) 12510 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12511 } 12512 12513 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 12514 // template, diagnose the missing 'template' keyword instead of diagnosing 12515 // an invalid use of a bound member function. 12516 // 12517 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 12518 // to C++1z [over.over]/1.4, but we already checked for that case above. 12519 if (Opc == BO_LT && inTemplateInstantiation() && 12520 (pty->getKind() == BuiltinType::BoundMember || 12521 pty->getKind() == BuiltinType::Overload)) { 12522 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 12523 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 12524 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 12525 return isa<FunctionTemplateDecl>(ND); 12526 })) { 12527 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 12528 : OE->getNameLoc(), 12529 diag::err_template_kw_missing) 12530 << OE->getName().getAsString() << ""; 12531 return ExprError(); 12532 } 12533 } 12534 12535 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 12536 if (LHS.isInvalid()) return ExprError(); 12537 LHSExpr = LHS.get(); 12538 } 12539 12540 // Handle pseudo-objects in the RHS. 12541 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 12542 // An overload in the RHS can potentially be resolved by the type 12543 // being assigned to. 12544 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 12545 if (getLangOpts().CPlusPlus && 12546 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 12547 LHSExpr->getType()->isOverloadableType())) 12548 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12549 12550 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 12551 } 12552 12553 // Don't resolve overloads if the other type is overloadable. 12554 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 12555 LHSExpr->getType()->isOverloadableType()) 12556 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12557 12558 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 12559 if (!resolvedRHS.isUsable()) return ExprError(); 12560 RHSExpr = resolvedRHS.get(); 12561 } 12562 12563 if (getLangOpts().CPlusPlus) { 12564 // If either expression is type-dependent, always build an 12565 // overloaded op. 12566 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 12567 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12568 12569 // Otherwise, build an overloaded op if either expression has an 12570 // overloadable type. 12571 if (LHSExpr->getType()->isOverloadableType() || 12572 RHSExpr->getType()->isOverloadableType()) 12573 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12574 } 12575 12576 // Build a built-in binary operation. 12577 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 12578 } 12579 12580 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 12581 if (T.isNull() || T->isDependentType()) 12582 return false; 12583 12584 if (!T->isPromotableIntegerType()) 12585 return true; 12586 12587 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 12588 } 12589 12590 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 12591 UnaryOperatorKind Opc, 12592 Expr *InputExpr) { 12593 ExprResult Input = InputExpr; 12594 ExprValueKind VK = VK_RValue; 12595 ExprObjectKind OK = OK_Ordinary; 12596 QualType resultType; 12597 bool CanOverflow = false; 12598 12599 bool ConvertHalfVec = false; 12600 if (getLangOpts().OpenCL) { 12601 QualType Ty = InputExpr->getType(); 12602 // The only legal unary operation for atomics is '&'. 12603 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 12604 // OpenCL special types - image, sampler, pipe, and blocks are to be used 12605 // only with a builtin functions and therefore should be disallowed here. 12606 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 12607 || Ty->isBlockPointerType())) { 12608 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12609 << InputExpr->getType() 12610 << Input.get()->getSourceRange()); 12611 } 12612 } 12613 switch (Opc) { 12614 case UO_PreInc: 12615 case UO_PreDec: 12616 case UO_PostInc: 12617 case UO_PostDec: 12618 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 12619 OpLoc, 12620 Opc == UO_PreInc || 12621 Opc == UO_PostInc, 12622 Opc == UO_PreInc || 12623 Opc == UO_PreDec); 12624 CanOverflow = isOverflowingIntegerType(Context, resultType); 12625 break; 12626 case UO_AddrOf: 12627 resultType = CheckAddressOfOperand(Input, OpLoc); 12628 RecordModifiableNonNullParam(*this, InputExpr); 12629 break; 12630 case UO_Deref: { 12631 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 12632 if (Input.isInvalid()) return ExprError(); 12633 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 12634 break; 12635 } 12636 case UO_Plus: 12637 case UO_Minus: 12638 CanOverflow = Opc == UO_Minus && 12639 isOverflowingIntegerType(Context, Input.get()->getType()); 12640 Input = UsualUnaryConversions(Input.get()); 12641 if (Input.isInvalid()) return ExprError(); 12642 // Unary plus and minus require promoting an operand of half vector to a 12643 // float vector and truncating the result back to a half vector. For now, we 12644 // do this only when HalfArgsAndReturns is set (that is, when the target is 12645 // arm or arm64). 12646 ConvertHalfVec = 12647 needsConversionOfHalfVec(true, Context, Input.get()->getType()); 12648 12649 // If the operand is a half vector, promote it to a float vector. 12650 if (ConvertHalfVec) 12651 Input = convertVector(Input.get(), Context.FloatTy, *this); 12652 resultType = Input.get()->getType(); 12653 if (resultType->isDependentType()) 12654 break; 12655 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 12656 break; 12657 else if (resultType->isVectorType() && 12658 // The z vector extensions don't allow + or - with bool vectors. 12659 (!Context.getLangOpts().ZVector || 12660 resultType->getAs<VectorType>()->getVectorKind() != 12661 VectorType::AltiVecBool)) 12662 break; 12663 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 12664 Opc == UO_Plus && 12665 resultType->isPointerType()) 12666 break; 12667 12668 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12669 << resultType << Input.get()->getSourceRange()); 12670 12671 case UO_Not: // bitwise complement 12672 Input = UsualUnaryConversions(Input.get()); 12673 if (Input.isInvalid()) 12674 return ExprError(); 12675 resultType = Input.get()->getType(); 12676 12677 if (resultType->isDependentType()) 12678 break; 12679 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 12680 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 12681 // C99 does not support '~' for complex conjugation. 12682 Diag(OpLoc, diag::ext_integer_complement_complex) 12683 << resultType << Input.get()->getSourceRange(); 12684 else if (resultType->hasIntegerRepresentation()) 12685 break; 12686 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 12687 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 12688 // on vector float types. 12689 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 12690 if (!T->isIntegerType()) 12691 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12692 << resultType << Input.get()->getSourceRange()); 12693 } else { 12694 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12695 << resultType << Input.get()->getSourceRange()); 12696 } 12697 break; 12698 12699 case UO_LNot: // logical negation 12700 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 12701 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 12702 if (Input.isInvalid()) return ExprError(); 12703 resultType = Input.get()->getType(); 12704 12705 // Though we still have to promote half FP to float... 12706 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 12707 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 12708 resultType = Context.FloatTy; 12709 } 12710 12711 if (resultType->isDependentType()) 12712 break; 12713 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 12714 // C99 6.5.3.3p1: ok, fallthrough; 12715 if (Context.getLangOpts().CPlusPlus) { 12716 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 12717 // operand contextually converted to bool. 12718 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 12719 ScalarTypeToBooleanCastKind(resultType)); 12720 } else if (Context.getLangOpts().OpenCL && 12721 Context.getLangOpts().OpenCLVersion < 120) { 12722 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 12723 // operate on scalar float types. 12724 if (!resultType->isIntegerType() && !resultType->isPointerType()) 12725 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12726 << resultType << Input.get()->getSourceRange()); 12727 } 12728 } else if (resultType->isExtVectorType()) { 12729 if (Context.getLangOpts().OpenCL && 12730 Context.getLangOpts().OpenCLVersion < 120) { 12731 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 12732 // operate on vector float types. 12733 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 12734 if (!T->isIntegerType()) 12735 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12736 << resultType << Input.get()->getSourceRange()); 12737 } 12738 // Vector logical not returns the signed variant of the operand type. 12739 resultType = GetSignedVectorType(resultType); 12740 break; 12741 } else { 12742 // FIXME: GCC's vector extension permits the usage of '!' with a vector 12743 // type in C++. We should allow that here too. 12744 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12745 << resultType << Input.get()->getSourceRange()); 12746 } 12747 12748 // LNot always has type int. C99 6.5.3.3p5. 12749 // In C++, it's bool. C++ 5.3.1p8 12750 resultType = Context.getLogicalOperationType(); 12751 break; 12752 case UO_Real: 12753 case UO_Imag: 12754 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 12755 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 12756 // complex l-values to ordinary l-values and all other values to r-values. 12757 if (Input.isInvalid()) return ExprError(); 12758 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 12759 if (Input.get()->getValueKind() != VK_RValue && 12760 Input.get()->getObjectKind() == OK_Ordinary) 12761 VK = Input.get()->getValueKind(); 12762 } else if (!getLangOpts().CPlusPlus) { 12763 // In C, a volatile scalar is read by __imag. In C++, it is not. 12764 Input = DefaultLvalueConversion(Input.get()); 12765 } 12766 break; 12767 case UO_Extension: 12768 resultType = Input.get()->getType(); 12769 VK = Input.get()->getValueKind(); 12770 OK = Input.get()->getObjectKind(); 12771 break; 12772 case UO_Coawait: 12773 // It's unnecessary to represent the pass-through operator co_await in the 12774 // AST; just return the input expression instead. 12775 assert(!Input.get()->getType()->isDependentType() && 12776 "the co_await expression must be non-dependant before " 12777 "building operator co_await"); 12778 return Input; 12779 } 12780 if (resultType.isNull() || Input.isInvalid()) 12781 return ExprError(); 12782 12783 // Check for array bounds violations in the operand of the UnaryOperator, 12784 // except for the '*' and '&' operators that have to be handled specially 12785 // by CheckArrayAccess (as there are special cases like &array[arraysize] 12786 // that are explicitly defined as valid by the standard). 12787 if (Opc != UO_AddrOf && Opc != UO_Deref) 12788 CheckArrayAccess(Input.get()); 12789 12790 auto *UO = new (Context) 12791 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow); 12792 // Convert the result back to a half vector. 12793 if (ConvertHalfVec) 12794 return convertVector(UO, Context.HalfTy, *this); 12795 return UO; 12796 } 12797 12798 /// Determine whether the given expression is a qualified member 12799 /// access expression, of a form that could be turned into a pointer to member 12800 /// with the address-of operator. 12801 static bool isQualifiedMemberAccess(Expr *E) { 12802 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12803 if (!DRE->getQualifier()) 12804 return false; 12805 12806 ValueDecl *VD = DRE->getDecl(); 12807 if (!VD->isCXXClassMember()) 12808 return false; 12809 12810 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 12811 return true; 12812 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 12813 return Method->isInstance(); 12814 12815 return false; 12816 } 12817 12818 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 12819 if (!ULE->getQualifier()) 12820 return false; 12821 12822 for (NamedDecl *D : ULE->decls()) { 12823 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 12824 if (Method->isInstance()) 12825 return true; 12826 } else { 12827 // Overload set does not contain methods. 12828 break; 12829 } 12830 } 12831 12832 return false; 12833 } 12834 12835 return false; 12836 } 12837 12838 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 12839 UnaryOperatorKind Opc, Expr *Input) { 12840 // First things first: handle placeholders so that the 12841 // overloaded-operator check considers the right type. 12842 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 12843 // Increment and decrement of pseudo-object references. 12844 if (pty->getKind() == BuiltinType::PseudoObject && 12845 UnaryOperator::isIncrementDecrementOp(Opc)) 12846 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 12847 12848 // extension is always a builtin operator. 12849 if (Opc == UO_Extension) 12850 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12851 12852 // & gets special logic for several kinds of placeholder. 12853 // The builtin code knows what to do. 12854 if (Opc == UO_AddrOf && 12855 (pty->getKind() == BuiltinType::Overload || 12856 pty->getKind() == BuiltinType::UnknownAny || 12857 pty->getKind() == BuiltinType::BoundMember)) 12858 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12859 12860 // Anything else needs to be handled now. 12861 ExprResult Result = CheckPlaceholderExpr(Input); 12862 if (Result.isInvalid()) return ExprError(); 12863 Input = Result.get(); 12864 } 12865 12866 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 12867 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 12868 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 12869 // Find all of the overloaded operators visible from this 12870 // point. We perform both an operator-name lookup from the local 12871 // scope and an argument-dependent lookup based on the types of 12872 // the arguments. 12873 UnresolvedSet<16> Functions; 12874 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 12875 if (S && OverOp != OO_None) 12876 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 12877 Functions); 12878 12879 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 12880 } 12881 12882 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12883 } 12884 12885 // Unary Operators. 'Tok' is the token for the operator. 12886 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 12887 tok::TokenKind Op, Expr *Input) { 12888 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 12889 } 12890 12891 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 12892 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 12893 LabelDecl *TheDecl) { 12894 TheDecl->markUsed(Context); 12895 // Create the AST node. The address of a label always has type 'void*'. 12896 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 12897 Context.getPointerType(Context.VoidTy)); 12898 } 12899 12900 /// Given the last statement in a statement-expression, check whether 12901 /// the result is a producing expression (like a call to an 12902 /// ns_returns_retained function) and, if so, rebuild it to hoist the 12903 /// release out of the full-expression. Otherwise, return null. 12904 /// Cannot fail. 12905 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 12906 // Should always be wrapped with one of these. 12907 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 12908 if (!cleanups) return nullptr; 12909 12910 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 12911 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 12912 return nullptr; 12913 12914 // Splice out the cast. This shouldn't modify any interesting 12915 // features of the statement. 12916 Expr *producer = cast->getSubExpr(); 12917 assert(producer->getType() == cast->getType()); 12918 assert(producer->getValueKind() == cast->getValueKind()); 12919 cleanups->setSubExpr(producer); 12920 return cleanups; 12921 } 12922 12923 void Sema::ActOnStartStmtExpr() { 12924 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 12925 } 12926 12927 void Sema::ActOnStmtExprError() { 12928 // Note that function is also called by TreeTransform when leaving a 12929 // StmtExpr scope without rebuilding anything. 12930 12931 DiscardCleanupsInEvaluationContext(); 12932 PopExpressionEvaluationContext(); 12933 } 12934 12935 ExprResult 12936 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 12937 SourceLocation RPLoc) { // "({..})" 12938 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 12939 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 12940 12941 if (hasAnyUnrecoverableErrorsInThisFunction()) 12942 DiscardCleanupsInEvaluationContext(); 12943 assert(!Cleanup.exprNeedsCleanups() && 12944 "cleanups within StmtExpr not correctly bound!"); 12945 PopExpressionEvaluationContext(); 12946 12947 // FIXME: there are a variety of strange constraints to enforce here, for 12948 // example, it is not possible to goto into a stmt expression apparently. 12949 // More semantic analysis is needed. 12950 12951 // If there are sub-stmts in the compound stmt, take the type of the last one 12952 // as the type of the stmtexpr. 12953 QualType Ty = Context.VoidTy; 12954 bool StmtExprMayBindToTemp = false; 12955 if (!Compound->body_empty()) { 12956 Stmt *LastStmt = Compound->body_back(); 12957 LabelStmt *LastLabelStmt = nullptr; 12958 // If LastStmt is a label, skip down through into the body. 12959 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 12960 LastLabelStmt = Label; 12961 LastStmt = Label->getSubStmt(); 12962 } 12963 12964 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 12965 // Do function/array conversion on the last expression, but not 12966 // lvalue-to-rvalue. However, initialize an unqualified type. 12967 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 12968 if (LastExpr.isInvalid()) 12969 return ExprError(); 12970 Ty = LastExpr.get()->getType().getUnqualifiedType(); 12971 12972 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 12973 // In ARC, if the final expression ends in a consume, splice 12974 // the consume out and bind it later. In the alternate case 12975 // (when dealing with a retainable type), the result 12976 // initialization will create a produce. In both cases the 12977 // result will be +1, and we'll need to balance that out with 12978 // a bind. 12979 if (Expr *rebuiltLastStmt 12980 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 12981 LastExpr = rebuiltLastStmt; 12982 } else { 12983 LastExpr = PerformCopyInitialization( 12984 InitializedEntity::InitializeResult(LPLoc, 12985 Ty, 12986 false), 12987 SourceLocation(), 12988 LastExpr); 12989 } 12990 12991 if (LastExpr.isInvalid()) 12992 return ExprError(); 12993 if (LastExpr.get() != nullptr) { 12994 if (!LastLabelStmt) 12995 Compound->setLastStmt(LastExpr.get()); 12996 else 12997 LastLabelStmt->setSubStmt(LastExpr.get()); 12998 StmtExprMayBindToTemp = true; 12999 } 13000 } 13001 } 13002 } 13003 13004 // FIXME: Check that expression type is complete/non-abstract; statement 13005 // expressions are not lvalues. 13006 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 13007 if (StmtExprMayBindToTemp) 13008 return MaybeBindToTemporary(ResStmtExpr); 13009 return ResStmtExpr; 13010 } 13011 13012 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 13013 TypeSourceInfo *TInfo, 13014 ArrayRef<OffsetOfComponent> Components, 13015 SourceLocation RParenLoc) { 13016 QualType ArgTy = TInfo->getType(); 13017 bool Dependent = ArgTy->isDependentType(); 13018 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 13019 13020 // We must have at least one component that refers to the type, and the first 13021 // one is known to be a field designator. Verify that the ArgTy represents 13022 // a struct/union/class. 13023 if (!Dependent && !ArgTy->isRecordType()) 13024 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 13025 << ArgTy << TypeRange); 13026 13027 // Type must be complete per C99 7.17p3 because a declaring a variable 13028 // with an incomplete type would be ill-formed. 13029 if (!Dependent 13030 && RequireCompleteType(BuiltinLoc, ArgTy, 13031 diag::err_offsetof_incomplete_type, TypeRange)) 13032 return ExprError(); 13033 13034 bool DidWarnAboutNonPOD = false; 13035 QualType CurrentType = ArgTy; 13036 SmallVector<OffsetOfNode, 4> Comps; 13037 SmallVector<Expr*, 4> Exprs; 13038 for (const OffsetOfComponent &OC : Components) { 13039 if (OC.isBrackets) { 13040 // Offset of an array sub-field. TODO: Should we allow vector elements? 13041 if (!CurrentType->isDependentType()) { 13042 const ArrayType *AT = Context.getAsArrayType(CurrentType); 13043 if(!AT) 13044 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 13045 << CurrentType); 13046 CurrentType = AT->getElementType(); 13047 } else 13048 CurrentType = Context.DependentTy; 13049 13050 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 13051 if (IdxRval.isInvalid()) 13052 return ExprError(); 13053 Expr *Idx = IdxRval.get(); 13054 13055 // The expression must be an integral expression. 13056 // FIXME: An integral constant expression? 13057 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 13058 !Idx->getType()->isIntegerType()) 13059 return ExprError(Diag(Idx->getLocStart(), 13060 diag::err_typecheck_subscript_not_integer) 13061 << Idx->getSourceRange()); 13062 13063 // Record this array index. 13064 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 13065 Exprs.push_back(Idx); 13066 continue; 13067 } 13068 13069 // Offset of a field. 13070 if (CurrentType->isDependentType()) { 13071 // We have the offset of a field, but we can't look into the dependent 13072 // type. Just record the identifier of the field. 13073 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 13074 CurrentType = Context.DependentTy; 13075 continue; 13076 } 13077 13078 // We need to have a complete type to look into. 13079 if (RequireCompleteType(OC.LocStart, CurrentType, 13080 diag::err_offsetof_incomplete_type)) 13081 return ExprError(); 13082 13083 // Look for the designated field. 13084 const RecordType *RC = CurrentType->getAs<RecordType>(); 13085 if (!RC) 13086 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 13087 << CurrentType); 13088 RecordDecl *RD = RC->getDecl(); 13089 13090 // C++ [lib.support.types]p5: 13091 // The macro offsetof accepts a restricted set of type arguments in this 13092 // International Standard. type shall be a POD structure or a POD union 13093 // (clause 9). 13094 // C++11 [support.types]p4: 13095 // If type is not a standard-layout class (Clause 9), the results are 13096 // undefined. 13097 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 13098 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 13099 unsigned DiagID = 13100 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 13101 : diag::ext_offsetof_non_pod_type; 13102 13103 if (!IsSafe && !DidWarnAboutNonPOD && 13104 DiagRuntimeBehavior(BuiltinLoc, nullptr, 13105 PDiag(DiagID) 13106 << SourceRange(Components[0].LocStart, OC.LocEnd) 13107 << CurrentType)) 13108 DidWarnAboutNonPOD = true; 13109 } 13110 13111 // Look for the field. 13112 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 13113 LookupQualifiedName(R, RD); 13114 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 13115 IndirectFieldDecl *IndirectMemberDecl = nullptr; 13116 if (!MemberDecl) { 13117 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 13118 MemberDecl = IndirectMemberDecl->getAnonField(); 13119 } 13120 13121 if (!MemberDecl) 13122 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 13123 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 13124 OC.LocEnd)); 13125 13126 // C99 7.17p3: 13127 // (If the specified member is a bit-field, the behavior is undefined.) 13128 // 13129 // We diagnose this as an error. 13130 if (MemberDecl->isBitField()) { 13131 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 13132 << MemberDecl->getDeclName() 13133 << SourceRange(BuiltinLoc, RParenLoc); 13134 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 13135 return ExprError(); 13136 } 13137 13138 RecordDecl *Parent = MemberDecl->getParent(); 13139 if (IndirectMemberDecl) 13140 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 13141 13142 // If the member was found in a base class, introduce OffsetOfNodes for 13143 // the base class indirections. 13144 CXXBasePaths Paths; 13145 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 13146 Paths)) { 13147 if (Paths.getDetectedVirtual()) { 13148 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 13149 << MemberDecl->getDeclName() 13150 << SourceRange(BuiltinLoc, RParenLoc); 13151 return ExprError(); 13152 } 13153 13154 CXXBasePath &Path = Paths.front(); 13155 for (const CXXBasePathElement &B : Path) 13156 Comps.push_back(OffsetOfNode(B.Base)); 13157 } 13158 13159 if (IndirectMemberDecl) { 13160 for (auto *FI : IndirectMemberDecl->chain()) { 13161 assert(isa<FieldDecl>(FI)); 13162 Comps.push_back(OffsetOfNode(OC.LocStart, 13163 cast<FieldDecl>(FI), OC.LocEnd)); 13164 } 13165 } else 13166 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 13167 13168 CurrentType = MemberDecl->getType().getNonReferenceType(); 13169 } 13170 13171 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 13172 Comps, Exprs, RParenLoc); 13173 } 13174 13175 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 13176 SourceLocation BuiltinLoc, 13177 SourceLocation TypeLoc, 13178 ParsedType ParsedArgTy, 13179 ArrayRef<OffsetOfComponent> Components, 13180 SourceLocation RParenLoc) { 13181 13182 TypeSourceInfo *ArgTInfo; 13183 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 13184 if (ArgTy.isNull()) 13185 return ExprError(); 13186 13187 if (!ArgTInfo) 13188 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 13189 13190 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 13191 } 13192 13193 13194 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 13195 Expr *CondExpr, 13196 Expr *LHSExpr, Expr *RHSExpr, 13197 SourceLocation RPLoc) { 13198 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 13199 13200 ExprValueKind VK = VK_RValue; 13201 ExprObjectKind OK = OK_Ordinary; 13202 QualType resType; 13203 bool ValueDependent = false; 13204 bool CondIsTrue = false; 13205 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 13206 resType = Context.DependentTy; 13207 ValueDependent = true; 13208 } else { 13209 // The conditional expression is required to be a constant expression. 13210 llvm::APSInt condEval(32); 13211 ExprResult CondICE 13212 = VerifyIntegerConstantExpression(CondExpr, &condEval, 13213 diag::err_typecheck_choose_expr_requires_constant, false); 13214 if (CondICE.isInvalid()) 13215 return ExprError(); 13216 CondExpr = CondICE.get(); 13217 CondIsTrue = condEval.getZExtValue(); 13218 13219 // If the condition is > zero, then the AST type is the same as the LHSExpr. 13220 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 13221 13222 resType = ActiveExpr->getType(); 13223 ValueDependent = ActiveExpr->isValueDependent(); 13224 VK = ActiveExpr->getValueKind(); 13225 OK = ActiveExpr->getObjectKind(); 13226 } 13227 13228 return new (Context) 13229 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 13230 CondIsTrue, resType->isDependentType(), ValueDependent); 13231 } 13232 13233 //===----------------------------------------------------------------------===// 13234 // Clang Extensions. 13235 //===----------------------------------------------------------------------===// 13236 13237 /// ActOnBlockStart - This callback is invoked when a block literal is started. 13238 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 13239 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 13240 13241 if (LangOpts.CPlusPlus) { 13242 Decl *ManglingContextDecl; 13243 if (MangleNumberingContext *MCtx = 13244 getCurrentMangleNumberContext(Block->getDeclContext(), 13245 ManglingContextDecl)) { 13246 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 13247 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 13248 } 13249 } 13250 13251 PushBlockScope(CurScope, Block); 13252 CurContext->addDecl(Block); 13253 if (CurScope) 13254 PushDeclContext(CurScope, Block); 13255 else 13256 CurContext = Block; 13257 13258 getCurBlock()->HasImplicitReturnType = true; 13259 13260 // Enter a new evaluation context to insulate the block from any 13261 // cleanups from the enclosing full-expression. 13262 PushExpressionEvaluationContext( 13263 ExpressionEvaluationContext::PotentiallyEvaluated); 13264 } 13265 13266 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 13267 Scope *CurScope) { 13268 assert(ParamInfo.getIdentifier() == nullptr && 13269 "block-id should have no identifier!"); 13270 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext); 13271 BlockScopeInfo *CurBlock = getCurBlock(); 13272 13273 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 13274 QualType T = Sig->getType(); 13275 13276 // FIXME: We should allow unexpanded parameter packs here, but that would, 13277 // in turn, make the block expression contain unexpanded parameter packs. 13278 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 13279 // Drop the parameters. 13280 FunctionProtoType::ExtProtoInfo EPI; 13281 EPI.HasTrailingReturn = false; 13282 EPI.TypeQuals |= DeclSpec::TQ_const; 13283 T = Context.getFunctionType(Context.DependentTy, None, EPI); 13284 Sig = Context.getTrivialTypeSourceInfo(T); 13285 } 13286 13287 // GetTypeForDeclarator always produces a function type for a block 13288 // literal signature. Furthermore, it is always a FunctionProtoType 13289 // unless the function was written with a typedef. 13290 assert(T->isFunctionType() && 13291 "GetTypeForDeclarator made a non-function block signature"); 13292 13293 // Look for an explicit signature in that function type. 13294 FunctionProtoTypeLoc ExplicitSignature; 13295 13296 if ((ExplicitSignature = 13297 Sig->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>())) { 13298 13299 // Check whether that explicit signature was synthesized by 13300 // GetTypeForDeclarator. If so, don't save that as part of the 13301 // written signature. 13302 if (ExplicitSignature.getLocalRangeBegin() == 13303 ExplicitSignature.getLocalRangeEnd()) { 13304 // This would be much cheaper if we stored TypeLocs instead of 13305 // TypeSourceInfos. 13306 TypeLoc Result = ExplicitSignature.getReturnLoc(); 13307 unsigned Size = Result.getFullDataSize(); 13308 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 13309 Sig->getTypeLoc().initializeFullCopy(Result, Size); 13310 13311 ExplicitSignature = FunctionProtoTypeLoc(); 13312 } 13313 } 13314 13315 CurBlock->TheDecl->setSignatureAsWritten(Sig); 13316 CurBlock->FunctionType = T; 13317 13318 const FunctionType *Fn = T->getAs<FunctionType>(); 13319 QualType RetTy = Fn->getReturnType(); 13320 bool isVariadic = 13321 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 13322 13323 CurBlock->TheDecl->setIsVariadic(isVariadic); 13324 13325 // Context.DependentTy is used as a placeholder for a missing block 13326 // return type. TODO: what should we do with declarators like: 13327 // ^ * { ... } 13328 // If the answer is "apply template argument deduction".... 13329 if (RetTy != Context.DependentTy) { 13330 CurBlock->ReturnType = RetTy; 13331 CurBlock->TheDecl->setBlockMissingReturnType(false); 13332 CurBlock->HasImplicitReturnType = false; 13333 } 13334 13335 // Push block parameters from the declarator if we had them. 13336 SmallVector<ParmVarDecl*, 8> Params; 13337 if (ExplicitSignature) { 13338 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 13339 ParmVarDecl *Param = ExplicitSignature.getParam(I); 13340 if (Param->getIdentifier() == nullptr && 13341 !Param->isImplicit() && 13342 !Param->isInvalidDecl() && 13343 !getLangOpts().CPlusPlus) 13344 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 13345 Params.push_back(Param); 13346 } 13347 13348 // Fake up parameter variables if we have a typedef, like 13349 // ^ fntype { ... } 13350 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 13351 for (const auto &I : Fn->param_types()) { 13352 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 13353 CurBlock->TheDecl, ParamInfo.getLocStart(), I); 13354 Params.push_back(Param); 13355 } 13356 } 13357 13358 // Set the parameters on the block decl. 13359 if (!Params.empty()) { 13360 CurBlock->TheDecl->setParams(Params); 13361 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 13362 /*CheckParameterNames=*/false); 13363 } 13364 13365 // Finally we can process decl attributes. 13366 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 13367 13368 // Put the parameter variables in scope. 13369 for (auto AI : CurBlock->TheDecl->parameters()) { 13370 AI->setOwningFunction(CurBlock->TheDecl); 13371 13372 // If this has an identifier, add it to the scope stack. 13373 if (AI->getIdentifier()) { 13374 CheckShadow(CurBlock->TheScope, AI); 13375 13376 PushOnScopeChains(AI, CurBlock->TheScope); 13377 } 13378 } 13379 } 13380 13381 /// ActOnBlockError - If there is an error parsing a block, this callback 13382 /// is invoked to pop the information about the block from the action impl. 13383 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 13384 // Leave the expression-evaluation context. 13385 DiscardCleanupsInEvaluationContext(); 13386 PopExpressionEvaluationContext(); 13387 13388 // Pop off CurBlock, handle nested blocks. 13389 PopDeclContext(); 13390 PopFunctionScopeInfo(); 13391 } 13392 13393 /// ActOnBlockStmtExpr - This is called when the body of a block statement 13394 /// literal was successfully completed. ^(int x){...} 13395 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 13396 Stmt *Body, Scope *CurScope) { 13397 // If blocks are disabled, emit an error. 13398 if (!LangOpts.Blocks) 13399 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 13400 13401 // Leave the expression-evaluation context. 13402 if (hasAnyUnrecoverableErrorsInThisFunction()) 13403 DiscardCleanupsInEvaluationContext(); 13404 assert(!Cleanup.exprNeedsCleanups() && 13405 "cleanups within block not correctly bound!"); 13406 PopExpressionEvaluationContext(); 13407 13408 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 13409 13410 if (BSI->HasImplicitReturnType) 13411 deduceClosureReturnType(*BSI); 13412 13413 PopDeclContext(); 13414 13415 QualType RetTy = Context.VoidTy; 13416 if (!BSI->ReturnType.isNull()) 13417 RetTy = BSI->ReturnType; 13418 13419 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 13420 QualType BlockTy; 13421 13422 // Set the captured variables on the block. 13423 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 13424 SmallVector<BlockDecl::Capture, 4> Captures; 13425 for (Capture &Cap : BSI->Captures) { 13426 if (Cap.isThisCapture()) 13427 continue; 13428 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 13429 Cap.isNested(), Cap.getInitExpr()); 13430 Captures.push_back(NewCap); 13431 } 13432 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 13433 13434 // If the user wrote a function type in some form, try to use that. 13435 if (!BSI->FunctionType.isNull()) { 13436 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 13437 13438 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 13439 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 13440 13441 // Turn protoless block types into nullary block types. 13442 if (isa<FunctionNoProtoType>(FTy)) { 13443 FunctionProtoType::ExtProtoInfo EPI; 13444 EPI.ExtInfo = Ext; 13445 BlockTy = Context.getFunctionType(RetTy, None, EPI); 13446 13447 // Otherwise, if we don't need to change anything about the function type, 13448 // preserve its sugar structure. 13449 } else if (FTy->getReturnType() == RetTy && 13450 (!NoReturn || FTy->getNoReturnAttr())) { 13451 BlockTy = BSI->FunctionType; 13452 13453 // Otherwise, make the minimal modifications to the function type. 13454 } else { 13455 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 13456 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 13457 EPI.TypeQuals = 0; // FIXME: silently? 13458 EPI.ExtInfo = Ext; 13459 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 13460 } 13461 13462 // If we don't have a function type, just build one from nothing. 13463 } else { 13464 FunctionProtoType::ExtProtoInfo EPI; 13465 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 13466 BlockTy = Context.getFunctionType(RetTy, None, EPI); 13467 } 13468 13469 DiagnoseUnusedParameters(BSI->TheDecl->parameters()); 13470 BlockTy = Context.getBlockPointerType(BlockTy); 13471 13472 // If needed, diagnose invalid gotos and switches in the block. 13473 if (getCurFunction()->NeedsScopeChecking() && 13474 !PP.isCodeCompletionEnabled()) 13475 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 13476 13477 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 13478 13479 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 13480 DiagnoseUnguardedAvailabilityViolations(BSI->TheDecl); 13481 13482 // Try to apply the named return value optimization. We have to check again 13483 // if we can do this, though, because blocks keep return statements around 13484 // to deduce an implicit return type. 13485 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 13486 !BSI->TheDecl->isDependentContext()) 13487 computeNRVO(Body, BSI); 13488 13489 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 13490 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 13491 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 13492 13493 // If the block isn't obviously global, i.e. it captures anything at 13494 // all, then we need to do a few things in the surrounding context: 13495 if (Result->getBlockDecl()->hasCaptures()) { 13496 // First, this expression has a new cleanup object. 13497 ExprCleanupObjects.push_back(Result->getBlockDecl()); 13498 Cleanup.setExprNeedsCleanups(true); 13499 13500 // It also gets a branch-protected scope if any of the captured 13501 // variables needs destruction. 13502 for (const auto &CI : Result->getBlockDecl()->captures()) { 13503 const VarDecl *var = CI.getVariable(); 13504 if (var->getType().isDestructedType() != QualType::DK_none) { 13505 setFunctionHasBranchProtectedScope(); 13506 break; 13507 } 13508 } 13509 } 13510 13511 return Result; 13512 } 13513 13514 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 13515 SourceLocation RPLoc) { 13516 TypeSourceInfo *TInfo; 13517 GetTypeFromParser(Ty, &TInfo); 13518 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 13519 } 13520 13521 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 13522 Expr *E, TypeSourceInfo *TInfo, 13523 SourceLocation RPLoc) { 13524 Expr *OrigExpr = E; 13525 bool IsMS = false; 13526 13527 // CUDA device code does not support varargs. 13528 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 13529 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 13530 CUDAFunctionTarget T = IdentifyCUDATarget(F); 13531 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 13532 return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device)); 13533 } 13534 } 13535 13536 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 13537 // as Microsoft ABI on an actual Microsoft platform, where 13538 // __builtin_ms_va_list and __builtin_va_list are the same.) 13539 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 13540 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 13541 QualType MSVaListType = Context.getBuiltinMSVaListType(); 13542 if (Context.hasSameType(MSVaListType, E->getType())) { 13543 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 13544 return ExprError(); 13545 IsMS = true; 13546 } 13547 } 13548 13549 // Get the va_list type 13550 QualType VaListType = Context.getBuiltinVaListType(); 13551 if (!IsMS) { 13552 if (VaListType->isArrayType()) { 13553 // Deal with implicit array decay; for example, on x86-64, 13554 // va_list is an array, but it's supposed to decay to 13555 // a pointer for va_arg. 13556 VaListType = Context.getArrayDecayedType(VaListType); 13557 // Make sure the input expression also decays appropriately. 13558 ExprResult Result = UsualUnaryConversions(E); 13559 if (Result.isInvalid()) 13560 return ExprError(); 13561 E = Result.get(); 13562 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 13563 // If va_list is a record type and we are compiling in C++ mode, 13564 // check the argument using reference binding. 13565 InitializedEntity Entity = InitializedEntity::InitializeParameter( 13566 Context, Context.getLValueReferenceType(VaListType), false); 13567 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 13568 if (Init.isInvalid()) 13569 return ExprError(); 13570 E = Init.getAs<Expr>(); 13571 } else { 13572 // Otherwise, the va_list argument must be an l-value because 13573 // it is modified by va_arg. 13574 if (!E->isTypeDependent() && 13575 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 13576 return ExprError(); 13577 } 13578 } 13579 13580 if (!IsMS && !E->isTypeDependent() && 13581 !Context.hasSameType(VaListType, E->getType())) 13582 return ExprError(Diag(E->getLocStart(), 13583 diag::err_first_argument_to_va_arg_not_of_type_va_list) 13584 << OrigExpr->getType() << E->getSourceRange()); 13585 13586 if (!TInfo->getType()->isDependentType()) { 13587 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 13588 diag::err_second_parameter_to_va_arg_incomplete, 13589 TInfo->getTypeLoc())) 13590 return ExprError(); 13591 13592 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 13593 TInfo->getType(), 13594 diag::err_second_parameter_to_va_arg_abstract, 13595 TInfo->getTypeLoc())) 13596 return ExprError(); 13597 13598 if (!TInfo->getType().isPODType(Context)) { 13599 Diag(TInfo->getTypeLoc().getBeginLoc(), 13600 TInfo->getType()->isObjCLifetimeType() 13601 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 13602 : diag::warn_second_parameter_to_va_arg_not_pod) 13603 << TInfo->getType() 13604 << TInfo->getTypeLoc().getSourceRange(); 13605 } 13606 13607 // Check for va_arg where arguments of the given type will be promoted 13608 // (i.e. this va_arg is guaranteed to have undefined behavior). 13609 QualType PromoteType; 13610 if (TInfo->getType()->isPromotableIntegerType()) { 13611 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 13612 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 13613 PromoteType = QualType(); 13614 } 13615 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 13616 PromoteType = Context.DoubleTy; 13617 if (!PromoteType.isNull()) 13618 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 13619 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 13620 << TInfo->getType() 13621 << PromoteType 13622 << TInfo->getTypeLoc().getSourceRange()); 13623 } 13624 13625 QualType T = TInfo->getType().getNonLValueExprType(Context); 13626 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 13627 } 13628 13629 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 13630 // The type of __null will be int or long, depending on the size of 13631 // pointers on the target. 13632 QualType Ty; 13633 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 13634 if (pw == Context.getTargetInfo().getIntWidth()) 13635 Ty = Context.IntTy; 13636 else if (pw == Context.getTargetInfo().getLongWidth()) 13637 Ty = Context.LongTy; 13638 else if (pw == Context.getTargetInfo().getLongLongWidth()) 13639 Ty = Context.LongLongTy; 13640 else { 13641 llvm_unreachable("I don't know size of pointer!"); 13642 } 13643 13644 return new (Context) GNUNullExpr(Ty, TokenLoc); 13645 } 13646 13647 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 13648 bool Diagnose) { 13649 if (!getLangOpts().ObjC1) 13650 return false; 13651 13652 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 13653 if (!PT) 13654 return false; 13655 13656 if (!PT->isObjCIdType()) { 13657 // Check if the destination is the 'NSString' interface. 13658 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 13659 if (!ID || !ID->getIdentifier()->isStr("NSString")) 13660 return false; 13661 } 13662 13663 // Ignore any parens, implicit casts (should only be 13664 // array-to-pointer decays), and not-so-opaque values. The last is 13665 // important for making this trigger for property assignments. 13666 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 13667 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 13668 if (OV->getSourceExpr()) 13669 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 13670 13671 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 13672 if (!SL || !SL->isAscii()) 13673 return false; 13674 if (Diagnose) { 13675 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix) 13676 << FixItHint::CreateInsertion(SL->getLocStart(), "@"); 13677 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get(); 13678 } 13679 return true; 13680 } 13681 13682 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 13683 const Expr *SrcExpr) { 13684 if (!DstType->isFunctionPointerType() || 13685 !SrcExpr->getType()->isFunctionType()) 13686 return false; 13687 13688 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 13689 if (!DRE) 13690 return false; 13691 13692 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 13693 if (!FD) 13694 return false; 13695 13696 return !S.checkAddressOfFunctionIsAvailable(FD, 13697 /*Complain=*/true, 13698 SrcExpr->getLocStart()); 13699 } 13700 13701 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 13702 SourceLocation Loc, 13703 QualType DstType, QualType SrcType, 13704 Expr *SrcExpr, AssignmentAction Action, 13705 bool *Complained) { 13706 if (Complained) 13707 *Complained = false; 13708 13709 // Decode the result (notice that AST's are still created for extensions). 13710 bool CheckInferredResultType = false; 13711 bool isInvalid = false; 13712 unsigned DiagKind = 0; 13713 FixItHint Hint; 13714 ConversionFixItGenerator ConvHints; 13715 bool MayHaveConvFixit = false; 13716 bool MayHaveFunctionDiff = false; 13717 const ObjCInterfaceDecl *IFace = nullptr; 13718 const ObjCProtocolDecl *PDecl = nullptr; 13719 13720 switch (ConvTy) { 13721 case Compatible: 13722 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 13723 return false; 13724 13725 case PointerToInt: 13726 DiagKind = diag::ext_typecheck_convert_pointer_int; 13727 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13728 MayHaveConvFixit = true; 13729 break; 13730 case IntToPointer: 13731 DiagKind = diag::ext_typecheck_convert_int_pointer; 13732 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13733 MayHaveConvFixit = true; 13734 break; 13735 case IncompatiblePointer: 13736 if (Action == AA_Passing_CFAudited) 13737 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 13738 else if (SrcType->isFunctionPointerType() && 13739 DstType->isFunctionPointerType()) 13740 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 13741 else 13742 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 13743 13744 CheckInferredResultType = DstType->isObjCObjectPointerType() && 13745 SrcType->isObjCObjectPointerType(); 13746 if (Hint.isNull() && !CheckInferredResultType) { 13747 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13748 } 13749 else if (CheckInferredResultType) { 13750 SrcType = SrcType.getUnqualifiedType(); 13751 DstType = DstType.getUnqualifiedType(); 13752 } 13753 MayHaveConvFixit = true; 13754 break; 13755 case IncompatiblePointerSign: 13756 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 13757 break; 13758 case FunctionVoidPointer: 13759 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 13760 break; 13761 case IncompatiblePointerDiscardsQualifiers: { 13762 // Perform array-to-pointer decay if necessary. 13763 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 13764 13765 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 13766 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 13767 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 13768 DiagKind = diag::err_typecheck_incompatible_address_space; 13769 break; 13770 13771 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 13772 DiagKind = diag::err_typecheck_incompatible_ownership; 13773 break; 13774 } 13775 13776 llvm_unreachable("unknown error case for discarding qualifiers!"); 13777 // fallthrough 13778 } 13779 case CompatiblePointerDiscardsQualifiers: 13780 // If the qualifiers lost were because we were applying the 13781 // (deprecated) C++ conversion from a string literal to a char* 13782 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 13783 // Ideally, this check would be performed in 13784 // checkPointerTypesForAssignment. However, that would require a 13785 // bit of refactoring (so that the second argument is an 13786 // expression, rather than a type), which should be done as part 13787 // of a larger effort to fix checkPointerTypesForAssignment for 13788 // C++ semantics. 13789 if (getLangOpts().CPlusPlus && 13790 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 13791 return false; 13792 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 13793 break; 13794 case IncompatibleNestedPointerQualifiers: 13795 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 13796 break; 13797 case IntToBlockPointer: 13798 DiagKind = diag::err_int_to_block_pointer; 13799 break; 13800 case IncompatibleBlockPointer: 13801 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 13802 break; 13803 case IncompatibleObjCQualifiedId: { 13804 if (SrcType->isObjCQualifiedIdType()) { 13805 const ObjCObjectPointerType *srcOPT = 13806 SrcType->getAs<ObjCObjectPointerType>(); 13807 for (auto *srcProto : srcOPT->quals()) { 13808 PDecl = srcProto; 13809 break; 13810 } 13811 if (const ObjCInterfaceType *IFaceT = 13812 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 13813 IFace = IFaceT->getDecl(); 13814 } 13815 else if (DstType->isObjCQualifiedIdType()) { 13816 const ObjCObjectPointerType *dstOPT = 13817 DstType->getAs<ObjCObjectPointerType>(); 13818 for (auto *dstProto : dstOPT->quals()) { 13819 PDecl = dstProto; 13820 break; 13821 } 13822 if (const ObjCInterfaceType *IFaceT = 13823 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 13824 IFace = IFaceT->getDecl(); 13825 } 13826 DiagKind = diag::warn_incompatible_qualified_id; 13827 break; 13828 } 13829 case IncompatibleVectors: 13830 DiagKind = diag::warn_incompatible_vectors; 13831 break; 13832 case IncompatibleObjCWeakRef: 13833 DiagKind = diag::err_arc_weak_unavailable_assign; 13834 break; 13835 case Incompatible: 13836 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 13837 if (Complained) 13838 *Complained = true; 13839 return true; 13840 } 13841 13842 DiagKind = diag::err_typecheck_convert_incompatible; 13843 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13844 MayHaveConvFixit = true; 13845 isInvalid = true; 13846 MayHaveFunctionDiff = true; 13847 break; 13848 } 13849 13850 QualType FirstType, SecondType; 13851 switch (Action) { 13852 case AA_Assigning: 13853 case AA_Initializing: 13854 // The destination type comes first. 13855 FirstType = DstType; 13856 SecondType = SrcType; 13857 break; 13858 13859 case AA_Returning: 13860 case AA_Passing: 13861 case AA_Passing_CFAudited: 13862 case AA_Converting: 13863 case AA_Sending: 13864 case AA_Casting: 13865 // The source type comes first. 13866 FirstType = SrcType; 13867 SecondType = DstType; 13868 break; 13869 } 13870 13871 PartialDiagnostic FDiag = PDiag(DiagKind); 13872 if (Action == AA_Passing_CFAudited) 13873 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 13874 else 13875 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 13876 13877 // If we can fix the conversion, suggest the FixIts. 13878 assert(ConvHints.isNull() || Hint.isNull()); 13879 if (!ConvHints.isNull()) { 13880 for (FixItHint &H : ConvHints.Hints) 13881 FDiag << H; 13882 } else { 13883 FDiag << Hint; 13884 } 13885 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 13886 13887 if (MayHaveFunctionDiff) 13888 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 13889 13890 Diag(Loc, FDiag); 13891 if (DiagKind == diag::warn_incompatible_qualified_id && 13892 PDecl && IFace && !IFace->hasDefinition()) 13893 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 13894 << IFace << PDecl; 13895 13896 if (SecondType == Context.OverloadTy) 13897 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 13898 FirstType, /*TakingAddress=*/true); 13899 13900 if (CheckInferredResultType) 13901 EmitRelatedResultTypeNote(SrcExpr); 13902 13903 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 13904 EmitRelatedResultTypeNoteForReturn(DstType); 13905 13906 if (Complained) 13907 *Complained = true; 13908 return isInvalid; 13909 } 13910 13911 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 13912 llvm::APSInt *Result) { 13913 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 13914 public: 13915 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 13916 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 13917 } 13918 } Diagnoser; 13919 13920 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 13921 } 13922 13923 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 13924 llvm::APSInt *Result, 13925 unsigned DiagID, 13926 bool AllowFold) { 13927 class IDDiagnoser : public VerifyICEDiagnoser { 13928 unsigned DiagID; 13929 13930 public: 13931 IDDiagnoser(unsigned DiagID) 13932 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 13933 13934 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 13935 S.Diag(Loc, DiagID) << SR; 13936 } 13937 } Diagnoser(DiagID); 13938 13939 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 13940 } 13941 13942 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 13943 SourceRange SR) { 13944 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 13945 } 13946 13947 ExprResult 13948 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 13949 VerifyICEDiagnoser &Diagnoser, 13950 bool AllowFold) { 13951 SourceLocation DiagLoc = E->getLocStart(); 13952 13953 if (getLangOpts().CPlusPlus11) { 13954 // C++11 [expr.const]p5: 13955 // If an expression of literal class type is used in a context where an 13956 // integral constant expression is required, then that class type shall 13957 // have a single non-explicit conversion function to an integral or 13958 // unscoped enumeration type 13959 ExprResult Converted; 13960 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 13961 public: 13962 CXX11ConvertDiagnoser(bool Silent) 13963 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 13964 Silent, true) {} 13965 13966 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 13967 QualType T) override { 13968 return S.Diag(Loc, diag::err_ice_not_integral) << T; 13969 } 13970 13971 SemaDiagnosticBuilder diagnoseIncomplete( 13972 Sema &S, SourceLocation Loc, QualType T) override { 13973 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 13974 } 13975 13976 SemaDiagnosticBuilder diagnoseExplicitConv( 13977 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 13978 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 13979 } 13980 13981 SemaDiagnosticBuilder noteExplicitConv( 13982 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 13983 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 13984 << ConvTy->isEnumeralType() << ConvTy; 13985 } 13986 13987 SemaDiagnosticBuilder diagnoseAmbiguous( 13988 Sema &S, SourceLocation Loc, QualType T) override { 13989 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 13990 } 13991 13992 SemaDiagnosticBuilder noteAmbiguous( 13993 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 13994 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 13995 << ConvTy->isEnumeralType() << ConvTy; 13996 } 13997 13998 SemaDiagnosticBuilder diagnoseConversion( 13999 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 14000 llvm_unreachable("conversion functions are permitted"); 14001 } 14002 } ConvertDiagnoser(Diagnoser.Suppress); 14003 14004 Converted = PerformContextualImplicitConversion(DiagLoc, E, 14005 ConvertDiagnoser); 14006 if (Converted.isInvalid()) 14007 return Converted; 14008 E = Converted.get(); 14009 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 14010 return ExprError(); 14011 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 14012 // An ICE must be of integral or unscoped enumeration type. 14013 if (!Diagnoser.Suppress) 14014 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 14015 return ExprError(); 14016 } 14017 14018 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 14019 // in the non-ICE case. 14020 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 14021 if (Result) 14022 *Result = E->EvaluateKnownConstInt(Context); 14023 return E; 14024 } 14025 14026 Expr::EvalResult EvalResult; 14027 SmallVector<PartialDiagnosticAt, 8> Notes; 14028 EvalResult.Diag = &Notes; 14029 14030 // Try to evaluate the expression, and produce diagnostics explaining why it's 14031 // not a constant expression as a side-effect. 14032 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 14033 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 14034 14035 // In C++11, we can rely on diagnostics being produced for any expression 14036 // which is not a constant expression. If no diagnostics were produced, then 14037 // this is a constant expression. 14038 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 14039 if (Result) 14040 *Result = EvalResult.Val.getInt(); 14041 return E; 14042 } 14043 14044 // If our only note is the usual "invalid subexpression" note, just point 14045 // the caret at its location rather than producing an essentially 14046 // redundant note. 14047 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 14048 diag::note_invalid_subexpr_in_const_expr) { 14049 DiagLoc = Notes[0].first; 14050 Notes.clear(); 14051 } 14052 14053 if (!Folded || !AllowFold) { 14054 if (!Diagnoser.Suppress) { 14055 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 14056 for (const PartialDiagnosticAt &Note : Notes) 14057 Diag(Note.first, Note.second); 14058 } 14059 14060 return ExprError(); 14061 } 14062 14063 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 14064 for (const PartialDiagnosticAt &Note : Notes) 14065 Diag(Note.first, Note.second); 14066 14067 if (Result) 14068 *Result = EvalResult.Val.getInt(); 14069 return E; 14070 } 14071 14072 namespace { 14073 // Handle the case where we conclude a expression which we speculatively 14074 // considered to be unevaluated is actually evaluated. 14075 class TransformToPE : public TreeTransform<TransformToPE> { 14076 typedef TreeTransform<TransformToPE> BaseTransform; 14077 14078 public: 14079 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 14080 14081 // Make sure we redo semantic analysis 14082 bool AlwaysRebuild() { return true; } 14083 14084 // Make sure we handle LabelStmts correctly. 14085 // FIXME: This does the right thing, but maybe we need a more general 14086 // fix to TreeTransform? 14087 StmtResult TransformLabelStmt(LabelStmt *S) { 14088 S->getDecl()->setStmt(nullptr); 14089 return BaseTransform::TransformLabelStmt(S); 14090 } 14091 14092 // We need to special-case DeclRefExprs referring to FieldDecls which 14093 // are not part of a member pointer formation; normal TreeTransforming 14094 // doesn't catch this case because of the way we represent them in the AST. 14095 // FIXME: This is a bit ugly; is it really the best way to handle this 14096 // case? 14097 // 14098 // Error on DeclRefExprs referring to FieldDecls. 14099 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 14100 if (isa<FieldDecl>(E->getDecl()) && 14101 !SemaRef.isUnevaluatedContext()) 14102 return SemaRef.Diag(E->getLocation(), 14103 diag::err_invalid_non_static_member_use) 14104 << E->getDecl() << E->getSourceRange(); 14105 14106 return BaseTransform::TransformDeclRefExpr(E); 14107 } 14108 14109 // Exception: filter out member pointer formation 14110 ExprResult TransformUnaryOperator(UnaryOperator *E) { 14111 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 14112 return E; 14113 14114 return BaseTransform::TransformUnaryOperator(E); 14115 } 14116 14117 ExprResult TransformLambdaExpr(LambdaExpr *E) { 14118 // Lambdas never need to be transformed. 14119 return E; 14120 } 14121 }; 14122 } 14123 14124 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 14125 assert(isUnevaluatedContext() && 14126 "Should only transform unevaluated expressions"); 14127 ExprEvalContexts.back().Context = 14128 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 14129 if (isUnevaluatedContext()) 14130 return E; 14131 return TransformToPE(*this).TransformExpr(E); 14132 } 14133 14134 void 14135 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 14136 Decl *LambdaContextDecl, 14137 bool IsDecltype) { 14138 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 14139 LambdaContextDecl, IsDecltype); 14140 Cleanup.reset(); 14141 if (!MaybeODRUseExprs.empty()) 14142 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 14143 } 14144 14145 void 14146 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 14147 ReuseLambdaContextDecl_t, 14148 bool IsDecltype) { 14149 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 14150 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 14151 } 14152 14153 void Sema::PopExpressionEvaluationContext() { 14154 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 14155 unsigned NumTypos = Rec.NumTypos; 14156 14157 if (!Rec.Lambdas.empty()) { 14158 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 14159 unsigned D; 14160 if (Rec.isUnevaluated()) { 14161 // C++11 [expr.prim.lambda]p2: 14162 // A lambda-expression shall not appear in an unevaluated operand 14163 // (Clause 5). 14164 D = diag::err_lambda_unevaluated_operand; 14165 } else { 14166 // C++1y [expr.const]p2: 14167 // A conditional-expression e is a core constant expression unless the 14168 // evaluation of e, following the rules of the abstract machine, would 14169 // evaluate [...] a lambda-expression. 14170 D = diag::err_lambda_in_constant_expression; 14171 } 14172 14173 // C++1z allows lambda expressions as core constant expressions. 14174 // FIXME: In C++1z, reinstate the restrictions on lambda expressions (CWG 14175 // 1607) from appearing within template-arguments and array-bounds that 14176 // are part of function-signatures. Be mindful that P0315 (Lambdas in 14177 // unevaluated contexts) might lift some of these restrictions in a 14178 // future version. 14179 if (!Rec.isConstantEvaluated() || !getLangOpts().CPlusPlus17) 14180 for (const auto *L : Rec.Lambdas) 14181 Diag(L->getLocStart(), D); 14182 } else { 14183 // Mark the capture expressions odr-used. This was deferred 14184 // during lambda expression creation. 14185 for (auto *Lambda : Rec.Lambdas) { 14186 for (auto *C : Lambda->capture_inits()) 14187 MarkDeclarationsReferencedInExpr(C); 14188 } 14189 } 14190 } 14191 14192 // When are coming out of an unevaluated context, clear out any 14193 // temporaries that we may have created as part of the evaluation of 14194 // the expression in that context: they aren't relevant because they 14195 // will never be constructed. 14196 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 14197 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 14198 ExprCleanupObjects.end()); 14199 Cleanup = Rec.ParentCleanup; 14200 CleanupVarDeclMarking(); 14201 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 14202 // Otherwise, merge the contexts together. 14203 } else { 14204 Cleanup.mergeFrom(Rec.ParentCleanup); 14205 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 14206 Rec.SavedMaybeODRUseExprs.end()); 14207 } 14208 14209 // Pop the current expression evaluation context off the stack. 14210 ExprEvalContexts.pop_back(); 14211 14212 if (!ExprEvalContexts.empty()) 14213 ExprEvalContexts.back().NumTypos += NumTypos; 14214 else 14215 assert(NumTypos == 0 && "There are outstanding typos after popping the " 14216 "last ExpressionEvaluationContextRecord"); 14217 } 14218 14219 void Sema::DiscardCleanupsInEvaluationContext() { 14220 ExprCleanupObjects.erase( 14221 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 14222 ExprCleanupObjects.end()); 14223 Cleanup.reset(); 14224 MaybeODRUseExprs.clear(); 14225 } 14226 14227 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 14228 if (!E->getType()->isVariablyModifiedType()) 14229 return E; 14230 return TransformToPotentiallyEvaluated(E); 14231 } 14232 14233 /// Are we within a context in which some evaluation could be performed (be it 14234 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite 14235 /// captured by C++'s idea of an "unevaluated context". 14236 static bool isEvaluatableContext(Sema &SemaRef) { 14237 switch (SemaRef.ExprEvalContexts.back().Context) { 14238 case Sema::ExpressionEvaluationContext::Unevaluated: 14239 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 14240 case Sema::ExpressionEvaluationContext::DiscardedStatement: 14241 // Expressions in this context are never evaluated. 14242 return false; 14243 14244 case Sema::ExpressionEvaluationContext::UnevaluatedList: 14245 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 14246 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 14247 // Expressions in this context could be evaluated. 14248 return true; 14249 14250 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 14251 // Referenced declarations will only be used if the construct in the 14252 // containing expression is used, at which point we'll be given another 14253 // turn to mark them. 14254 return false; 14255 } 14256 llvm_unreachable("Invalid context"); 14257 } 14258 14259 /// Are we within a context in which references to resolved functions or to 14260 /// variables result in odr-use? 14261 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) { 14262 // An expression in a template is not really an expression until it's been 14263 // instantiated, so it doesn't trigger odr-use. 14264 if (SkipDependentUses && SemaRef.CurContext->isDependentContext()) 14265 return false; 14266 14267 switch (SemaRef.ExprEvalContexts.back().Context) { 14268 case Sema::ExpressionEvaluationContext::Unevaluated: 14269 case Sema::ExpressionEvaluationContext::UnevaluatedList: 14270 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 14271 case Sema::ExpressionEvaluationContext::DiscardedStatement: 14272 return false; 14273 14274 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 14275 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 14276 return true; 14277 14278 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 14279 return false; 14280 } 14281 llvm_unreachable("Invalid context"); 14282 } 14283 14284 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 14285 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 14286 return Func->isConstexpr() && 14287 (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided())); 14288 } 14289 14290 /// Mark a function referenced, and check whether it is odr-used 14291 /// (C++ [basic.def.odr]p2, C99 6.9p3) 14292 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 14293 bool MightBeOdrUse) { 14294 assert(Func && "No function?"); 14295 14296 Func->setReferenced(); 14297 14298 // C++11 [basic.def.odr]p3: 14299 // A function whose name appears as a potentially-evaluated expression is 14300 // odr-used if it is the unique lookup result or the selected member of a 14301 // set of overloaded functions [...]. 14302 // 14303 // We (incorrectly) mark overload resolution as an unevaluated context, so we 14304 // can just check that here. 14305 bool OdrUse = MightBeOdrUse && isOdrUseContext(*this); 14306 14307 // Determine whether we require a function definition to exist, per 14308 // C++11 [temp.inst]p3: 14309 // Unless a function template specialization has been explicitly 14310 // instantiated or explicitly specialized, the function template 14311 // specialization is implicitly instantiated when the specialization is 14312 // referenced in a context that requires a function definition to exist. 14313 // 14314 // That is either when this is an odr-use, or when a usage of a constexpr 14315 // function occurs within an evaluatable context. 14316 bool NeedDefinition = 14317 OdrUse || (isEvaluatableContext(*this) && 14318 isImplicitlyDefinableConstexprFunction(Func)); 14319 14320 // C++14 [temp.expl.spec]p6: 14321 // If a template [...] is explicitly specialized then that specialization 14322 // shall be declared before the first use of that specialization that would 14323 // cause an implicit instantiation to take place, in every translation unit 14324 // in which such a use occurs 14325 if (NeedDefinition && 14326 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 14327 Func->getMemberSpecializationInfo())) 14328 checkSpecializationVisibility(Loc, Func); 14329 14330 // C++14 [except.spec]p17: 14331 // An exception-specification is considered to be needed when: 14332 // - the function is odr-used or, if it appears in an unevaluated operand, 14333 // would be odr-used if the expression were potentially-evaluated; 14334 // 14335 // Note, we do this even if MightBeOdrUse is false. That indicates that the 14336 // function is a pure virtual function we're calling, and in that case the 14337 // function was selected by overload resolution and we need to resolve its 14338 // exception specification for a different reason. 14339 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 14340 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 14341 ResolveExceptionSpec(Loc, FPT); 14342 14343 // If we don't need to mark the function as used, and we don't need to 14344 // try to provide a definition, there's nothing more to do. 14345 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) && 14346 (!NeedDefinition || Func->getBody())) 14347 return; 14348 14349 // Note that this declaration has been used. 14350 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 14351 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 14352 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 14353 if (Constructor->isDefaultConstructor()) { 14354 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 14355 return; 14356 DefineImplicitDefaultConstructor(Loc, Constructor); 14357 } else if (Constructor->isCopyConstructor()) { 14358 DefineImplicitCopyConstructor(Loc, Constructor); 14359 } else if (Constructor->isMoveConstructor()) { 14360 DefineImplicitMoveConstructor(Loc, Constructor); 14361 } 14362 } else if (Constructor->getInheritedConstructor()) { 14363 DefineInheritingConstructor(Loc, Constructor); 14364 } 14365 } else if (CXXDestructorDecl *Destructor = 14366 dyn_cast<CXXDestructorDecl>(Func)) { 14367 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 14368 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 14369 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 14370 return; 14371 DefineImplicitDestructor(Loc, Destructor); 14372 } 14373 if (Destructor->isVirtual() && getLangOpts().AppleKext) 14374 MarkVTableUsed(Loc, Destructor->getParent()); 14375 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 14376 if (MethodDecl->isOverloadedOperator() && 14377 MethodDecl->getOverloadedOperator() == OO_Equal) { 14378 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 14379 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 14380 if (MethodDecl->isCopyAssignmentOperator()) 14381 DefineImplicitCopyAssignment(Loc, MethodDecl); 14382 else if (MethodDecl->isMoveAssignmentOperator()) 14383 DefineImplicitMoveAssignment(Loc, MethodDecl); 14384 } 14385 } else if (isa<CXXConversionDecl>(MethodDecl) && 14386 MethodDecl->getParent()->isLambda()) { 14387 CXXConversionDecl *Conversion = 14388 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 14389 if (Conversion->isLambdaToBlockPointerConversion()) 14390 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 14391 else 14392 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 14393 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 14394 MarkVTableUsed(Loc, MethodDecl->getParent()); 14395 } 14396 14397 // Recursive functions should be marked when used from another function. 14398 // FIXME: Is this really right? 14399 if (CurContext == Func) return; 14400 14401 // Implicit instantiation of function templates and member functions of 14402 // class templates. 14403 if (Func->isImplicitlyInstantiable()) { 14404 TemplateSpecializationKind TSK = Func->getTemplateSpecializationKind(); 14405 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 14406 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 14407 if (FirstInstantiation) { 14408 PointOfInstantiation = Loc; 14409 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 14410 } else if (TSK != TSK_ImplicitInstantiation) { 14411 // Use the point of use as the point of instantiation, instead of the 14412 // point of explicit instantiation (which we track as the actual point of 14413 // instantiation). This gives better backtraces in diagnostics. 14414 PointOfInstantiation = Loc; 14415 } 14416 14417 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 14418 Func->isConstexpr()) { 14419 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 14420 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 14421 CodeSynthesisContexts.size()) 14422 PendingLocalImplicitInstantiations.push_back( 14423 std::make_pair(Func, PointOfInstantiation)); 14424 else if (Func->isConstexpr()) 14425 // Do not defer instantiations of constexpr functions, to avoid the 14426 // expression evaluator needing to call back into Sema if it sees a 14427 // call to such a function. 14428 InstantiateFunctionDefinition(PointOfInstantiation, Func); 14429 else { 14430 Func->setInstantiationIsPending(true); 14431 PendingInstantiations.push_back(std::make_pair(Func, 14432 PointOfInstantiation)); 14433 // Notify the consumer that a function was implicitly instantiated. 14434 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 14435 } 14436 } 14437 } else { 14438 // Walk redefinitions, as some of them may be instantiable. 14439 for (auto i : Func->redecls()) { 14440 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 14441 MarkFunctionReferenced(Loc, i, OdrUse); 14442 } 14443 } 14444 14445 if (!OdrUse) return; 14446 14447 // Keep track of used but undefined functions. 14448 if (!Func->isDefined()) { 14449 if (mightHaveNonExternalLinkage(Func)) 14450 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14451 else if (Func->getMostRecentDecl()->isInlined() && 14452 !LangOpts.GNUInline && 14453 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 14454 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14455 else if (isExternalWithNoLinkageType(Func)) 14456 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14457 } 14458 14459 Func->markUsed(Context); 14460 } 14461 14462 static void 14463 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 14464 ValueDecl *var, DeclContext *DC) { 14465 DeclContext *VarDC = var->getDeclContext(); 14466 14467 // If the parameter still belongs to the translation unit, then 14468 // we're actually just using one parameter in the declaration of 14469 // the next. 14470 if (isa<ParmVarDecl>(var) && 14471 isa<TranslationUnitDecl>(VarDC)) 14472 return; 14473 14474 // For C code, don't diagnose about capture if we're not actually in code 14475 // right now; it's impossible to write a non-constant expression outside of 14476 // function context, so we'll get other (more useful) diagnostics later. 14477 // 14478 // For C++, things get a bit more nasty... it would be nice to suppress this 14479 // diagnostic for certain cases like using a local variable in an array bound 14480 // for a member of a local class, but the correct predicate is not obvious. 14481 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 14482 return; 14483 14484 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 14485 unsigned ContextKind = 3; // unknown 14486 if (isa<CXXMethodDecl>(VarDC) && 14487 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 14488 ContextKind = 2; 14489 } else if (isa<FunctionDecl>(VarDC)) { 14490 ContextKind = 0; 14491 } else if (isa<BlockDecl>(VarDC)) { 14492 ContextKind = 1; 14493 } 14494 14495 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 14496 << var << ValueKind << ContextKind << VarDC; 14497 S.Diag(var->getLocation(), diag::note_entity_declared_at) 14498 << var; 14499 14500 // FIXME: Add additional diagnostic info about class etc. which prevents 14501 // capture. 14502 } 14503 14504 14505 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 14506 bool &SubCapturesAreNested, 14507 QualType &CaptureType, 14508 QualType &DeclRefType) { 14509 // Check whether we've already captured it. 14510 if (CSI->CaptureMap.count(Var)) { 14511 // If we found a capture, any subcaptures are nested. 14512 SubCapturesAreNested = true; 14513 14514 // Retrieve the capture type for this variable. 14515 CaptureType = CSI->getCapture(Var).getCaptureType(); 14516 14517 // Compute the type of an expression that refers to this variable. 14518 DeclRefType = CaptureType.getNonReferenceType(); 14519 14520 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 14521 // are mutable in the sense that user can change their value - they are 14522 // private instances of the captured declarations. 14523 const Capture &Cap = CSI->getCapture(Var); 14524 if (Cap.isCopyCapture() && 14525 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 14526 !(isa<CapturedRegionScopeInfo>(CSI) && 14527 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 14528 DeclRefType.addConst(); 14529 return true; 14530 } 14531 return false; 14532 } 14533 14534 // Only block literals, captured statements, and lambda expressions can 14535 // capture; other scopes don't work. 14536 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 14537 SourceLocation Loc, 14538 const bool Diagnose, Sema &S) { 14539 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 14540 return getLambdaAwareParentOfDeclContext(DC); 14541 else if (Var->hasLocalStorage()) { 14542 if (Diagnose) 14543 diagnoseUncapturableValueReference(S, Loc, Var, DC); 14544 } 14545 return nullptr; 14546 } 14547 14548 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 14549 // certain types of variables (unnamed, variably modified types etc.) 14550 // so check for eligibility. 14551 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 14552 SourceLocation Loc, 14553 const bool Diagnose, Sema &S) { 14554 14555 bool IsBlock = isa<BlockScopeInfo>(CSI); 14556 bool IsLambda = isa<LambdaScopeInfo>(CSI); 14557 14558 // Lambdas are not allowed to capture unnamed variables 14559 // (e.g. anonymous unions). 14560 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 14561 // assuming that's the intent. 14562 if (IsLambda && !Var->getDeclName()) { 14563 if (Diagnose) { 14564 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 14565 S.Diag(Var->getLocation(), diag::note_declared_at); 14566 } 14567 return false; 14568 } 14569 14570 // Prohibit variably-modified types in blocks; they're difficult to deal with. 14571 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 14572 if (Diagnose) { 14573 S.Diag(Loc, diag::err_ref_vm_type); 14574 S.Diag(Var->getLocation(), diag::note_previous_decl) 14575 << Var->getDeclName(); 14576 } 14577 return false; 14578 } 14579 // Prohibit structs with flexible array members too. 14580 // We cannot capture what is in the tail end of the struct. 14581 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 14582 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 14583 if (Diagnose) { 14584 if (IsBlock) 14585 S.Diag(Loc, diag::err_ref_flexarray_type); 14586 else 14587 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 14588 << Var->getDeclName(); 14589 S.Diag(Var->getLocation(), diag::note_previous_decl) 14590 << Var->getDeclName(); 14591 } 14592 return false; 14593 } 14594 } 14595 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 14596 // Lambdas and captured statements are not allowed to capture __block 14597 // variables; they don't support the expected semantics. 14598 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 14599 if (Diagnose) { 14600 S.Diag(Loc, diag::err_capture_block_variable) 14601 << Var->getDeclName() << !IsLambda; 14602 S.Diag(Var->getLocation(), diag::note_previous_decl) 14603 << Var->getDeclName(); 14604 } 14605 return false; 14606 } 14607 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 14608 if (S.getLangOpts().OpenCL && IsBlock && 14609 Var->getType()->isBlockPointerType()) { 14610 if (Diagnose) 14611 S.Diag(Loc, diag::err_opencl_block_ref_block); 14612 return false; 14613 } 14614 14615 return true; 14616 } 14617 14618 // Returns true if the capture by block was successful. 14619 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 14620 SourceLocation Loc, 14621 const bool BuildAndDiagnose, 14622 QualType &CaptureType, 14623 QualType &DeclRefType, 14624 const bool Nested, 14625 Sema &S) { 14626 Expr *CopyExpr = nullptr; 14627 bool ByRef = false; 14628 14629 // Blocks are not allowed to capture arrays. 14630 if (CaptureType->isArrayType()) { 14631 if (BuildAndDiagnose) { 14632 S.Diag(Loc, diag::err_ref_array_type); 14633 S.Diag(Var->getLocation(), diag::note_previous_decl) 14634 << Var->getDeclName(); 14635 } 14636 return false; 14637 } 14638 14639 // Forbid the block-capture of autoreleasing variables. 14640 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 14641 if (BuildAndDiagnose) { 14642 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 14643 << /*block*/ 0; 14644 S.Diag(Var->getLocation(), diag::note_previous_decl) 14645 << Var->getDeclName(); 14646 } 14647 return false; 14648 } 14649 14650 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 14651 if (const auto *PT = CaptureType->getAs<PointerType>()) { 14652 // This function finds out whether there is an AttributedType of kind 14653 // attr_objc_ownership in Ty. The existence of AttributedType of kind 14654 // attr_objc_ownership implies __autoreleasing was explicitly specified 14655 // rather than being added implicitly by the compiler. 14656 auto IsObjCOwnershipAttributedType = [](QualType Ty) { 14657 while (const auto *AttrTy = Ty->getAs<AttributedType>()) { 14658 if (AttrTy->getAttrKind() == AttributedType::attr_objc_ownership) 14659 return true; 14660 14661 // Peel off AttributedTypes that are not of kind objc_ownership. 14662 Ty = AttrTy->getModifiedType(); 14663 } 14664 14665 return false; 14666 }; 14667 14668 QualType PointeeTy = PT->getPointeeType(); 14669 14670 if (PointeeTy->getAs<ObjCObjectPointerType>() && 14671 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 14672 !IsObjCOwnershipAttributedType(PointeeTy)) { 14673 if (BuildAndDiagnose) { 14674 SourceLocation VarLoc = Var->getLocation(); 14675 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 14676 S.Diag(VarLoc, diag::note_declare_parameter_strong); 14677 } 14678 } 14679 } 14680 14681 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 14682 if (HasBlocksAttr || CaptureType->isReferenceType() || 14683 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 14684 // Block capture by reference does not change the capture or 14685 // declaration reference types. 14686 ByRef = true; 14687 } else { 14688 // Block capture by copy introduces 'const'. 14689 CaptureType = CaptureType.getNonReferenceType().withConst(); 14690 DeclRefType = CaptureType; 14691 14692 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 14693 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 14694 // The capture logic needs the destructor, so make sure we mark it. 14695 // Usually this is unnecessary because most local variables have 14696 // their destructors marked at declaration time, but parameters are 14697 // an exception because it's technically only the call site that 14698 // actually requires the destructor. 14699 if (isa<ParmVarDecl>(Var)) 14700 S.FinalizeVarWithDestructor(Var, Record); 14701 14702 // Enter a new evaluation context to insulate the copy 14703 // full-expression. 14704 EnterExpressionEvaluationContext scope( 14705 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 14706 14707 // According to the blocks spec, the capture of a variable from 14708 // the stack requires a const copy constructor. This is not true 14709 // of the copy/move done to move a __block variable to the heap. 14710 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 14711 DeclRefType.withConst(), 14712 VK_LValue, Loc); 14713 14714 ExprResult Result 14715 = S.PerformCopyInitialization( 14716 InitializedEntity::InitializeBlock(Var->getLocation(), 14717 CaptureType, false), 14718 Loc, DeclRef); 14719 14720 // Build a full-expression copy expression if initialization 14721 // succeeded and used a non-trivial constructor. Recover from 14722 // errors by pretending that the copy isn't necessary. 14723 if (!Result.isInvalid() && 14724 !cast<CXXConstructExpr>(Result.get())->getConstructor() 14725 ->isTrivial()) { 14726 Result = S.MaybeCreateExprWithCleanups(Result); 14727 CopyExpr = Result.get(); 14728 } 14729 } 14730 } 14731 } 14732 14733 // Actually capture the variable. 14734 if (BuildAndDiagnose) 14735 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 14736 SourceLocation(), CaptureType, CopyExpr); 14737 14738 return true; 14739 14740 } 14741 14742 14743 /// Capture the given variable in the captured region. 14744 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 14745 VarDecl *Var, 14746 SourceLocation Loc, 14747 const bool BuildAndDiagnose, 14748 QualType &CaptureType, 14749 QualType &DeclRefType, 14750 const bool RefersToCapturedVariable, 14751 Sema &S) { 14752 // By default, capture variables by reference. 14753 bool ByRef = true; 14754 // Using an LValue reference type is consistent with Lambdas (see below). 14755 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 14756 if (S.isOpenMPCapturedDecl(Var)) { 14757 bool HasConst = DeclRefType.isConstQualified(); 14758 DeclRefType = DeclRefType.getUnqualifiedType(); 14759 // Don't lose diagnostics about assignments to const. 14760 if (HasConst) 14761 DeclRefType.addConst(); 14762 } 14763 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel); 14764 } 14765 14766 if (ByRef) 14767 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 14768 else 14769 CaptureType = DeclRefType; 14770 14771 Expr *CopyExpr = nullptr; 14772 if (BuildAndDiagnose) { 14773 // The current implementation assumes that all variables are captured 14774 // by references. Since there is no capture by copy, no expression 14775 // evaluation will be needed. 14776 RecordDecl *RD = RSI->TheRecordDecl; 14777 14778 FieldDecl *Field 14779 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 14780 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 14781 nullptr, false, ICIS_NoInit); 14782 Field->setImplicit(true); 14783 Field->setAccess(AS_private); 14784 RD->addDecl(Field); 14785 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) 14786 S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel); 14787 14788 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, 14789 DeclRefType, VK_LValue, Loc); 14790 Var->setReferenced(true); 14791 Var->markUsed(S.Context); 14792 } 14793 14794 // Actually capture the variable. 14795 if (BuildAndDiagnose) 14796 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 14797 SourceLocation(), CaptureType, CopyExpr); 14798 14799 14800 return true; 14801 } 14802 14803 /// Create a field within the lambda class for the variable 14804 /// being captured. 14805 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, 14806 QualType FieldType, QualType DeclRefType, 14807 SourceLocation Loc, 14808 bool RefersToCapturedVariable) { 14809 CXXRecordDecl *Lambda = LSI->Lambda; 14810 14811 // Build the non-static data member. 14812 FieldDecl *Field 14813 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 14814 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 14815 nullptr, false, ICIS_NoInit); 14816 Field->setImplicit(true); 14817 Field->setAccess(AS_private); 14818 Lambda->addDecl(Field); 14819 } 14820 14821 /// Capture the given variable in the lambda. 14822 static bool captureInLambda(LambdaScopeInfo *LSI, 14823 VarDecl *Var, 14824 SourceLocation Loc, 14825 const bool BuildAndDiagnose, 14826 QualType &CaptureType, 14827 QualType &DeclRefType, 14828 const bool RefersToCapturedVariable, 14829 const Sema::TryCaptureKind Kind, 14830 SourceLocation EllipsisLoc, 14831 const bool IsTopScope, 14832 Sema &S) { 14833 14834 // Determine whether we are capturing by reference or by value. 14835 bool ByRef = false; 14836 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 14837 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 14838 } else { 14839 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 14840 } 14841 14842 // Compute the type of the field that will capture this variable. 14843 if (ByRef) { 14844 // C++11 [expr.prim.lambda]p15: 14845 // An entity is captured by reference if it is implicitly or 14846 // explicitly captured but not captured by copy. It is 14847 // unspecified whether additional unnamed non-static data 14848 // members are declared in the closure type for entities 14849 // captured by reference. 14850 // 14851 // FIXME: It is not clear whether we want to build an lvalue reference 14852 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 14853 // to do the former, while EDG does the latter. Core issue 1249 will 14854 // clarify, but for now we follow GCC because it's a more permissive and 14855 // easily defensible position. 14856 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 14857 } else { 14858 // C++11 [expr.prim.lambda]p14: 14859 // For each entity captured by copy, an unnamed non-static 14860 // data member is declared in the closure type. The 14861 // declaration order of these members is unspecified. The type 14862 // of such a data member is the type of the corresponding 14863 // captured entity if the entity is not a reference to an 14864 // object, or the referenced type otherwise. [Note: If the 14865 // captured entity is a reference to a function, the 14866 // corresponding data member is also a reference to a 14867 // function. - end note ] 14868 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 14869 if (!RefType->getPointeeType()->isFunctionType()) 14870 CaptureType = RefType->getPointeeType(); 14871 } 14872 14873 // Forbid the lambda copy-capture of autoreleasing variables. 14874 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 14875 if (BuildAndDiagnose) { 14876 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 14877 S.Diag(Var->getLocation(), diag::note_previous_decl) 14878 << Var->getDeclName(); 14879 } 14880 return false; 14881 } 14882 14883 // Make sure that by-copy captures are of a complete and non-abstract type. 14884 if (BuildAndDiagnose) { 14885 if (!CaptureType->isDependentType() && 14886 S.RequireCompleteType(Loc, CaptureType, 14887 diag::err_capture_of_incomplete_type, 14888 Var->getDeclName())) 14889 return false; 14890 14891 if (S.RequireNonAbstractType(Loc, CaptureType, 14892 diag::err_capture_of_abstract_type)) 14893 return false; 14894 } 14895 } 14896 14897 // Capture this variable in the lambda. 14898 if (BuildAndDiagnose) 14899 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc, 14900 RefersToCapturedVariable); 14901 14902 // Compute the type of a reference to this captured variable. 14903 if (ByRef) 14904 DeclRefType = CaptureType.getNonReferenceType(); 14905 else { 14906 // C++ [expr.prim.lambda]p5: 14907 // The closure type for a lambda-expression has a public inline 14908 // function call operator [...]. This function call operator is 14909 // declared const (9.3.1) if and only if the lambda-expression's 14910 // parameter-declaration-clause is not followed by mutable. 14911 DeclRefType = CaptureType.getNonReferenceType(); 14912 if (!LSI->Mutable && !CaptureType->isReferenceType()) 14913 DeclRefType.addConst(); 14914 } 14915 14916 // Add the capture. 14917 if (BuildAndDiagnose) 14918 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 14919 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 14920 14921 return true; 14922 } 14923 14924 bool Sema::tryCaptureVariable( 14925 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 14926 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 14927 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 14928 // An init-capture is notionally from the context surrounding its 14929 // declaration, but its parent DC is the lambda class. 14930 DeclContext *VarDC = Var->getDeclContext(); 14931 if (Var->isInitCapture()) 14932 VarDC = VarDC->getParent(); 14933 14934 DeclContext *DC = CurContext; 14935 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 14936 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 14937 // We need to sync up the Declaration Context with the 14938 // FunctionScopeIndexToStopAt 14939 if (FunctionScopeIndexToStopAt) { 14940 unsigned FSIndex = FunctionScopes.size() - 1; 14941 while (FSIndex != MaxFunctionScopesIndex) { 14942 DC = getLambdaAwareParentOfDeclContext(DC); 14943 --FSIndex; 14944 } 14945 } 14946 14947 14948 // If the variable is declared in the current context, there is no need to 14949 // capture it. 14950 if (VarDC == DC) return true; 14951 14952 // Capture global variables if it is required to use private copy of this 14953 // variable. 14954 bool IsGlobal = !Var->hasLocalStorage(); 14955 if (IsGlobal && !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var))) 14956 return true; 14957 Var = Var->getCanonicalDecl(); 14958 14959 // Walk up the stack to determine whether we can capture the variable, 14960 // performing the "simple" checks that don't depend on type. We stop when 14961 // we've either hit the declared scope of the variable or find an existing 14962 // capture of that variable. We start from the innermost capturing-entity 14963 // (the DC) and ensure that all intervening capturing-entities 14964 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 14965 // declcontext can either capture the variable or have already captured 14966 // the variable. 14967 CaptureType = Var->getType(); 14968 DeclRefType = CaptureType.getNonReferenceType(); 14969 bool Nested = false; 14970 bool Explicit = (Kind != TryCapture_Implicit); 14971 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 14972 do { 14973 // Only block literals, captured statements, and lambda expressions can 14974 // capture; other scopes don't work. 14975 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 14976 ExprLoc, 14977 BuildAndDiagnose, 14978 *this); 14979 // We need to check for the parent *first* because, if we *have* 14980 // private-captured a global variable, we need to recursively capture it in 14981 // intermediate blocks, lambdas, etc. 14982 if (!ParentDC) { 14983 if (IsGlobal) { 14984 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 14985 break; 14986 } 14987 return true; 14988 } 14989 14990 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 14991 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 14992 14993 14994 // Check whether we've already captured it. 14995 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 14996 DeclRefType)) { 14997 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 14998 break; 14999 } 15000 // If we are instantiating a generic lambda call operator body, 15001 // we do not want to capture new variables. What was captured 15002 // during either a lambdas transformation or initial parsing 15003 // should be used. 15004 if (isGenericLambdaCallOperatorSpecialization(DC)) { 15005 if (BuildAndDiagnose) { 15006 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 15007 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 15008 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 15009 Diag(Var->getLocation(), diag::note_previous_decl) 15010 << Var->getDeclName(); 15011 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); 15012 } else 15013 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 15014 } 15015 return true; 15016 } 15017 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 15018 // certain types of variables (unnamed, variably modified types etc.) 15019 // so check for eligibility. 15020 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 15021 return true; 15022 15023 // Try to capture variable-length arrays types. 15024 if (Var->getType()->isVariablyModifiedType()) { 15025 // We're going to walk down into the type and look for VLA 15026 // expressions. 15027 QualType QTy = Var->getType(); 15028 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 15029 QTy = PVD->getOriginalType(); 15030 captureVariablyModifiedType(Context, QTy, CSI); 15031 } 15032 15033 if (getLangOpts().OpenMP) { 15034 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 15035 // OpenMP private variables should not be captured in outer scope, so 15036 // just break here. Similarly, global variables that are captured in a 15037 // target region should not be captured outside the scope of the region. 15038 if (RSI->CapRegionKind == CR_OpenMP) { 15039 bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel); 15040 auto IsTargetCap = !IsOpenMPPrivateDecl && 15041 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 15042 // When we detect target captures we are looking from inside the 15043 // target region, therefore we need to propagate the capture from the 15044 // enclosing region. Therefore, the capture is not initially nested. 15045 if (IsTargetCap) 15046 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 15047 15048 if (IsTargetCap || IsOpenMPPrivateDecl) { 15049 Nested = !IsTargetCap; 15050 DeclRefType = DeclRefType.getUnqualifiedType(); 15051 CaptureType = Context.getLValueReferenceType(DeclRefType); 15052 break; 15053 } 15054 } 15055 } 15056 } 15057 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 15058 // No capture-default, and this is not an explicit capture 15059 // so cannot capture this variable. 15060 if (BuildAndDiagnose) { 15061 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 15062 Diag(Var->getLocation(), diag::note_previous_decl) 15063 << Var->getDeclName(); 15064 if (cast<LambdaScopeInfo>(CSI)->Lambda) 15065 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 15066 diag::note_lambda_decl); 15067 // FIXME: If we error out because an outer lambda can not implicitly 15068 // capture a variable that an inner lambda explicitly captures, we 15069 // should have the inner lambda do the explicit capture - because 15070 // it makes for cleaner diagnostics later. This would purely be done 15071 // so that the diagnostic does not misleadingly claim that a variable 15072 // can not be captured by a lambda implicitly even though it is captured 15073 // explicitly. Suggestion: 15074 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 15075 // at the function head 15076 // - cache the StartingDeclContext - this must be a lambda 15077 // - captureInLambda in the innermost lambda the variable. 15078 } 15079 return true; 15080 } 15081 15082 FunctionScopesIndex--; 15083 DC = ParentDC; 15084 Explicit = false; 15085 } while (!VarDC->Equals(DC)); 15086 15087 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 15088 // computing the type of the capture at each step, checking type-specific 15089 // requirements, and adding captures if requested. 15090 // If the variable had already been captured previously, we start capturing 15091 // at the lambda nested within that one. 15092 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 15093 ++I) { 15094 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 15095 15096 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 15097 if (!captureInBlock(BSI, Var, ExprLoc, 15098 BuildAndDiagnose, CaptureType, 15099 DeclRefType, Nested, *this)) 15100 return true; 15101 Nested = true; 15102 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 15103 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 15104 BuildAndDiagnose, CaptureType, 15105 DeclRefType, Nested, *this)) 15106 return true; 15107 Nested = true; 15108 } else { 15109 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 15110 if (!captureInLambda(LSI, Var, ExprLoc, 15111 BuildAndDiagnose, CaptureType, 15112 DeclRefType, Nested, Kind, EllipsisLoc, 15113 /*IsTopScope*/I == N - 1, *this)) 15114 return true; 15115 Nested = true; 15116 } 15117 } 15118 return false; 15119 } 15120 15121 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 15122 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 15123 QualType CaptureType; 15124 QualType DeclRefType; 15125 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 15126 /*BuildAndDiagnose=*/true, CaptureType, 15127 DeclRefType, nullptr); 15128 } 15129 15130 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 15131 QualType CaptureType; 15132 QualType DeclRefType; 15133 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 15134 /*BuildAndDiagnose=*/false, CaptureType, 15135 DeclRefType, nullptr); 15136 } 15137 15138 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 15139 QualType CaptureType; 15140 QualType DeclRefType; 15141 15142 // Determine whether we can capture this variable. 15143 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 15144 /*BuildAndDiagnose=*/false, CaptureType, 15145 DeclRefType, nullptr)) 15146 return QualType(); 15147 15148 return DeclRefType; 15149 } 15150 15151 15152 15153 // If either the type of the variable or the initializer is dependent, 15154 // return false. Otherwise, determine whether the variable is a constant 15155 // expression. Use this if you need to know if a variable that might or 15156 // might not be dependent is truly a constant expression. 15157 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 15158 ASTContext &Context) { 15159 15160 if (Var->getType()->isDependentType()) 15161 return false; 15162 const VarDecl *DefVD = nullptr; 15163 Var->getAnyInitializer(DefVD); 15164 if (!DefVD) 15165 return false; 15166 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 15167 Expr *Init = cast<Expr>(Eval->Value); 15168 if (Init->isValueDependent()) 15169 return false; 15170 return IsVariableAConstantExpression(Var, Context); 15171 } 15172 15173 15174 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 15175 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 15176 // an object that satisfies the requirements for appearing in a 15177 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 15178 // is immediately applied." This function handles the lvalue-to-rvalue 15179 // conversion part. 15180 MaybeODRUseExprs.erase(E->IgnoreParens()); 15181 15182 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 15183 // to a variable that is a constant expression, and if so, identify it as 15184 // a reference to a variable that does not involve an odr-use of that 15185 // variable. 15186 if (LambdaScopeInfo *LSI = getCurLambda()) { 15187 Expr *SansParensExpr = E->IgnoreParens(); 15188 VarDecl *Var = nullptr; 15189 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 15190 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 15191 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 15192 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 15193 15194 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 15195 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 15196 } 15197 } 15198 15199 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 15200 Res = CorrectDelayedTyposInExpr(Res); 15201 15202 if (!Res.isUsable()) 15203 return Res; 15204 15205 // If a constant-expression is a reference to a variable where we delay 15206 // deciding whether it is an odr-use, just assume we will apply the 15207 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 15208 // (a non-type template argument), we have special handling anyway. 15209 UpdateMarkingForLValueToRValue(Res.get()); 15210 return Res; 15211 } 15212 15213 void Sema::CleanupVarDeclMarking() { 15214 for (Expr *E : MaybeODRUseExprs) { 15215 VarDecl *Var; 15216 SourceLocation Loc; 15217 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 15218 Var = cast<VarDecl>(DRE->getDecl()); 15219 Loc = DRE->getLocation(); 15220 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 15221 Var = cast<VarDecl>(ME->getMemberDecl()); 15222 Loc = ME->getMemberLoc(); 15223 } else { 15224 llvm_unreachable("Unexpected expression"); 15225 } 15226 15227 MarkVarDeclODRUsed(Var, Loc, *this, 15228 /*MaxFunctionScopeIndex Pointer*/ nullptr); 15229 } 15230 15231 MaybeODRUseExprs.clear(); 15232 } 15233 15234 15235 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 15236 VarDecl *Var, Expr *E) { 15237 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 15238 "Invalid Expr argument to DoMarkVarDeclReferenced"); 15239 Var->setReferenced(); 15240 15241 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 15242 15243 bool OdrUseContext = isOdrUseContext(SemaRef); 15244 bool UsableInConstantExpr = 15245 Var->isUsableInConstantExpressions(SemaRef.Context); 15246 bool NeedDefinition = 15247 OdrUseContext || (isEvaluatableContext(SemaRef) && UsableInConstantExpr); 15248 15249 VarTemplateSpecializationDecl *VarSpec = 15250 dyn_cast<VarTemplateSpecializationDecl>(Var); 15251 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 15252 "Can't instantiate a partial template specialization."); 15253 15254 // If this might be a member specialization of a static data member, check 15255 // the specialization is visible. We already did the checks for variable 15256 // template specializations when we created them. 15257 if (NeedDefinition && TSK != TSK_Undeclared && 15258 !isa<VarTemplateSpecializationDecl>(Var)) 15259 SemaRef.checkSpecializationVisibility(Loc, Var); 15260 15261 // Perform implicit instantiation of static data members, static data member 15262 // templates of class templates, and variable template specializations. Delay 15263 // instantiations of variable templates, except for those that could be used 15264 // in a constant expression. 15265 if (NeedDefinition && isTemplateInstantiation(TSK)) { 15266 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 15267 // instantiation declaration if a variable is usable in a constant 15268 // expression (among other cases). 15269 bool TryInstantiating = 15270 TSK == TSK_ImplicitInstantiation || 15271 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 15272 15273 if (TryInstantiating) { 15274 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 15275 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 15276 if (FirstInstantiation) { 15277 PointOfInstantiation = Loc; 15278 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 15279 } 15280 15281 bool InstantiationDependent = false; 15282 bool IsNonDependent = 15283 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 15284 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 15285 : true; 15286 15287 // Do not instantiate specializations that are still type-dependent. 15288 if (IsNonDependent) { 15289 if (UsableInConstantExpr) { 15290 // Do not defer instantiations of variables that could be used in a 15291 // constant expression. 15292 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 15293 } else if (FirstInstantiation || 15294 isa<VarTemplateSpecializationDecl>(Var)) { 15295 // FIXME: For a specialization of a variable template, we don't 15296 // distinguish between "declaration and type implicitly instantiated" 15297 // and "implicit instantiation of definition requested", so we have 15298 // no direct way to avoid enqueueing the pending instantiation 15299 // multiple times. 15300 SemaRef.PendingInstantiations 15301 .push_back(std::make_pair(Var, PointOfInstantiation)); 15302 } 15303 } 15304 } 15305 } 15306 15307 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 15308 // the requirements for appearing in a constant expression (5.19) and, if 15309 // it is an object, the lvalue-to-rvalue conversion (4.1) 15310 // is immediately applied." We check the first part here, and 15311 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 15312 // Note that we use the C++11 definition everywhere because nothing in 15313 // C++03 depends on whether we get the C++03 version correct. The second 15314 // part does not apply to references, since they are not objects. 15315 if (OdrUseContext && E && 15316 IsVariableAConstantExpression(Var, SemaRef.Context)) { 15317 // A reference initialized by a constant expression can never be 15318 // odr-used, so simply ignore it. 15319 if (!Var->getType()->isReferenceType() || 15320 (SemaRef.LangOpts.OpenMP && SemaRef.isOpenMPCapturedDecl(Var))) 15321 SemaRef.MaybeODRUseExprs.insert(E); 15322 } else if (OdrUseContext) { 15323 MarkVarDeclODRUsed(Var, Loc, SemaRef, 15324 /*MaxFunctionScopeIndex ptr*/ nullptr); 15325 } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) { 15326 // If this is a dependent context, we don't need to mark variables as 15327 // odr-used, but we may still need to track them for lambda capture. 15328 // FIXME: Do we also need to do this inside dependent typeid expressions 15329 // (which are modeled as unevaluated at this point)? 15330 const bool RefersToEnclosingScope = 15331 (SemaRef.CurContext != Var->getDeclContext() && 15332 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 15333 if (RefersToEnclosingScope) { 15334 LambdaScopeInfo *const LSI = 15335 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 15336 if (LSI && (!LSI->CallOperator || 15337 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 15338 // If a variable could potentially be odr-used, defer marking it so 15339 // until we finish analyzing the full expression for any 15340 // lvalue-to-rvalue 15341 // or discarded value conversions that would obviate odr-use. 15342 // Add it to the list of potential captures that will be analyzed 15343 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 15344 // unless the variable is a reference that was initialized by a constant 15345 // expression (this will never need to be captured or odr-used). 15346 assert(E && "Capture variable should be used in an expression."); 15347 if (!Var->getType()->isReferenceType() || 15348 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 15349 LSI->addPotentialCapture(E->IgnoreParens()); 15350 } 15351 } 15352 } 15353 } 15354 15355 /// Mark a variable referenced, and check whether it is odr-used 15356 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 15357 /// used directly for normal expressions referring to VarDecl. 15358 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 15359 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 15360 } 15361 15362 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 15363 Decl *D, Expr *E, bool MightBeOdrUse) { 15364 if (SemaRef.isInOpenMPDeclareTargetContext()) 15365 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 15366 15367 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 15368 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 15369 return; 15370 } 15371 15372 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 15373 15374 // If this is a call to a method via a cast, also mark the method in the 15375 // derived class used in case codegen can devirtualize the call. 15376 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 15377 if (!ME) 15378 return; 15379 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 15380 if (!MD) 15381 return; 15382 // Only attempt to devirtualize if this is truly a virtual call. 15383 bool IsVirtualCall = MD->isVirtual() && 15384 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 15385 if (!IsVirtualCall) 15386 return; 15387 15388 // If it's possible to devirtualize the call, mark the called function 15389 // referenced. 15390 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 15391 ME->getBase(), SemaRef.getLangOpts().AppleKext); 15392 if (DM) 15393 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 15394 } 15395 15396 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 15397 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 15398 // TODO: update this with DR# once a defect report is filed. 15399 // C++11 defect. The address of a pure member should not be an ODR use, even 15400 // if it's a qualified reference. 15401 bool OdrUse = true; 15402 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 15403 if (Method->isVirtual() && 15404 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 15405 OdrUse = false; 15406 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 15407 } 15408 15409 /// Perform reference-marking and odr-use handling for a MemberExpr. 15410 void Sema::MarkMemberReferenced(MemberExpr *E) { 15411 // C++11 [basic.def.odr]p2: 15412 // A non-overloaded function whose name appears as a potentially-evaluated 15413 // expression or a member of a set of candidate functions, if selected by 15414 // overload resolution when referred to from a potentially-evaluated 15415 // expression, is odr-used, unless it is a pure virtual function and its 15416 // name is not explicitly qualified. 15417 bool MightBeOdrUse = true; 15418 if (E->performsVirtualDispatch(getLangOpts())) { 15419 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 15420 if (Method->isPure()) 15421 MightBeOdrUse = false; 15422 } 15423 SourceLocation Loc = E->getMemberLoc().isValid() ? 15424 E->getMemberLoc() : E->getLocStart(); 15425 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 15426 } 15427 15428 /// Perform marking for a reference to an arbitrary declaration. It 15429 /// marks the declaration referenced, and performs odr-use checking for 15430 /// functions and variables. This method should not be used when building a 15431 /// normal expression which refers to a variable. 15432 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 15433 bool MightBeOdrUse) { 15434 if (MightBeOdrUse) { 15435 if (auto *VD = dyn_cast<VarDecl>(D)) { 15436 MarkVariableReferenced(Loc, VD); 15437 return; 15438 } 15439 } 15440 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 15441 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 15442 return; 15443 } 15444 D->setReferenced(); 15445 } 15446 15447 namespace { 15448 // Mark all of the declarations used by a type as referenced. 15449 // FIXME: Not fully implemented yet! We need to have a better understanding 15450 // of when we're entering a context we should not recurse into. 15451 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 15452 // TreeTransforms rebuilding the type in a new context. Rather than 15453 // duplicating the TreeTransform logic, we should consider reusing it here. 15454 // Currently that causes problems when rebuilding LambdaExprs. 15455 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 15456 Sema &S; 15457 SourceLocation Loc; 15458 15459 public: 15460 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 15461 15462 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 15463 15464 bool TraverseTemplateArgument(const TemplateArgument &Arg); 15465 }; 15466 } 15467 15468 bool MarkReferencedDecls::TraverseTemplateArgument( 15469 const TemplateArgument &Arg) { 15470 { 15471 // A non-type template argument is a constant-evaluated context. 15472 EnterExpressionEvaluationContext Evaluated( 15473 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 15474 if (Arg.getKind() == TemplateArgument::Declaration) { 15475 if (Decl *D = Arg.getAsDecl()) 15476 S.MarkAnyDeclReferenced(Loc, D, true); 15477 } else if (Arg.getKind() == TemplateArgument::Expression) { 15478 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 15479 } 15480 } 15481 15482 return Inherited::TraverseTemplateArgument(Arg); 15483 } 15484 15485 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 15486 MarkReferencedDecls Marker(*this, Loc); 15487 Marker.TraverseType(T); 15488 } 15489 15490 namespace { 15491 /// Helper class that marks all of the declarations referenced by 15492 /// potentially-evaluated subexpressions as "referenced". 15493 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 15494 Sema &S; 15495 bool SkipLocalVariables; 15496 15497 public: 15498 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 15499 15500 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 15501 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 15502 15503 void VisitDeclRefExpr(DeclRefExpr *E) { 15504 // If we were asked not to visit local variables, don't. 15505 if (SkipLocalVariables) { 15506 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 15507 if (VD->hasLocalStorage()) 15508 return; 15509 } 15510 15511 S.MarkDeclRefReferenced(E); 15512 } 15513 15514 void VisitMemberExpr(MemberExpr *E) { 15515 S.MarkMemberReferenced(E); 15516 Inherited::VisitMemberExpr(E); 15517 } 15518 15519 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 15520 S.MarkFunctionReferenced(E->getLocStart(), 15521 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 15522 Visit(E->getSubExpr()); 15523 } 15524 15525 void VisitCXXNewExpr(CXXNewExpr *E) { 15526 if (E->getOperatorNew()) 15527 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 15528 if (E->getOperatorDelete()) 15529 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 15530 Inherited::VisitCXXNewExpr(E); 15531 } 15532 15533 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 15534 if (E->getOperatorDelete()) 15535 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 15536 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 15537 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 15538 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 15539 S.MarkFunctionReferenced(E->getLocStart(), 15540 S.LookupDestructor(Record)); 15541 } 15542 15543 Inherited::VisitCXXDeleteExpr(E); 15544 } 15545 15546 void VisitCXXConstructExpr(CXXConstructExpr *E) { 15547 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 15548 Inherited::VisitCXXConstructExpr(E); 15549 } 15550 15551 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 15552 Visit(E->getExpr()); 15553 } 15554 15555 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 15556 Inherited::VisitImplicitCastExpr(E); 15557 15558 if (E->getCastKind() == CK_LValueToRValue) 15559 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 15560 } 15561 }; 15562 } 15563 15564 /// Mark any declarations that appear within this expression or any 15565 /// potentially-evaluated subexpressions as "referenced". 15566 /// 15567 /// \param SkipLocalVariables If true, don't mark local variables as 15568 /// 'referenced'. 15569 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 15570 bool SkipLocalVariables) { 15571 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 15572 } 15573 15574 /// Emit a diagnostic that describes an effect on the run-time behavior 15575 /// of the program being compiled. 15576 /// 15577 /// This routine emits the given diagnostic when the code currently being 15578 /// type-checked is "potentially evaluated", meaning that there is a 15579 /// possibility that the code will actually be executable. Code in sizeof() 15580 /// expressions, code used only during overload resolution, etc., are not 15581 /// potentially evaluated. This routine will suppress such diagnostics or, 15582 /// in the absolutely nutty case of potentially potentially evaluated 15583 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 15584 /// later. 15585 /// 15586 /// This routine should be used for all diagnostics that describe the run-time 15587 /// behavior of a program, such as passing a non-POD value through an ellipsis. 15588 /// Failure to do so will likely result in spurious diagnostics or failures 15589 /// during overload resolution or within sizeof/alignof/typeof/typeid. 15590 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 15591 const PartialDiagnostic &PD) { 15592 switch (ExprEvalContexts.back().Context) { 15593 case ExpressionEvaluationContext::Unevaluated: 15594 case ExpressionEvaluationContext::UnevaluatedList: 15595 case ExpressionEvaluationContext::UnevaluatedAbstract: 15596 case ExpressionEvaluationContext::DiscardedStatement: 15597 // The argument will never be evaluated, so don't complain. 15598 break; 15599 15600 case ExpressionEvaluationContext::ConstantEvaluated: 15601 // Relevant diagnostics should be produced by constant evaluation. 15602 break; 15603 15604 case ExpressionEvaluationContext::PotentiallyEvaluated: 15605 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 15606 if (Statement && getCurFunctionOrMethodDecl()) { 15607 FunctionScopes.back()->PossiblyUnreachableDiags. 15608 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 15609 return true; 15610 } 15611 15612 // The initializer of a constexpr variable or of the first declaration of a 15613 // static data member is not syntactically a constant evaluated constant, 15614 // but nonetheless is always required to be a constant expression, so we 15615 // can skip diagnosing. 15616 // FIXME: Using the mangling context here is a hack. 15617 if (auto *VD = dyn_cast_or_null<VarDecl>( 15618 ExprEvalContexts.back().ManglingContextDecl)) { 15619 if (VD->isConstexpr() || 15620 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 15621 break; 15622 // FIXME: For any other kind of variable, we should build a CFG for its 15623 // initializer and check whether the context in question is reachable. 15624 } 15625 15626 Diag(Loc, PD); 15627 return true; 15628 } 15629 15630 return false; 15631 } 15632 15633 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 15634 CallExpr *CE, FunctionDecl *FD) { 15635 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 15636 return false; 15637 15638 // If we're inside a decltype's expression, don't check for a valid return 15639 // type or construct temporaries until we know whether this is the last call. 15640 if (ExprEvalContexts.back().IsDecltype) { 15641 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 15642 return false; 15643 } 15644 15645 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 15646 FunctionDecl *FD; 15647 CallExpr *CE; 15648 15649 public: 15650 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 15651 : FD(FD), CE(CE) { } 15652 15653 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 15654 if (!FD) { 15655 S.Diag(Loc, diag::err_call_incomplete_return) 15656 << T << CE->getSourceRange(); 15657 return; 15658 } 15659 15660 S.Diag(Loc, diag::err_call_function_incomplete_return) 15661 << CE->getSourceRange() << FD->getDeclName() << T; 15662 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 15663 << FD->getDeclName(); 15664 } 15665 } Diagnoser(FD, CE); 15666 15667 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 15668 return true; 15669 15670 return false; 15671 } 15672 15673 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 15674 // will prevent this condition from triggering, which is what we want. 15675 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 15676 SourceLocation Loc; 15677 15678 unsigned diagnostic = diag::warn_condition_is_assignment; 15679 bool IsOrAssign = false; 15680 15681 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 15682 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 15683 return; 15684 15685 IsOrAssign = Op->getOpcode() == BO_OrAssign; 15686 15687 // Greylist some idioms by putting them into a warning subcategory. 15688 if (ObjCMessageExpr *ME 15689 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 15690 Selector Sel = ME->getSelector(); 15691 15692 // self = [<foo> init...] 15693 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 15694 diagnostic = diag::warn_condition_is_idiomatic_assignment; 15695 15696 // <foo> = [<bar> nextObject] 15697 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 15698 diagnostic = diag::warn_condition_is_idiomatic_assignment; 15699 } 15700 15701 Loc = Op->getOperatorLoc(); 15702 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 15703 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 15704 return; 15705 15706 IsOrAssign = Op->getOperator() == OO_PipeEqual; 15707 Loc = Op->getOperatorLoc(); 15708 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 15709 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 15710 else { 15711 // Not an assignment. 15712 return; 15713 } 15714 15715 Diag(Loc, diagnostic) << E->getSourceRange(); 15716 15717 SourceLocation Open = E->getLocStart(); 15718 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 15719 Diag(Loc, diag::note_condition_assign_silence) 15720 << FixItHint::CreateInsertion(Open, "(") 15721 << FixItHint::CreateInsertion(Close, ")"); 15722 15723 if (IsOrAssign) 15724 Diag(Loc, diag::note_condition_or_assign_to_comparison) 15725 << FixItHint::CreateReplacement(Loc, "!="); 15726 else 15727 Diag(Loc, diag::note_condition_assign_to_comparison) 15728 << FixItHint::CreateReplacement(Loc, "=="); 15729 } 15730 15731 /// Redundant parentheses over an equality comparison can indicate 15732 /// that the user intended an assignment used as condition. 15733 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 15734 // Don't warn if the parens came from a macro. 15735 SourceLocation parenLoc = ParenE->getLocStart(); 15736 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 15737 return; 15738 // Don't warn for dependent expressions. 15739 if (ParenE->isTypeDependent()) 15740 return; 15741 15742 Expr *E = ParenE->IgnoreParens(); 15743 15744 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 15745 if (opE->getOpcode() == BO_EQ && 15746 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 15747 == Expr::MLV_Valid) { 15748 SourceLocation Loc = opE->getOperatorLoc(); 15749 15750 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 15751 SourceRange ParenERange = ParenE->getSourceRange(); 15752 Diag(Loc, diag::note_equality_comparison_silence) 15753 << FixItHint::CreateRemoval(ParenERange.getBegin()) 15754 << FixItHint::CreateRemoval(ParenERange.getEnd()); 15755 Diag(Loc, diag::note_equality_comparison_to_assign) 15756 << FixItHint::CreateReplacement(Loc, "="); 15757 } 15758 } 15759 15760 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 15761 bool IsConstexpr) { 15762 DiagnoseAssignmentAsCondition(E); 15763 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 15764 DiagnoseEqualityWithExtraParens(parenE); 15765 15766 ExprResult result = CheckPlaceholderExpr(E); 15767 if (result.isInvalid()) return ExprError(); 15768 E = result.get(); 15769 15770 if (!E->isTypeDependent()) { 15771 if (getLangOpts().CPlusPlus) 15772 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 15773 15774 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 15775 if (ERes.isInvalid()) 15776 return ExprError(); 15777 E = ERes.get(); 15778 15779 QualType T = E->getType(); 15780 if (!T->isScalarType()) { // C99 6.8.4.1p1 15781 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 15782 << T << E->getSourceRange(); 15783 return ExprError(); 15784 } 15785 CheckBoolLikeConversion(E, Loc); 15786 } 15787 15788 return E; 15789 } 15790 15791 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 15792 Expr *SubExpr, ConditionKind CK) { 15793 // Empty conditions are valid in for-statements. 15794 if (!SubExpr) 15795 return ConditionResult(); 15796 15797 ExprResult Cond; 15798 switch (CK) { 15799 case ConditionKind::Boolean: 15800 Cond = CheckBooleanCondition(Loc, SubExpr); 15801 break; 15802 15803 case ConditionKind::ConstexprIf: 15804 Cond = CheckBooleanCondition(Loc, SubExpr, true); 15805 break; 15806 15807 case ConditionKind::Switch: 15808 Cond = CheckSwitchCondition(Loc, SubExpr); 15809 break; 15810 } 15811 if (Cond.isInvalid()) 15812 return ConditionError(); 15813 15814 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 15815 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 15816 if (!FullExpr.get()) 15817 return ConditionError(); 15818 15819 return ConditionResult(*this, nullptr, FullExpr, 15820 CK == ConditionKind::ConstexprIf); 15821 } 15822 15823 namespace { 15824 /// A visitor for rebuilding a call to an __unknown_any expression 15825 /// to have an appropriate type. 15826 struct RebuildUnknownAnyFunction 15827 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 15828 15829 Sema &S; 15830 15831 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 15832 15833 ExprResult VisitStmt(Stmt *S) { 15834 llvm_unreachable("unexpected statement!"); 15835 } 15836 15837 ExprResult VisitExpr(Expr *E) { 15838 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 15839 << E->getSourceRange(); 15840 return ExprError(); 15841 } 15842 15843 /// Rebuild an expression which simply semantically wraps another 15844 /// expression which it shares the type and value kind of. 15845 template <class T> ExprResult rebuildSugarExpr(T *E) { 15846 ExprResult SubResult = Visit(E->getSubExpr()); 15847 if (SubResult.isInvalid()) return ExprError(); 15848 15849 Expr *SubExpr = SubResult.get(); 15850 E->setSubExpr(SubExpr); 15851 E->setType(SubExpr->getType()); 15852 E->setValueKind(SubExpr->getValueKind()); 15853 assert(E->getObjectKind() == OK_Ordinary); 15854 return E; 15855 } 15856 15857 ExprResult VisitParenExpr(ParenExpr *E) { 15858 return rebuildSugarExpr(E); 15859 } 15860 15861 ExprResult VisitUnaryExtension(UnaryOperator *E) { 15862 return rebuildSugarExpr(E); 15863 } 15864 15865 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 15866 ExprResult SubResult = Visit(E->getSubExpr()); 15867 if (SubResult.isInvalid()) return ExprError(); 15868 15869 Expr *SubExpr = SubResult.get(); 15870 E->setSubExpr(SubExpr); 15871 E->setType(S.Context.getPointerType(SubExpr->getType())); 15872 assert(E->getValueKind() == VK_RValue); 15873 assert(E->getObjectKind() == OK_Ordinary); 15874 return E; 15875 } 15876 15877 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 15878 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 15879 15880 E->setType(VD->getType()); 15881 15882 assert(E->getValueKind() == VK_RValue); 15883 if (S.getLangOpts().CPlusPlus && 15884 !(isa<CXXMethodDecl>(VD) && 15885 cast<CXXMethodDecl>(VD)->isInstance())) 15886 E->setValueKind(VK_LValue); 15887 15888 return E; 15889 } 15890 15891 ExprResult VisitMemberExpr(MemberExpr *E) { 15892 return resolveDecl(E, E->getMemberDecl()); 15893 } 15894 15895 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 15896 return resolveDecl(E, E->getDecl()); 15897 } 15898 }; 15899 } 15900 15901 /// Given a function expression of unknown-any type, try to rebuild it 15902 /// to have a function type. 15903 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 15904 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 15905 if (Result.isInvalid()) return ExprError(); 15906 return S.DefaultFunctionArrayConversion(Result.get()); 15907 } 15908 15909 namespace { 15910 /// A visitor for rebuilding an expression of type __unknown_anytype 15911 /// into one which resolves the type directly on the referring 15912 /// expression. Strict preservation of the original source 15913 /// structure is not a goal. 15914 struct RebuildUnknownAnyExpr 15915 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 15916 15917 Sema &S; 15918 15919 /// The current destination type. 15920 QualType DestType; 15921 15922 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 15923 : S(S), DestType(CastType) {} 15924 15925 ExprResult VisitStmt(Stmt *S) { 15926 llvm_unreachable("unexpected statement!"); 15927 } 15928 15929 ExprResult VisitExpr(Expr *E) { 15930 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 15931 << E->getSourceRange(); 15932 return ExprError(); 15933 } 15934 15935 ExprResult VisitCallExpr(CallExpr *E); 15936 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 15937 15938 /// Rebuild an expression which simply semantically wraps another 15939 /// expression which it shares the type and value kind of. 15940 template <class T> ExprResult rebuildSugarExpr(T *E) { 15941 ExprResult SubResult = Visit(E->getSubExpr()); 15942 if (SubResult.isInvalid()) return ExprError(); 15943 Expr *SubExpr = SubResult.get(); 15944 E->setSubExpr(SubExpr); 15945 E->setType(SubExpr->getType()); 15946 E->setValueKind(SubExpr->getValueKind()); 15947 assert(E->getObjectKind() == OK_Ordinary); 15948 return E; 15949 } 15950 15951 ExprResult VisitParenExpr(ParenExpr *E) { 15952 return rebuildSugarExpr(E); 15953 } 15954 15955 ExprResult VisitUnaryExtension(UnaryOperator *E) { 15956 return rebuildSugarExpr(E); 15957 } 15958 15959 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 15960 const PointerType *Ptr = DestType->getAs<PointerType>(); 15961 if (!Ptr) { 15962 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 15963 << E->getSourceRange(); 15964 return ExprError(); 15965 } 15966 15967 if (isa<CallExpr>(E->getSubExpr())) { 15968 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 15969 << E->getSourceRange(); 15970 return ExprError(); 15971 } 15972 15973 assert(E->getValueKind() == VK_RValue); 15974 assert(E->getObjectKind() == OK_Ordinary); 15975 E->setType(DestType); 15976 15977 // Build the sub-expression as if it were an object of the pointee type. 15978 DestType = Ptr->getPointeeType(); 15979 ExprResult SubResult = Visit(E->getSubExpr()); 15980 if (SubResult.isInvalid()) return ExprError(); 15981 E->setSubExpr(SubResult.get()); 15982 return E; 15983 } 15984 15985 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 15986 15987 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 15988 15989 ExprResult VisitMemberExpr(MemberExpr *E) { 15990 return resolveDecl(E, E->getMemberDecl()); 15991 } 15992 15993 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 15994 return resolveDecl(E, E->getDecl()); 15995 } 15996 }; 15997 } 15998 15999 /// Rebuilds a call expression which yielded __unknown_anytype. 16000 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 16001 Expr *CalleeExpr = E->getCallee(); 16002 16003 enum FnKind { 16004 FK_MemberFunction, 16005 FK_FunctionPointer, 16006 FK_BlockPointer 16007 }; 16008 16009 FnKind Kind; 16010 QualType CalleeType = CalleeExpr->getType(); 16011 if (CalleeType == S.Context.BoundMemberTy) { 16012 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 16013 Kind = FK_MemberFunction; 16014 CalleeType = Expr::findBoundMemberType(CalleeExpr); 16015 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 16016 CalleeType = Ptr->getPointeeType(); 16017 Kind = FK_FunctionPointer; 16018 } else { 16019 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 16020 Kind = FK_BlockPointer; 16021 } 16022 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 16023 16024 // Verify that this is a legal result type of a function. 16025 if (DestType->isArrayType() || DestType->isFunctionType()) { 16026 unsigned diagID = diag::err_func_returning_array_function; 16027 if (Kind == FK_BlockPointer) 16028 diagID = diag::err_block_returning_array_function; 16029 16030 S.Diag(E->getExprLoc(), diagID) 16031 << DestType->isFunctionType() << DestType; 16032 return ExprError(); 16033 } 16034 16035 // Otherwise, go ahead and set DestType as the call's result. 16036 E->setType(DestType.getNonLValueExprType(S.Context)); 16037 E->setValueKind(Expr::getValueKindForType(DestType)); 16038 assert(E->getObjectKind() == OK_Ordinary); 16039 16040 // Rebuild the function type, replacing the result type with DestType. 16041 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 16042 if (Proto) { 16043 // __unknown_anytype(...) is a special case used by the debugger when 16044 // it has no idea what a function's signature is. 16045 // 16046 // We want to build this call essentially under the K&R 16047 // unprototyped rules, but making a FunctionNoProtoType in C++ 16048 // would foul up all sorts of assumptions. However, we cannot 16049 // simply pass all arguments as variadic arguments, nor can we 16050 // portably just call the function under a non-variadic type; see 16051 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 16052 // However, it turns out that in practice it is generally safe to 16053 // call a function declared as "A foo(B,C,D);" under the prototype 16054 // "A foo(B,C,D,...);". The only known exception is with the 16055 // Windows ABI, where any variadic function is implicitly cdecl 16056 // regardless of its normal CC. Therefore we change the parameter 16057 // types to match the types of the arguments. 16058 // 16059 // This is a hack, but it is far superior to moving the 16060 // corresponding target-specific code from IR-gen to Sema/AST. 16061 16062 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 16063 SmallVector<QualType, 8> ArgTypes; 16064 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 16065 ArgTypes.reserve(E->getNumArgs()); 16066 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 16067 Expr *Arg = E->getArg(i); 16068 QualType ArgType = Arg->getType(); 16069 if (E->isLValue()) { 16070 ArgType = S.Context.getLValueReferenceType(ArgType); 16071 } else if (E->isXValue()) { 16072 ArgType = S.Context.getRValueReferenceType(ArgType); 16073 } 16074 ArgTypes.push_back(ArgType); 16075 } 16076 ParamTypes = ArgTypes; 16077 } 16078 DestType = S.Context.getFunctionType(DestType, ParamTypes, 16079 Proto->getExtProtoInfo()); 16080 } else { 16081 DestType = S.Context.getFunctionNoProtoType(DestType, 16082 FnType->getExtInfo()); 16083 } 16084 16085 // Rebuild the appropriate pointer-to-function type. 16086 switch (Kind) { 16087 case FK_MemberFunction: 16088 // Nothing to do. 16089 break; 16090 16091 case FK_FunctionPointer: 16092 DestType = S.Context.getPointerType(DestType); 16093 break; 16094 16095 case FK_BlockPointer: 16096 DestType = S.Context.getBlockPointerType(DestType); 16097 break; 16098 } 16099 16100 // Finally, we can recurse. 16101 ExprResult CalleeResult = Visit(CalleeExpr); 16102 if (!CalleeResult.isUsable()) return ExprError(); 16103 E->setCallee(CalleeResult.get()); 16104 16105 // Bind a temporary if necessary. 16106 return S.MaybeBindToTemporary(E); 16107 } 16108 16109 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 16110 // Verify that this is a legal result type of a call. 16111 if (DestType->isArrayType() || DestType->isFunctionType()) { 16112 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 16113 << DestType->isFunctionType() << DestType; 16114 return ExprError(); 16115 } 16116 16117 // Rewrite the method result type if available. 16118 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 16119 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 16120 Method->setReturnType(DestType); 16121 } 16122 16123 // Change the type of the message. 16124 E->setType(DestType.getNonReferenceType()); 16125 E->setValueKind(Expr::getValueKindForType(DestType)); 16126 16127 return S.MaybeBindToTemporary(E); 16128 } 16129 16130 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 16131 // The only case we should ever see here is a function-to-pointer decay. 16132 if (E->getCastKind() == CK_FunctionToPointerDecay) { 16133 assert(E->getValueKind() == VK_RValue); 16134 assert(E->getObjectKind() == OK_Ordinary); 16135 16136 E->setType(DestType); 16137 16138 // Rebuild the sub-expression as the pointee (function) type. 16139 DestType = DestType->castAs<PointerType>()->getPointeeType(); 16140 16141 ExprResult Result = Visit(E->getSubExpr()); 16142 if (!Result.isUsable()) return ExprError(); 16143 16144 E->setSubExpr(Result.get()); 16145 return E; 16146 } else if (E->getCastKind() == CK_LValueToRValue) { 16147 assert(E->getValueKind() == VK_RValue); 16148 assert(E->getObjectKind() == OK_Ordinary); 16149 16150 assert(isa<BlockPointerType>(E->getType())); 16151 16152 E->setType(DestType); 16153 16154 // The sub-expression has to be a lvalue reference, so rebuild it as such. 16155 DestType = S.Context.getLValueReferenceType(DestType); 16156 16157 ExprResult Result = Visit(E->getSubExpr()); 16158 if (!Result.isUsable()) return ExprError(); 16159 16160 E->setSubExpr(Result.get()); 16161 return E; 16162 } else { 16163 llvm_unreachable("Unhandled cast type!"); 16164 } 16165 } 16166 16167 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 16168 ExprValueKind ValueKind = VK_LValue; 16169 QualType Type = DestType; 16170 16171 // We know how to make this work for certain kinds of decls: 16172 16173 // - functions 16174 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 16175 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 16176 DestType = Ptr->getPointeeType(); 16177 ExprResult Result = resolveDecl(E, VD); 16178 if (Result.isInvalid()) return ExprError(); 16179 return S.ImpCastExprToType(Result.get(), Type, 16180 CK_FunctionToPointerDecay, VK_RValue); 16181 } 16182 16183 if (!Type->isFunctionType()) { 16184 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 16185 << VD << E->getSourceRange(); 16186 return ExprError(); 16187 } 16188 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 16189 // We must match the FunctionDecl's type to the hack introduced in 16190 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 16191 // type. See the lengthy commentary in that routine. 16192 QualType FDT = FD->getType(); 16193 const FunctionType *FnType = FDT->castAs<FunctionType>(); 16194 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 16195 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 16196 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 16197 SourceLocation Loc = FD->getLocation(); 16198 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(), 16199 FD->getDeclContext(), 16200 Loc, Loc, FD->getNameInfo().getName(), 16201 DestType, FD->getTypeSourceInfo(), 16202 SC_None, false/*isInlineSpecified*/, 16203 FD->hasPrototype(), 16204 false/*isConstexprSpecified*/); 16205 16206 if (FD->getQualifier()) 16207 NewFD->setQualifierInfo(FD->getQualifierLoc()); 16208 16209 SmallVector<ParmVarDecl*, 16> Params; 16210 for (const auto &AI : FT->param_types()) { 16211 ParmVarDecl *Param = 16212 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 16213 Param->setScopeInfo(0, Params.size()); 16214 Params.push_back(Param); 16215 } 16216 NewFD->setParams(Params); 16217 DRE->setDecl(NewFD); 16218 VD = DRE->getDecl(); 16219 } 16220 } 16221 16222 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 16223 if (MD->isInstance()) { 16224 ValueKind = VK_RValue; 16225 Type = S.Context.BoundMemberTy; 16226 } 16227 16228 // Function references aren't l-values in C. 16229 if (!S.getLangOpts().CPlusPlus) 16230 ValueKind = VK_RValue; 16231 16232 // - variables 16233 } else if (isa<VarDecl>(VD)) { 16234 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 16235 Type = RefTy->getPointeeType(); 16236 } else if (Type->isFunctionType()) { 16237 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 16238 << VD << E->getSourceRange(); 16239 return ExprError(); 16240 } 16241 16242 // - nothing else 16243 } else { 16244 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 16245 << VD << E->getSourceRange(); 16246 return ExprError(); 16247 } 16248 16249 // Modifying the declaration like this is friendly to IR-gen but 16250 // also really dangerous. 16251 VD->setType(DestType); 16252 E->setType(Type); 16253 E->setValueKind(ValueKind); 16254 return E; 16255 } 16256 16257 /// Check a cast of an unknown-any type. We intentionally only 16258 /// trigger this for C-style casts. 16259 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 16260 Expr *CastExpr, CastKind &CastKind, 16261 ExprValueKind &VK, CXXCastPath &Path) { 16262 // The type we're casting to must be either void or complete. 16263 if (!CastType->isVoidType() && 16264 RequireCompleteType(TypeRange.getBegin(), CastType, 16265 diag::err_typecheck_cast_to_incomplete)) 16266 return ExprError(); 16267 16268 // Rewrite the casted expression from scratch. 16269 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 16270 if (!result.isUsable()) return ExprError(); 16271 16272 CastExpr = result.get(); 16273 VK = CastExpr->getValueKind(); 16274 CastKind = CK_NoOp; 16275 16276 return CastExpr; 16277 } 16278 16279 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 16280 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 16281 } 16282 16283 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 16284 Expr *arg, QualType ¶mType) { 16285 // If the syntactic form of the argument is not an explicit cast of 16286 // any sort, just do default argument promotion. 16287 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 16288 if (!castArg) { 16289 ExprResult result = DefaultArgumentPromotion(arg); 16290 if (result.isInvalid()) return ExprError(); 16291 paramType = result.get()->getType(); 16292 return result; 16293 } 16294 16295 // Otherwise, use the type that was written in the explicit cast. 16296 assert(!arg->hasPlaceholderType()); 16297 paramType = castArg->getTypeAsWritten(); 16298 16299 // Copy-initialize a parameter of that type. 16300 InitializedEntity entity = 16301 InitializedEntity::InitializeParameter(Context, paramType, 16302 /*consumed*/ false); 16303 return PerformCopyInitialization(entity, callLoc, arg); 16304 } 16305 16306 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 16307 Expr *orig = E; 16308 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 16309 while (true) { 16310 E = E->IgnoreParenImpCasts(); 16311 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 16312 E = call->getCallee(); 16313 diagID = diag::err_uncasted_call_of_unknown_any; 16314 } else { 16315 break; 16316 } 16317 } 16318 16319 SourceLocation loc; 16320 NamedDecl *d; 16321 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 16322 loc = ref->getLocation(); 16323 d = ref->getDecl(); 16324 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 16325 loc = mem->getMemberLoc(); 16326 d = mem->getMemberDecl(); 16327 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 16328 diagID = diag::err_uncasted_call_of_unknown_any; 16329 loc = msg->getSelectorStartLoc(); 16330 d = msg->getMethodDecl(); 16331 if (!d) { 16332 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 16333 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 16334 << orig->getSourceRange(); 16335 return ExprError(); 16336 } 16337 } else { 16338 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 16339 << E->getSourceRange(); 16340 return ExprError(); 16341 } 16342 16343 S.Diag(loc, diagID) << d << orig->getSourceRange(); 16344 16345 // Never recoverable. 16346 return ExprError(); 16347 } 16348 16349 /// Check for operands with placeholder types and complain if found. 16350 /// Returns ExprError() if there was an error and no recovery was possible. 16351 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 16352 if (!getLangOpts().CPlusPlus) { 16353 // C cannot handle TypoExpr nodes on either side of a binop because it 16354 // doesn't handle dependent types properly, so make sure any TypoExprs have 16355 // been dealt with before checking the operands. 16356 ExprResult Result = CorrectDelayedTyposInExpr(E); 16357 if (!Result.isUsable()) return ExprError(); 16358 E = Result.get(); 16359 } 16360 16361 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 16362 if (!placeholderType) return E; 16363 16364 switch (placeholderType->getKind()) { 16365 16366 // Overloaded expressions. 16367 case BuiltinType::Overload: { 16368 // Try to resolve a single function template specialization. 16369 // This is obligatory. 16370 ExprResult Result = E; 16371 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 16372 return Result; 16373 16374 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 16375 // leaves Result unchanged on failure. 16376 Result = E; 16377 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) 16378 return Result; 16379 16380 // If that failed, try to recover with a call. 16381 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 16382 /*complain*/ true); 16383 return Result; 16384 } 16385 16386 // Bound member functions. 16387 case BuiltinType::BoundMember: { 16388 ExprResult result = E; 16389 const Expr *BME = E->IgnoreParens(); 16390 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 16391 // Try to give a nicer diagnostic if it is a bound member that we recognize. 16392 if (isa<CXXPseudoDestructorExpr>(BME)) { 16393 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 16394 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 16395 if (ME->getMemberNameInfo().getName().getNameKind() == 16396 DeclarationName::CXXDestructorName) 16397 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 16398 } 16399 tryToRecoverWithCall(result, PD, 16400 /*complain*/ true); 16401 return result; 16402 } 16403 16404 // ARC unbridged casts. 16405 case BuiltinType::ARCUnbridgedCast: { 16406 Expr *realCast = stripARCUnbridgedCast(E); 16407 diagnoseARCUnbridgedCast(realCast); 16408 return realCast; 16409 } 16410 16411 // Expressions of unknown type. 16412 case BuiltinType::UnknownAny: 16413 return diagnoseUnknownAnyExpr(*this, E); 16414 16415 // Pseudo-objects. 16416 case BuiltinType::PseudoObject: 16417 return checkPseudoObjectRValue(E); 16418 16419 case BuiltinType::BuiltinFn: { 16420 // Accept __noop without parens by implicitly converting it to a call expr. 16421 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 16422 if (DRE) { 16423 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 16424 if (FD->getBuiltinID() == Builtin::BI__noop) { 16425 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 16426 CK_BuiltinFnToFnPtr).get(); 16427 return new (Context) CallExpr(Context, E, None, Context.IntTy, 16428 VK_RValue, SourceLocation()); 16429 } 16430 } 16431 16432 Diag(E->getLocStart(), diag::err_builtin_fn_use); 16433 return ExprError(); 16434 } 16435 16436 // Expressions of unknown type. 16437 case BuiltinType::OMPArraySection: 16438 Diag(E->getLocStart(), diag::err_omp_array_section_use); 16439 return ExprError(); 16440 16441 // Everything else should be impossible. 16442 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 16443 case BuiltinType::Id: 16444 #include "clang/Basic/OpenCLImageTypes.def" 16445 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 16446 #define PLACEHOLDER_TYPE(Id, SingletonId) 16447 #include "clang/AST/BuiltinTypes.def" 16448 break; 16449 } 16450 16451 llvm_unreachable("invalid placeholder type!"); 16452 } 16453 16454 bool Sema::CheckCaseExpression(Expr *E) { 16455 if (E->isTypeDependent()) 16456 return true; 16457 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 16458 return E->getType()->isIntegralOrEnumerationType(); 16459 return false; 16460 } 16461 16462 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 16463 ExprResult 16464 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 16465 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 16466 "Unknown Objective-C Boolean value!"); 16467 QualType BoolT = Context.ObjCBuiltinBoolTy; 16468 if (!Context.getBOOLDecl()) { 16469 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 16470 Sema::LookupOrdinaryName); 16471 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 16472 NamedDecl *ND = Result.getFoundDecl(); 16473 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 16474 Context.setBOOLDecl(TD); 16475 } 16476 } 16477 if (Context.getBOOLDecl()) 16478 BoolT = Context.getBOOLType(); 16479 return new (Context) 16480 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 16481 } 16482 16483 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 16484 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 16485 SourceLocation RParen) { 16486 16487 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 16488 16489 auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(), 16490 [&](const AvailabilitySpec &Spec) { 16491 return Spec.getPlatform() == Platform; 16492 }); 16493 16494 VersionTuple Version; 16495 if (Spec != AvailSpecs.end()) 16496 Version = Spec->getVersion(); 16497 16498 // The use of `@available` in the enclosing function should be analyzed to 16499 // warn when it's used inappropriately (i.e. not if(@available)). 16500 if (getCurFunctionOrMethodDecl()) 16501 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 16502 else if (getCurBlock() || getCurLambda()) 16503 getCurFunction()->HasPotentialAvailabilityViolations = true; 16504 16505 return new (Context) 16506 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 16507 } 16508