1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for expressions. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "TreeTransform.h" 14 #include "clang/AST/ASTConsumer.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTLambda.h" 17 #include "clang/AST/ASTMutationListener.h" 18 #include "clang/AST/CXXInheritance.h" 19 #include "clang/AST/DeclObjC.h" 20 #include "clang/AST/DeclTemplate.h" 21 #include "clang/AST/EvaluatedExprVisitor.h" 22 #include "clang/AST/Expr.h" 23 #include "clang/AST/ExprCXX.h" 24 #include "clang/AST/ExprObjC.h" 25 #include "clang/AST/ExprOpenMP.h" 26 #include "clang/AST/RecursiveASTVisitor.h" 27 #include "clang/AST/TypeLoc.h" 28 #include "clang/Basic/FixedPoint.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 // See if this is an aligned allocation/deallocation function that is 70 // unavailable. 71 if (TreatUnavailableAsInvalid && 72 isUnavailableAlignedAllocationFunction(*FD)) 73 return false; 74 } 75 76 // See if this function is unavailable. 77 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 78 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 79 return false; 80 81 return true; 82 } 83 84 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 85 // Warn if this is used but marked unused. 86 if (const auto *A = D->getAttr<UnusedAttr>()) { 87 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 88 // should diagnose them. 89 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 90 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 91 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 92 if (DC && !DC->hasAttr<UnusedAttr>()) 93 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 94 } 95 } 96 } 97 98 /// Emit a note explaining that this function is deleted. 99 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 100 assert(Decl->isDeleted()); 101 102 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 103 104 if (Method && Method->isDeleted() && Method->isDefaulted()) { 105 // If the method was explicitly defaulted, point at that declaration. 106 if (!Method->isImplicit()) 107 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 108 109 // Try to diagnose why this special member function was implicitly 110 // deleted. This might fail, if that reason no longer applies. 111 CXXSpecialMember CSM = getSpecialMember(Method); 112 if (CSM != CXXInvalid) 113 ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true); 114 115 return; 116 } 117 118 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 119 if (Ctor && Ctor->isInheritingConstructor()) 120 return NoteDeletedInheritingConstructor(Ctor); 121 122 Diag(Decl->getLocation(), diag::note_availability_specified_here) 123 << Decl << 1; 124 } 125 126 /// Determine whether a FunctionDecl was ever declared with an 127 /// explicit storage class. 128 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 129 for (auto I : D->redecls()) { 130 if (I->getStorageClass() != SC_None) 131 return true; 132 } 133 return false; 134 } 135 136 /// Check whether we're in an extern inline function and referring to a 137 /// variable or function with internal linkage (C11 6.7.4p3). 138 /// 139 /// This is only a warning because we used to silently accept this code, but 140 /// in many cases it will not behave correctly. This is not enabled in C++ mode 141 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 142 /// and so while there may still be user mistakes, most of the time we can't 143 /// prove that there are errors. 144 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 145 const NamedDecl *D, 146 SourceLocation Loc) { 147 // This is disabled under C++; there are too many ways for this to fire in 148 // contexts where the warning is a false positive, or where it is technically 149 // correct but benign. 150 if (S.getLangOpts().CPlusPlus) 151 return; 152 153 // Check if this is an inlined function or method. 154 FunctionDecl *Current = S.getCurFunctionDecl(); 155 if (!Current) 156 return; 157 if (!Current->isInlined()) 158 return; 159 if (!Current->isExternallyVisible()) 160 return; 161 162 // Check if the decl has internal linkage. 163 if (D->getFormalLinkage() != InternalLinkage) 164 return; 165 166 // Downgrade from ExtWarn to Extension if 167 // (1) the supposedly external inline function is in the main file, 168 // and probably won't be included anywhere else. 169 // (2) the thing we're referencing is a pure function. 170 // (3) the thing we're referencing is another inline function. 171 // This last can give us false negatives, but it's better than warning on 172 // wrappers for simple C library functions. 173 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 174 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 175 if (!DowngradeWarning && UsedFn) 176 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 177 178 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 179 : diag::ext_internal_in_extern_inline) 180 << /*IsVar=*/!UsedFn << D; 181 182 S.MaybeSuggestAddingStaticToDecl(Current); 183 184 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 185 << D; 186 } 187 188 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 189 const FunctionDecl *First = Cur->getFirstDecl(); 190 191 // Suggest "static" on the function, if possible. 192 if (!hasAnyExplicitStorageClass(First)) { 193 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 194 Diag(DeclBegin, diag::note_convert_inline_to_static) 195 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 196 } 197 } 198 199 /// Determine whether the use of this declaration is valid, and 200 /// emit any corresponding diagnostics. 201 /// 202 /// This routine diagnoses various problems with referencing 203 /// declarations that can occur when using a declaration. For example, 204 /// it might warn if a deprecated or unavailable declaration is being 205 /// used, or produce an error (and return true) if a C++0x deleted 206 /// function is being used. 207 /// 208 /// \returns true if there was an error (this declaration cannot be 209 /// referenced), false otherwise. 210 /// 211 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 212 const ObjCInterfaceDecl *UnknownObjCClass, 213 bool ObjCPropertyAccess, 214 bool AvoidPartialAvailabilityChecks, 215 ObjCInterfaceDecl *ClassReceiver) { 216 SourceLocation Loc = Locs.front(); 217 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 218 // If there were any diagnostics suppressed by template argument deduction, 219 // emit them now. 220 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 221 if (Pos != SuppressedDiagnostics.end()) { 222 for (const PartialDiagnosticAt &Suppressed : Pos->second) 223 Diag(Suppressed.first, Suppressed.second); 224 225 // Clear out the list of suppressed diagnostics, so that we don't emit 226 // them again for this specialization. However, we don't obsolete this 227 // entry from the table, because we want to avoid ever emitting these 228 // diagnostics again. 229 Pos->second.clear(); 230 } 231 232 // C++ [basic.start.main]p3: 233 // The function 'main' shall not be used within a program. 234 if (cast<FunctionDecl>(D)->isMain()) 235 Diag(Loc, diag::ext_main_used); 236 237 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); 238 } 239 240 // See if this is an auto-typed variable whose initializer we are parsing. 241 if (ParsingInitForAutoVars.count(D)) { 242 if (isa<BindingDecl>(D)) { 243 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 244 << D->getDeclName(); 245 } else { 246 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 247 << D->getDeclName() << cast<VarDecl>(D)->getType(); 248 } 249 return true; 250 } 251 252 // See if this is a deleted function. 253 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 254 if (FD->isDeleted()) { 255 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 256 if (Ctor && Ctor->isInheritingConstructor()) 257 Diag(Loc, diag::err_deleted_inherited_ctor_use) 258 << Ctor->getParent() 259 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 260 else 261 Diag(Loc, diag::err_deleted_function_use); 262 NoteDeletedFunction(FD); 263 return true; 264 } 265 266 // If the function has a deduced return type, and we can't deduce it, 267 // then we can't use it either. 268 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 269 DeduceReturnType(FD, Loc)) 270 return true; 271 272 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 273 return true; 274 } 275 276 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 277 // Lambdas are only default-constructible or assignable in C++2a onwards. 278 if (MD->getParent()->isLambda() && 279 ((isa<CXXConstructorDecl>(MD) && 280 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || 281 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { 282 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) 283 << !isa<CXXConstructorDecl>(MD); 284 } 285 } 286 287 auto getReferencedObjCProp = [](const NamedDecl *D) -> 288 const ObjCPropertyDecl * { 289 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 290 return MD->findPropertyDecl(); 291 return nullptr; 292 }; 293 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 294 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 295 return true; 296 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 297 return true; 298 } 299 300 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 301 // Only the variables omp_in and omp_out are allowed in the combiner. 302 // Only the variables omp_priv and omp_orig are allowed in the 303 // initializer-clause. 304 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 305 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 306 isa<VarDecl>(D)) { 307 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 308 << getCurFunction()->HasOMPDeclareReductionCombiner; 309 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 310 return true; 311 } 312 313 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions 314 // List-items in map clauses on this construct may only refer to the declared 315 // variable var and entities that could be referenced by a procedure defined 316 // at the same location 317 auto *DMD = dyn_cast<OMPDeclareMapperDecl>(CurContext); 318 if (LangOpts.OpenMP && DMD && !CurContext->containsDecl(D) && 319 isa<VarDecl>(D)) { 320 Diag(Loc, diag::err_omp_declare_mapper_wrong_var) 321 << DMD->getVarName().getAsString(); 322 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 323 return true; 324 } 325 326 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 327 AvoidPartialAvailabilityChecks, ClassReceiver); 328 329 DiagnoseUnusedOfDecl(*this, D, Loc); 330 331 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 332 333 return false; 334 } 335 336 /// Retrieve the message suffix that should be added to a 337 /// diagnostic complaining about the given function being deleted or 338 /// unavailable. 339 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 340 std::string Message; 341 if (FD->getAvailability(&Message)) 342 return ": " + Message; 343 344 return std::string(); 345 } 346 347 /// DiagnoseSentinelCalls - This routine checks whether a call or 348 /// message-send is to a declaration with the sentinel attribute, and 349 /// if so, it checks that the requirements of the sentinel are 350 /// satisfied. 351 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 352 ArrayRef<Expr *> Args) { 353 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 354 if (!attr) 355 return; 356 357 // The number of formal parameters of the declaration. 358 unsigned numFormalParams; 359 360 // The kind of declaration. This is also an index into a %select in 361 // the diagnostic. 362 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 363 364 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 365 numFormalParams = MD->param_size(); 366 calleeType = CT_Method; 367 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 368 numFormalParams = FD->param_size(); 369 calleeType = CT_Function; 370 } else if (isa<VarDecl>(D)) { 371 QualType type = cast<ValueDecl>(D)->getType(); 372 const FunctionType *fn = nullptr; 373 if (const PointerType *ptr = type->getAs<PointerType>()) { 374 fn = ptr->getPointeeType()->getAs<FunctionType>(); 375 if (!fn) return; 376 calleeType = CT_Function; 377 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 378 fn = ptr->getPointeeType()->castAs<FunctionType>(); 379 calleeType = CT_Block; 380 } else { 381 return; 382 } 383 384 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 385 numFormalParams = proto->getNumParams(); 386 } else { 387 numFormalParams = 0; 388 } 389 } else { 390 return; 391 } 392 393 // "nullPos" is the number of formal parameters at the end which 394 // effectively count as part of the variadic arguments. This is 395 // useful if you would prefer to not have *any* formal parameters, 396 // but the language forces you to have at least one. 397 unsigned nullPos = attr->getNullPos(); 398 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 399 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 400 401 // The number of arguments which should follow the sentinel. 402 unsigned numArgsAfterSentinel = attr->getSentinel(); 403 404 // If there aren't enough arguments for all the formal parameters, 405 // the sentinel, and the args after the sentinel, complain. 406 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 407 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 408 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 409 return; 410 } 411 412 // Otherwise, find the sentinel expression. 413 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 414 if (!sentinelExpr) return; 415 if (sentinelExpr->isValueDependent()) return; 416 if (Context.isSentinelNullExpr(sentinelExpr)) return; 417 418 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 419 // or 'NULL' if those are actually defined in the context. Only use 420 // 'nil' for ObjC methods, where it's much more likely that the 421 // variadic arguments form a list of object pointers. 422 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 423 std::string NullValue; 424 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 425 NullValue = "nil"; 426 else if (getLangOpts().CPlusPlus11) 427 NullValue = "nullptr"; 428 else if (PP.isMacroDefined("NULL")) 429 NullValue = "NULL"; 430 else 431 NullValue = "(void*) 0"; 432 433 if (MissingNilLoc.isInvalid()) 434 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 435 else 436 Diag(MissingNilLoc, diag::warn_missing_sentinel) 437 << int(calleeType) 438 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 439 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 440 } 441 442 SourceRange Sema::getExprRange(Expr *E) const { 443 return E ? E->getSourceRange() : SourceRange(); 444 } 445 446 //===----------------------------------------------------------------------===// 447 // Standard Promotions and Conversions 448 //===----------------------------------------------------------------------===// 449 450 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 451 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 452 // Handle any placeholder expressions which made it here. 453 if (E->getType()->isPlaceholderType()) { 454 ExprResult result = CheckPlaceholderExpr(E); 455 if (result.isInvalid()) return ExprError(); 456 E = result.get(); 457 } 458 459 QualType Ty = E->getType(); 460 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 461 462 if (Ty->isFunctionType()) { 463 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 464 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 465 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 466 return ExprError(); 467 468 E = ImpCastExprToType(E, Context.getPointerType(Ty), 469 CK_FunctionToPointerDecay).get(); 470 } else if (Ty->isArrayType()) { 471 // In C90 mode, arrays only promote to pointers if the array expression is 472 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 473 // type 'array of type' is converted to an expression that has type 'pointer 474 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 475 // that has type 'array of type' ...". The relevant change is "an lvalue" 476 // (C90) to "an expression" (C99). 477 // 478 // C++ 4.2p1: 479 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 480 // T" can be converted to an rvalue of type "pointer to T". 481 // 482 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 483 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 484 CK_ArrayToPointerDecay).get(); 485 } 486 return E; 487 } 488 489 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 490 // Check to see if we are dereferencing a null pointer. If so, 491 // and if not volatile-qualified, this is undefined behavior that the 492 // optimizer will delete, so warn about it. People sometimes try to use this 493 // to get a deterministic trap and are surprised by clang's behavior. This 494 // only handles the pattern "*null", which is a very syntactic check. 495 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 496 if (UO->getOpcode() == UO_Deref && 497 UO->getSubExpr()->IgnoreParenCasts()-> 498 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 499 !UO->getType().isVolatileQualified()) { 500 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 501 S.PDiag(diag::warn_indirection_through_null) 502 << UO->getSubExpr()->getSourceRange()); 503 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 504 S.PDiag(diag::note_indirection_through_null)); 505 } 506 } 507 508 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 509 SourceLocation AssignLoc, 510 const Expr* RHS) { 511 const ObjCIvarDecl *IV = OIRE->getDecl(); 512 if (!IV) 513 return; 514 515 DeclarationName MemberName = IV->getDeclName(); 516 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 517 if (!Member || !Member->isStr("isa")) 518 return; 519 520 const Expr *Base = OIRE->getBase(); 521 QualType BaseType = Base->getType(); 522 if (OIRE->isArrow()) 523 BaseType = BaseType->getPointeeType(); 524 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 525 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 526 ObjCInterfaceDecl *ClassDeclared = nullptr; 527 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 528 if (!ClassDeclared->getSuperClass() 529 && (*ClassDeclared->ivar_begin()) == IV) { 530 if (RHS) { 531 NamedDecl *ObjectSetClass = 532 S.LookupSingleName(S.TUScope, 533 &S.Context.Idents.get("object_setClass"), 534 SourceLocation(), S.LookupOrdinaryName); 535 if (ObjectSetClass) { 536 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 537 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 538 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 539 "object_setClass(") 540 << FixItHint::CreateReplacement( 541 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 542 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 543 } 544 else 545 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 546 } else { 547 NamedDecl *ObjectGetClass = 548 S.LookupSingleName(S.TUScope, 549 &S.Context.Idents.get("object_getClass"), 550 SourceLocation(), S.LookupOrdinaryName); 551 if (ObjectGetClass) 552 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 553 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 554 "object_getClass(") 555 << FixItHint::CreateReplacement( 556 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 557 else 558 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 559 } 560 S.Diag(IV->getLocation(), diag::note_ivar_decl); 561 } 562 } 563 } 564 565 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 566 // Handle any placeholder expressions which made it here. 567 if (E->getType()->isPlaceholderType()) { 568 ExprResult result = CheckPlaceholderExpr(E); 569 if (result.isInvalid()) return ExprError(); 570 E = result.get(); 571 } 572 573 // C++ [conv.lval]p1: 574 // A glvalue of a non-function, non-array type T can be 575 // converted to a prvalue. 576 if (!E->isGLValue()) return E; 577 578 QualType T = E->getType(); 579 assert(!T.isNull() && "r-value conversion on typeless expression?"); 580 581 // We don't want to throw lvalue-to-rvalue casts on top of 582 // expressions of certain types in C++. 583 if (getLangOpts().CPlusPlus && 584 (E->getType() == Context.OverloadTy || 585 T->isDependentType() || 586 T->isRecordType())) 587 return E; 588 589 // The C standard is actually really unclear on this point, and 590 // DR106 tells us what the result should be but not why. It's 591 // generally best to say that void types just doesn't undergo 592 // lvalue-to-rvalue at all. Note that expressions of unqualified 593 // 'void' type are never l-values, but qualified void can be. 594 if (T->isVoidType()) 595 return E; 596 597 // OpenCL usually rejects direct accesses to values of 'half' type. 598 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 599 T->isHalfType()) { 600 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 601 << 0 << T; 602 return ExprError(); 603 } 604 605 CheckForNullPointerDereference(*this, E); 606 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 607 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 608 &Context.Idents.get("object_getClass"), 609 SourceLocation(), LookupOrdinaryName); 610 if (ObjectGetClass) 611 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 612 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 613 << FixItHint::CreateReplacement( 614 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 615 else 616 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 617 } 618 else if (const ObjCIvarRefExpr *OIRE = 619 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 620 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 621 622 // C++ [conv.lval]p1: 623 // [...] If T is a non-class type, the type of the prvalue is the 624 // cv-unqualified version of T. Otherwise, the type of the 625 // rvalue is T. 626 // 627 // C99 6.3.2.1p2: 628 // If the lvalue has qualified type, the value has the unqualified 629 // version of the type of the lvalue; otherwise, the value has the 630 // type of the lvalue. 631 if (T.hasQualifiers()) 632 T = T.getUnqualifiedType(); 633 634 // Under the MS ABI, lock down the inheritance model now. 635 if (T->isMemberPointerType() && 636 Context.getTargetInfo().getCXXABI().isMicrosoft()) 637 (void)isCompleteType(E->getExprLoc(), T); 638 639 UpdateMarkingForLValueToRValue(E); 640 641 // Loading a __weak object implicitly retains the value, so we need a cleanup to 642 // balance that. 643 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 644 Cleanup.setExprNeedsCleanups(true); 645 646 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 647 nullptr, VK_RValue); 648 649 // C11 6.3.2.1p2: 650 // ... if the lvalue has atomic type, the value has the non-atomic version 651 // of the type of the lvalue ... 652 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 653 T = Atomic->getValueType().getUnqualifiedType(); 654 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 655 nullptr, VK_RValue); 656 } 657 658 return Res; 659 } 660 661 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 662 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 663 if (Res.isInvalid()) 664 return ExprError(); 665 Res = DefaultLvalueConversion(Res.get()); 666 if (Res.isInvalid()) 667 return ExprError(); 668 return Res; 669 } 670 671 /// CallExprUnaryConversions - a special case of an unary conversion 672 /// performed on a function designator of a call expression. 673 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 674 QualType Ty = E->getType(); 675 ExprResult Res = E; 676 // Only do implicit cast for a function type, but not for a pointer 677 // to function type. 678 if (Ty->isFunctionType()) { 679 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 680 CK_FunctionToPointerDecay).get(); 681 if (Res.isInvalid()) 682 return ExprError(); 683 } 684 Res = DefaultLvalueConversion(Res.get()); 685 if (Res.isInvalid()) 686 return ExprError(); 687 return Res.get(); 688 } 689 690 /// UsualUnaryConversions - Performs various conversions that are common to most 691 /// operators (C99 6.3). The conversions of array and function types are 692 /// sometimes suppressed. For example, the array->pointer conversion doesn't 693 /// apply if the array is an argument to the sizeof or address (&) operators. 694 /// In these instances, this routine should *not* be called. 695 ExprResult Sema::UsualUnaryConversions(Expr *E) { 696 // First, convert to an r-value. 697 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 698 if (Res.isInvalid()) 699 return ExprError(); 700 E = Res.get(); 701 702 QualType Ty = E->getType(); 703 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 704 705 // Half FP have to be promoted to float unless it is natively supported 706 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 707 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 708 709 // Try to perform integral promotions if the object has a theoretically 710 // promotable type. 711 if (Ty->isIntegralOrUnscopedEnumerationType()) { 712 // C99 6.3.1.1p2: 713 // 714 // The following may be used in an expression wherever an int or 715 // unsigned int may be used: 716 // - an object or expression with an integer type whose integer 717 // conversion rank is less than or equal to the rank of int 718 // and unsigned int. 719 // - A bit-field of type _Bool, int, signed int, or unsigned int. 720 // 721 // If an int can represent all values of the original type, the 722 // value is converted to an int; otherwise, it is converted to an 723 // unsigned int. These are called the integer promotions. All 724 // other types are unchanged by the integer promotions. 725 726 QualType PTy = Context.isPromotableBitField(E); 727 if (!PTy.isNull()) { 728 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 729 return E; 730 } 731 if (Ty->isPromotableIntegerType()) { 732 QualType PT = Context.getPromotedIntegerType(Ty); 733 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 734 return E; 735 } 736 } 737 return E; 738 } 739 740 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 741 /// do not have a prototype. Arguments that have type float or __fp16 742 /// are promoted to double. All other argument types are converted by 743 /// UsualUnaryConversions(). 744 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 745 QualType Ty = E->getType(); 746 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 747 748 ExprResult Res = UsualUnaryConversions(E); 749 if (Res.isInvalid()) 750 return ExprError(); 751 E = Res.get(); 752 753 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 754 // promote to double. 755 // Note that default argument promotion applies only to float (and 756 // half/fp16); it does not apply to _Float16. 757 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 758 if (BTy && (BTy->getKind() == BuiltinType::Half || 759 BTy->getKind() == BuiltinType::Float)) { 760 if (getLangOpts().OpenCL && 761 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 762 if (BTy->getKind() == BuiltinType::Half) { 763 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 764 } 765 } else { 766 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 767 } 768 } 769 770 // C++ performs lvalue-to-rvalue conversion as a default argument 771 // promotion, even on class types, but note: 772 // C++11 [conv.lval]p2: 773 // When an lvalue-to-rvalue conversion occurs in an unevaluated 774 // operand or a subexpression thereof the value contained in the 775 // referenced object is not accessed. Otherwise, if the glvalue 776 // has a class type, the conversion copy-initializes a temporary 777 // of type T from the glvalue and the result of the conversion 778 // is a prvalue for the temporary. 779 // FIXME: add some way to gate this entire thing for correctness in 780 // potentially potentially evaluated contexts. 781 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 782 ExprResult Temp = PerformCopyInitialization( 783 InitializedEntity::InitializeTemporary(E->getType()), 784 E->getExprLoc(), E); 785 if (Temp.isInvalid()) 786 return ExprError(); 787 E = Temp.get(); 788 } 789 790 return E; 791 } 792 793 /// Determine the degree of POD-ness for an expression. 794 /// Incomplete types are considered POD, since this check can be performed 795 /// when we're in an unevaluated context. 796 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 797 if (Ty->isIncompleteType()) { 798 // C++11 [expr.call]p7: 799 // After these conversions, if the argument does not have arithmetic, 800 // enumeration, pointer, pointer to member, or class type, the program 801 // is ill-formed. 802 // 803 // Since we've already performed array-to-pointer and function-to-pointer 804 // decay, the only such type in C++ is cv void. This also handles 805 // initializer lists as variadic arguments. 806 if (Ty->isVoidType()) 807 return VAK_Invalid; 808 809 if (Ty->isObjCObjectType()) 810 return VAK_Invalid; 811 return VAK_Valid; 812 } 813 814 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 815 return VAK_Invalid; 816 817 if (Ty.isCXX98PODType(Context)) 818 return VAK_Valid; 819 820 // C++11 [expr.call]p7: 821 // Passing a potentially-evaluated argument of class type (Clause 9) 822 // having a non-trivial copy constructor, a non-trivial move constructor, 823 // or a non-trivial destructor, with no corresponding parameter, 824 // is conditionally-supported with implementation-defined semantics. 825 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 826 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 827 if (!Record->hasNonTrivialCopyConstructor() && 828 !Record->hasNonTrivialMoveConstructor() && 829 !Record->hasNonTrivialDestructor()) 830 return VAK_ValidInCXX11; 831 832 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 833 return VAK_Valid; 834 835 if (Ty->isObjCObjectType()) 836 return VAK_Invalid; 837 838 if (getLangOpts().MSVCCompat) 839 return VAK_MSVCUndefined; 840 841 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 842 // permitted to reject them. We should consider doing so. 843 return VAK_Undefined; 844 } 845 846 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 847 // Don't allow one to pass an Objective-C interface to a vararg. 848 const QualType &Ty = E->getType(); 849 VarArgKind VAK = isValidVarArgType(Ty); 850 851 // Complain about passing non-POD types through varargs. 852 switch (VAK) { 853 case VAK_ValidInCXX11: 854 DiagRuntimeBehavior( 855 E->getBeginLoc(), nullptr, 856 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 857 LLVM_FALLTHROUGH; 858 case VAK_Valid: 859 if (Ty->isRecordType()) { 860 // This is unlikely to be what the user intended. If the class has a 861 // 'c_str' member function, the user probably meant to call that. 862 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 863 PDiag(diag::warn_pass_class_arg_to_vararg) 864 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 865 } 866 break; 867 868 case VAK_Undefined: 869 case VAK_MSVCUndefined: 870 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 871 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 872 << getLangOpts().CPlusPlus11 << Ty << CT); 873 break; 874 875 case VAK_Invalid: 876 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 877 Diag(E->getBeginLoc(), 878 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 879 << Ty << CT; 880 else if (Ty->isObjCObjectType()) 881 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 882 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 883 << Ty << CT); 884 else 885 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 886 << isa<InitListExpr>(E) << Ty << CT; 887 break; 888 } 889 } 890 891 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 892 /// will create a trap if the resulting type is not a POD type. 893 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 894 FunctionDecl *FDecl) { 895 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 896 // Strip the unbridged-cast placeholder expression off, if applicable. 897 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 898 (CT == VariadicMethod || 899 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 900 E = stripARCUnbridgedCast(E); 901 902 // Otherwise, do normal placeholder checking. 903 } else { 904 ExprResult ExprRes = CheckPlaceholderExpr(E); 905 if (ExprRes.isInvalid()) 906 return ExprError(); 907 E = ExprRes.get(); 908 } 909 } 910 911 ExprResult ExprRes = DefaultArgumentPromotion(E); 912 if (ExprRes.isInvalid()) 913 return ExprError(); 914 E = ExprRes.get(); 915 916 // Diagnostics regarding non-POD argument types are 917 // emitted along with format string checking in Sema::CheckFunctionCall(). 918 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 919 // Turn this into a trap. 920 CXXScopeSpec SS; 921 SourceLocation TemplateKWLoc; 922 UnqualifiedId Name; 923 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 924 E->getBeginLoc()); 925 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 926 Name, true, false); 927 if (TrapFn.isInvalid()) 928 return ExprError(); 929 930 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 931 None, E->getEndLoc()); 932 if (Call.isInvalid()) 933 return ExprError(); 934 935 ExprResult Comma = 936 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 937 if (Comma.isInvalid()) 938 return ExprError(); 939 return Comma.get(); 940 } 941 942 if (!getLangOpts().CPlusPlus && 943 RequireCompleteType(E->getExprLoc(), E->getType(), 944 diag::err_call_incomplete_argument)) 945 return ExprError(); 946 947 return E; 948 } 949 950 /// Converts an integer to complex float type. Helper function of 951 /// UsualArithmeticConversions() 952 /// 953 /// \return false if the integer expression is an integer type and is 954 /// successfully converted to the complex type. 955 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 956 ExprResult &ComplexExpr, 957 QualType IntTy, 958 QualType ComplexTy, 959 bool SkipCast) { 960 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 961 if (SkipCast) return false; 962 if (IntTy->isIntegerType()) { 963 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 964 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 965 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 966 CK_FloatingRealToComplex); 967 } else { 968 assert(IntTy->isComplexIntegerType()); 969 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 970 CK_IntegralComplexToFloatingComplex); 971 } 972 return false; 973 } 974 975 /// Handle arithmetic conversion with complex types. Helper function of 976 /// UsualArithmeticConversions() 977 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 978 ExprResult &RHS, QualType LHSType, 979 QualType RHSType, 980 bool IsCompAssign) { 981 // if we have an integer operand, the result is the complex type. 982 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 983 /*skipCast*/false)) 984 return LHSType; 985 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 986 /*skipCast*/IsCompAssign)) 987 return RHSType; 988 989 // This handles complex/complex, complex/float, or float/complex. 990 // When both operands are complex, the shorter operand is converted to the 991 // type of the longer, and that is the type of the result. This corresponds 992 // to what is done when combining two real floating-point operands. 993 // The fun begins when size promotion occur across type domains. 994 // From H&S 6.3.4: When one operand is complex and the other is a real 995 // floating-point type, the less precise type is converted, within it's 996 // real or complex domain, to the precision of the other type. For example, 997 // when combining a "long double" with a "double _Complex", the 998 // "double _Complex" is promoted to "long double _Complex". 999 1000 // Compute the rank of the two types, regardless of whether they are complex. 1001 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1002 1003 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1004 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1005 QualType LHSElementType = 1006 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1007 QualType RHSElementType = 1008 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1009 1010 QualType ResultType = S.Context.getComplexType(LHSElementType); 1011 if (Order < 0) { 1012 // Promote the precision of the LHS if not an assignment. 1013 ResultType = S.Context.getComplexType(RHSElementType); 1014 if (!IsCompAssign) { 1015 if (LHSComplexType) 1016 LHS = 1017 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1018 else 1019 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1020 } 1021 } else if (Order > 0) { 1022 // Promote the precision of the RHS. 1023 if (RHSComplexType) 1024 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1025 else 1026 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1027 } 1028 return ResultType; 1029 } 1030 1031 /// Handle arithmetic conversion from integer to float. Helper function 1032 /// of UsualArithmeticConversions() 1033 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1034 ExprResult &IntExpr, 1035 QualType FloatTy, QualType IntTy, 1036 bool ConvertFloat, bool ConvertInt) { 1037 if (IntTy->isIntegerType()) { 1038 if (ConvertInt) 1039 // Convert intExpr to the lhs floating point type. 1040 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1041 CK_IntegralToFloating); 1042 return FloatTy; 1043 } 1044 1045 // Convert both sides to the appropriate complex float. 1046 assert(IntTy->isComplexIntegerType()); 1047 QualType result = S.Context.getComplexType(FloatTy); 1048 1049 // _Complex int -> _Complex float 1050 if (ConvertInt) 1051 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1052 CK_IntegralComplexToFloatingComplex); 1053 1054 // float -> _Complex float 1055 if (ConvertFloat) 1056 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1057 CK_FloatingRealToComplex); 1058 1059 return result; 1060 } 1061 1062 /// Handle arithmethic conversion with floating point types. Helper 1063 /// function of UsualArithmeticConversions() 1064 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1065 ExprResult &RHS, QualType LHSType, 1066 QualType RHSType, bool IsCompAssign) { 1067 bool LHSFloat = LHSType->isRealFloatingType(); 1068 bool RHSFloat = RHSType->isRealFloatingType(); 1069 1070 // If we have two real floating types, convert the smaller operand 1071 // to the bigger result. 1072 if (LHSFloat && RHSFloat) { 1073 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1074 if (order > 0) { 1075 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1076 return LHSType; 1077 } 1078 1079 assert(order < 0 && "illegal float comparison"); 1080 if (!IsCompAssign) 1081 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1082 return RHSType; 1083 } 1084 1085 if (LHSFloat) { 1086 // Half FP has to be promoted to float unless it is natively supported 1087 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1088 LHSType = S.Context.FloatTy; 1089 1090 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1091 /*convertFloat=*/!IsCompAssign, 1092 /*convertInt=*/ true); 1093 } 1094 assert(RHSFloat); 1095 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1096 /*convertInt=*/ true, 1097 /*convertFloat=*/!IsCompAssign); 1098 } 1099 1100 /// Diagnose attempts to convert between __float128 and long double if 1101 /// there is no support for such conversion. Helper function of 1102 /// UsualArithmeticConversions(). 1103 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1104 QualType RHSType) { 1105 /* No issue converting if at least one of the types is not a floating point 1106 type or the two types have the same rank. 1107 */ 1108 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1109 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1110 return false; 1111 1112 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1113 "The remaining types must be floating point types."); 1114 1115 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1116 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1117 1118 QualType LHSElemType = LHSComplex ? 1119 LHSComplex->getElementType() : LHSType; 1120 QualType RHSElemType = RHSComplex ? 1121 RHSComplex->getElementType() : RHSType; 1122 1123 // No issue if the two types have the same representation 1124 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1125 &S.Context.getFloatTypeSemantics(RHSElemType)) 1126 return false; 1127 1128 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1129 RHSElemType == S.Context.LongDoubleTy); 1130 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1131 RHSElemType == S.Context.Float128Ty); 1132 1133 // We've handled the situation where __float128 and long double have the same 1134 // representation. We allow all conversions for all possible long double types 1135 // except PPC's double double. 1136 return Float128AndLongDouble && 1137 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1138 &llvm::APFloat::PPCDoubleDouble()); 1139 } 1140 1141 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1142 1143 namespace { 1144 /// These helper callbacks are placed in an anonymous namespace to 1145 /// permit their use as function template parameters. 1146 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1147 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1148 } 1149 1150 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1151 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1152 CK_IntegralComplexCast); 1153 } 1154 } 1155 1156 /// Handle integer arithmetic conversions. Helper function of 1157 /// UsualArithmeticConversions() 1158 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1159 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1160 ExprResult &RHS, QualType LHSType, 1161 QualType RHSType, bool IsCompAssign) { 1162 // The rules for this case are in C99 6.3.1.8 1163 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1164 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1165 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1166 if (LHSSigned == RHSSigned) { 1167 // Same signedness; use the higher-ranked type 1168 if (order >= 0) { 1169 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1170 return LHSType; 1171 } else if (!IsCompAssign) 1172 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1173 return RHSType; 1174 } else if (order != (LHSSigned ? 1 : -1)) { 1175 // The unsigned type has greater than or equal rank to the 1176 // signed type, so use the unsigned type 1177 if (RHSSigned) { 1178 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1179 return LHSType; 1180 } else if (!IsCompAssign) 1181 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1182 return RHSType; 1183 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1184 // The two types are different widths; if we are here, that 1185 // means the signed type is larger than the unsigned type, so 1186 // use the signed type. 1187 if (LHSSigned) { 1188 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1189 return LHSType; 1190 } else if (!IsCompAssign) 1191 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1192 return RHSType; 1193 } else { 1194 // The signed type is higher-ranked than the unsigned type, 1195 // but isn't actually any bigger (like unsigned int and long 1196 // on most 32-bit systems). Use the unsigned type corresponding 1197 // to the signed type. 1198 QualType result = 1199 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1200 RHS = (*doRHSCast)(S, RHS.get(), result); 1201 if (!IsCompAssign) 1202 LHS = (*doLHSCast)(S, LHS.get(), result); 1203 return result; 1204 } 1205 } 1206 1207 /// Handle conversions with GCC complex int extension. Helper function 1208 /// of UsualArithmeticConversions() 1209 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1210 ExprResult &RHS, QualType LHSType, 1211 QualType RHSType, 1212 bool IsCompAssign) { 1213 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1214 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1215 1216 if (LHSComplexInt && RHSComplexInt) { 1217 QualType LHSEltType = LHSComplexInt->getElementType(); 1218 QualType RHSEltType = RHSComplexInt->getElementType(); 1219 QualType ScalarType = 1220 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1221 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1222 1223 return S.Context.getComplexType(ScalarType); 1224 } 1225 1226 if (LHSComplexInt) { 1227 QualType LHSEltType = LHSComplexInt->getElementType(); 1228 QualType ScalarType = 1229 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1230 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1231 QualType ComplexType = S.Context.getComplexType(ScalarType); 1232 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1233 CK_IntegralRealToComplex); 1234 1235 return ComplexType; 1236 } 1237 1238 assert(RHSComplexInt); 1239 1240 QualType RHSEltType = RHSComplexInt->getElementType(); 1241 QualType ScalarType = 1242 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1243 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1244 QualType ComplexType = S.Context.getComplexType(ScalarType); 1245 1246 if (!IsCompAssign) 1247 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1248 CK_IntegralRealToComplex); 1249 return ComplexType; 1250 } 1251 1252 /// Return the rank of a given fixed point or integer type. The value itself 1253 /// doesn't matter, but the values must be increasing with proper increasing 1254 /// rank as described in N1169 4.1.1. 1255 static unsigned GetFixedPointRank(QualType Ty) { 1256 const auto *BTy = Ty->getAs<BuiltinType>(); 1257 assert(BTy && "Expected a builtin type."); 1258 1259 switch (BTy->getKind()) { 1260 case BuiltinType::ShortFract: 1261 case BuiltinType::UShortFract: 1262 case BuiltinType::SatShortFract: 1263 case BuiltinType::SatUShortFract: 1264 return 1; 1265 case BuiltinType::Fract: 1266 case BuiltinType::UFract: 1267 case BuiltinType::SatFract: 1268 case BuiltinType::SatUFract: 1269 return 2; 1270 case BuiltinType::LongFract: 1271 case BuiltinType::ULongFract: 1272 case BuiltinType::SatLongFract: 1273 case BuiltinType::SatULongFract: 1274 return 3; 1275 case BuiltinType::ShortAccum: 1276 case BuiltinType::UShortAccum: 1277 case BuiltinType::SatShortAccum: 1278 case BuiltinType::SatUShortAccum: 1279 return 4; 1280 case BuiltinType::Accum: 1281 case BuiltinType::UAccum: 1282 case BuiltinType::SatAccum: 1283 case BuiltinType::SatUAccum: 1284 return 5; 1285 case BuiltinType::LongAccum: 1286 case BuiltinType::ULongAccum: 1287 case BuiltinType::SatLongAccum: 1288 case BuiltinType::SatULongAccum: 1289 return 6; 1290 default: 1291 if (BTy->isInteger()) 1292 return 0; 1293 llvm_unreachable("Unexpected fixed point or integer type"); 1294 } 1295 } 1296 1297 /// handleFixedPointConversion - Fixed point operations between fixed 1298 /// point types and integers or other fixed point types do not fall under 1299 /// usual arithmetic conversion since these conversions could result in loss 1300 /// of precsision (N1169 4.1.4). These operations should be calculated with 1301 /// the full precision of their result type (N1169 4.1.6.2.1). 1302 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1303 QualType RHSTy) { 1304 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1305 "Expected at least one of the operands to be a fixed point type"); 1306 assert((LHSTy->isFixedPointOrIntegerType() || 1307 RHSTy->isFixedPointOrIntegerType()) && 1308 "Special fixed point arithmetic operation conversions are only " 1309 "applied to ints or other fixed point types"); 1310 1311 // If one operand has signed fixed-point type and the other operand has 1312 // unsigned fixed-point type, then the unsigned fixed-point operand is 1313 // converted to its corresponding signed fixed-point type and the resulting 1314 // type is the type of the converted operand. 1315 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1316 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1317 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1318 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1319 1320 // The result type is the type with the highest rank, whereby a fixed-point 1321 // conversion rank is always greater than an integer conversion rank; if the 1322 // type of either of the operands is a saturating fixedpoint type, the result 1323 // type shall be the saturating fixed-point type corresponding to the type 1324 // with the highest rank; the resulting value is converted (taking into 1325 // account rounding and overflow) to the precision of the resulting type. 1326 // Same ranks between signed and unsigned types are resolved earlier, so both 1327 // types are either signed or both unsigned at this point. 1328 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1329 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1330 1331 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1332 1333 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1334 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1335 1336 return ResultTy; 1337 } 1338 1339 /// UsualArithmeticConversions - Performs various conversions that are common to 1340 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1341 /// routine returns the first non-arithmetic type found. The client is 1342 /// responsible for emitting appropriate error diagnostics. 1343 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1344 bool IsCompAssign) { 1345 if (!IsCompAssign) { 1346 LHS = UsualUnaryConversions(LHS.get()); 1347 if (LHS.isInvalid()) 1348 return QualType(); 1349 } 1350 1351 RHS = UsualUnaryConversions(RHS.get()); 1352 if (RHS.isInvalid()) 1353 return QualType(); 1354 1355 // For conversion purposes, we ignore any qualifiers. 1356 // For example, "const float" and "float" are equivalent. 1357 QualType LHSType = 1358 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1359 QualType RHSType = 1360 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1361 1362 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1363 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1364 LHSType = AtomicLHS->getValueType(); 1365 1366 // If both types are identical, no conversion is needed. 1367 if (LHSType == RHSType) 1368 return LHSType; 1369 1370 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1371 // The caller can deal with this (e.g. pointer + int). 1372 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1373 return QualType(); 1374 1375 // Apply unary and bitfield promotions to the LHS's type. 1376 QualType LHSUnpromotedType = LHSType; 1377 if (LHSType->isPromotableIntegerType()) 1378 LHSType = Context.getPromotedIntegerType(LHSType); 1379 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1380 if (!LHSBitfieldPromoteTy.isNull()) 1381 LHSType = LHSBitfieldPromoteTy; 1382 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1383 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1384 1385 // If both types are identical, no conversion is needed. 1386 if (LHSType == RHSType) 1387 return LHSType; 1388 1389 // At this point, we have two different arithmetic types. 1390 1391 // Diagnose attempts to convert between __float128 and long double where 1392 // such conversions currently can't be handled. 1393 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1394 return QualType(); 1395 1396 // Handle complex types first (C99 6.3.1.8p1). 1397 if (LHSType->isComplexType() || RHSType->isComplexType()) 1398 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1399 IsCompAssign); 1400 1401 // Now handle "real" floating types (i.e. float, double, long double). 1402 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1403 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1404 IsCompAssign); 1405 1406 // Handle GCC complex int extension. 1407 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1408 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1409 IsCompAssign); 1410 1411 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1412 return handleFixedPointConversion(*this, LHSType, RHSType); 1413 1414 // Finally, we have two differing integer types. 1415 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1416 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1417 } 1418 1419 //===----------------------------------------------------------------------===// 1420 // Semantic Analysis for various Expression Types 1421 //===----------------------------------------------------------------------===// 1422 1423 1424 ExprResult 1425 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1426 SourceLocation DefaultLoc, 1427 SourceLocation RParenLoc, 1428 Expr *ControllingExpr, 1429 ArrayRef<ParsedType> ArgTypes, 1430 ArrayRef<Expr *> ArgExprs) { 1431 unsigned NumAssocs = ArgTypes.size(); 1432 assert(NumAssocs == ArgExprs.size()); 1433 1434 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1435 for (unsigned i = 0; i < NumAssocs; ++i) { 1436 if (ArgTypes[i]) 1437 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1438 else 1439 Types[i] = nullptr; 1440 } 1441 1442 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1443 ControllingExpr, 1444 llvm::makeArrayRef(Types, NumAssocs), 1445 ArgExprs); 1446 delete [] Types; 1447 return ER; 1448 } 1449 1450 ExprResult 1451 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1452 SourceLocation DefaultLoc, 1453 SourceLocation RParenLoc, 1454 Expr *ControllingExpr, 1455 ArrayRef<TypeSourceInfo *> Types, 1456 ArrayRef<Expr *> Exprs) { 1457 unsigned NumAssocs = Types.size(); 1458 assert(NumAssocs == Exprs.size()); 1459 1460 // Decay and strip qualifiers for the controlling expression type, and handle 1461 // placeholder type replacement. See committee discussion from WG14 DR423. 1462 { 1463 EnterExpressionEvaluationContext Unevaluated( 1464 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1465 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1466 if (R.isInvalid()) 1467 return ExprError(); 1468 ControllingExpr = R.get(); 1469 } 1470 1471 // The controlling expression is an unevaluated operand, so side effects are 1472 // likely unintended. 1473 if (!inTemplateInstantiation() && 1474 ControllingExpr->HasSideEffects(Context, false)) 1475 Diag(ControllingExpr->getExprLoc(), 1476 diag::warn_side_effects_unevaluated_context); 1477 1478 bool TypeErrorFound = false, 1479 IsResultDependent = ControllingExpr->isTypeDependent(), 1480 ContainsUnexpandedParameterPack 1481 = ControllingExpr->containsUnexpandedParameterPack(); 1482 1483 for (unsigned i = 0; i < NumAssocs; ++i) { 1484 if (Exprs[i]->containsUnexpandedParameterPack()) 1485 ContainsUnexpandedParameterPack = true; 1486 1487 if (Types[i]) { 1488 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1489 ContainsUnexpandedParameterPack = true; 1490 1491 if (Types[i]->getType()->isDependentType()) { 1492 IsResultDependent = true; 1493 } else { 1494 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1495 // complete object type other than a variably modified type." 1496 unsigned D = 0; 1497 if (Types[i]->getType()->isIncompleteType()) 1498 D = diag::err_assoc_type_incomplete; 1499 else if (!Types[i]->getType()->isObjectType()) 1500 D = diag::err_assoc_type_nonobject; 1501 else if (Types[i]->getType()->isVariablyModifiedType()) 1502 D = diag::err_assoc_type_variably_modified; 1503 1504 if (D != 0) { 1505 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1506 << Types[i]->getTypeLoc().getSourceRange() 1507 << Types[i]->getType(); 1508 TypeErrorFound = true; 1509 } 1510 1511 // C11 6.5.1.1p2 "No two generic associations in the same generic 1512 // selection shall specify compatible types." 1513 for (unsigned j = i+1; j < NumAssocs; ++j) 1514 if (Types[j] && !Types[j]->getType()->isDependentType() && 1515 Context.typesAreCompatible(Types[i]->getType(), 1516 Types[j]->getType())) { 1517 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1518 diag::err_assoc_compatible_types) 1519 << Types[j]->getTypeLoc().getSourceRange() 1520 << Types[j]->getType() 1521 << Types[i]->getType(); 1522 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1523 diag::note_compat_assoc) 1524 << Types[i]->getTypeLoc().getSourceRange() 1525 << Types[i]->getType(); 1526 TypeErrorFound = true; 1527 } 1528 } 1529 } 1530 } 1531 if (TypeErrorFound) 1532 return ExprError(); 1533 1534 // If we determined that the generic selection is result-dependent, don't 1535 // try to compute the result expression. 1536 if (IsResultDependent) 1537 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1538 Exprs, DefaultLoc, RParenLoc, 1539 ContainsUnexpandedParameterPack); 1540 1541 SmallVector<unsigned, 1> CompatIndices; 1542 unsigned DefaultIndex = -1U; 1543 for (unsigned i = 0; i < NumAssocs; ++i) { 1544 if (!Types[i]) 1545 DefaultIndex = i; 1546 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1547 Types[i]->getType())) 1548 CompatIndices.push_back(i); 1549 } 1550 1551 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1552 // type compatible with at most one of the types named in its generic 1553 // association list." 1554 if (CompatIndices.size() > 1) { 1555 // We strip parens here because the controlling expression is typically 1556 // parenthesized in macro definitions. 1557 ControllingExpr = ControllingExpr->IgnoreParens(); 1558 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1559 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1560 << (unsigned)CompatIndices.size(); 1561 for (unsigned I : CompatIndices) { 1562 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1563 diag::note_compat_assoc) 1564 << Types[I]->getTypeLoc().getSourceRange() 1565 << Types[I]->getType(); 1566 } 1567 return ExprError(); 1568 } 1569 1570 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1571 // its controlling expression shall have type compatible with exactly one of 1572 // the types named in its generic association list." 1573 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1574 // We strip parens here because the controlling expression is typically 1575 // parenthesized in macro definitions. 1576 ControllingExpr = ControllingExpr->IgnoreParens(); 1577 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1578 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1579 return ExprError(); 1580 } 1581 1582 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1583 // type name that is compatible with the type of the controlling expression, 1584 // then the result expression of the generic selection is the expression 1585 // in that generic association. Otherwise, the result expression of the 1586 // generic selection is the expression in the default generic association." 1587 unsigned ResultIndex = 1588 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1589 1590 return GenericSelectionExpr::Create( 1591 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1592 ContainsUnexpandedParameterPack, ResultIndex); 1593 } 1594 1595 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1596 /// location of the token and the offset of the ud-suffix within it. 1597 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1598 unsigned Offset) { 1599 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1600 S.getLangOpts()); 1601 } 1602 1603 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1604 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1605 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1606 IdentifierInfo *UDSuffix, 1607 SourceLocation UDSuffixLoc, 1608 ArrayRef<Expr*> Args, 1609 SourceLocation LitEndLoc) { 1610 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1611 1612 QualType ArgTy[2]; 1613 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1614 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1615 if (ArgTy[ArgIdx]->isArrayType()) 1616 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1617 } 1618 1619 DeclarationName OpName = 1620 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1621 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1622 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1623 1624 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1625 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1626 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1627 /*AllowStringTemplate*/ false, 1628 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1629 return ExprError(); 1630 1631 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1632 } 1633 1634 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1635 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1636 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1637 /// multiple tokens. However, the common case is that StringToks points to one 1638 /// string. 1639 /// 1640 ExprResult 1641 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1642 assert(!StringToks.empty() && "Must have at least one string!"); 1643 1644 StringLiteralParser Literal(StringToks, PP); 1645 if (Literal.hadError) 1646 return ExprError(); 1647 1648 SmallVector<SourceLocation, 4> StringTokLocs; 1649 for (const Token &Tok : StringToks) 1650 StringTokLocs.push_back(Tok.getLocation()); 1651 1652 QualType CharTy = Context.CharTy; 1653 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1654 if (Literal.isWide()) { 1655 CharTy = Context.getWideCharType(); 1656 Kind = StringLiteral::Wide; 1657 } else if (Literal.isUTF8()) { 1658 if (getLangOpts().Char8) 1659 CharTy = Context.Char8Ty; 1660 Kind = StringLiteral::UTF8; 1661 } else if (Literal.isUTF16()) { 1662 CharTy = Context.Char16Ty; 1663 Kind = StringLiteral::UTF16; 1664 } else if (Literal.isUTF32()) { 1665 CharTy = Context.Char32Ty; 1666 Kind = StringLiteral::UTF32; 1667 } else if (Literal.isPascal()) { 1668 CharTy = Context.UnsignedCharTy; 1669 } 1670 1671 // Warn on initializing an array of char from a u8 string literal; this 1672 // becomes ill-formed in C++2a. 1673 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus2a && 1674 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1675 Diag(StringTokLocs.front(), diag::warn_cxx2a_compat_utf8_string); 1676 1677 // Create removals for all 'u8' prefixes in the string literal(s). This 1678 // ensures C++2a compatibility (but may change the program behavior when 1679 // built by non-Clang compilers for which the execution character set is 1680 // not always UTF-8). 1681 auto RemovalDiag = PDiag(diag::note_cxx2a_compat_utf8_string_remove_u8); 1682 SourceLocation RemovalDiagLoc; 1683 for (const Token &Tok : StringToks) { 1684 if (Tok.getKind() == tok::utf8_string_literal) { 1685 if (RemovalDiagLoc.isInvalid()) 1686 RemovalDiagLoc = Tok.getLocation(); 1687 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1688 Tok.getLocation(), 1689 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1690 getSourceManager(), getLangOpts()))); 1691 } 1692 } 1693 Diag(RemovalDiagLoc, RemovalDiag); 1694 } 1695 1696 1697 QualType CharTyConst = CharTy; 1698 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1699 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1700 CharTyConst.addConst(); 1701 1702 CharTyConst = Context.adjustStringLiteralBaseType(CharTyConst); 1703 1704 // Get an array type for the string, according to C99 6.4.5. This includes 1705 // the nul terminator character as well as the string length for pascal 1706 // strings. 1707 QualType StrTy = Context.getConstantArrayType( 1708 CharTyConst, llvm::APInt(32, Literal.GetNumStringChars() + 1), 1709 ArrayType::Normal, 0); 1710 1711 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1712 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1713 Kind, Literal.Pascal, StrTy, 1714 &StringTokLocs[0], 1715 StringTokLocs.size()); 1716 if (Literal.getUDSuffix().empty()) 1717 return Lit; 1718 1719 // We're building a user-defined literal. 1720 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1721 SourceLocation UDSuffixLoc = 1722 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1723 Literal.getUDSuffixOffset()); 1724 1725 // Make sure we're allowed user-defined literals here. 1726 if (!UDLScope) 1727 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1728 1729 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1730 // operator "" X (str, len) 1731 QualType SizeType = Context.getSizeType(); 1732 1733 DeclarationName OpName = 1734 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1735 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1736 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1737 1738 QualType ArgTy[] = { 1739 Context.getArrayDecayedType(StrTy), SizeType 1740 }; 1741 1742 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1743 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1744 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1745 /*AllowStringTemplate*/ true, 1746 /*DiagnoseMissing*/ true)) { 1747 1748 case LOLR_Cooked: { 1749 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1750 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1751 StringTokLocs[0]); 1752 Expr *Args[] = { Lit, LenArg }; 1753 1754 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1755 } 1756 1757 case LOLR_StringTemplate: { 1758 TemplateArgumentListInfo ExplicitArgs; 1759 1760 unsigned CharBits = Context.getIntWidth(CharTy); 1761 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1762 llvm::APSInt Value(CharBits, CharIsUnsigned); 1763 1764 TemplateArgument TypeArg(CharTy); 1765 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1766 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1767 1768 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1769 Value = Lit->getCodeUnit(I); 1770 TemplateArgument Arg(Context, Value, CharTy); 1771 TemplateArgumentLocInfo ArgInfo; 1772 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1773 } 1774 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1775 &ExplicitArgs); 1776 } 1777 case LOLR_Raw: 1778 case LOLR_Template: 1779 case LOLR_ErrorNoDiagnostic: 1780 llvm_unreachable("unexpected literal operator lookup result"); 1781 case LOLR_Error: 1782 return ExprError(); 1783 } 1784 llvm_unreachable("unexpected literal operator lookup result"); 1785 } 1786 1787 ExprResult 1788 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1789 SourceLocation Loc, 1790 const CXXScopeSpec *SS) { 1791 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1792 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1793 } 1794 1795 /// BuildDeclRefExpr - Build an expression that references a 1796 /// declaration that does not require a closure capture. 1797 ExprResult 1798 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1799 const DeclarationNameInfo &NameInfo, 1800 const CXXScopeSpec *SS, NamedDecl *FoundD, 1801 const TemplateArgumentListInfo *TemplateArgs) { 1802 bool RefersToCapturedVariable = 1803 isa<VarDecl>(D) && 1804 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1805 1806 DeclRefExpr *E; 1807 if (isa<VarTemplateSpecializationDecl>(D)) { 1808 VarTemplateSpecializationDecl *VarSpec = 1809 cast<VarTemplateSpecializationDecl>(D); 1810 1811 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1812 : NestedNameSpecifierLoc(), 1813 VarSpec->getTemplateKeywordLoc(), D, 1814 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK, 1815 FoundD, TemplateArgs); 1816 } else { 1817 assert(!TemplateArgs && "No template arguments for non-variable" 1818 " template specialization references"); 1819 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1820 : NestedNameSpecifierLoc(), 1821 SourceLocation(), D, RefersToCapturedVariable, 1822 NameInfo, Ty, VK, FoundD); 1823 } 1824 1825 MarkDeclRefReferenced(E); 1826 1827 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1828 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 1829 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 1830 getCurFunction()->recordUseOfWeak(E); 1831 1832 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1833 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 1834 FD = IFD->getAnonField(); 1835 if (FD) { 1836 UnusedPrivateFields.remove(FD); 1837 // Just in case we're building an illegal pointer-to-member. 1838 if (FD->isBitField()) 1839 E->setObjectKind(OK_BitField); 1840 } 1841 1842 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1843 // designates a bit-field. 1844 if (auto *BD = dyn_cast<BindingDecl>(D)) 1845 if (auto *BE = BD->getBinding()) 1846 E->setObjectKind(BE->getObjectKind()); 1847 1848 return E; 1849 } 1850 1851 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1852 /// possibly a list of template arguments. 1853 /// 1854 /// If this produces template arguments, it is permitted to call 1855 /// DecomposeTemplateName. 1856 /// 1857 /// This actually loses a lot of source location information for 1858 /// non-standard name kinds; we should consider preserving that in 1859 /// some way. 1860 void 1861 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1862 TemplateArgumentListInfo &Buffer, 1863 DeclarationNameInfo &NameInfo, 1864 const TemplateArgumentListInfo *&TemplateArgs) { 1865 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 1866 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1867 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1868 1869 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1870 Id.TemplateId->NumArgs); 1871 translateTemplateArguments(TemplateArgsPtr, Buffer); 1872 1873 TemplateName TName = Id.TemplateId->Template.get(); 1874 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1875 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1876 TemplateArgs = &Buffer; 1877 } else { 1878 NameInfo = GetNameFromUnqualifiedId(Id); 1879 TemplateArgs = nullptr; 1880 } 1881 } 1882 1883 static void emitEmptyLookupTypoDiagnostic( 1884 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1885 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1886 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1887 DeclContext *Ctx = 1888 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1889 if (!TC) { 1890 // Emit a special diagnostic for failed member lookups. 1891 // FIXME: computing the declaration context might fail here (?) 1892 if (Ctx) 1893 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1894 << SS.getRange(); 1895 else 1896 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1897 return; 1898 } 1899 1900 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1901 bool DroppedSpecifier = 1902 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1903 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1904 ? diag::note_implicit_param_decl 1905 : diag::note_previous_decl; 1906 if (!Ctx) 1907 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1908 SemaRef.PDiag(NoteID)); 1909 else 1910 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1911 << Typo << Ctx << DroppedSpecifier 1912 << SS.getRange(), 1913 SemaRef.PDiag(NoteID)); 1914 } 1915 1916 /// Diagnose an empty lookup. 1917 /// 1918 /// \return false if new lookup candidates were found 1919 bool 1920 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1921 std::unique_ptr<CorrectionCandidateCallback> CCC, 1922 TemplateArgumentListInfo *ExplicitTemplateArgs, 1923 ArrayRef<Expr *> Args, TypoExpr **Out) { 1924 DeclarationName Name = R.getLookupName(); 1925 1926 unsigned diagnostic = diag::err_undeclared_var_use; 1927 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1928 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1929 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1930 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1931 diagnostic = diag::err_undeclared_use; 1932 diagnostic_suggest = diag::err_undeclared_use_suggest; 1933 } 1934 1935 // If the original lookup was an unqualified lookup, fake an 1936 // unqualified lookup. This is useful when (for example) the 1937 // original lookup would not have found something because it was a 1938 // dependent name. 1939 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1940 while (DC) { 1941 if (isa<CXXRecordDecl>(DC)) { 1942 LookupQualifiedName(R, DC); 1943 1944 if (!R.empty()) { 1945 // Don't give errors about ambiguities in this lookup. 1946 R.suppressDiagnostics(); 1947 1948 // During a default argument instantiation the CurContext points 1949 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1950 // function parameter list, hence add an explicit check. 1951 bool isDefaultArgument = 1952 !CodeSynthesisContexts.empty() && 1953 CodeSynthesisContexts.back().Kind == 1954 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 1955 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1956 bool isInstance = CurMethod && 1957 CurMethod->isInstance() && 1958 DC == CurMethod->getParent() && !isDefaultArgument; 1959 1960 // Give a code modification hint to insert 'this->'. 1961 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1962 // Actually quite difficult! 1963 if (getLangOpts().MSVCCompat) 1964 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1965 if (isInstance) { 1966 Diag(R.getNameLoc(), diagnostic) << Name 1967 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1968 CheckCXXThisCapture(R.getNameLoc()); 1969 } else { 1970 Diag(R.getNameLoc(), diagnostic) << Name; 1971 } 1972 1973 // Do we really want to note all of these? 1974 for (NamedDecl *D : R) 1975 Diag(D->getLocation(), diag::note_dependent_var_use); 1976 1977 // Return true if we are inside a default argument instantiation 1978 // and the found name refers to an instance member function, otherwise 1979 // the function calling DiagnoseEmptyLookup will try to create an 1980 // implicit member call and this is wrong for default argument. 1981 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1982 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1983 return true; 1984 } 1985 1986 // Tell the callee to try to recover. 1987 return false; 1988 } 1989 1990 R.clear(); 1991 } 1992 1993 // In Microsoft mode, if we are performing lookup from within a friend 1994 // function definition declared at class scope then we must set 1995 // DC to the lexical parent to be able to search into the parent 1996 // class. 1997 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1998 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1999 DC->getLexicalParent()->isRecord()) 2000 DC = DC->getLexicalParent(); 2001 else 2002 DC = DC->getParent(); 2003 } 2004 2005 // We didn't find anything, so try to correct for a typo. 2006 TypoCorrection Corrected; 2007 if (S && Out) { 2008 SourceLocation TypoLoc = R.getNameLoc(); 2009 assert(!ExplicitTemplateArgs && 2010 "Diagnosing an empty lookup with explicit template args!"); 2011 *Out = CorrectTypoDelayed( 2012 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC), 2013 [=](const TypoCorrection &TC) { 2014 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2015 diagnostic, diagnostic_suggest); 2016 }, 2017 nullptr, CTK_ErrorRecovery); 2018 if (*Out) 2019 return true; 2020 } else if (S && (Corrected = 2021 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, 2022 &SS, std::move(CCC), CTK_ErrorRecovery))) { 2023 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2024 bool DroppedSpecifier = 2025 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2026 R.setLookupName(Corrected.getCorrection()); 2027 2028 bool AcceptableWithRecovery = false; 2029 bool AcceptableWithoutRecovery = false; 2030 NamedDecl *ND = Corrected.getFoundDecl(); 2031 if (ND) { 2032 if (Corrected.isOverloaded()) { 2033 OverloadCandidateSet OCS(R.getNameLoc(), 2034 OverloadCandidateSet::CSK_Normal); 2035 OverloadCandidateSet::iterator Best; 2036 for (NamedDecl *CD : Corrected) { 2037 if (FunctionTemplateDecl *FTD = 2038 dyn_cast<FunctionTemplateDecl>(CD)) 2039 AddTemplateOverloadCandidate( 2040 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2041 Args, OCS); 2042 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2043 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2044 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2045 Args, OCS); 2046 } 2047 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2048 case OR_Success: 2049 ND = Best->FoundDecl; 2050 Corrected.setCorrectionDecl(ND); 2051 break; 2052 default: 2053 // FIXME: Arbitrarily pick the first declaration for the note. 2054 Corrected.setCorrectionDecl(ND); 2055 break; 2056 } 2057 } 2058 R.addDecl(ND); 2059 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2060 CXXRecordDecl *Record = nullptr; 2061 if (Corrected.getCorrectionSpecifier()) { 2062 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2063 Record = Ty->getAsCXXRecordDecl(); 2064 } 2065 if (!Record) 2066 Record = cast<CXXRecordDecl>( 2067 ND->getDeclContext()->getRedeclContext()); 2068 R.setNamingClass(Record); 2069 } 2070 2071 auto *UnderlyingND = ND->getUnderlyingDecl(); 2072 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2073 isa<FunctionTemplateDecl>(UnderlyingND); 2074 // FIXME: If we ended up with a typo for a type name or 2075 // Objective-C class name, we're in trouble because the parser 2076 // is in the wrong place to recover. Suggest the typo 2077 // correction, but don't make it a fix-it since we're not going 2078 // to recover well anyway. 2079 AcceptableWithoutRecovery = 2080 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND); 2081 } else { 2082 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2083 // because we aren't able to recover. 2084 AcceptableWithoutRecovery = true; 2085 } 2086 2087 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2088 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2089 ? diag::note_implicit_param_decl 2090 : diag::note_previous_decl; 2091 if (SS.isEmpty()) 2092 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2093 PDiag(NoteID), AcceptableWithRecovery); 2094 else 2095 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2096 << Name << computeDeclContext(SS, false) 2097 << DroppedSpecifier << SS.getRange(), 2098 PDiag(NoteID), AcceptableWithRecovery); 2099 2100 // Tell the callee whether to try to recover. 2101 return !AcceptableWithRecovery; 2102 } 2103 } 2104 R.clear(); 2105 2106 // Emit a special diagnostic for failed member lookups. 2107 // FIXME: computing the declaration context might fail here (?) 2108 if (!SS.isEmpty()) { 2109 Diag(R.getNameLoc(), diag::err_no_member) 2110 << Name << computeDeclContext(SS, false) 2111 << SS.getRange(); 2112 return true; 2113 } 2114 2115 // Give up, we can't recover. 2116 Diag(R.getNameLoc(), diagnostic) << Name; 2117 return true; 2118 } 2119 2120 /// In Microsoft mode, if we are inside a template class whose parent class has 2121 /// dependent base classes, and we can't resolve an unqualified identifier, then 2122 /// assume the identifier is a member of a dependent base class. We can only 2123 /// recover successfully in static methods, instance methods, and other contexts 2124 /// where 'this' is available. This doesn't precisely match MSVC's 2125 /// instantiation model, but it's close enough. 2126 static Expr * 2127 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2128 DeclarationNameInfo &NameInfo, 2129 SourceLocation TemplateKWLoc, 2130 const TemplateArgumentListInfo *TemplateArgs) { 2131 // Only try to recover from lookup into dependent bases in static methods or 2132 // contexts where 'this' is available. 2133 QualType ThisType = S.getCurrentThisType(); 2134 const CXXRecordDecl *RD = nullptr; 2135 if (!ThisType.isNull()) 2136 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2137 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2138 RD = MD->getParent(); 2139 if (!RD || !RD->hasAnyDependentBases()) 2140 return nullptr; 2141 2142 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2143 // is available, suggest inserting 'this->' as a fixit. 2144 SourceLocation Loc = NameInfo.getLoc(); 2145 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2146 DB << NameInfo.getName() << RD; 2147 2148 if (!ThisType.isNull()) { 2149 DB << FixItHint::CreateInsertion(Loc, "this->"); 2150 return CXXDependentScopeMemberExpr::Create( 2151 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2152 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2153 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 2154 } 2155 2156 // Synthesize a fake NNS that points to the derived class. This will 2157 // perform name lookup during template instantiation. 2158 CXXScopeSpec SS; 2159 auto *NNS = 2160 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2161 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2162 return DependentScopeDeclRefExpr::Create( 2163 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2164 TemplateArgs); 2165 } 2166 2167 ExprResult 2168 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2169 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2170 bool HasTrailingLParen, bool IsAddressOfOperand, 2171 std::unique_ptr<CorrectionCandidateCallback> CCC, 2172 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2173 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2174 "cannot be direct & operand and have a trailing lparen"); 2175 if (SS.isInvalid()) 2176 return ExprError(); 2177 2178 TemplateArgumentListInfo TemplateArgsBuffer; 2179 2180 // Decompose the UnqualifiedId into the following data. 2181 DeclarationNameInfo NameInfo; 2182 const TemplateArgumentListInfo *TemplateArgs; 2183 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2184 2185 DeclarationName Name = NameInfo.getName(); 2186 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2187 SourceLocation NameLoc = NameInfo.getLoc(); 2188 2189 if (II && II->isEditorPlaceholder()) { 2190 // FIXME: When typed placeholders are supported we can create a typed 2191 // placeholder expression node. 2192 return ExprError(); 2193 } 2194 2195 // C++ [temp.dep.expr]p3: 2196 // An id-expression is type-dependent if it contains: 2197 // -- an identifier that was declared with a dependent type, 2198 // (note: handled after lookup) 2199 // -- a template-id that is dependent, 2200 // (note: handled in BuildTemplateIdExpr) 2201 // -- a conversion-function-id that specifies a dependent type, 2202 // -- a nested-name-specifier that contains a class-name that 2203 // names a dependent type. 2204 // Determine whether this is a member of an unknown specialization; 2205 // we need to handle these differently. 2206 bool DependentID = false; 2207 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2208 Name.getCXXNameType()->isDependentType()) { 2209 DependentID = true; 2210 } else if (SS.isSet()) { 2211 if (DeclContext *DC = computeDeclContext(SS, false)) { 2212 if (RequireCompleteDeclContext(SS, DC)) 2213 return ExprError(); 2214 } else { 2215 DependentID = true; 2216 } 2217 } 2218 2219 if (DependentID) 2220 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2221 IsAddressOfOperand, TemplateArgs); 2222 2223 // Perform the required lookup. 2224 LookupResult R(*this, NameInfo, 2225 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2226 ? LookupObjCImplicitSelfParam 2227 : LookupOrdinaryName); 2228 if (TemplateKWLoc.isValid() || TemplateArgs) { 2229 // Lookup the template name again to correctly establish the context in 2230 // which it was found. This is really unfortunate as we already did the 2231 // lookup to determine that it was a template name in the first place. If 2232 // this becomes a performance hit, we can work harder to preserve those 2233 // results until we get here but it's likely not worth it. 2234 bool MemberOfUnknownSpecialization; 2235 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2236 MemberOfUnknownSpecialization, TemplateKWLoc)) 2237 return ExprError(); 2238 2239 if (MemberOfUnknownSpecialization || 2240 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2241 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2242 IsAddressOfOperand, TemplateArgs); 2243 } else { 2244 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2245 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2246 2247 // If the result might be in a dependent base class, this is a dependent 2248 // id-expression. 2249 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2250 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2251 IsAddressOfOperand, TemplateArgs); 2252 2253 // If this reference is in an Objective-C method, then we need to do 2254 // some special Objective-C lookup, too. 2255 if (IvarLookupFollowUp) { 2256 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2257 if (E.isInvalid()) 2258 return ExprError(); 2259 2260 if (Expr *Ex = E.getAs<Expr>()) 2261 return Ex; 2262 } 2263 } 2264 2265 if (R.isAmbiguous()) 2266 return ExprError(); 2267 2268 // This could be an implicitly declared function reference (legal in C90, 2269 // extension in C99, forbidden in C++). 2270 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2271 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2272 if (D) R.addDecl(D); 2273 } 2274 2275 // Determine whether this name might be a candidate for 2276 // argument-dependent lookup. 2277 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2278 2279 if (R.empty() && !ADL) { 2280 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2281 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2282 TemplateKWLoc, TemplateArgs)) 2283 return E; 2284 } 2285 2286 // Don't diagnose an empty lookup for inline assembly. 2287 if (IsInlineAsmIdentifier) 2288 return ExprError(); 2289 2290 // If this name wasn't predeclared and if this is not a function 2291 // call, diagnose the problem. 2292 TypoExpr *TE = nullptr; 2293 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2294 II, SS.isValid() ? SS.getScopeRep() : nullptr); 2295 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; 2296 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2297 "Typo correction callback misconfigured"); 2298 if (CCC) { 2299 // Make sure the callback knows what the typo being diagnosed is. 2300 CCC->setTypoName(II); 2301 if (SS.isValid()) 2302 CCC->setTypoNNS(SS.getScopeRep()); 2303 } 2304 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2305 // a template name, but we happen to have always already looked up the name 2306 // before we get here if it must be a template name. 2307 if (DiagnoseEmptyLookup(S, SS, R, 2308 CCC ? std::move(CCC) : std::move(DefaultValidator), 2309 nullptr, None, &TE)) { 2310 if (TE && KeywordReplacement) { 2311 auto &State = getTypoExprState(TE); 2312 auto BestTC = State.Consumer->getNextCorrection(); 2313 if (BestTC.isKeyword()) { 2314 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2315 if (State.DiagHandler) 2316 State.DiagHandler(BestTC); 2317 KeywordReplacement->startToken(); 2318 KeywordReplacement->setKind(II->getTokenID()); 2319 KeywordReplacement->setIdentifierInfo(II); 2320 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2321 // Clean up the state associated with the TypoExpr, since it has 2322 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2323 clearDelayedTypo(TE); 2324 // Signal that a correction to a keyword was performed by returning a 2325 // valid-but-null ExprResult. 2326 return (Expr*)nullptr; 2327 } 2328 State.Consumer->resetCorrectionStream(); 2329 } 2330 return TE ? TE : ExprError(); 2331 } 2332 2333 assert(!R.empty() && 2334 "DiagnoseEmptyLookup returned false but added no results"); 2335 2336 // If we found an Objective-C instance variable, let 2337 // LookupInObjCMethod build the appropriate expression to 2338 // reference the ivar. 2339 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2340 R.clear(); 2341 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2342 // In a hopelessly buggy code, Objective-C instance variable 2343 // lookup fails and no expression will be built to reference it. 2344 if (!E.isInvalid() && !E.get()) 2345 return ExprError(); 2346 return E; 2347 } 2348 } 2349 2350 // This is guaranteed from this point on. 2351 assert(!R.empty() || ADL); 2352 2353 // Check whether this might be a C++ implicit instance member access. 2354 // C++ [class.mfct.non-static]p3: 2355 // When an id-expression that is not part of a class member access 2356 // syntax and not used to form a pointer to member is used in the 2357 // body of a non-static member function of class X, if name lookup 2358 // resolves the name in the id-expression to a non-static non-type 2359 // member of some class C, the id-expression is transformed into a 2360 // class member access expression using (*this) as the 2361 // postfix-expression to the left of the . operator. 2362 // 2363 // But we don't actually need to do this for '&' operands if R 2364 // resolved to a function or overloaded function set, because the 2365 // expression is ill-formed if it actually works out to be a 2366 // non-static member function: 2367 // 2368 // C++ [expr.ref]p4: 2369 // Otherwise, if E1.E2 refers to a non-static member function. . . 2370 // [t]he expression can be used only as the left-hand operand of a 2371 // member function call. 2372 // 2373 // There are other safeguards against such uses, but it's important 2374 // to get this right here so that we don't end up making a 2375 // spuriously dependent expression if we're inside a dependent 2376 // instance method. 2377 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2378 bool MightBeImplicitMember; 2379 if (!IsAddressOfOperand) 2380 MightBeImplicitMember = true; 2381 else if (!SS.isEmpty()) 2382 MightBeImplicitMember = false; 2383 else if (R.isOverloadedResult()) 2384 MightBeImplicitMember = false; 2385 else if (R.isUnresolvableResult()) 2386 MightBeImplicitMember = true; 2387 else 2388 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2389 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2390 isa<MSPropertyDecl>(R.getFoundDecl()); 2391 2392 if (MightBeImplicitMember) 2393 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2394 R, TemplateArgs, S); 2395 } 2396 2397 if (TemplateArgs || TemplateKWLoc.isValid()) { 2398 2399 // In C++1y, if this is a variable template id, then check it 2400 // in BuildTemplateIdExpr(). 2401 // The single lookup result must be a variable template declaration. 2402 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2403 Id.TemplateId->Kind == TNK_Var_template) { 2404 assert(R.getAsSingle<VarTemplateDecl>() && 2405 "There should only be one declaration found."); 2406 } 2407 2408 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2409 } 2410 2411 return BuildDeclarationNameExpr(SS, R, ADL); 2412 } 2413 2414 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2415 /// declaration name, generally during template instantiation. 2416 /// There's a large number of things which don't need to be done along 2417 /// this path. 2418 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2419 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2420 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2421 DeclContext *DC = computeDeclContext(SS, false); 2422 if (!DC) 2423 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2424 NameInfo, /*TemplateArgs=*/nullptr); 2425 2426 if (RequireCompleteDeclContext(SS, DC)) 2427 return ExprError(); 2428 2429 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2430 LookupQualifiedName(R, DC); 2431 2432 if (R.isAmbiguous()) 2433 return ExprError(); 2434 2435 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2436 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2437 NameInfo, /*TemplateArgs=*/nullptr); 2438 2439 if (R.empty()) { 2440 Diag(NameInfo.getLoc(), diag::err_no_member) 2441 << NameInfo.getName() << DC << SS.getRange(); 2442 return ExprError(); 2443 } 2444 2445 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2446 // Diagnose a missing typename if this resolved unambiguously to a type in 2447 // a dependent context. If we can recover with a type, downgrade this to 2448 // a warning in Microsoft compatibility mode. 2449 unsigned DiagID = diag::err_typename_missing; 2450 if (RecoveryTSI && getLangOpts().MSVCCompat) 2451 DiagID = diag::ext_typename_missing; 2452 SourceLocation Loc = SS.getBeginLoc(); 2453 auto D = Diag(Loc, DiagID); 2454 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2455 << SourceRange(Loc, NameInfo.getEndLoc()); 2456 2457 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2458 // context. 2459 if (!RecoveryTSI) 2460 return ExprError(); 2461 2462 // Only issue the fixit if we're prepared to recover. 2463 D << FixItHint::CreateInsertion(Loc, "typename "); 2464 2465 // Recover by pretending this was an elaborated type. 2466 QualType Ty = Context.getTypeDeclType(TD); 2467 TypeLocBuilder TLB; 2468 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2469 2470 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2471 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2472 QTL.setElaboratedKeywordLoc(SourceLocation()); 2473 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2474 2475 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2476 2477 return ExprEmpty(); 2478 } 2479 2480 // Defend against this resolving to an implicit member access. We usually 2481 // won't get here if this might be a legitimate a class member (we end up in 2482 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2483 // a pointer-to-member or in an unevaluated context in C++11. 2484 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2485 return BuildPossibleImplicitMemberExpr(SS, 2486 /*TemplateKWLoc=*/SourceLocation(), 2487 R, /*TemplateArgs=*/nullptr, S); 2488 2489 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2490 } 2491 2492 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2493 /// detected that we're currently inside an ObjC method. Perform some 2494 /// additional lookup. 2495 /// 2496 /// Ideally, most of this would be done by lookup, but there's 2497 /// actually quite a lot of extra work involved. 2498 /// 2499 /// Returns a null sentinel to indicate trivial success. 2500 ExprResult 2501 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2502 IdentifierInfo *II, bool AllowBuiltinCreation) { 2503 SourceLocation Loc = Lookup.getNameLoc(); 2504 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2505 2506 // Check for error condition which is already reported. 2507 if (!CurMethod) 2508 return ExprError(); 2509 2510 // There are two cases to handle here. 1) scoped lookup could have failed, 2511 // in which case we should look for an ivar. 2) scoped lookup could have 2512 // found a decl, but that decl is outside the current instance method (i.e. 2513 // a global variable). In these two cases, we do a lookup for an ivar with 2514 // this name, if the lookup sucedes, we replace it our current decl. 2515 2516 // If we're in a class method, we don't normally want to look for 2517 // ivars. But if we don't find anything else, and there's an 2518 // ivar, that's an error. 2519 bool IsClassMethod = CurMethod->isClassMethod(); 2520 2521 bool LookForIvars; 2522 if (Lookup.empty()) 2523 LookForIvars = true; 2524 else if (IsClassMethod) 2525 LookForIvars = false; 2526 else 2527 LookForIvars = (Lookup.isSingleResult() && 2528 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2529 ObjCInterfaceDecl *IFace = nullptr; 2530 if (LookForIvars) { 2531 IFace = CurMethod->getClassInterface(); 2532 ObjCInterfaceDecl *ClassDeclared; 2533 ObjCIvarDecl *IV = nullptr; 2534 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2535 // Diagnose using an ivar in a class method. 2536 if (IsClassMethod) 2537 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2538 << IV->getDeclName()); 2539 2540 // If we're referencing an invalid decl, just return this as a silent 2541 // error node. The error diagnostic was already emitted on the decl. 2542 if (IV->isInvalidDecl()) 2543 return ExprError(); 2544 2545 // Check if referencing a field with __attribute__((deprecated)). 2546 if (DiagnoseUseOfDecl(IV, Loc)) 2547 return ExprError(); 2548 2549 // Diagnose the use of an ivar outside of the declaring class. 2550 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2551 !declaresSameEntity(ClassDeclared, IFace) && 2552 !getLangOpts().DebuggerSupport) 2553 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2554 2555 // FIXME: This should use a new expr for a direct reference, don't 2556 // turn this into Self->ivar, just return a BareIVarExpr or something. 2557 IdentifierInfo &II = Context.Idents.get("self"); 2558 UnqualifiedId SelfName; 2559 SelfName.setIdentifier(&II, SourceLocation()); 2560 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam); 2561 CXXScopeSpec SelfScopeSpec; 2562 SourceLocation TemplateKWLoc; 2563 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2564 SelfName, false, false); 2565 if (SelfExpr.isInvalid()) 2566 return ExprError(); 2567 2568 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2569 if (SelfExpr.isInvalid()) 2570 return ExprError(); 2571 2572 MarkAnyDeclReferenced(Loc, IV, true); 2573 2574 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2575 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2576 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2577 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2578 2579 ObjCIvarRefExpr *Result = new (Context) 2580 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2581 IV->getLocation(), SelfExpr.get(), true, true); 2582 2583 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2584 if (!isUnevaluatedContext() && 2585 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2586 getCurFunction()->recordUseOfWeak(Result); 2587 } 2588 if (getLangOpts().ObjCAutoRefCount) { 2589 if (CurContext->isClosure()) 2590 Diag(Loc, diag::warn_implicitly_retains_self) 2591 << FixItHint::CreateInsertion(Loc, "self->"); 2592 } 2593 2594 return Result; 2595 } 2596 } else if (CurMethod->isInstanceMethod()) { 2597 // We should warn if a local variable hides an ivar. 2598 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2599 ObjCInterfaceDecl *ClassDeclared; 2600 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2601 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2602 declaresSameEntity(IFace, ClassDeclared)) 2603 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2604 } 2605 } 2606 } else if (Lookup.isSingleResult() && 2607 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2608 // If accessing a stand-alone ivar in a class method, this is an error. 2609 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2610 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2611 << IV->getDeclName()); 2612 } 2613 2614 if (Lookup.empty() && II && AllowBuiltinCreation) { 2615 // FIXME. Consolidate this with similar code in LookupName. 2616 if (unsigned BuiltinID = II->getBuiltinID()) { 2617 if (!(getLangOpts().CPlusPlus && 2618 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2619 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2620 S, Lookup.isForRedeclaration(), 2621 Lookup.getNameLoc()); 2622 if (D) Lookup.addDecl(D); 2623 } 2624 } 2625 } 2626 // Sentinel value saying that we didn't do anything special. 2627 return ExprResult((Expr *)nullptr); 2628 } 2629 2630 /// Cast a base object to a member's actual type. 2631 /// 2632 /// Logically this happens in three phases: 2633 /// 2634 /// * First we cast from the base type to the naming class. 2635 /// The naming class is the class into which we were looking 2636 /// when we found the member; it's the qualifier type if a 2637 /// qualifier was provided, and otherwise it's the base type. 2638 /// 2639 /// * Next we cast from the naming class to the declaring class. 2640 /// If the member we found was brought into a class's scope by 2641 /// a using declaration, this is that class; otherwise it's 2642 /// the class declaring the member. 2643 /// 2644 /// * Finally we cast from the declaring class to the "true" 2645 /// declaring class of the member. This conversion does not 2646 /// obey access control. 2647 ExprResult 2648 Sema::PerformObjectMemberConversion(Expr *From, 2649 NestedNameSpecifier *Qualifier, 2650 NamedDecl *FoundDecl, 2651 NamedDecl *Member) { 2652 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2653 if (!RD) 2654 return From; 2655 2656 QualType DestRecordType; 2657 QualType DestType; 2658 QualType FromRecordType; 2659 QualType FromType = From->getType(); 2660 bool PointerConversions = false; 2661 if (isa<FieldDecl>(Member)) { 2662 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2663 2664 if (FromType->getAs<PointerType>()) { 2665 DestType = Context.getPointerType(DestRecordType); 2666 FromRecordType = FromType->getPointeeType(); 2667 PointerConversions = true; 2668 } else { 2669 DestType = DestRecordType; 2670 FromRecordType = FromType; 2671 } 2672 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2673 if (Method->isStatic()) 2674 return From; 2675 2676 DestType = Method->getThisType(); 2677 DestRecordType = DestType->getPointeeType(); 2678 2679 if (FromType->getAs<PointerType>()) { 2680 FromRecordType = FromType->getPointeeType(); 2681 PointerConversions = true; 2682 } else { 2683 FromRecordType = FromType; 2684 DestType = DestRecordType; 2685 } 2686 } else { 2687 // No conversion necessary. 2688 return From; 2689 } 2690 2691 if (DestType->isDependentType() || FromType->isDependentType()) 2692 return From; 2693 2694 // If the unqualified types are the same, no conversion is necessary. 2695 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2696 return From; 2697 2698 SourceRange FromRange = From->getSourceRange(); 2699 SourceLocation FromLoc = FromRange.getBegin(); 2700 2701 ExprValueKind VK = From->getValueKind(); 2702 2703 // C++ [class.member.lookup]p8: 2704 // [...] Ambiguities can often be resolved by qualifying a name with its 2705 // class name. 2706 // 2707 // If the member was a qualified name and the qualified referred to a 2708 // specific base subobject type, we'll cast to that intermediate type 2709 // first and then to the object in which the member is declared. That allows 2710 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2711 // 2712 // class Base { public: int x; }; 2713 // class Derived1 : public Base { }; 2714 // class Derived2 : public Base { }; 2715 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2716 // 2717 // void VeryDerived::f() { 2718 // x = 17; // error: ambiguous base subobjects 2719 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2720 // } 2721 if (Qualifier && Qualifier->getAsType()) { 2722 QualType QType = QualType(Qualifier->getAsType(), 0); 2723 assert(QType->isRecordType() && "lookup done with non-record type"); 2724 2725 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2726 2727 // In C++98, the qualifier type doesn't actually have to be a base 2728 // type of the object type, in which case we just ignore it. 2729 // Otherwise build the appropriate casts. 2730 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2731 CXXCastPath BasePath; 2732 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2733 FromLoc, FromRange, &BasePath)) 2734 return ExprError(); 2735 2736 if (PointerConversions) 2737 QType = Context.getPointerType(QType); 2738 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2739 VK, &BasePath).get(); 2740 2741 FromType = QType; 2742 FromRecordType = QRecordType; 2743 2744 // If the qualifier type was the same as the destination type, 2745 // we're done. 2746 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2747 return From; 2748 } 2749 } 2750 2751 bool IgnoreAccess = false; 2752 2753 // If we actually found the member through a using declaration, cast 2754 // down to the using declaration's type. 2755 // 2756 // Pointer equality is fine here because only one declaration of a 2757 // class ever has member declarations. 2758 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2759 assert(isa<UsingShadowDecl>(FoundDecl)); 2760 QualType URecordType = Context.getTypeDeclType( 2761 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2762 2763 // We only need to do this if the naming-class to declaring-class 2764 // conversion is non-trivial. 2765 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2766 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2767 CXXCastPath BasePath; 2768 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2769 FromLoc, FromRange, &BasePath)) 2770 return ExprError(); 2771 2772 QualType UType = URecordType; 2773 if (PointerConversions) 2774 UType = Context.getPointerType(UType); 2775 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2776 VK, &BasePath).get(); 2777 FromType = UType; 2778 FromRecordType = URecordType; 2779 } 2780 2781 // We don't do access control for the conversion from the 2782 // declaring class to the true declaring class. 2783 IgnoreAccess = true; 2784 } 2785 2786 CXXCastPath BasePath; 2787 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2788 FromLoc, FromRange, &BasePath, 2789 IgnoreAccess)) 2790 return ExprError(); 2791 2792 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2793 VK, &BasePath); 2794 } 2795 2796 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2797 const LookupResult &R, 2798 bool HasTrailingLParen) { 2799 // Only when used directly as the postfix-expression of a call. 2800 if (!HasTrailingLParen) 2801 return false; 2802 2803 // Never if a scope specifier was provided. 2804 if (SS.isSet()) 2805 return false; 2806 2807 // Only in C++ or ObjC++. 2808 if (!getLangOpts().CPlusPlus) 2809 return false; 2810 2811 // Turn off ADL when we find certain kinds of declarations during 2812 // normal lookup: 2813 for (NamedDecl *D : R) { 2814 // C++0x [basic.lookup.argdep]p3: 2815 // -- a declaration of a class member 2816 // Since using decls preserve this property, we check this on the 2817 // original decl. 2818 if (D->isCXXClassMember()) 2819 return false; 2820 2821 // C++0x [basic.lookup.argdep]p3: 2822 // -- a block-scope function declaration that is not a 2823 // using-declaration 2824 // NOTE: we also trigger this for function templates (in fact, we 2825 // don't check the decl type at all, since all other decl types 2826 // turn off ADL anyway). 2827 if (isa<UsingShadowDecl>(D)) 2828 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2829 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2830 return false; 2831 2832 // C++0x [basic.lookup.argdep]p3: 2833 // -- a declaration that is neither a function or a function 2834 // template 2835 // And also for builtin functions. 2836 if (isa<FunctionDecl>(D)) { 2837 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2838 2839 // But also builtin functions. 2840 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2841 return false; 2842 } else if (!isa<FunctionTemplateDecl>(D)) 2843 return false; 2844 } 2845 2846 return true; 2847 } 2848 2849 2850 /// Diagnoses obvious problems with the use of the given declaration 2851 /// as an expression. This is only actually called for lookups that 2852 /// were not overloaded, and it doesn't promise that the declaration 2853 /// will in fact be used. 2854 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2855 if (D->isInvalidDecl()) 2856 return true; 2857 2858 if (isa<TypedefNameDecl>(D)) { 2859 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2860 return true; 2861 } 2862 2863 if (isa<ObjCInterfaceDecl>(D)) { 2864 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2865 return true; 2866 } 2867 2868 if (isa<NamespaceDecl>(D)) { 2869 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2870 return true; 2871 } 2872 2873 return false; 2874 } 2875 2876 // Certain multiversion types should be treated as overloaded even when there is 2877 // only one result. 2878 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 2879 assert(R.isSingleResult() && "Expected only a single result"); 2880 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 2881 return FD && 2882 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 2883 } 2884 2885 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2886 LookupResult &R, bool NeedsADL, 2887 bool AcceptInvalidDecl) { 2888 // If this is a single, fully-resolved result and we don't need ADL, 2889 // just build an ordinary singleton decl ref. 2890 if (!NeedsADL && R.isSingleResult() && 2891 !R.getAsSingle<FunctionTemplateDecl>() && 2892 !ShouldLookupResultBeMultiVersionOverload(R)) 2893 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2894 R.getRepresentativeDecl(), nullptr, 2895 AcceptInvalidDecl); 2896 2897 // We only need to check the declaration if there's exactly one 2898 // result, because in the overloaded case the results can only be 2899 // functions and function templates. 2900 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 2901 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2902 return ExprError(); 2903 2904 // Otherwise, just build an unresolved lookup expression. Suppress 2905 // any lookup-related diagnostics; we'll hash these out later, when 2906 // we've picked a target. 2907 R.suppressDiagnostics(); 2908 2909 UnresolvedLookupExpr *ULE 2910 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2911 SS.getWithLocInContext(Context), 2912 R.getLookupNameInfo(), 2913 NeedsADL, R.isOverloadedResult(), 2914 R.begin(), R.end()); 2915 2916 return ULE; 2917 } 2918 2919 static void 2920 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 2921 ValueDecl *var, DeclContext *DC); 2922 2923 /// Complete semantic analysis for a reference to the given declaration. 2924 ExprResult Sema::BuildDeclarationNameExpr( 2925 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2926 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2927 bool AcceptInvalidDecl) { 2928 assert(D && "Cannot refer to a NULL declaration"); 2929 assert(!isa<FunctionTemplateDecl>(D) && 2930 "Cannot refer unambiguously to a function template"); 2931 2932 SourceLocation Loc = NameInfo.getLoc(); 2933 if (CheckDeclInExpr(*this, Loc, D)) 2934 return ExprError(); 2935 2936 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2937 // Specifically diagnose references to class templates that are missing 2938 // a template argument list. 2939 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 2940 return ExprError(); 2941 } 2942 2943 // Make sure that we're referring to a value. 2944 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2945 if (!VD) { 2946 Diag(Loc, diag::err_ref_non_value) 2947 << D << SS.getRange(); 2948 Diag(D->getLocation(), diag::note_declared_at); 2949 return ExprError(); 2950 } 2951 2952 // Check whether this declaration can be used. Note that we suppress 2953 // this check when we're going to perform argument-dependent lookup 2954 // on this function name, because this might not be the function 2955 // that overload resolution actually selects. 2956 if (DiagnoseUseOfDecl(VD, Loc)) 2957 return ExprError(); 2958 2959 // Only create DeclRefExpr's for valid Decl's. 2960 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2961 return ExprError(); 2962 2963 // Handle members of anonymous structs and unions. If we got here, 2964 // and the reference is to a class member indirect field, then this 2965 // must be the subject of a pointer-to-member expression. 2966 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2967 if (!indirectField->isCXXClassMember()) 2968 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2969 indirectField); 2970 2971 { 2972 QualType type = VD->getType(); 2973 if (type.isNull()) 2974 return ExprError(); 2975 if (auto *FPT = type->getAs<FunctionProtoType>()) { 2976 // C++ [except.spec]p17: 2977 // An exception-specification is considered to be needed when: 2978 // - in an expression, the function is the unique lookup result or 2979 // the selected member of a set of overloaded functions. 2980 ResolveExceptionSpec(Loc, FPT); 2981 type = VD->getType(); 2982 } 2983 ExprValueKind valueKind = VK_RValue; 2984 2985 switch (D->getKind()) { 2986 // Ignore all the non-ValueDecl kinds. 2987 #define ABSTRACT_DECL(kind) 2988 #define VALUE(type, base) 2989 #define DECL(type, base) \ 2990 case Decl::type: 2991 #include "clang/AST/DeclNodes.inc" 2992 llvm_unreachable("invalid value decl kind"); 2993 2994 // These shouldn't make it here. 2995 case Decl::ObjCAtDefsField: 2996 case Decl::ObjCIvar: 2997 llvm_unreachable("forming non-member reference to ivar?"); 2998 2999 // Enum constants are always r-values and never references. 3000 // Unresolved using declarations are dependent. 3001 case Decl::EnumConstant: 3002 case Decl::UnresolvedUsingValue: 3003 case Decl::OMPDeclareReduction: 3004 case Decl::OMPDeclareMapper: 3005 valueKind = VK_RValue; 3006 break; 3007 3008 // Fields and indirect fields that got here must be for 3009 // pointer-to-member expressions; we just call them l-values for 3010 // internal consistency, because this subexpression doesn't really 3011 // exist in the high-level semantics. 3012 case Decl::Field: 3013 case Decl::IndirectField: 3014 assert(getLangOpts().CPlusPlus && 3015 "building reference to field in C?"); 3016 3017 // These can't have reference type in well-formed programs, but 3018 // for internal consistency we do this anyway. 3019 type = type.getNonReferenceType(); 3020 valueKind = VK_LValue; 3021 break; 3022 3023 // Non-type template parameters are either l-values or r-values 3024 // depending on the type. 3025 case Decl::NonTypeTemplateParm: { 3026 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3027 type = reftype->getPointeeType(); 3028 valueKind = VK_LValue; // even if the parameter is an r-value reference 3029 break; 3030 } 3031 3032 // For non-references, we need to strip qualifiers just in case 3033 // the template parameter was declared as 'const int' or whatever. 3034 valueKind = VK_RValue; 3035 type = type.getUnqualifiedType(); 3036 break; 3037 } 3038 3039 case Decl::Var: 3040 case Decl::VarTemplateSpecialization: 3041 case Decl::VarTemplatePartialSpecialization: 3042 case Decl::Decomposition: 3043 case Decl::OMPCapturedExpr: 3044 // In C, "extern void blah;" is valid and is an r-value. 3045 if (!getLangOpts().CPlusPlus && 3046 !type.hasQualifiers() && 3047 type->isVoidType()) { 3048 valueKind = VK_RValue; 3049 break; 3050 } 3051 LLVM_FALLTHROUGH; 3052 3053 case Decl::ImplicitParam: 3054 case Decl::ParmVar: { 3055 // These are always l-values. 3056 valueKind = VK_LValue; 3057 type = type.getNonReferenceType(); 3058 3059 // FIXME: Does the addition of const really only apply in 3060 // potentially-evaluated contexts? Since the variable isn't actually 3061 // captured in an unevaluated context, it seems that the answer is no. 3062 if (!isUnevaluatedContext()) { 3063 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3064 if (!CapturedType.isNull()) 3065 type = CapturedType; 3066 } 3067 3068 break; 3069 } 3070 3071 case Decl::Binding: { 3072 // These are always lvalues. 3073 valueKind = VK_LValue; 3074 type = type.getNonReferenceType(); 3075 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3076 // decides how that's supposed to work. 3077 auto *BD = cast<BindingDecl>(VD); 3078 if (BD->getDeclContext()->isFunctionOrMethod() && 3079 BD->getDeclContext() != CurContext) 3080 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 3081 break; 3082 } 3083 3084 case Decl::Function: { 3085 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3086 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3087 type = Context.BuiltinFnTy; 3088 valueKind = VK_RValue; 3089 break; 3090 } 3091 } 3092 3093 const FunctionType *fty = type->castAs<FunctionType>(); 3094 3095 // If we're referring to a function with an __unknown_anytype 3096 // result type, make the entire expression __unknown_anytype. 3097 if (fty->getReturnType() == Context.UnknownAnyTy) { 3098 type = Context.UnknownAnyTy; 3099 valueKind = VK_RValue; 3100 break; 3101 } 3102 3103 // Functions are l-values in C++. 3104 if (getLangOpts().CPlusPlus) { 3105 valueKind = VK_LValue; 3106 break; 3107 } 3108 3109 // C99 DR 316 says that, if a function type comes from a 3110 // function definition (without a prototype), that type is only 3111 // used for checking compatibility. Therefore, when referencing 3112 // the function, we pretend that we don't have the full function 3113 // type. 3114 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3115 isa<FunctionProtoType>(fty)) 3116 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3117 fty->getExtInfo()); 3118 3119 // Functions are r-values in C. 3120 valueKind = VK_RValue; 3121 break; 3122 } 3123 3124 case Decl::CXXDeductionGuide: 3125 llvm_unreachable("building reference to deduction guide"); 3126 3127 case Decl::MSProperty: 3128 valueKind = VK_LValue; 3129 break; 3130 3131 case Decl::CXXMethod: 3132 // If we're referring to a method with an __unknown_anytype 3133 // result type, make the entire expression __unknown_anytype. 3134 // This should only be possible with a type written directly. 3135 if (const FunctionProtoType *proto 3136 = dyn_cast<FunctionProtoType>(VD->getType())) 3137 if (proto->getReturnType() == Context.UnknownAnyTy) { 3138 type = Context.UnknownAnyTy; 3139 valueKind = VK_RValue; 3140 break; 3141 } 3142 3143 // C++ methods are l-values if static, r-values if non-static. 3144 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3145 valueKind = VK_LValue; 3146 break; 3147 } 3148 LLVM_FALLTHROUGH; 3149 3150 case Decl::CXXConversion: 3151 case Decl::CXXDestructor: 3152 case Decl::CXXConstructor: 3153 valueKind = VK_RValue; 3154 break; 3155 } 3156 3157 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3158 TemplateArgs); 3159 } 3160 } 3161 3162 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3163 SmallString<32> &Target) { 3164 Target.resize(CharByteWidth * (Source.size() + 1)); 3165 char *ResultPtr = &Target[0]; 3166 const llvm::UTF8 *ErrorPtr; 3167 bool success = 3168 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3169 (void)success; 3170 assert(success); 3171 Target.resize(ResultPtr - &Target[0]); 3172 } 3173 3174 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3175 PredefinedExpr::IdentKind IK) { 3176 // Pick the current block, lambda, captured statement or function. 3177 Decl *currentDecl = nullptr; 3178 if (const BlockScopeInfo *BSI = getCurBlock()) 3179 currentDecl = BSI->TheDecl; 3180 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3181 currentDecl = LSI->CallOperator; 3182 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3183 currentDecl = CSI->TheCapturedDecl; 3184 else 3185 currentDecl = getCurFunctionOrMethodDecl(); 3186 3187 if (!currentDecl) { 3188 Diag(Loc, diag::ext_predef_outside_function); 3189 currentDecl = Context.getTranslationUnitDecl(); 3190 } 3191 3192 QualType ResTy; 3193 StringLiteral *SL = nullptr; 3194 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3195 ResTy = Context.DependentTy; 3196 else { 3197 // Pre-defined identifiers are of type char[x], where x is the length of 3198 // the string. 3199 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3200 unsigned Length = Str.length(); 3201 3202 llvm::APInt LengthI(32, Length + 1); 3203 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3204 ResTy = 3205 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3206 SmallString<32> RawChars; 3207 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3208 Str, RawChars); 3209 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3210 /*IndexTypeQuals*/ 0); 3211 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3212 /*Pascal*/ false, ResTy, Loc); 3213 } else { 3214 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3215 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3216 /*IndexTypeQuals*/ 0); 3217 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3218 /*Pascal*/ false, ResTy, Loc); 3219 } 3220 } 3221 3222 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3223 } 3224 3225 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3226 PredefinedExpr::IdentKind IK; 3227 3228 switch (Kind) { 3229 default: llvm_unreachable("Unknown simple primary expr!"); 3230 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3231 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3232 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3233 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3234 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3235 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3236 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3237 } 3238 3239 return BuildPredefinedExpr(Loc, IK); 3240 } 3241 3242 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3243 SmallString<16> CharBuffer; 3244 bool Invalid = false; 3245 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3246 if (Invalid) 3247 return ExprError(); 3248 3249 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3250 PP, Tok.getKind()); 3251 if (Literal.hadError()) 3252 return ExprError(); 3253 3254 QualType Ty; 3255 if (Literal.isWide()) 3256 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3257 else if (Literal.isUTF8() && getLangOpts().Char8) 3258 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3259 else if (Literal.isUTF16()) 3260 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3261 else if (Literal.isUTF32()) 3262 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3263 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3264 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3265 else 3266 Ty = Context.CharTy; // 'x' -> char in C++ 3267 3268 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3269 if (Literal.isWide()) 3270 Kind = CharacterLiteral::Wide; 3271 else if (Literal.isUTF16()) 3272 Kind = CharacterLiteral::UTF16; 3273 else if (Literal.isUTF32()) 3274 Kind = CharacterLiteral::UTF32; 3275 else if (Literal.isUTF8()) 3276 Kind = CharacterLiteral::UTF8; 3277 3278 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3279 Tok.getLocation()); 3280 3281 if (Literal.getUDSuffix().empty()) 3282 return Lit; 3283 3284 // We're building a user-defined literal. 3285 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3286 SourceLocation UDSuffixLoc = 3287 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3288 3289 // Make sure we're allowed user-defined literals here. 3290 if (!UDLScope) 3291 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3292 3293 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3294 // operator "" X (ch) 3295 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3296 Lit, Tok.getLocation()); 3297 } 3298 3299 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3300 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3301 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3302 Context.IntTy, Loc); 3303 } 3304 3305 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3306 QualType Ty, SourceLocation Loc) { 3307 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3308 3309 using llvm::APFloat; 3310 APFloat Val(Format); 3311 3312 APFloat::opStatus result = Literal.GetFloatValue(Val); 3313 3314 // Overflow is always an error, but underflow is only an error if 3315 // we underflowed to zero (APFloat reports denormals as underflow). 3316 if ((result & APFloat::opOverflow) || 3317 ((result & APFloat::opUnderflow) && Val.isZero())) { 3318 unsigned diagnostic; 3319 SmallString<20> buffer; 3320 if (result & APFloat::opOverflow) { 3321 diagnostic = diag::warn_float_overflow; 3322 APFloat::getLargest(Format).toString(buffer); 3323 } else { 3324 diagnostic = diag::warn_float_underflow; 3325 APFloat::getSmallest(Format).toString(buffer); 3326 } 3327 3328 S.Diag(Loc, diagnostic) 3329 << Ty 3330 << StringRef(buffer.data(), buffer.size()); 3331 } 3332 3333 bool isExact = (result == APFloat::opOK); 3334 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3335 } 3336 3337 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3338 assert(E && "Invalid expression"); 3339 3340 if (E->isValueDependent()) 3341 return false; 3342 3343 QualType QT = E->getType(); 3344 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3345 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3346 return true; 3347 } 3348 3349 llvm::APSInt ValueAPS; 3350 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3351 3352 if (R.isInvalid()) 3353 return true; 3354 3355 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3356 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3357 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3358 << ValueAPS.toString(10) << ValueIsPositive; 3359 return true; 3360 } 3361 3362 return false; 3363 } 3364 3365 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3366 // Fast path for a single digit (which is quite common). A single digit 3367 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3368 if (Tok.getLength() == 1) { 3369 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3370 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3371 } 3372 3373 SmallString<128> SpellingBuffer; 3374 // NumericLiteralParser wants to overread by one character. Add padding to 3375 // the buffer in case the token is copied to the buffer. If getSpelling() 3376 // returns a StringRef to the memory buffer, it should have a null char at 3377 // the EOF, so it is also safe. 3378 SpellingBuffer.resize(Tok.getLength() + 1); 3379 3380 // Get the spelling of the token, which eliminates trigraphs, etc. 3381 bool Invalid = false; 3382 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3383 if (Invalid) 3384 return ExprError(); 3385 3386 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3387 if (Literal.hadError) 3388 return ExprError(); 3389 3390 if (Literal.hasUDSuffix()) { 3391 // We're building a user-defined literal. 3392 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3393 SourceLocation UDSuffixLoc = 3394 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3395 3396 // Make sure we're allowed user-defined literals here. 3397 if (!UDLScope) 3398 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3399 3400 QualType CookedTy; 3401 if (Literal.isFloatingLiteral()) { 3402 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3403 // long double, the literal is treated as a call of the form 3404 // operator "" X (f L) 3405 CookedTy = Context.LongDoubleTy; 3406 } else { 3407 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3408 // unsigned long long, the literal is treated as a call of the form 3409 // operator "" X (n ULL) 3410 CookedTy = Context.UnsignedLongLongTy; 3411 } 3412 3413 DeclarationName OpName = 3414 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3415 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3416 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3417 3418 SourceLocation TokLoc = Tok.getLocation(); 3419 3420 // Perform literal operator lookup to determine if we're building a raw 3421 // literal or a cooked one. 3422 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3423 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3424 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3425 /*AllowStringTemplate*/ false, 3426 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3427 case LOLR_ErrorNoDiagnostic: 3428 // Lookup failure for imaginary constants isn't fatal, there's still the 3429 // GNU extension producing _Complex types. 3430 break; 3431 case LOLR_Error: 3432 return ExprError(); 3433 case LOLR_Cooked: { 3434 Expr *Lit; 3435 if (Literal.isFloatingLiteral()) { 3436 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3437 } else { 3438 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3439 if (Literal.GetIntegerValue(ResultVal)) 3440 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3441 << /* Unsigned */ 1; 3442 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3443 Tok.getLocation()); 3444 } 3445 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3446 } 3447 3448 case LOLR_Raw: { 3449 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3450 // literal is treated as a call of the form 3451 // operator "" X ("n") 3452 unsigned Length = Literal.getUDSuffixOffset(); 3453 QualType StrTy = Context.getConstantArrayType( 3454 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3455 llvm::APInt(32, Length + 1), ArrayType::Normal, 0); 3456 Expr *Lit = StringLiteral::Create( 3457 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3458 /*Pascal*/false, StrTy, &TokLoc, 1); 3459 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3460 } 3461 3462 case LOLR_Template: { 3463 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3464 // template), L is treated as a call fo the form 3465 // operator "" X <'c1', 'c2', ... 'ck'>() 3466 // where n is the source character sequence c1 c2 ... ck. 3467 TemplateArgumentListInfo ExplicitArgs; 3468 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3469 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3470 llvm::APSInt Value(CharBits, CharIsUnsigned); 3471 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3472 Value = TokSpelling[I]; 3473 TemplateArgument Arg(Context, Value, Context.CharTy); 3474 TemplateArgumentLocInfo ArgInfo; 3475 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3476 } 3477 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3478 &ExplicitArgs); 3479 } 3480 case LOLR_StringTemplate: 3481 llvm_unreachable("unexpected literal operator lookup result"); 3482 } 3483 } 3484 3485 Expr *Res; 3486 3487 if (Literal.isFixedPointLiteral()) { 3488 QualType Ty; 3489 3490 if (Literal.isAccum) { 3491 if (Literal.isHalf) { 3492 Ty = Context.ShortAccumTy; 3493 } else if (Literal.isLong) { 3494 Ty = Context.LongAccumTy; 3495 } else { 3496 Ty = Context.AccumTy; 3497 } 3498 } else if (Literal.isFract) { 3499 if (Literal.isHalf) { 3500 Ty = Context.ShortFractTy; 3501 } else if (Literal.isLong) { 3502 Ty = Context.LongFractTy; 3503 } else { 3504 Ty = Context.FractTy; 3505 } 3506 } 3507 3508 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3509 3510 bool isSigned = !Literal.isUnsigned; 3511 unsigned scale = Context.getFixedPointScale(Ty); 3512 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3513 3514 llvm::APInt Val(bit_width, 0, isSigned); 3515 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3516 bool ValIsZero = Val.isNullValue() && !Overflowed; 3517 3518 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3519 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3520 // Clause 6.4.4 - The value of a constant shall be in the range of 3521 // representable values for its type, with exception for constants of a 3522 // fract type with a value of exactly 1; such a constant shall denote 3523 // the maximal value for the type. 3524 --Val; 3525 else if (Val.ugt(MaxVal) || Overflowed) 3526 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3527 3528 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3529 Tok.getLocation(), scale); 3530 } else if (Literal.isFloatingLiteral()) { 3531 QualType Ty; 3532 if (Literal.isHalf){ 3533 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3534 Ty = Context.HalfTy; 3535 else { 3536 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3537 return ExprError(); 3538 } 3539 } else if (Literal.isFloat) 3540 Ty = Context.FloatTy; 3541 else if (Literal.isLong) 3542 Ty = Context.LongDoubleTy; 3543 else if (Literal.isFloat16) 3544 Ty = Context.Float16Ty; 3545 else if (Literal.isFloat128) 3546 Ty = Context.Float128Ty; 3547 else 3548 Ty = Context.DoubleTy; 3549 3550 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3551 3552 if (Ty == Context.DoubleTy) { 3553 if (getLangOpts().SinglePrecisionConstants) { 3554 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3555 if (BTy->getKind() != BuiltinType::Float) { 3556 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3557 } 3558 } else if (getLangOpts().OpenCL && 3559 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3560 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3561 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3562 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3563 } 3564 } 3565 } else if (!Literal.isIntegerLiteral()) { 3566 return ExprError(); 3567 } else { 3568 QualType Ty; 3569 3570 // 'long long' is a C99 or C++11 feature. 3571 if (!getLangOpts().C99 && Literal.isLongLong) { 3572 if (getLangOpts().CPlusPlus) 3573 Diag(Tok.getLocation(), 3574 getLangOpts().CPlusPlus11 ? 3575 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3576 else 3577 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3578 } 3579 3580 // Get the value in the widest-possible width. 3581 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3582 llvm::APInt ResultVal(MaxWidth, 0); 3583 3584 if (Literal.GetIntegerValue(ResultVal)) { 3585 // If this value didn't fit into uintmax_t, error and force to ull. 3586 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3587 << /* Unsigned */ 1; 3588 Ty = Context.UnsignedLongLongTy; 3589 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3590 "long long is not intmax_t?"); 3591 } else { 3592 // If this value fits into a ULL, try to figure out what else it fits into 3593 // according to the rules of C99 6.4.4.1p5. 3594 3595 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3596 // be an unsigned int. 3597 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3598 3599 // Check from smallest to largest, picking the smallest type we can. 3600 unsigned Width = 0; 3601 3602 // Microsoft specific integer suffixes are explicitly sized. 3603 if (Literal.MicrosoftInteger) { 3604 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3605 Width = 8; 3606 Ty = Context.CharTy; 3607 } else { 3608 Width = Literal.MicrosoftInteger; 3609 Ty = Context.getIntTypeForBitwidth(Width, 3610 /*Signed=*/!Literal.isUnsigned); 3611 } 3612 } 3613 3614 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3615 // Are int/unsigned possibilities? 3616 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3617 3618 // Does it fit in a unsigned int? 3619 if (ResultVal.isIntN(IntSize)) { 3620 // Does it fit in a signed int? 3621 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3622 Ty = Context.IntTy; 3623 else if (AllowUnsigned) 3624 Ty = Context.UnsignedIntTy; 3625 Width = IntSize; 3626 } 3627 } 3628 3629 // Are long/unsigned long possibilities? 3630 if (Ty.isNull() && !Literal.isLongLong) { 3631 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3632 3633 // Does it fit in a unsigned long? 3634 if (ResultVal.isIntN(LongSize)) { 3635 // Does it fit in a signed long? 3636 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3637 Ty = Context.LongTy; 3638 else if (AllowUnsigned) 3639 Ty = Context.UnsignedLongTy; 3640 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3641 // is compatible. 3642 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3643 const unsigned LongLongSize = 3644 Context.getTargetInfo().getLongLongWidth(); 3645 Diag(Tok.getLocation(), 3646 getLangOpts().CPlusPlus 3647 ? Literal.isLong 3648 ? diag::warn_old_implicitly_unsigned_long_cxx 3649 : /*C++98 UB*/ diag:: 3650 ext_old_implicitly_unsigned_long_cxx 3651 : diag::warn_old_implicitly_unsigned_long) 3652 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3653 : /*will be ill-formed*/ 1); 3654 Ty = Context.UnsignedLongTy; 3655 } 3656 Width = LongSize; 3657 } 3658 } 3659 3660 // Check long long if needed. 3661 if (Ty.isNull()) { 3662 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3663 3664 // Does it fit in a unsigned long long? 3665 if (ResultVal.isIntN(LongLongSize)) { 3666 // Does it fit in a signed long long? 3667 // To be compatible with MSVC, hex integer literals ending with the 3668 // LL or i64 suffix are always signed in Microsoft mode. 3669 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3670 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3671 Ty = Context.LongLongTy; 3672 else if (AllowUnsigned) 3673 Ty = Context.UnsignedLongLongTy; 3674 Width = LongLongSize; 3675 } 3676 } 3677 3678 // If we still couldn't decide a type, we probably have something that 3679 // does not fit in a signed long long, but has no U suffix. 3680 if (Ty.isNull()) { 3681 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3682 Ty = Context.UnsignedLongLongTy; 3683 Width = Context.getTargetInfo().getLongLongWidth(); 3684 } 3685 3686 if (ResultVal.getBitWidth() != Width) 3687 ResultVal = ResultVal.trunc(Width); 3688 } 3689 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3690 } 3691 3692 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3693 if (Literal.isImaginary) { 3694 Res = new (Context) ImaginaryLiteral(Res, 3695 Context.getComplexType(Res->getType())); 3696 3697 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3698 } 3699 return Res; 3700 } 3701 3702 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3703 assert(E && "ActOnParenExpr() missing expr"); 3704 return new (Context) ParenExpr(L, R, E); 3705 } 3706 3707 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3708 SourceLocation Loc, 3709 SourceRange ArgRange) { 3710 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3711 // scalar or vector data type argument..." 3712 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3713 // type (C99 6.2.5p18) or void. 3714 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3715 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3716 << T << ArgRange; 3717 return true; 3718 } 3719 3720 assert((T->isVoidType() || !T->isIncompleteType()) && 3721 "Scalar types should always be complete"); 3722 return false; 3723 } 3724 3725 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3726 SourceLocation Loc, 3727 SourceRange ArgRange, 3728 UnaryExprOrTypeTrait TraitKind) { 3729 // Invalid types must be hard errors for SFINAE in C++. 3730 if (S.LangOpts.CPlusPlus) 3731 return true; 3732 3733 // C99 6.5.3.4p1: 3734 if (T->isFunctionType() && 3735 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 3736 TraitKind == UETT_PreferredAlignOf)) { 3737 // sizeof(function)/alignof(function) is allowed as an extension. 3738 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3739 << TraitKind << ArgRange; 3740 return false; 3741 } 3742 3743 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3744 // this is an error (OpenCL v1.1 s6.3.k) 3745 if (T->isVoidType()) { 3746 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3747 : diag::ext_sizeof_alignof_void_type; 3748 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3749 return false; 3750 } 3751 3752 return true; 3753 } 3754 3755 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3756 SourceLocation Loc, 3757 SourceRange ArgRange, 3758 UnaryExprOrTypeTrait TraitKind) { 3759 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3760 // runtime doesn't allow it. 3761 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3762 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3763 << T << (TraitKind == UETT_SizeOf) 3764 << ArgRange; 3765 return true; 3766 } 3767 3768 return false; 3769 } 3770 3771 /// Check whether E is a pointer from a decayed array type (the decayed 3772 /// pointer type is equal to T) and emit a warning if it is. 3773 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3774 Expr *E) { 3775 // Don't warn if the operation changed the type. 3776 if (T != E->getType()) 3777 return; 3778 3779 // Now look for array decays. 3780 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3781 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3782 return; 3783 3784 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3785 << ICE->getType() 3786 << ICE->getSubExpr()->getType(); 3787 } 3788 3789 /// Check the constraints on expression operands to unary type expression 3790 /// and type traits. 3791 /// 3792 /// Completes any types necessary and validates the constraints on the operand 3793 /// expression. The logic mostly mirrors the type-based overload, but may modify 3794 /// the expression as it completes the type for that expression through template 3795 /// instantiation, etc. 3796 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3797 UnaryExprOrTypeTrait ExprKind) { 3798 QualType ExprTy = E->getType(); 3799 assert(!ExprTy->isReferenceType()); 3800 3801 if (ExprKind == UETT_VecStep) 3802 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3803 E->getSourceRange()); 3804 3805 // Whitelist some types as extensions 3806 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3807 E->getSourceRange(), ExprKind)) 3808 return false; 3809 3810 // 'alignof' applied to an expression only requires the base element type of 3811 // the expression to be complete. 'sizeof' requires the expression's type to 3812 // be complete (and will attempt to complete it if it's an array of unknown 3813 // bound). 3814 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 3815 if (RequireCompleteType(E->getExprLoc(), 3816 Context.getBaseElementType(E->getType()), 3817 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3818 E->getSourceRange())) 3819 return true; 3820 } else { 3821 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3822 ExprKind, E->getSourceRange())) 3823 return true; 3824 } 3825 3826 // Completing the expression's type may have changed it. 3827 ExprTy = E->getType(); 3828 assert(!ExprTy->isReferenceType()); 3829 3830 if (ExprTy->isFunctionType()) { 3831 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3832 << ExprKind << E->getSourceRange(); 3833 return true; 3834 } 3835 3836 // The operand for sizeof and alignof is in an unevaluated expression context, 3837 // so side effects could result in unintended consequences. 3838 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 3839 ExprKind == UETT_PreferredAlignOf) && 3840 !inTemplateInstantiation() && E->HasSideEffects(Context, false)) 3841 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3842 3843 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3844 E->getSourceRange(), ExprKind)) 3845 return true; 3846 3847 if (ExprKind == UETT_SizeOf) { 3848 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3849 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3850 QualType OType = PVD->getOriginalType(); 3851 QualType Type = PVD->getType(); 3852 if (Type->isPointerType() && OType->isArrayType()) { 3853 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3854 << Type << OType; 3855 Diag(PVD->getLocation(), diag::note_declared_at); 3856 } 3857 } 3858 } 3859 3860 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3861 // decays into a pointer and returns an unintended result. This is most 3862 // likely a typo for "sizeof(array) op x". 3863 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3864 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3865 BO->getLHS()); 3866 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3867 BO->getRHS()); 3868 } 3869 } 3870 3871 return false; 3872 } 3873 3874 /// Check the constraints on operands to unary expression and type 3875 /// traits. 3876 /// 3877 /// This will complete any types necessary, and validate the various constraints 3878 /// on those operands. 3879 /// 3880 /// The UsualUnaryConversions() function is *not* called by this routine. 3881 /// C99 6.3.2.1p[2-4] all state: 3882 /// Except when it is the operand of the sizeof operator ... 3883 /// 3884 /// C++ [expr.sizeof]p4 3885 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3886 /// standard conversions are not applied to the operand of sizeof. 3887 /// 3888 /// This policy is followed for all of the unary trait expressions. 3889 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3890 SourceLocation OpLoc, 3891 SourceRange ExprRange, 3892 UnaryExprOrTypeTrait ExprKind) { 3893 if (ExprType->isDependentType()) 3894 return false; 3895 3896 // C++ [expr.sizeof]p2: 3897 // When applied to a reference or a reference type, the result 3898 // is the size of the referenced type. 3899 // C++11 [expr.alignof]p3: 3900 // When alignof is applied to a reference type, the result 3901 // shall be the alignment of the referenced type. 3902 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3903 ExprType = Ref->getPointeeType(); 3904 3905 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3906 // When alignof or _Alignof is applied to an array type, the result 3907 // is the alignment of the element type. 3908 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 3909 ExprKind == UETT_OpenMPRequiredSimdAlign) 3910 ExprType = Context.getBaseElementType(ExprType); 3911 3912 if (ExprKind == UETT_VecStep) 3913 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3914 3915 // Whitelist some types as extensions 3916 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3917 ExprKind)) 3918 return false; 3919 3920 if (RequireCompleteType(OpLoc, ExprType, 3921 diag::err_sizeof_alignof_incomplete_type, 3922 ExprKind, ExprRange)) 3923 return true; 3924 3925 if (ExprType->isFunctionType()) { 3926 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3927 << ExprKind << ExprRange; 3928 return true; 3929 } 3930 3931 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3932 ExprKind)) 3933 return true; 3934 3935 return false; 3936 } 3937 3938 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 3939 E = E->IgnoreParens(); 3940 3941 // Cannot know anything else if the expression is dependent. 3942 if (E->isTypeDependent()) 3943 return false; 3944 3945 if (E->getObjectKind() == OK_BitField) { 3946 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3947 << 1 << E->getSourceRange(); 3948 return true; 3949 } 3950 3951 ValueDecl *D = nullptr; 3952 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3953 D = DRE->getDecl(); 3954 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3955 D = ME->getMemberDecl(); 3956 } 3957 3958 // If it's a field, require the containing struct to have a 3959 // complete definition so that we can compute the layout. 3960 // 3961 // This can happen in C++11 onwards, either by naming the member 3962 // in a way that is not transformed into a member access expression 3963 // (in an unevaluated operand, for instance), or by naming the member 3964 // in a trailing-return-type. 3965 // 3966 // For the record, since __alignof__ on expressions is a GCC 3967 // extension, GCC seems to permit this but always gives the 3968 // nonsensical answer 0. 3969 // 3970 // We don't really need the layout here --- we could instead just 3971 // directly check for all the appropriate alignment-lowing 3972 // attributes --- but that would require duplicating a lot of 3973 // logic that just isn't worth duplicating for such a marginal 3974 // use-case. 3975 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3976 // Fast path this check, since we at least know the record has a 3977 // definition if we can find a member of it. 3978 if (!FD->getParent()->isCompleteDefinition()) { 3979 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3980 << E->getSourceRange(); 3981 return true; 3982 } 3983 3984 // Otherwise, if it's a field, and the field doesn't have 3985 // reference type, then it must have a complete type (or be a 3986 // flexible array member, which we explicitly want to 3987 // white-list anyway), which makes the following checks trivial. 3988 if (!FD->getType()->isReferenceType()) 3989 return false; 3990 } 3991 3992 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 3993 } 3994 3995 bool Sema::CheckVecStepExpr(Expr *E) { 3996 E = E->IgnoreParens(); 3997 3998 // Cannot know anything else if the expression is dependent. 3999 if (E->isTypeDependent()) 4000 return false; 4001 4002 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4003 } 4004 4005 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4006 CapturingScopeInfo *CSI) { 4007 assert(T->isVariablyModifiedType()); 4008 assert(CSI != nullptr); 4009 4010 // We're going to walk down into the type and look for VLA expressions. 4011 do { 4012 const Type *Ty = T.getTypePtr(); 4013 switch (Ty->getTypeClass()) { 4014 #define TYPE(Class, Base) 4015 #define ABSTRACT_TYPE(Class, Base) 4016 #define NON_CANONICAL_TYPE(Class, Base) 4017 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4018 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4019 #include "clang/AST/TypeNodes.def" 4020 T = QualType(); 4021 break; 4022 // These types are never variably-modified. 4023 case Type::Builtin: 4024 case Type::Complex: 4025 case Type::Vector: 4026 case Type::ExtVector: 4027 case Type::Record: 4028 case Type::Enum: 4029 case Type::Elaborated: 4030 case Type::TemplateSpecialization: 4031 case Type::ObjCObject: 4032 case Type::ObjCInterface: 4033 case Type::ObjCObjectPointer: 4034 case Type::ObjCTypeParam: 4035 case Type::Pipe: 4036 llvm_unreachable("type class is never variably-modified!"); 4037 case Type::Adjusted: 4038 T = cast<AdjustedType>(Ty)->getOriginalType(); 4039 break; 4040 case Type::Decayed: 4041 T = cast<DecayedType>(Ty)->getPointeeType(); 4042 break; 4043 case Type::Pointer: 4044 T = cast<PointerType>(Ty)->getPointeeType(); 4045 break; 4046 case Type::BlockPointer: 4047 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4048 break; 4049 case Type::LValueReference: 4050 case Type::RValueReference: 4051 T = cast<ReferenceType>(Ty)->getPointeeType(); 4052 break; 4053 case Type::MemberPointer: 4054 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4055 break; 4056 case Type::ConstantArray: 4057 case Type::IncompleteArray: 4058 // Losing element qualification here is fine. 4059 T = cast<ArrayType>(Ty)->getElementType(); 4060 break; 4061 case Type::VariableArray: { 4062 // Losing element qualification here is fine. 4063 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4064 4065 // Unknown size indication requires no size computation. 4066 // Otherwise, evaluate and record it. 4067 if (auto Size = VAT->getSizeExpr()) { 4068 if (!CSI->isVLATypeCaptured(VAT)) { 4069 RecordDecl *CapRecord = nullptr; 4070 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 4071 CapRecord = LSI->Lambda; 4072 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 4073 CapRecord = CRSI->TheRecordDecl; 4074 } 4075 if (CapRecord) { 4076 auto ExprLoc = Size->getExprLoc(); 4077 auto SizeType = Context.getSizeType(); 4078 // Build the non-static data member. 4079 auto Field = 4080 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc, 4081 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 4082 /*BW*/ nullptr, /*Mutable*/ false, 4083 /*InitStyle*/ ICIS_NoInit); 4084 Field->setImplicit(true); 4085 Field->setAccess(AS_private); 4086 Field->setCapturedVLAType(VAT); 4087 CapRecord->addDecl(Field); 4088 4089 CSI->addVLATypeCapture(ExprLoc, SizeType); 4090 } 4091 } 4092 } 4093 T = VAT->getElementType(); 4094 break; 4095 } 4096 case Type::FunctionProto: 4097 case Type::FunctionNoProto: 4098 T = cast<FunctionType>(Ty)->getReturnType(); 4099 break; 4100 case Type::Paren: 4101 case Type::TypeOf: 4102 case Type::UnaryTransform: 4103 case Type::Attributed: 4104 case Type::SubstTemplateTypeParm: 4105 case Type::PackExpansion: 4106 // Keep walking after single level desugaring. 4107 T = T.getSingleStepDesugaredType(Context); 4108 break; 4109 case Type::Typedef: 4110 T = cast<TypedefType>(Ty)->desugar(); 4111 break; 4112 case Type::Decltype: 4113 T = cast<DecltypeType>(Ty)->desugar(); 4114 break; 4115 case Type::Auto: 4116 case Type::DeducedTemplateSpecialization: 4117 T = cast<DeducedType>(Ty)->getDeducedType(); 4118 break; 4119 case Type::TypeOfExpr: 4120 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4121 break; 4122 case Type::Atomic: 4123 T = cast<AtomicType>(Ty)->getValueType(); 4124 break; 4125 } 4126 } while (!T.isNull() && T->isVariablyModifiedType()); 4127 } 4128 4129 /// Build a sizeof or alignof expression given a type operand. 4130 ExprResult 4131 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4132 SourceLocation OpLoc, 4133 UnaryExprOrTypeTrait ExprKind, 4134 SourceRange R) { 4135 if (!TInfo) 4136 return ExprError(); 4137 4138 QualType T = TInfo->getType(); 4139 4140 if (!T->isDependentType() && 4141 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4142 return ExprError(); 4143 4144 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4145 if (auto *TT = T->getAs<TypedefType>()) { 4146 for (auto I = FunctionScopes.rbegin(), 4147 E = std::prev(FunctionScopes.rend()); 4148 I != E; ++I) { 4149 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4150 if (CSI == nullptr) 4151 break; 4152 DeclContext *DC = nullptr; 4153 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4154 DC = LSI->CallOperator; 4155 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4156 DC = CRSI->TheCapturedDecl; 4157 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4158 DC = BSI->TheDecl; 4159 if (DC) { 4160 if (DC->containsDecl(TT->getDecl())) 4161 break; 4162 captureVariablyModifiedType(Context, T, CSI); 4163 } 4164 } 4165 } 4166 } 4167 4168 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4169 return new (Context) UnaryExprOrTypeTraitExpr( 4170 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4171 } 4172 4173 /// Build a sizeof or alignof expression given an expression 4174 /// operand. 4175 ExprResult 4176 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4177 UnaryExprOrTypeTrait ExprKind) { 4178 ExprResult PE = CheckPlaceholderExpr(E); 4179 if (PE.isInvalid()) 4180 return ExprError(); 4181 4182 E = PE.get(); 4183 4184 // Verify that the operand is valid. 4185 bool isInvalid = false; 4186 if (E->isTypeDependent()) { 4187 // Delay type-checking for type-dependent expressions. 4188 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4189 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4190 } else if (ExprKind == UETT_VecStep) { 4191 isInvalid = CheckVecStepExpr(E); 4192 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4193 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4194 isInvalid = true; 4195 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4196 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4197 isInvalid = true; 4198 } else { 4199 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4200 } 4201 4202 if (isInvalid) 4203 return ExprError(); 4204 4205 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4206 PE = TransformToPotentiallyEvaluated(E); 4207 if (PE.isInvalid()) return ExprError(); 4208 E = PE.get(); 4209 } 4210 4211 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4212 return new (Context) UnaryExprOrTypeTraitExpr( 4213 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4214 } 4215 4216 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4217 /// expr and the same for @c alignof and @c __alignof 4218 /// Note that the ArgRange is invalid if isType is false. 4219 ExprResult 4220 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4221 UnaryExprOrTypeTrait ExprKind, bool IsType, 4222 void *TyOrEx, SourceRange ArgRange) { 4223 // If error parsing type, ignore. 4224 if (!TyOrEx) return ExprError(); 4225 4226 if (IsType) { 4227 TypeSourceInfo *TInfo; 4228 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4229 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4230 } 4231 4232 Expr *ArgEx = (Expr *)TyOrEx; 4233 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4234 return Result; 4235 } 4236 4237 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4238 bool IsReal) { 4239 if (V.get()->isTypeDependent()) 4240 return S.Context.DependentTy; 4241 4242 // _Real and _Imag are only l-values for normal l-values. 4243 if (V.get()->getObjectKind() != OK_Ordinary) { 4244 V = S.DefaultLvalueConversion(V.get()); 4245 if (V.isInvalid()) 4246 return QualType(); 4247 } 4248 4249 // These operators return the element type of a complex type. 4250 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4251 return CT->getElementType(); 4252 4253 // Otherwise they pass through real integer and floating point types here. 4254 if (V.get()->getType()->isArithmeticType()) 4255 return V.get()->getType(); 4256 4257 // Test for placeholders. 4258 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4259 if (PR.isInvalid()) return QualType(); 4260 if (PR.get() != V.get()) { 4261 V = PR; 4262 return CheckRealImagOperand(S, V, Loc, IsReal); 4263 } 4264 4265 // Reject anything else. 4266 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4267 << (IsReal ? "__real" : "__imag"); 4268 return QualType(); 4269 } 4270 4271 4272 4273 ExprResult 4274 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4275 tok::TokenKind Kind, Expr *Input) { 4276 UnaryOperatorKind Opc; 4277 switch (Kind) { 4278 default: llvm_unreachable("Unknown unary op!"); 4279 case tok::plusplus: Opc = UO_PostInc; break; 4280 case tok::minusminus: Opc = UO_PostDec; break; 4281 } 4282 4283 // Since this might is a postfix expression, get rid of ParenListExprs. 4284 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4285 if (Result.isInvalid()) return ExprError(); 4286 Input = Result.get(); 4287 4288 return BuildUnaryOp(S, OpLoc, Opc, Input); 4289 } 4290 4291 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4292 /// 4293 /// \return true on error 4294 static bool checkArithmeticOnObjCPointer(Sema &S, 4295 SourceLocation opLoc, 4296 Expr *op) { 4297 assert(op->getType()->isObjCObjectPointerType()); 4298 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4299 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4300 return false; 4301 4302 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4303 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4304 << op->getSourceRange(); 4305 return true; 4306 } 4307 4308 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4309 auto *BaseNoParens = Base->IgnoreParens(); 4310 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4311 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4312 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4313 } 4314 4315 ExprResult 4316 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4317 Expr *idx, SourceLocation rbLoc) { 4318 if (base && !base->getType().isNull() && 4319 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4320 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4321 /*Length=*/nullptr, rbLoc); 4322 4323 // Since this might be a postfix expression, get rid of ParenListExprs. 4324 if (isa<ParenListExpr>(base)) { 4325 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4326 if (result.isInvalid()) return ExprError(); 4327 base = result.get(); 4328 } 4329 4330 // Handle any non-overload placeholder types in the base and index 4331 // expressions. We can't handle overloads here because the other 4332 // operand might be an overloadable type, in which case the overload 4333 // resolution for the operator overload should get the first crack 4334 // at the overload. 4335 bool IsMSPropertySubscript = false; 4336 if (base->getType()->isNonOverloadPlaceholderType()) { 4337 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4338 if (!IsMSPropertySubscript) { 4339 ExprResult result = CheckPlaceholderExpr(base); 4340 if (result.isInvalid()) 4341 return ExprError(); 4342 base = result.get(); 4343 } 4344 } 4345 if (idx->getType()->isNonOverloadPlaceholderType()) { 4346 ExprResult result = CheckPlaceholderExpr(idx); 4347 if (result.isInvalid()) return ExprError(); 4348 idx = result.get(); 4349 } 4350 4351 // Build an unanalyzed expression if either operand is type-dependent. 4352 if (getLangOpts().CPlusPlus && 4353 (base->isTypeDependent() || idx->isTypeDependent())) { 4354 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4355 VK_LValue, OK_Ordinary, rbLoc); 4356 } 4357 4358 // MSDN, property (C++) 4359 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4360 // This attribute can also be used in the declaration of an empty array in a 4361 // class or structure definition. For example: 4362 // __declspec(property(get=GetX, put=PutX)) int x[]; 4363 // The above statement indicates that x[] can be used with one or more array 4364 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4365 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4366 if (IsMSPropertySubscript) { 4367 // Build MS property subscript expression if base is MS property reference 4368 // or MS property subscript. 4369 return new (Context) MSPropertySubscriptExpr( 4370 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4371 } 4372 4373 // Use C++ overloaded-operator rules if either operand has record 4374 // type. The spec says to do this if either type is *overloadable*, 4375 // but enum types can't declare subscript operators or conversion 4376 // operators, so there's nothing interesting for overload resolution 4377 // to do if there aren't any record types involved. 4378 // 4379 // ObjC pointers have their own subscripting logic that is not tied 4380 // to overload resolution and so should not take this path. 4381 if (getLangOpts().CPlusPlus && 4382 (base->getType()->isRecordType() || 4383 (!base->getType()->isObjCObjectPointerType() && 4384 idx->getType()->isRecordType()))) { 4385 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4386 } 4387 4388 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4389 4390 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4391 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4392 4393 return Res; 4394 } 4395 4396 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4397 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4398 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4399 4400 // For expressions like `&(*s).b`, the base is recorded and what should be 4401 // checked. 4402 const MemberExpr *Member = nullptr; 4403 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4404 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4405 4406 LastRecord.PossibleDerefs.erase(StrippedExpr); 4407 } 4408 4409 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4410 QualType ResultTy = E->getType(); 4411 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4412 4413 // Bail if the element is an array since it is not memory access. 4414 if (isa<ArrayType>(ResultTy)) 4415 return; 4416 4417 if (ResultTy->hasAttr(attr::NoDeref)) { 4418 LastRecord.PossibleDerefs.insert(E); 4419 return; 4420 } 4421 4422 // Check if the base type is a pointer to a member access of a struct 4423 // marked with noderef. 4424 const Expr *Base = E->getBase(); 4425 QualType BaseTy = Base->getType(); 4426 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4427 // Not a pointer access 4428 return; 4429 4430 const MemberExpr *Member = nullptr; 4431 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4432 Member->isArrow()) 4433 Base = Member->getBase(); 4434 4435 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4436 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4437 LastRecord.PossibleDerefs.insert(E); 4438 } 4439 } 4440 4441 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4442 Expr *LowerBound, 4443 SourceLocation ColonLoc, Expr *Length, 4444 SourceLocation RBLoc) { 4445 if (Base->getType()->isPlaceholderType() && 4446 !Base->getType()->isSpecificPlaceholderType( 4447 BuiltinType::OMPArraySection)) { 4448 ExprResult Result = CheckPlaceholderExpr(Base); 4449 if (Result.isInvalid()) 4450 return ExprError(); 4451 Base = Result.get(); 4452 } 4453 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4454 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4455 if (Result.isInvalid()) 4456 return ExprError(); 4457 Result = DefaultLvalueConversion(Result.get()); 4458 if (Result.isInvalid()) 4459 return ExprError(); 4460 LowerBound = Result.get(); 4461 } 4462 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4463 ExprResult Result = CheckPlaceholderExpr(Length); 4464 if (Result.isInvalid()) 4465 return ExprError(); 4466 Result = DefaultLvalueConversion(Result.get()); 4467 if (Result.isInvalid()) 4468 return ExprError(); 4469 Length = Result.get(); 4470 } 4471 4472 // Build an unanalyzed expression if either operand is type-dependent. 4473 if (Base->isTypeDependent() || 4474 (LowerBound && 4475 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4476 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4477 return new (Context) 4478 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4479 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4480 } 4481 4482 // Perform default conversions. 4483 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4484 QualType ResultTy; 4485 if (OriginalTy->isAnyPointerType()) { 4486 ResultTy = OriginalTy->getPointeeType(); 4487 } else if (OriginalTy->isArrayType()) { 4488 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4489 } else { 4490 return ExprError( 4491 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4492 << Base->getSourceRange()); 4493 } 4494 // C99 6.5.2.1p1 4495 if (LowerBound) { 4496 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4497 LowerBound); 4498 if (Res.isInvalid()) 4499 return ExprError(Diag(LowerBound->getExprLoc(), 4500 diag::err_omp_typecheck_section_not_integer) 4501 << 0 << LowerBound->getSourceRange()); 4502 LowerBound = Res.get(); 4503 4504 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4505 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4506 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4507 << 0 << LowerBound->getSourceRange(); 4508 } 4509 if (Length) { 4510 auto Res = 4511 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4512 if (Res.isInvalid()) 4513 return ExprError(Diag(Length->getExprLoc(), 4514 diag::err_omp_typecheck_section_not_integer) 4515 << 1 << Length->getSourceRange()); 4516 Length = Res.get(); 4517 4518 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4519 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4520 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4521 << 1 << Length->getSourceRange(); 4522 } 4523 4524 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4525 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4526 // type. Note that functions are not objects, and that (in C99 parlance) 4527 // incomplete types are not object types. 4528 if (ResultTy->isFunctionType()) { 4529 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4530 << ResultTy << Base->getSourceRange(); 4531 return ExprError(); 4532 } 4533 4534 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4535 diag::err_omp_section_incomplete_type, Base)) 4536 return ExprError(); 4537 4538 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4539 Expr::EvalResult Result; 4540 if (LowerBound->EvaluateAsInt(Result, Context)) { 4541 // OpenMP 4.5, [2.4 Array Sections] 4542 // The array section must be a subset of the original array. 4543 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 4544 if (LowerBoundValue.isNegative()) { 4545 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4546 << LowerBound->getSourceRange(); 4547 return ExprError(); 4548 } 4549 } 4550 } 4551 4552 if (Length) { 4553 Expr::EvalResult Result; 4554 if (Length->EvaluateAsInt(Result, Context)) { 4555 // OpenMP 4.5, [2.4 Array Sections] 4556 // The length must evaluate to non-negative integers. 4557 llvm::APSInt LengthValue = Result.Val.getInt(); 4558 if (LengthValue.isNegative()) { 4559 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4560 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4561 << Length->getSourceRange(); 4562 return ExprError(); 4563 } 4564 } 4565 } else if (ColonLoc.isValid() && 4566 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4567 !OriginalTy->isVariableArrayType()))) { 4568 // OpenMP 4.5, [2.4 Array Sections] 4569 // When the size of the array dimension is not known, the length must be 4570 // specified explicitly. 4571 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4572 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4573 return ExprError(); 4574 } 4575 4576 if (!Base->getType()->isSpecificPlaceholderType( 4577 BuiltinType::OMPArraySection)) { 4578 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4579 if (Result.isInvalid()) 4580 return ExprError(); 4581 Base = Result.get(); 4582 } 4583 return new (Context) 4584 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4585 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4586 } 4587 4588 ExprResult 4589 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4590 Expr *Idx, SourceLocation RLoc) { 4591 Expr *LHSExp = Base; 4592 Expr *RHSExp = Idx; 4593 4594 ExprValueKind VK = VK_LValue; 4595 ExprObjectKind OK = OK_Ordinary; 4596 4597 // Per C++ core issue 1213, the result is an xvalue if either operand is 4598 // a non-lvalue array, and an lvalue otherwise. 4599 if (getLangOpts().CPlusPlus11) { 4600 for (auto *Op : {LHSExp, RHSExp}) { 4601 Op = Op->IgnoreImplicit(); 4602 if (Op->getType()->isArrayType() && !Op->isLValue()) 4603 VK = VK_XValue; 4604 } 4605 } 4606 4607 // Perform default conversions. 4608 if (!LHSExp->getType()->getAs<VectorType>()) { 4609 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4610 if (Result.isInvalid()) 4611 return ExprError(); 4612 LHSExp = Result.get(); 4613 } 4614 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4615 if (Result.isInvalid()) 4616 return ExprError(); 4617 RHSExp = Result.get(); 4618 4619 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4620 4621 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4622 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4623 // in the subscript position. As a result, we need to derive the array base 4624 // and index from the expression types. 4625 Expr *BaseExpr, *IndexExpr; 4626 QualType ResultType; 4627 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4628 BaseExpr = LHSExp; 4629 IndexExpr = RHSExp; 4630 ResultType = Context.DependentTy; 4631 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4632 BaseExpr = LHSExp; 4633 IndexExpr = RHSExp; 4634 ResultType = PTy->getPointeeType(); 4635 } else if (const ObjCObjectPointerType *PTy = 4636 LHSTy->getAs<ObjCObjectPointerType>()) { 4637 BaseExpr = LHSExp; 4638 IndexExpr = RHSExp; 4639 4640 // Use custom logic if this should be the pseudo-object subscript 4641 // expression. 4642 if (!LangOpts.isSubscriptPointerArithmetic()) 4643 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4644 nullptr); 4645 4646 ResultType = PTy->getPointeeType(); 4647 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4648 // Handle the uncommon case of "123[Ptr]". 4649 BaseExpr = RHSExp; 4650 IndexExpr = LHSExp; 4651 ResultType = PTy->getPointeeType(); 4652 } else if (const ObjCObjectPointerType *PTy = 4653 RHSTy->getAs<ObjCObjectPointerType>()) { 4654 // Handle the uncommon case of "123[Ptr]". 4655 BaseExpr = RHSExp; 4656 IndexExpr = LHSExp; 4657 ResultType = PTy->getPointeeType(); 4658 if (!LangOpts.isSubscriptPointerArithmetic()) { 4659 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4660 << ResultType << BaseExpr->getSourceRange(); 4661 return ExprError(); 4662 } 4663 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4664 BaseExpr = LHSExp; // vectors: V[123] 4665 IndexExpr = RHSExp; 4666 // We apply C++ DR1213 to vector subscripting too. 4667 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { 4668 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 4669 if (Materialized.isInvalid()) 4670 return ExprError(); 4671 LHSExp = Materialized.get(); 4672 } 4673 VK = LHSExp->getValueKind(); 4674 if (VK != VK_RValue) 4675 OK = OK_VectorComponent; 4676 4677 ResultType = VTy->getElementType(); 4678 QualType BaseType = BaseExpr->getType(); 4679 Qualifiers BaseQuals = BaseType.getQualifiers(); 4680 Qualifiers MemberQuals = ResultType.getQualifiers(); 4681 Qualifiers Combined = BaseQuals + MemberQuals; 4682 if (Combined != MemberQuals) 4683 ResultType = Context.getQualifiedType(ResultType, Combined); 4684 } else if (LHSTy->isArrayType()) { 4685 // If we see an array that wasn't promoted by 4686 // DefaultFunctionArrayLvalueConversion, it must be an array that 4687 // wasn't promoted because of the C90 rule that doesn't 4688 // allow promoting non-lvalue arrays. Warn, then 4689 // force the promotion here. 4690 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 4691 << LHSExp->getSourceRange(); 4692 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4693 CK_ArrayToPointerDecay).get(); 4694 LHSTy = LHSExp->getType(); 4695 4696 BaseExpr = LHSExp; 4697 IndexExpr = RHSExp; 4698 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4699 } else if (RHSTy->isArrayType()) { 4700 // Same as previous, except for 123[f().a] case 4701 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 4702 << RHSExp->getSourceRange(); 4703 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4704 CK_ArrayToPointerDecay).get(); 4705 RHSTy = RHSExp->getType(); 4706 4707 BaseExpr = RHSExp; 4708 IndexExpr = LHSExp; 4709 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4710 } else { 4711 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4712 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4713 } 4714 // C99 6.5.2.1p1 4715 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4716 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4717 << IndexExpr->getSourceRange()); 4718 4719 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4720 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4721 && !IndexExpr->isTypeDependent()) 4722 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4723 4724 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4725 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4726 // type. Note that Functions are not objects, and that (in C99 parlance) 4727 // incomplete types are not object types. 4728 if (ResultType->isFunctionType()) { 4729 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 4730 << ResultType << BaseExpr->getSourceRange(); 4731 return ExprError(); 4732 } 4733 4734 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4735 // GNU extension: subscripting on pointer to void 4736 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4737 << BaseExpr->getSourceRange(); 4738 4739 // C forbids expressions of unqualified void type from being l-values. 4740 // See IsCForbiddenLValueType. 4741 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4742 } else if (!ResultType->isDependentType() && 4743 RequireCompleteType(LLoc, ResultType, 4744 diag::err_subscript_incomplete_type, BaseExpr)) 4745 return ExprError(); 4746 4747 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4748 !ResultType.isCForbiddenLValueType()); 4749 4750 return new (Context) 4751 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4752 } 4753 4754 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 4755 ParmVarDecl *Param) { 4756 if (Param->hasUnparsedDefaultArg()) { 4757 Diag(CallLoc, 4758 diag::err_use_of_default_argument_to_function_declared_later) << 4759 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4760 Diag(UnparsedDefaultArgLocs[Param], 4761 diag::note_default_argument_declared_here); 4762 return true; 4763 } 4764 4765 if (Param->hasUninstantiatedDefaultArg()) { 4766 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4767 4768 EnterExpressionEvaluationContext EvalContext( 4769 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 4770 4771 // Instantiate the expression. 4772 // 4773 // FIXME: Pass in a correct Pattern argument, otherwise 4774 // getTemplateInstantiationArgs uses the lexical context of FD, e.g. 4775 // 4776 // template<typename T> 4777 // struct A { 4778 // static int FooImpl(); 4779 // 4780 // template<typename Tp> 4781 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level 4782 // // template argument list [[T], [Tp]], should be [[Tp]]. 4783 // friend A<Tp> Foo(int a); 4784 // }; 4785 // 4786 // template<typename T> 4787 // A<T> Foo(int a = A<T>::FooImpl()); 4788 MultiLevelTemplateArgumentList MutiLevelArgList 4789 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4790 4791 InstantiatingTemplate Inst(*this, CallLoc, Param, 4792 MutiLevelArgList.getInnermost()); 4793 if (Inst.isInvalid()) 4794 return true; 4795 if (Inst.isAlreadyInstantiating()) { 4796 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 4797 Param->setInvalidDecl(); 4798 return true; 4799 } 4800 4801 ExprResult Result; 4802 { 4803 // C++ [dcl.fct.default]p5: 4804 // The names in the [default argument] expression are bound, and 4805 // the semantic constraints are checked, at the point where the 4806 // default argument expression appears. 4807 ContextRAII SavedContext(*this, FD); 4808 LocalInstantiationScope Local(*this); 4809 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 4810 /*DirectInit*/false); 4811 } 4812 if (Result.isInvalid()) 4813 return true; 4814 4815 // Check the expression as an initializer for the parameter. 4816 InitializedEntity Entity 4817 = InitializedEntity::InitializeParameter(Context, Param); 4818 InitializationKind Kind = InitializationKind::CreateCopy( 4819 Param->getLocation(), 4820 /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc()); 4821 Expr *ResultE = Result.getAs<Expr>(); 4822 4823 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4824 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4825 if (Result.isInvalid()) 4826 return true; 4827 4828 Result = 4829 ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(), 4830 /*DiscardedValue*/ false); 4831 if (Result.isInvalid()) 4832 return true; 4833 4834 // Remember the instantiated default argument. 4835 Param->setDefaultArg(Result.getAs<Expr>()); 4836 if (ASTMutationListener *L = getASTMutationListener()) { 4837 L->DefaultArgumentInstantiated(Param); 4838 } 4839 } 4840 4841 // If the default argument expression is not set yet, we are building it now. 4842 if (!Param->hasInit()) { 4843 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 4844 Param->setInvalidDecl(); 4845 return true; 4846 } 4847 4848 // If the default expression creates temporaries, we need to 4849 // push them to the current stack of expression temporaries so they'll 4850 // be properly destroyed. 4851 // FIXME: We should really be rebuilding the default argument with new 4852 // bound temporaries; see the comment in PR5810. 4853 // We don't need to do that with block decls, though, because 4854 // blocks in default argument expression can never capture anything. 4855 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 4856 // Set the "needs cleanups" bit regardless of whether there are 4857 // any explicit objects. 4858 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 4859 4860 // Append all the objects to the cleanup list. Right now, this 4861 // should always be a no-op, because blocks in default argument 4862 // expressions should never be able to capture anything. 4863 assert(!Init->getNumObjects() && 4864 "default argument expression has capturing blocks?"); 4865 } 4866 4867 // We already type-checked the argument, so we know it works. 4868 // Just mark all of the declarations in this potentially-evaluated expression 4869 // as being "referenced". 4870 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4871 /*SkipLocalVariables=*/true); 4872 return false; 4873 } 4874 4875 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4876 FunctionDecl *FD, ParmVarDecl *Param) { 4877 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 4878 return ExprError(); 4879 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4880 } 4881 4882 Sema::VariadicCallType 4883 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4884 Expr *Fn) { 4885 if (Proto && Proto->isVariadic()) { 4886 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4887 return VariadicConstructor; 4888 else if (Fn && Fn->getType()->isBlockPointerType()) 4889 return VariadicBlock; 4890 else if (FDecl) { 4891 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4892 if (Method->isInstance()) 4893 return VariadicMethod; 4894 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4895 return VariadicMethod; 4896 return VariadicFunction; 4897 } 4898 return VariadicDoesNotApply; 4899 } 4900 4901 namespace { 4902 class FunctionCallCCC : public FunctionCallFilterCCC { 4903 public: 4904 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4905 unsigned NumArgs, MemberExpr *ME) 4906 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4907 FunctionName(FuncName) {} 4908 4909 bool ValidateCandidate(const TypoCorrection &candidate) override { 4910 if (!candidate.getCorrectionSpecifier() || 4911 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4912 return false; 4913 } 4914 4915 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4916 } 4917 4918 private: 4919 const IdentifierInfo *const FunctionName; 4920 }; 4921 } 4922 4923 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4924 FunctionDecl *FDecl, 4925 ArrayRef<Expr *> Args) { 4926 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4927 DeclarationName FuncName = FDecl->getDeclName(); 4928 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 4929 4930 if (TypoCorrection Corrected = S.CorrectTypo( 4931 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4932 S.getScopeForContext(S.CurContext), nullptr, 4933 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4934 Args.size(), ME), 4935 Sema::CTK_ErrorRecovery)) { 4936 if (NamedDecl *ND = Corrected.getFoundDecl()) { 4937 if (Corrected.isOverloaded()) { 4938 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4939 OverloadCandidateSet::iterator Best; 4940 for (NamedDecl *CD : Corrected) { 4941 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 4942 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4943 OCS); 4944 } 4945 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4946 case OR_Success: 4947 ND = Best->FoundDecl; 4948 Corrected.setCorrectionDecl(ND); 4949 break; 4950 default: 4951 break; 4952 } 4953 } 4954 ND = ND->getUnderlyingDecl(); 4955 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 4956 return Corrected; 4957 } 4958 } 4959 return TypoCorrection(); 4960 } 4961 4962 /// ConvertArgumentsForCall - Converts the arguments specified in 4963 /// Args/NumArgs to the parameter types of the function FDecl with 4964 /// function prototype Proto. Call is the call expression itself, and 4965 /// Fn is the function expression. For a C++ member function, this 4966 /// routine does not attempt to convert the object argument. Returns 4967 /// true if the call is ill-formed. 4968 bool 4969 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4970 FunctionDecl *FDecl, 4971 const FunctionProtoType *Proto, 4972 ArrayRef<Expr *> Args, 4973 SourceLocation RParenLoc, 4974 bool IsExecConfig) { 4975 // Bail out early if calling a builtin with custom typechecking. 4976 if (FDecl) 4977 if (unsigned ID = FDecl->getBuiltinID()) 4978 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4979 return false; 4980 4981 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4982 // assignment, to the types of the corresponding parameter, ... 4983 unsigned NumParams = Proto->getNumParams(); 4984 bool Invalid = false; 4985 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4986 unsigned FnKind = Fn->getType()->isBlockPointerType() 4987 ? 1 /* block */ 4988 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4989 : 0 /* function */); 4990 4991 // If too few arguments are available (and we don't have default 4992 // arguments for the remaining parameters), don't make the call. 4993 if (Args.size() < NumParams) { 4994 if (Args.size() < MinArgs) { 4995 TypoCorrection TC; 4996 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4997 unsigned diag_id = 4998 MinArgs == NumParams && !Proto->isVariadic() 4999 ? diag::err_typecheck_call_too_few_args_suggest 5000 : diag::err_typecheck_call_too_few_args_at_least_suggest; 5001 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 5002 << static_cast<unsigned>(Args.size()) 5003 << TC.getCorrectionRange()); 5004 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 5005 Diag(RParenLoc, 5006 MinArgs == NumParams && !Proto->isVariadic() 5007 ? diag::err_typecheck_call_too_few_args_one 5008 : diag::err_typecheck_call_too_few_args_at_least_one) 5009 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 5010 else 5011 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 5012 ? diag::err_typecheck_call_too_few_args 5013 : diag::err_typecheck_call_too_few_args_at_least) 5014 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 5015 << Fn->getSourceRange(); 5016 5017 // Emit the location of the prototype. 5018 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5019 Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl; 5020 5021 return true; 5022 } 5023 // We reserve space for the default arguments when we create 5024 // the call expression, before calling ConvertArgumentsForCall. 5025 assert((Call->getNumArgs() == NumParams) && 5026 "We should have reserved space for the default arguments before!"); 5027 } 5028 5029 // If too many are passed and not variadic, error on the extras and drop 5030 // them. 5031 if (Args.size() > NumParams) { 5032 if (!Proto->isVariadic()) { 5033 TypoCorrection TC; 5034 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5035 unsigned diag_id = 5036 MinArgs == NumParams && !Proto->isVariadic() 5037 ? diag::err_typecheck_call_too_many_args_suggest 5038 : diag::err_typecheck_call_too_many_args_at_most_suggest; 5039 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 5040 << static_cast<unsigned>(Args.size()) 5041 << TC.getCorrectionRange()); 5042 } else if (NumParams == 1 && FDecl && 5043 FDecl->getParamDecl(0)->getDeclName()) 5044 Diag(Args[NumParams]->getBeginLoc(), 5045 MinArgs == NumParams 5046 ? diag::err_typecheck_call_too_many_args_one 5047 : diag::err_typecheck_call_too_many_args_at_most_one) 5048 << FnKind << FDecl->getParamDecl(0) 5049 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 5050 << SourceRange(Args[NumParams]->getBeginLoc(), 5051 Args.back()->getEndLoc()); 5052 else 5053 Diag(Args[NumParams]->getBeginLoc(), 5054 MinArgs == NumParams 5055 ? diag::err_typecheck_call_too_many_args 5056 : diag::err_typecheck_call_too_many_args_at_most) 5057 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 5058 << Fn->getSourceRange() 5059 << SourceRange(Args[NumParams]->getBeginLoc(), 5060 Args.back()->getEndLoc()); 5061 5062 // Emit the location of the prototype. 5063 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5064 Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl; 5065 5066 // This deletes the extra arguments. 5067 Call->shrinkNumArgs(NumParams); 5068 return true; 5069 } 5070 } 5071 SmallVector<Expr *, 8> AllArgs; 5072 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 5073 5074 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 5075 AllArgs, CallType); 5076 if (Invalid) 5077 return true; 5078 unsigned TotalNumArgs = AllArgs.size(); 5079 for (unsigned i = 0; i < TotalNumArgs; ++i) 5080 Call->setArg(i, AllArgs[i]); 5081 5082 return false; 5083 } 5084 5085 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 5086 const FunctionProtoType *Proto, 5087 unsigned FirstParam, ArrayRef<Expr *> Args, 5088 SmallVectorImpl<Expr *> &AllArgs, 5089 VariadicCallType CallType, bool AllowExplicit, 5090 bool IsListInitialization) { 5091 unsigned NumParams = Proto->getNumParams(); 5092 bool Invalid = false; 5093 size_t ArgIx = 0; 5094 // Continue to check argument types (even if we have too few/many args). 5095 for (unsigned i = FirstParam; i < NumParams; i++) { 5096 QualType ProtoArgType = Proto->getParamType(i); 5097 5098 Expr *Arg; 5099 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 5100 if (ArgIx < Args.size()) { 5101 Arg = Args[ArgIx++]; 5102 5103 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5104 diag::err_call_incomplete_argument, Arg)) 5105 return true; 5106 5107 // Strip the unbridged-cast placeholder expression off, if applicable. 5108 bool CFAudited = false; 5109 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5110 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5111 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5112 Arg = stripARCUnbridgedCast(Arg); 5113 else if (getLangOpts().ObjCAutoRefCount && 5114 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5115 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5116 CFAudited = true; 5117 5118 if (Proto->getExtParameterInfo(i).isNoEscape()) 5119 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 5120 BE->getBlockDecl()->setDoesNotEscape(); 5121 5122 InitializedEntity Entity = 5123 Param ? InitializedEntity::InitializeParameter(Context, Param, 5124 ProtoArgType) 5125 : InitializedEntity::InitializeParameter( 5126 Context, ProtoArgType, Proto->isParamConsumed(i)); 5127 5128 // Remember that parameter belongs to a CF audited API. 5129 if (CFAudited) 5130 Entity.setParameterCFAudited(); 5131 5132 ExprResult ArgE = PerformCopyInitialization( 5133 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 5134 if (ArgE.isInvalid()) 5135 return true; 5136 5137 Arg = ArgE.getAs<Expr>(); 5138 } else { 5139 assert(Param && "can't use default arguments without a known callee"); 5140 5141 ExprResult ArgExpr = 5142 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 5143 if (ArgExpr.isInvalid()) 5144 return true; 5145 5146 Arg = ArgExpr.getAs<Expr>(); 5147 } 5148 5149 // Check for array bounds violations for each argument to the call. This 5150 // check only triggers warnings when the argument isn't a more complex Expr 5151 // with its own checking, such as a BinaryOperator. 5152 CheckArrayAccess(Arg); 5153 5154 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 5155 CheckStaticArrayArgument(CallLoc, Param, Arg); 5156 5157 AllArgs.push_back(Arg); 5158 } 5159 5160 // If this is a variadic call, handle args passed through "...". 5161 if (CallType != VariadicDoesNotApply) { 5162 // Assume that extern "C" functions with variadic arguments that 5163 // return __unknown_anytype aren't *really* variadic. 5164 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 5165 FDecl->isExternC()) { 5166 for (Expr *A : Args.slice(ArgIx)) { 5167 QualType paramType; // ignored 5168 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 5169 Invalid |= arg.isInvalid(); 5170 AllArgs.push_back(arg.get()); 5171 } 5172 5173 // Otherwise do argument promotion, (C99 6.5.2.2p7). 5174 } else { 5175 for (Expr *A : Args.slice(ArgIx)) { 5176 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 5177 Invalid |= Arg.isInvalid(); 5178 AllArgs.push_back(Arg.get()); 5179 } 5180 } 5181 5182 // Check for array bounds violations. 5183 for (Expr *A : Args.slice(ArgIx)) 5184 CheckArrayAccess(A); 5185 } 5186 return Invalid; 5187 } 5188 5189 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 5190 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 5191 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 5192 TL = DTL.getOriginalLoc(); 5193 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 5194 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 5195 << ATL.getLocalSourceRange(); 5196 } 5197 5198 /// CheckStaticArrayArgument - If the given argument corresponds to a static 5199 /// array parameter, check that it is non-null, and that if it is formed by 5200 /// array-to-pointer decay, the underlying array is sufficiently large. 5201 /// 5202 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 5203 /// array type derivation, then for each call to the function, the value of the 5204 /// corresponding actual argument shall provide access to the first element of 5205 /// an array with at least as many elements as specified by the size expression. 5206 void 5207 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 5208 ParmVarDecl *Param, 5209 const Expr *ArgExpr) { 5210 // Static array parameters are not supported in C++. 5211 if (!Param || getLangOpts().CPlusPlus) 5212 return; 5213 5214 QualType OrigTy = Param->getOriginalType(); 5215 5216 const ArrayType *AT = Context.getAsArrayType(OrigTy); 5217 if (!AT || AT->getSizeModifier() != ArrayType::Static) 5218 return; 5219 5220 if (ArgExpr->isNullPointerConstant(Context, 5221 Expr::NPC_NeverValueDependent)) { 5222 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 5223 DiagnoseCalleeStaticArrayParam(*this, Param); 5224 return; 5225 } 5226 5227 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 5228 if (!CAT) 5229 return; 5230 5231 const ConstantArrayType *ArgCAT = 5232 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 5233 if (!ArgCAT) 5234 return; 5235 5236 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 5237 ArgCAT->getElementType())) { 5238 if (ArgCAT->getSize().ult(CAT->getSize())) { 5239 Diag(CallLoc, diag::warn_static_array_too_small) 5240 << ArgExpr->getSourceRange() 5241 << (unsigned)ArgCAT->getSize().getZExtValue() 5242 << (unsigned)CAT->getSize().getZExtValue() << 0; 5243 DiagnoseCalleeStaticArrayParam(*this, Param); 5244 } 5245 return; 5246 } 5247 5248 Optional<CharUnits> ArgSize = 5249 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 5250 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 5251 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 5252 Diag(CallLoc, diag::warn_static_array_too_small) 5253 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 5254 << (unsigned)ParmSize->getQuantity() << 1; 5255 DiagnoseCalleeStaticArrayParam(*this, Param); 5256 } 5257 } 5258 5259 /// Given a function expression of unknown-any type, try to rebuild it 5260 /// to have a function type. 5261 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 5262 5263 /// Is the given type a placeholder that we need to lower out 5264 /// immediately during argument processing? 5265 static bool isPlaceholderToRemoveAsArg(QualType type) { 5266 // Placeholders are never sugared. 5267 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 5268 if (!placeholder) return false; 5269 5270 switch (placeholder->getKind()) { 5271 // Ignore all the non-placeholder types. 5272 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 5273 case BuiltinType::Id: 5274 #include "clang/Basic/OpenCLImageTypes.def" 5275 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 5276 case BuiltinType::Id: 5277 #include "clang/Basic/OpenCLExtensionTypes.def" 5278 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 5279 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 5280 #include "clang/AST/BuiltinTypes.def" 5281 return false; 5282 5283 // We cannot lower out overload sets; they might validly be resolved 5284 // by the call machinery. 5285 case BuiltinType::Overload: 5286 return false; 5287 5288 // Unbridged casts in ARC can be handled in some call positions and 5289 // should be left in place. 5290 case BuiltinType::ARCUnbridgedCast: 5291 return false; 5292 5293 // Pseudo-objects should be converted as soon as possible. 5294 case BuiltinType::PseudoObject: 5295 return true; 5296 5297 // The debugger mode could theoretically but currently does not try 5298 // to resolve unknown-typed arguments based on known parameter types. 5299 case BuiltinType::UnknownAny: 5300 return true; 5301 5302 // These are always invalid as call arguments and should be reported. 5303 case BuiltinType::BoundMember: 5304 case BuiltinType::BuiltinFn: 5305 case BuiltinType::OMPArraySection: 5306 return true; 5307 5308 } 5309 llvm_unreachable("bad builtin type kind"); 5310 } 5311 5312 /// Check an argument list for placeholders that we won't try to 5313 /// handle later. 5314 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5315 // Apply this processing to all the arguments at once instead of 5316 // dying at the first failure. 5317 bool hasInvalid = false; 5318 for (size_t i = 0, e = args.size(); i != e; i++) { 5319 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5320 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5321 if (result.isInvalid()) hasInvalid = true; 5322 else args[i] = result.get(); 5323 } else if (hasInvalid) { 5324 (void)S.CorrectDelayedTyposInExpr(args[i]); 5325 } 5326 } 5327 return hasInvalid; 5328 } 5329 5330 /// If a builtin function has a pointer argument with no explicit address 5331 /// space, then it should be able to accept a pointer to any address 5332 /// space as input. In order to do this, we need to replace the 5333 /// standard builtin declaration with one that uses the same address space 5334 /// as the call. 5335 /// 5336 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5337 /// it does not contain any pointer arguments without 5338 /// an address space qualifer. Otherwise the rewritten 5339 /// FunctionDecl is returned. 5340 /// TODO: Handle pointer return types. 5341 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5342 const FunctionDecl *FDecl, 5343 MultiExprArg ArgExprs) { 5344 5345 QualType DeclType = FDecl->getType(); 5346 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5347 5348 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 5349 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 5350 return nullptr; 5351 5352 bool NeedsNewDecl = false; 5353 unsigned i = 0; 5354 SmallVector<QualType, 8> OverloadParams; 5355 5356 for (QualType ParamType : FT->param_types()) { 5357 5358 // Convert array arguments to pointer to simplify type lookup. 5359 ExprResult ArgRes = 5360 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5361 if (ArgRes.isInvalid()) 5362 return nullptr; 5363 Expr *Arg = ArgRes.get(); 5364 QualType ArgType = Arg->getType(); 5365 if (!ParamType->isPointerType() || 5366 ParamType.getQualifiers().hasAddressSpace() || 5367 !ArgType->isPointerType() || 5368 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 5369 OverloadParams.push_back(ParamType); 5370 continue; 5371 } 5372 5373 QualType PointeeType = ParamType->getPointeeType(); 5374 if (PointeeType.getQualifiers().hasAddressSpace()) 5375 continue; 5376 5377 NeedsNewDecl = true; 5378 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 5379 5380 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5381 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5382 } 5383 5384 if (!NeedsNewDecl) 5385 return nullptr; 5386 5387 FunctionProtoType::ExtProtoInfo EPI; 5388 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5389 OverloadParams, EPI); 5390 DeclContext *Parent = Context.getTranslationUnitDecl(); 5391 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5392 FDecl->getLocation(), 5393 FDecl->getLocation(), 5394 FDecl->getIdentifier(), 5395 OverloadTy, 5396 /*TInfo=*/nullptr, 5397 SC_Extern, false, 5398 /*hasPrototype=*/true); 5399 SmallVector<ParmVarDecl*, 16> Params; 5400 FT = cast<FunctionProtoType>(OverloadTy); 5401 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5402 QualType ParamType = FT->getParamType(i); 5403 ParmVarDecl *Parm = 5404 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5405 SourceLocation(), nullptr, ParamType, 5406 /*TInfo=*/nullptr, SC_None, nullptr); 5407 Parm->setScopeInfo(0, i); 5408 Params.push_back(Parm); 5409 } 5410 OverloadDecl->setParams(Params); 5411 return OverloadDecl; 5412 } 5413 5414 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 5415 FunctionDecl *Callee, 5416 MultiExprArg ArgExprs) { 5417 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 5418 // similar attributes) really don't like it when functions are called with an 5419 // invalid number of args. 5420 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 5421 /*PartialOverloading=*/false) && 5422 !Callee->isVariadic()) 5423 return; 5424 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 5425 return; 5426 5427 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) { 5428 S.Diag(Fn->getBeginLoc(), 5429 isa<CXXMethodDecl>(Callee) 5430 ? diag::err_ovl_no_viable_member_function_in_call 5431 : diag::err_ovl_no_viable_function_in_call) 5432 << Callee << Callee->getSourceRange(); 5433 S.Diag(Callee->getLocation(), 5434 diag::note_ovl_candidate_disabled_by_function_cond_attr) 5435 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5436 return; 5437 } 5438 } 5439 5440 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 5441 const UnresolvedMemberExpr *const UME, Sema &S) { 5442 5443 const auto GetFunctionLevelDCIfCXXClass = 5444 [](Sema &S) -> const CXXRecordDecl * { 5445 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 5446 if (!DC || !DC->getParent()) 5447 return nullptr; 5448 5449 // If the call to some member function was made from within a member 5450 // function body 'M' return return 'M's parent. 5451 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 5452 return MD->getParent()->getCanonicalDecl(); 5453 // else the call was made from within a default member initializer of a 5454 // class, so return the class. 5455 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 5456 return RD->getCanonicalDecl(); 5457 return nullptr; 5458 }; 5459 // If our DeclContext is neither a member function nor a class (in the 5460 // case of a lambda in a default member initializer), we can't have an 5461 // enclosing 'this'. 5462 5463 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 5464 if (!CurParentClass) 5465 return false; 5466 5467 // The naming class for implicit member functions call is the class in which 5468 // name lookup starts. 5469 const CXXRecordDecl *const NamingClass = 5470 UME->getNamingClass()->getCanonicalDecl(); 5471 assert(NamingClass && "Must have naming class even for implicit access"); 5472 5473 // If the unresolved member functions were found in a 'naming class' that is 5474 // related (either the same or derived from) to the class that contains the 5475 // member function that itself contained the implicit member access. 5476 5477 return CurParentClass == NamingClass || 5478 CurParentClass->isDerivedFrom(NamingClass); 5479 } 5480 5481 static void 5482 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5483 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 5484 5485 if (!UME) 5486 return; 5487 5488 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 5489 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 5490 // already been captured, or if this is an implicit member function call (if 5491 // it isn't, an attempt to capture 'this' should already have been made). 5492 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 5493 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 5494 return; 5495 5496 // Check if the naming class in which the unresolved members were found is 5497 // related (same as or is a base of) to the enclosing class. 5498 5499 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 5500 return; 5501 5502 5503 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 5504 // If the enclosing function is not dependent, then this lambda is 5505 // capture ready, so if we can capture this, do so. 5506 if (!EnclosingFunctionCtx->isDependentContext()) { 5507 // If the current lambda and all enclosing lambdas can capture 'this' - 5508 // then go ahead and capture 'this' (since our unresolved overload set 5509 // contains at least one non-static member function). 5510 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 5511 S.CheckCXXThisCapture(CallLoc); 5512 } else if (S.CurContext->isDependentContext()) { 5513 // ... since this is an implicit member reference, that might potentially 5514 // involve a 'this' capture, mark 'this' for potential capture in 5515 // enclosing lambdas. 5516 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 5517 CurLSI->addPotentialThisCapture(CallLoc); 5518 } 5519 } 5520 5521 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 5522 /// This provides the location of the left/right parens and a list of comma 5523 /// locations. 5524 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5525 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5526 Expr *ExecConfig, bool IsExecConfig) { 5527 // Since this might be a postfix expression, get rid of ParenListExprs. 5528 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 5529 if (Result.isInvalid()) return ExprError(); 5530 Fn = Result.get(); 5531 5532 if (checkArgsForPlaceholders(*this, ArgExprs)) 5533 return ExprError(); 5534 5535 if (getLangOpts().CPlusPlus) { 5536 // If this is a pseudo-destructor expression, build the call immediately. 5537 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5538 if (!ArgExprs.empty()) { 5539 // Pseudo-destructor calls should not have any arguments. 5540 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 5541 << FixItHint::CreateRemoval( 5542 SourceRange(ArgExprs.front()->getBeginLoc(), 5543 ArgExprs.back()->getEndLoc())); 5544 } 5545 5546 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 5547 VK_RValue, RParenLoc); 5548 } 5549 if (Fn->getType() == Context.PseudoObjectTy) { 5550 ExprResult result = CheckPlaceholderExpr(Fn); 5551 if (result.isInvalid()) return ExprError(); 5552 Fn = result.get(); 5553 } 5554 5555 // Determine whether this is a dependent call inside a C++ template, 5556 // in which case we won't do any semantic analysis now. 5557 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 5558 if (ExecConfig) { 5559 return CUDAKernelCallExpr::Create( 5560 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5561 Context.DependentTy, VK_RValue, RParenLoc); 5562 } else { 5563 5564 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5565 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 5566 Fn->getBeginLoc()); 5567 5568 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 5569 VK_RValue, RParenLoc); 5570 } 5571 } 5572 5573 // Determine whether this is a call to an object (C++ [over.call.object]). 5574 if (Fn->getType()->isRecordType()) 5575 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 5576 RParenLoc); 5577 5578 if (Fn->getType() == Context.UnknownAnyTy) { 5579 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5580 if (result.isInvalid()) return ExprError(); 5581 Fn = result.get(); 5582 } 5583 5584 if (Fn->getType() == Context.BoundMemberTy) { 5585 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5586 RParenLoc); 5587 } 5588 } 5589 5590 // Check for overloaded calls. This can happen even in C due to extensions. 5591 if (Fn->getType() == Context.OverloadTy) { 5592 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5593 5594 // We aren't supposed to apply this logic if there's an '&' involved. 5595 if (!find.HasFormOfMemberPointer) { 5596 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5597 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 5598 VK_RValue, RParenLoc); 5599 OverloadExpr *ovl = find.Expression; 5600 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5601 return BuildOverloadedCallExpr( 5602 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 5603 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 5604 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5605 RParenLoc); 5606 } 5607 } 5608 5609 // If we're directly calling a function, get the appropriate declaration. 5610 if (Fn->getType() == Context.UnknownAnyTy) { 5611 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5612 if (result.isInvalid()) return ExprError(); 5613 Fn = result.get(); 5614 } 5615 5616 Expr *NakedFn = Fn->IgnoreParens(); 5617 5618 bool CallingNDeclIndirectly = false; 5619 NamedDecl *NDecl = nullptr; 5620 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5621 if (UnOp->getOpcode() == UO_AddrOf) { 5622 CallingNDeclIndirectly = true; 5623 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5624 } 5625 } 5626 5627 if (isa<DeclRefExpr>(NakedFn)) { 5628 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 5629 5630 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5631 if (FDecl && FDecl->getBuiltinID()) { 5632 // Rewrite the function decl for this builtin by replacing parameters 5633 // with no explicit address space with the address space of the arguments 5634 // in ArgExprs. 5635 if ((FDecl = 5636 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5637 NDecl = FDecl; 5638 Fn = DeclRefExpr::Create( 5639 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 5640 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl); 5641 } 5642 } 5643 } else if (isa<MemberExpr>(NakedFn)) 5644 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5645 5646 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5647 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 5648 FD, /*Complain=*/true, Fn->getBeginLoc())) 5649 return ExprError(); 5650 5651 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 5652 return ExprError(); 5653 5654 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 5655 } 5656 5657 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5658 ExecConfig, IsExecConfig); 5659 } 5660 5661 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5662 /// 5663 /// __builtin_astype( value, dst type ) 5664 /// 5665 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5666 SourceLocation BuiltinLoc, 5667 SourceLocation RParenLoc) { 5668 ExprValueKind VK = VK_RValue; 5669 ExprObjectKind OK = OK_Ordinary; 5670 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5671 QualType SrcTy = E->getType(); 5672 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5673 return ExprError(Diag(BuiltinLoc, 5674 diag::err_invalid_astype_of_different_size) 5675 << DstTy 5676 << SrcTy 5677 << E->getSourceRange()); 5678 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5679 } 5680 5681 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5682 /// provided arguments. 5683 /// 5684 /// __builtin_convertvector( value, dst type ) 5685 /// 5686 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5687 SourceLocation BuiltinLoc, 5688 SourceLocation RParenLoc) { 5689 TypeSourceInfo *TInfo; 5690 GetTypeFromParser(ParsedDestTy, &TInfo); 5691 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5692 } 5693 5694 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5695 /// i.e. an expression not of \p OverloadTy. The expression should 5696 /// unary-convert to an expression of function-pointer or 5697 /// block-pointer type. 5698 /// 5699 /// \param NDecl the declaration being called, if available 5700 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5701 SourceLocation LParenLoc, 5702 ArrayRef<Expr *> Args, 5703 SourceLocation RParenLoc, Expr *Config, 5704 bool IsExecConfig, ADLCallKind UsesADL) { 5705 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5706 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5707 5708 // Functions with 'interrupt' attribute cannot be called directly. 5709 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5710 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5711 return ExprError(); 5712 } 5713 5714 // Interrupt handlers don't save off the VFP regs automatically on ARM, 5715 // so there's some risk when calling out to non-interrupt handler functions 5716 // that the callee might not preserve them. This is easy to diagnose here, 5717 // but can be very challenging to debug. 5718 if (auto *Caller = getCurFunctionDecl()) 5719 if (Caller->hasAttr<ARMInterruptAttr>()) { 5720 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 5721 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) 5722 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 5723 } 5724 5725 // Promote the function operand. 5726 // We special-case function promotion here because we only allow promoting 5727 // builtin functions to function pointers in the callee of a call. 5728 ExprResult Result; 5729 QualType ResultTy; 5730 if (BuiltinID && 5731 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5732 // Extract the return type from the (builtin) function pointer type. 5733 // FIXME Several builtins still have setType in 5734 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 5735 // Builtins.def to ensure they are correct before removing setType calls. 5736 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 5737 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 5738 ResultTy = FDecl->getCallResultType(); 5739 } else { 5740 Result = CallExprUnaryConversions(Fn); 5741 ResultTy = Context.BoolTy; 5742 } 5743 if (Result.isInvalid()) 5744 return ExprError(); 5745 Fn = Result.get(); 5746 5747 // Check for a valid function type, but only if it is not a builtin which 5748 // requires custom type checking. These will be handled by 5749 // CheckBuiltinFunctionCall below just after creation of the call expression. 5750 const FunctionType *FuncT = nullptr; 5751 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 5752 retry: 5753 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5754 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5755 // have type pointer to function". 5756 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5757 if (!FuncT) 5758 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5759 << Fn->getType() << Fn->getSourceRange()); 5760 } else if (const BlockPointerType *BPT = 5761 Fn->getType()->getAs<BlockPointerType>()) { 5762 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5763 } else { 5764 // Handle calls to expressions of unknown-any type. 5765 if (Fn->getType() == Context.UnknownAnyTy) { 5766 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5767 if (rewrite.isInvalid()) return ExprError(); 5768 Fn = rewrite.get(); 5769 goto retry; 5770 } 5771 5772 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5773 << Fn->getType() << Fn->getSourceRange()); 5774 } 5775 } 5776 5777 // Get the number of parameters in the function prototype, if any. 5778 // We will allocate space for max(Args.size(), NumParams) arguments 5779 // in the call expression. 5780 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 5781 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 5782 5783 CallExpr *TheCall; 5784 if (Config) { 5785 assert(UsesADL == ADLCallKind::NotADL && 5786 "CUDAKernelCallExpr should not use ADL"); 5787 TheCall = 5788 CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args, 5789 ResultTy, VK_RValue, RParenLoc, NumParams); 5790 } else { 5791 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, 5792 RParenLoc, NumParams, UsesADL); 5793 } 5794 5795 if (!getLangOpts().CPlusPlus) { 5796 // Forget about the nulled arguments since typo correction 5797 // do not handle them well. 5798 TheCall->shrinkNumArgs(Args.size()); 5799 // C cannot always handle TypoExpr nodes in builtin calls and direct 5800 // function calls as their argument checking don't necessarily handle 5801 // dependent types properly, so make sure any TypoExprs have been 5802 // dealt with. 5803 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5804 if (!Result.isUsable()) return ExprError(); 5805 CallExpr *TheOldCall = TheCall; 5806 TheCall = dyn_cast<CallExpr>(Result.get()); 5807 bool CorrectedTypos = TheCall != TheOldCall; 5808 if (!TheCall) return Result; 5809 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5810 5811 // A new call expression node was created if some typos were corrected. 5812 // However it may not have been constructed with enough storage. In this 5813 // case, rebuild the node with enough storage. The waste of space is 5814 // immaterial since this only happens when some typos were corrected. 5815 if (CorrectedTypos && Args.size() < NumParams) { 5816 if (Config) 5817 TheCall = CUDAKernelCallExpr::Create( 5818 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue, 5819 RParenLoc, NumParams); 5820 else 5821 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, 5822 RParenLoc, NumParams, UsesADL); 5823 } 5824 // We can now handle the nulled arguments for the default arguments. 5825 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 5826 } 5827 5828 // Bail out early if calling a builtin with custom type checking. 5829 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5830 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5831 5832 if (getLangOpts().CUDA) { 5833 if (Config) { 5834 // CUDA: Kernel calls must be to global functions 5835 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5836 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5837 << FDecl << Fn->getSourceRange()); 5838 5839 // CUDA: Kernel function must have 'void' return type 5840 if (!FuncT->getReturnType()->isVoidType()) 5841 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5842 << Fn->getType() << Fn->getSourceRange()); 5843 } else { 5844 // CUDA: Calls to global functions must be configured 5845 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5846 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5847 << FDecl << Fn->getSourceRange()); 5848 } 5849 } 5850 5851 // Check for a valid return type 5852 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 5853 FDecl)) 5854 return ExprError(); 5855 5856 // We know the result type of the call, set it. 5857 TheCall->setType(FuncT->getCallResultType(Context)); 5858 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5859 5860 if (Proto) { 5861 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5862 IsExecConfig)) 5863 return ExprError(); 5864 } else { 5865 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5866 5867 if (FDecl) { 5868 // Check if we have too few/too many template arguments, based 5869 // on our knowledge of the function definition. 5870 const FunctionDecl *Def = nullptr; 5871 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5872 Proto = Def->getType()->getAs<FunctionProtoType>(); 5873 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5874 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5875 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5876 } 5877 5878 // If the function we're calling isn't a function prototype, but we have 5879 // a function prototype from a prior declaratiom, use that prototype. 5880 if (!FDecl->hasPrototype()) 5881 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5882 } 5883 5884 // Promote the arguments (C99 6.5.2.2p6). 5885 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5886 Expr *Arg = Args[i]; 5887 5888 if (Proto && i < Proto->getNumParams()) { 5889 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5890 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5891 ExprResult ArgE = 5892 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5893 if (ArgE.isInvalid()) 5894 return true; 5895 5896 Arg = ArgE.getAs<Expr>(); 5897 5898 } else { 5899 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5900 5901 if (ArgE.isInvalid()) 5902 return true; 5903 5904 Arg = ArgE.getAs<Expr>(); 5905 } 5906 5907 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 5908 diag::err_call_incomplete_argument, Arg)) 5909 return ExprError(); 5910 5911 TheCall->setArg(i, Arg); 5912 } 5913 } 5914 5915 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5916 if (!Method->isStatic()) 5917 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5918 << Fn->getSourceRange()); 5919 5920 // Check for sentinels 5921 if (NDecl) 5922 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5923 5924 // Do special checking on direct calls to functions. 5925 if (FDecl) { 5926 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5927 return ExprError(); 5928 5929 if (BuiltinID) 5930 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5931 } else if (NDecl) { 5932 if (CheckPointerCall(NDecl, TheCall, Proto)) 5933 return ExprError(); 5934 } else { 5935 if (CheckOtherCall(TheCall, Proto)) 5936 return ExprError(); 5937 } 5938 5939 return MaybeBindToTemporary(TheCall); 5940 } 5941 5942 ExprResult 5943 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5944 SourceLocation RParenLoc, Expr *InitExpr) { 5945 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5946 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 5947 5948 TypeSourceInfo *TInfo; 5949 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5950 if (!TInfo) 5951 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5952 5953 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5954 } 5955 5956 ExprResult 5957 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5958 SourceLocation RParenLoc, Expr *LiteralExpr) { 5959 QualType literalType = TInfo->getType(); 5960 5961 if (literalType->isArrayType()) { 5962 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5963 diag::err_illegal_decl_array_incomplete_type, 5964 SourceRange(LParenLoc, 5965 LiteralExpr->getSourceRange().getEnd()))) 5966 return ExprError(); 5967 if (literalType->isVariableArrayType()) 5968 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5969 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5970 } else if (!literalType->isDependentType() && 5971 RequireCompleteType(LParenLoc, literalType, 5972 diag::err_typecheck_decl_incomplete_type, 5973 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5974 return ExprError(); 5975 5976 InitializedEntity Entity 5977 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5978 InitializationKind Kind 5979 = InitializationKind::CreateCStyleCast(LParenLoc, 5980 SourceRange(LParenLoc, RParenLoc), 5981 /*InitList=*/true); 5982 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5983 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5984 &literalType); 5985 if (Result.isInvalid()) 5986 return ExprError(); 5987 LiteralExpr = Result.get(); 5988 5989 bool isFileScope = !CurContext->isFunctionOrMethod(); 5990 5991 // In C, compound literals are l-values for some reason. 5992 // For GCC compatibility, in C++, file-scope array compound literals with 5993 // constant initializers are also l-values, and compound literals are 5994 // otherwise prvalues. 5995 // 5996 // (GCC also treats C++ list-initialized file-scope array prvalues with 5997 // constant initializers as l-values, but that's non-conforming, so we don't 5998 // follow it there.) 5999 // 6000 // FIXME: It would be better to handle the lvalue cases as materializing and 6001 // lifetime-extending a temporary object, but our materialized temporaries 6002 // representation only supports lifetime extension from a variable, not "out 6003 // of thin air". 6004 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 6005 // is bound to the result of applying array-to-pointer decay to the compound 6006 // literal. 6007 // FIXME: GCC supports compound literals of reference type, which should 6008 // obviously have a value kind derived from the kind of reference involved. 6009 ExprValueKind VK = 6010 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 6011 ? VK_RValue 6012 : VK_LValue; 6013 6014 if (isFileScope) 6015 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 6016 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 6017 Expr *Init = ILE->getInit(i); 6018 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 6019 } 6020 6021 Expr *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 6022 VK, LiteralExpr, isFileScope); 6023 if (isFileScope) { 6024 if (!LiteralExpr->isTypeDependent() && 6025 !LiteralExpr->isValueDependent() && 6026 !literalType->isDependentType()) // C99 6.5.2.5p3 6027 if (CheckForConstantInitializer(LiteralExpr, literalType)) 6028 return ExprError(); 6029 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 6030 literalType.getAddressSpace() != LangAS::Default) { 6031 // Embedded-C extensions to C99 6.5.2.5: 6032 // "If the compound literal occurs inside the body of a function, the 6033 // type name shall not be qualified by an address-space qualifier." 6034 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 6035 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 6036 return ExprError(); 6037 } 6038 6039 return MaybeBindToTemporary(E); 6040 } 6041 6042 ExprResult 6043 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6044 SourceLocation RBraceLoc) { 6045 // Immediately handle non-overload placeholders. Overloads can be 6046 // resolved contextually, but everything else here can't. 6047 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6048 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 6049 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 6050 6051 // Ignore failures; dropping the entire initializer list because 6052 // of one failure would be terrible for indexing/etc. 6053 if (result.isInvalid()) continue; 6054 6055 InitArgList[I] = result.get(); 6056 } 6057 } 6058 6059 // Semantic analysis for initializers is done by ActOnDeclarator() and 6060 // CheckInitializer() - it requires knowledge of the object being initialized. 6061 6062 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 6063 RBraceLoc); 6064 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 6065 return E; 6066 } 6067 6068 /// Do an explicit extend of the given block pointer if we're in ARC. 6069 void Sema::maybeExtendBlockObject(ExprResult &E) { 6070 assert(E.get()->getType()->isBlockPointerType()); 6071 assert(E.get()->isRValue()); 6072 6073 // Only do this in an r-value context. 6074 if (!getLangOpts().ObjCAutoRefCount) return; 6075 6076 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 6077 CK_ARCExtendBlockObject, E.get(), 6078 /*base path*/ nullptr, VK_RValue); 6079 Cleanup.setExprNeedsCleanups(true); 6080 } 6081 6082 /// Prepare a conversion of the given expression to an ObjC object 6083 /// pointer type. 6084 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 6085 QualType type = E.get()->getType(); 6086 if (type->isObjCObjectPointerType()) { 6087 return CK_BitCast; 6088 } else if (type->isBlockPointerType()) { 6089 maybeExtendBlockObject(E); 6090 return CK_BlockPointerToObjCPointerCast; 6091 } else { 6092 assert(type->isPointerType()); 6093 return CK_CPointerToObjCPointerCast; 6094 } 6095 } 6096 6097 /// Prepares for a scalar cast, performing all the necessary stages 6098 /// except the final cast and returning the kind required. 6099 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 6100 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 6101 // Also, callers should have filtered out the invalid cases with 6102 // pointers. Everything else should be possible. 6103 6104 QualType SrcTy = Src.get()->getType(); 6105 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 6106 return CK_NoOp; 6107 6108 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 6109 case Type::STK_MemberPointer: 6110 llvm_unreachable("member pointer type in C"); 6111 6112 case Type::STK_CPointer: 6113 case Type::STK_BlockPointer: 6114 case Type::STK_ObjCObjectPointer: 6115 switch (DestTy->getScalarTypeKind()) { 6116 case Type::STK_CPointer: { 6117 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 6118 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 6119 if (SrcAS != DestAS) 6120 return CK_AddressSpaceConversion; 6121 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 6122 return CK_NoOp; 6123 return CK_BitCast; 6124 } 6125 case Type::STK_BlockPointer: 6126 return (SrcKind == Type::STK_BlockPointer 6127 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 6128 case Type::STK_ObjCObjectPointer: 6129 if (SrcKind == Type::STK_ObjCObjectPointer) 6130 return CK_BitCast; 6131 if (SrcKind == Type::STK_CPointer) 6132 return CK_CPointerToObjCPointerCast; 6133 maybeExtendBlockObject(Src); 6134 return CK_BlockPointerToObjCPointerCast; 6135 case Type::STK_Bool: 6136 return CK_PointerToBoolean; 6137 case Type::STK_Integral: 6138 return CK_PointerToIntegral; 6139 case Type::STK_Floating: 6140 case Type::STK_FloatingComplex: 6141 case Type::STK_IntegralComplex: 6142 case Type::STK_MemberPointer: 6143 case Type::STK_FixedPoint: 6144 llvm_unreachable("illegal cast from pointer"); 6145 } 6146 llvm_unreachable("Should have returned before this"); 6147 6148 case Type::STK_FixedPoint: 6149 switch (DestTy->getScalarTypeKind()) { 6150 case Type::STK_FixedPoint: 6151 return CK_FixedPointCast; 6152 case Type::STK_Bool: 6153 return CK_FixedPointToBoolean; 6154 case Type::STK_Integral: 6155 return CK_FixedPointToIntegral; 6156 case Type::STK_Floating: 6157 case Type::STK_IntegralComplex: 6158 case Type::STK_FloatingComplex: 6159 Diag(Src.get()->getExprLoc(), 6160 diag::err_unimplemented_conversion_with_fixed_point_type) 6161 << DestTy; 6162 return CK_IntegralCast; 6163 case Type::STK_CPointer: 6164 case Type::STK_ObjCObjectPointer: 6165 case Type::STK_BlockPointer: 6166 case Type::STK_MemberPointer: 6167 llvm_unreachable("illegal cast to pointer type"); 6168 } 6169 llvm_unreachable("Should have returned before this"); 6170 6171 case Type::STK_Bool: // casting from bool is like casting from an integer 6172 case Type::STK_Integral: 6173 switch (DestTy->getScalarTypeKind()) { 6174 case Type::STK_CPointer: 6175 case Type::STK_ObjCObjectPointer: 6176 case Type::STK_BlockPointer: 6177 if (Src.get()->isNullPointerConstant(Context, 6178 Expr::NPC_ValueDependentIsNull)) 6179 return CK_NullToPointer; 6180 return CK_IntegralToPointer; 6181 case Type::STK_Bool: 6182 return CK_IntegralToBoolean; 6183 case Type::STK_Integral: 6184 return CK_IntegralCast; 6185 case Type::STK_Floating: 6186 return CK_IntegralToFloating; 6187 case Type::STK_IntegralComplex: 6188 Src = ImpCastExprToType(Src.get(), 6189 DestTy->castAs<ComplexType>()->getElementType(), 6190 CK_IntegralCast); 6191 return CK_IntegralRealToComplex; 6192 case Type::STK_FloatingComplex: 6193 Src = ImpCastExprToType(Src.get(), 6194 DestTy->castAs<ComplexType>()->getElementType(), 6195 CK_IntegralToFloating); 6196 return CK_FloatingRealToComplex; 6197 case Type::STK_MemberPointer: 6198 llvm_unreachable("member pointer type in C"); 6199 case Type::STK_FixedPoint: 6200 return CK_IntegralToFixedPoint; 6201 } 6202 llvm_unreachable("Should have returned before this"); 6203 6204 case Type::STK_Floating: 6205 switch (DestTy->getScalarTypeKind()) { 6206 case Type::STK_Floating: 6207 return CK_FloatingCast; 6208 case Type::STK_Bool: 6209 return CK_FloatingToBoolean; 6210 case Type::STK_Integral: 6211 return CK_FloatingToIntegral; 6212 case Type::STK_FloatingComplex: 6213 Src = ImpCastExprToType(Src.get(), 6214 DestTy->castAs<ComplexType>()->getElementType(), 6215 CK_FloatingCast); 6216 return CK_FloatingRealToComplex; 6217 case Type::STK_IntegralComplex: 6218 Src = ImpCastExprToType(Src.get(), 6219 DestTy->castAs<ComplexType>()->getElementType(), 6220 CK_FloatingToIntegral); 6221 return CK_IntegralRealToComplex; 6222 case Type::STK_CPointer: 6223 case Type::STK_ObjCObjectPointer: 6224 case Type::STK_BlockPointer: 6225 llvm_unreachable("valid float->pointer cast?"); 6226 case Type::STK_MemberPointer: 6227 llvm_unreachable("member pointer type in C"); 6228 case Type::STK_FixedPoint: 6229 Diag(Src.get()->getExprLoc(), 6230 diag::err_unimplemented_conversion_with_fixed_point_type) 6231 << SrcTy; 6232 return CK_IntegralCast; 6233 } 6234 llvm_unreachable("Should have returned before this"); 6235 6236 case Type::STK_FloatingComplex: 6237 switch (DestTy->getScalarTypeKind()) { 6238 case Type::STK_FloatingComplex: 6239 return CK_FloatingComplexCast; 6240 case Type::STK_IntegralComplex: 6241 return CK_FloatingComplexToIntegralComplex; 6242 case Type::STK_Floating: { 6243 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 6244 if (Context.hasSameType(ET, DestTy)) 6245 return CK_FloatingComplexToReal; 6246 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 6247 return CK_FloatingCast; 6248 } 6249 case Type::STK_Bool: 6250 return CK_FloatingComplexToBoolean; 6251 case Type::STK_Integral: 6252 Src = ImpCastExprToType(Src.get(), 6253 SrcTy->castAs<ComplexType>()->getElementType(), 6254 CK_FloatingComplexToReal); 6255 return CK_FloatingToIntegral; 6256 case Type::STK_CPointer: 6257 case Type::STK_ObjCObjectPointer: 6258 case Type::STK_BlockPointer: 6259 llvm_unreachable("valid complex float->pointer cast?"); 6260 case Type::STK_MemberPointer: 6261 llvm_unreachable("member pointer type in C"); 6262 case Type::STK_FixedPoint: 6263 Diag(Src.get()->getExprLoc(), 6264 diag::err_unimplemented_conversion_with_fixed_point_type) 6265 << SrcTy; 6266 return CK_IntegralCast; 6267 } 6268 llvm_unreachable("Should have returned before this"); 6269 6270 case Type::STK_IntegralComplex: 6271 switch (DestTy->getScalarTypeKind()) { 6272 case Type::STK_FloatingComplex: 6273 return CK_IntegralComplexToFloatingComplex; 6274 case Type::STK_IntegralComplex: 6275 return CK_IntegralComplexCast; 6276 case Type::STK_Integral: { 6277 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 6278 if (Context.hasSameType(ET, DestTy)) 6279 return CK_IntegralComplexToReal; 6280 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 6281 return CK_IntegralCast; 6282 } 6283 case Type::STK_Bool: 6284 return CK_IntegralComplexToBoolean; 6285 case Type::STK_Floating: 6286 Src = ImpCastExprToType(Src.get(), 6287 SrcTy->castAs<ComplexType>()->getElementType(), 6288 CK_IntegralComplexToReal); 6289 return CK_IntegralToFloating; 6290 case Type::STK_CPointer: 6291 case Type::STK_ObjCObjectPointer: 6292 case Type::STK_BlockPointer: 6293 llvm_unreachable("valid complex int->pointer cast?"); 6294 case Type::STK_MemberPointer: 6295 llvm_unreachable("member pointer type in C"); 6296 case Type::STK_FixedPoint: 6297 Diag(Src.get()->getExprLoc(), 6298 diag::err_unimplemented_conversion_with_fixed_point_type) 6299 << SrcTy; 6300 return CK_IntegralCast; 6301 } 6302 llvm_unreachable("Should have returned before this"); 6303 } 6304 6305 llvm_unreachable("Unhandled scalar cast"); 6306 } 6307 6308 static bool breakDownVectorType(QualType type, uint64_t &len, 6309 QualType &eltType) { 6310 // Vectors are simple. 6311 if (const VectorType *vecType = type->getAs<VectorType>()) { 6312 len = vecType->getNumElements(); 6313 eltType = vecType->getElementType(); 6314 assert(eltType->isScalarType()); 6315 return true; 6316 } 6317 6318 // We allow lax conversion to and from non-vector types, but only if 6319 // they're real types (i.e. non-complex, non-pointer scalar types). 6320 if (!type->isRealType()) return false; 6321 6322 len = 1; 6323 eltType = type; 6324 return true; 6325 } 6326 6327 /// Are the two types lax-compatible vector types? That is, given 6328 /// that one of them is a vector, do they have equal storage sizes, 6329 /// where the storage size is the number of elements times the element 6330 /// size? 6331 /// 6332 /// This will also return false if either of the types is neither a 6333 /// vector nor a real type. 6334 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 6335 assert(destTy->isVectorType() || srcTy->isVectorType()); 6336 6337 // Disallow lax conversions between scalars and ExtVectors (these 6338 // conversions are allowed for other vector types because common headers 6339 // depend on them). Most scalar OP ExtVector cases are handled by the 6340 // splat path anyway, which does what we want (convert, not bitcast). 6341 // What this rules out for ExtVectors is crazy things like char4*float. 6342 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 6343 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 6344 6345 uint64_t srcLen, destLen; 6346 QualType srcEltTy, destEltTy; 6347 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 6348 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 6349 6350 // ASTContext::getTypeSize will return the size rounded up to a 6351 // power of 2, so instead of using that, we need to use the raw 6352 // element size multiplied by the element count. 6353 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 6354 uint64_t destEltSize = Context.getTypeSize(destEltTy); 6355 6356 return (srcLen * srcEltSize == destLen * destEltSize); 6357 } 6358 6359 /// Is this a legal conversion between two types, one of which is 6360 /// known to be a vector type? 6361 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 6362 assert(destTy->isVectorType() || srcTy->isVectorType()); 6363 6364 if (!Context.getLangOpts().LaxVectorConversions) 6365 return false; 6366 return areLaxCompatibleVectorTypes(srcTy, destTy); 6367 } 6368 6369 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 6370 CastKind &Kind) { 6371 assert(VectorTy->isVectorType() && "Not a vector type!"); 6372 6373 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 6374 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 6375 return Diag(R.getBegin(), 6376 Ty->isVectorType() ? 6377 diag::err_invalid_conversion_between_vectors : 6378 diag::err_invalid_conversion_between_vector_and_integer) 6379 << VectorTy << Ty << R; 6380 } else 6381 return Diag(R.getBegin(), 6382 diag::err_invalid_conversion_between_vector_and_scalar) 6383 << VectorTy << Ty << R; 6384 6385 Kind = CK_BitCast; 6386 return false; 6387 } 6388 6389 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 6390 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 6391 6392 if (DestElemTy == SplattedExpr->getType()) 6393 return SplattedExpr; 6394 6395 assert(DestElemTy->isFloatingType() || 6396 DestElemTy->isIntegralOrEnumerationType()); 6397 6398 CastKind CK; 6399 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 6400 // OpenCL requires that we convert `true` boolean expressions to -1, but 6401 // only when splatting vectors. 6402 if (DestElemTy->isFloatingType()) { 6403 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 6404 // in two steps: boolean to signed integral, then to floating. 6405 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 6406 CK_BooleanToSignedIntegral); 6407 SplattedExpr = CastExprRes.get(); 6408 CK = CK_IntegralToFloating; 6409 } else { 6410 CK = CK_BooleanToSignedIntegral; 6411 } 6412 } else { 6413 ExprResult CastExprRes = SplattedExpr; 6414 CK = PrepareScalarCast(CastExprRes, DestElemTy); 6415 if (CastExprRes.isInvalid()) 6416 return ExprError(); 6417 SplattedExpr = CastExprRes.get(); 6418 } 6419 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 6420 } 6421 6422 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 6423 Expr *CastExpr, CastKind &Kind) { 6424 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 6425 6426 QualType SrcTy = CastExpr->getType(); 6427 6428 // If SrcTy is a VectorType, the total size must match to explicitly cast to 6429 // an ExtVectorType. 6430 // In OpenCL, casts between vectors of different types are not allowed. 6431 // (See OpenCL 6.2). 6432 if (SrcTy->isVectorType()) { 6433 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 6434 (getLangOpts().OpenCL && 6435 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 6436 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 6437 << DestTy << SrcTy << R; 6438 return ExprError(); 6439 } 6440 Kind = CK_BitCast; 6441 return CastExpr; 6442 } 6443 6444 // All non-pointer scalars can be cast to ExtVector type. The appropriate 6445 // conversion will take place first from scalar to elt type, and then 6446 // splat from elt type to vector. 6447 if (SrcTy->isPointerType()) 6448 return Diag(R.getBegin(), 6449 diag::err_invalid_conversion_between_vector_and_scalar) 6450 << DestTy << SrcTy << R; 6451 6452 Kind = CK_VectorSplat; 6453 return prepareVectorSplat(DestTy, CastExpr); 6454 } 6455 6456 ExprResult 6457 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 6458 Declarator &D, ParsedType &Ty, 6459 SourceLocation RParenLoc, Expr *CastExpr) { 6460 assert(!D.isInvalidType() && (CastExpr != nullptr) && 6461 "ActOnCastExpr(): missing type or expr"); 6462 6463 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 6464 if (D.isInvalidType()) 6465 return ExprError(); 6466 6467 if (getLangOpts().CPlusPlus) { 6468 // Check that there are no default arguments (C++ only). 6469 CheckExtraCXXDefaultArguments(D); 6470 } else { 6471 // Make sure any TypoExprs have been dealt with. 6472 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 6473 if (!Res.isUsable()) 6474 return ExprError(); 6475 CastExpr = Res.get(); 6476 } 6477 6478 checkUnusedDeclAttributes(D); 6479 6480 QualType castType = castTInfo->getType(); 6481 Ty = CreateParsedType(castType, castTInfo); 6482 6483 bool isVectorLiteral = false; 6484 6485 // Check for an altivec or OpenCL literal, 6486 // i.e. all the elements are integer constants. 6487 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 6488 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 6489 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 6490 && castType->isVectorType() && (PE || PLE)) { 6491 if (PLE && PLE->getNumExprs() == 0) { 6492 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 6493 return ExprError(); 6494 } 6495 if (PE || PLE->getNumExprs() == 1) { 6496 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 6497 if (!E->getType()->isVectorType()) 6498 isVectorLiteral = true; 6499 } 6500 else 6501 isVectorLiteral = true; 6502 } 6503 6504 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 6505 // then handle it as such. 6506 if (isVectorLiteral) 6507 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 6508 6509 // If the Expr being casted is a ParenListExpr, handle it specially. 6510 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 6511 // sequence of BinOp comma operators. 6512 if (isa<ParenListExpr>(CastExpr)) { 6513 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 6514 if (Result.isInvalid()) return ExprError(); 6515 CastExpr = Result.get(); 6516 } 6517 6518 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6519 !getSourceManager().isInSystemMacro(LParenLoc)) 6520 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6521 6522 CheckTollFreeBridgeCast(castType, CastExpr); 6523 6524 CheckObjCBridgeRelatedCast(castType, CastExpr); 6525 6526 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 6527 6528 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6529 } 6530 6531 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6532 SourceLocation RParenLoc, Expr *E, 6533 TypeSourceInfo *TInfo) { 6534 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6535 "Expected paren or paren list expression"); 6536 6537 Expr **exprs; 6538 unsigned numExprs; 6539 Expr *subExpr; 6540 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6541 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6542 LiteralLParenLoc = PE->getLParenLoc(); 6543 LiteralRParenLoc = PE->getRParenLoc(); 6544 exprs = PE->getExprs(); 6545 numExprs = PE->getNumExprs(); 6546 } else { // isa<ParenExpr> by assertion at function entrance 6547 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6548 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6549 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6550 exprs = &subExpr; 6551 numExprs = 1; 6552 } 6553 6554 QualType Ty = TInfo->getType(); 6555 assert(Ty->isVectorType() && "Expected vector type"); 6556 6557 SmallVector<Expr *, 8> initExprs; 6558 const VectorType *VTy = Ty->getAs<VectorType>(); 6559 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 6560 6561 // '(...)' form of vector initialization in AltiVec: the number of 6562 // initializers must be one or must match the size of the vector. 6563 // If a single value is specified in the initializer then it will be 6564 // replicated to all the components of the vector 6565 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6566 // The number of initializers must be one or must match the size of the 6567 // vector. If a single value is specified in the initializer then it will 6568 // be replicated to all the components of the vector 6569 if (numExprs == 1) { 6570 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6571 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6572 if (Literal.isInvalid()) 6573 return ExprError(); 6574 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6575 PrepareScalarCast(Literal, ElemTy)); 6576 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6577 } 6578 else if (numExprs < numElems) { 6579 Diag(E->getExprLoc(), 6580 diag::err_incorrect_number_of_vector_initializers); 6581 return ExprError(); 6582 } 6583 else 6584 initExprs.append(exprs, exprs + numExprs); 6585 } 6586 else { 6587 // For OpenCL, when the number of initializers is a single value, 6588 // it will be replicated to all components of the vector. 6589 if (getLangOpts().OpenCL && 6590 VTy->getVectorKind() == VectorType::GenericVector && 6591 numExprs == 1) { 6592 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6593 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6594 if (Literal.isInvalid()) 6595 return ExprError(); 6596 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6597 PrepareScalarCast(Literal, ElemTy)); 6598 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6599 } 6600 6601 initExprs.append(exprs, exprs + numExprs); 6602 } 6603 // FIXME: This means that pretty-printing the final AST will produce curly 6604 // braces instead of the original commas. 6605 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6606 initExprs, LiteralRParenLoc); 6607 initE->setType(Ty); 6608 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6609 } 6610 6611 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6612 /// the ParenListExpr into a sequence of comma binary operators. 6613 ExprResult 6614 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6615 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6616 if (!E) 6617 return OrigExpr; 6618 6619 ExprResult Result(E->getExpr(0)); 6620 6621 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6622 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6623 E->getExpr(i)); 6624 6625 if (Result.isInvalid()) return ExprError(); 6626 6627 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6628 } 6629 6630 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6631 SourceLocation R, 6632 MultiExprArg Val) { 6633 return ParenListExpr::Create(Context, L, Val, R); 6634 } 6635 6636 /// Emit a specialized diagnostic when one expression is a null pointer 6637 /// constant and the other is not a pointer. Returns true if a diagnostic is 6638 /// emitted. 6639 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6640 SourceLocation QuestionLoc) { 6641 Expr *NullExpr = LHSExpr; 6642 Expr *NonPointerExpr = RHSExpr; 6643 Expr::NullPointerConstantKind NullKind = 6644 NullExpr->isNullPointerConstant(Context, 6645 Expr::NPC_ValueDependentIsNotNull); 6646 6647 if (NullKind == Expr::NPCK_NotNull) { 6648 NullExpr = RHSExpr; 6649 NonPointerExpr = LHSExpr; 6650 NullKind = 6651 NullExpr->isNullPointerConstant(Context, 6652 Expr::NPC_ValueDependentIsNotNull); 6653 } 6654 6655 if (NullKind == Expr::NPCK_NotNull) 6656 return false; 6657 6658 if (NullKind == Expr::NPCK_ZeroExpression) 6659 return false; 6660 6661 if (NullKind == Expr::NPCK_ZeroLiteral) { 6662 // In this case, check to make sure that we got here from a "NULL" 6663 // string in the source code. 6664 NullExpr = NullExpr->IgnoreParenImpCasts(); 6665 SourceLocation loc = NullExpr->getExprLoc(); 6666 if (!findMacroSpelling(loc, "NULL")) 6667 return false; 6668 } 6669 6670 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6671 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6672 << NonPointerExpr->getType() << DiagType 6673 << NonPointerExpr->getSourceRange(); 6674 return true; 6675 } 6676 6677 /// Return false if the condition expression is valid, true otherwise. 6678 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6679 QualType CondTy = Cond->getType(); 6680 6681 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6682 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6683 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6684 << CondTy << Cond->getSourceRange(); 6685 return true; 6686 } 6687 6688 // C99 6.5.15p2 6689 if (CondTy->isScalarType()) return false; 6690 6691 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6692 << CondTy << Cond->getSourceRange(); 6693 return true; 6694 } 6695 6696 /// Handle when one or both operands are void type. 6697 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6698 ExprResult &RHS) { 6699 Expr *LHSExpr = LHS.get(); 6700 Expr *RHSExpr = RHS.get(); 6701 6702 if (!LHSExpr->getType()->isVoidType()) 6703 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 6704 << RHSExpr->getSourceRange(); 6705 if (!RHSExpr->getType()->isVoidType()) 6706 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 6707 << LHSExpr->getSourceRange(); 6708 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6709 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6710 return S.Context.VoidTy; 6711 } 6712 6713 /// Return false if the NullExpr can be promoted to PointerTy, 6714 /// true otherwise. 6715 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6716 QualType PointerTy) { 6717 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6718 !NullExpr.get()->isNullPointerConstant(S.Context, 6719 Expr::NPC_ValueDependentIsNull)) 6720 return true; 6721 6722 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6723 return false; 6724 } 6725 6726 /// Checks compatibility between two pointers and return the resulting 6727 /// type. 6728 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6729 ExprResult &RHS, 6730 SourceLocation Loc) { 6731 QualType LHSTy = LHS.get()->getType(); 6732 QualType RHSTy = RHS.get()->getType(); 6733 6734 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6735 // Two identical pointers types are always compatible. 6736 return LHSTy; 6737 } 6738 6739 QualType lhptee, rhptee; 6740 6741 // Get the pointee types. 6742 bool IsBlockPointer = false; 6743 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6744 lhptee = LHSBTy->getPointeeType(); 6745 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6746 IsBlockPointer = true; 6747 } else { 6748 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6749 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6750 } 6751 6752 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6753 // differently qualified versions of compatible types, the result type is 6754 // a pointer to an appropriately qualified version of the composite 6755 // type. 6756 6757 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6758 // clause doesn't make sense for our extensions. E.g. address space 2 should 6759 // be incompatible with address space 3: they may live on different devices or 6760 // anything. 6761 Qualifiers lhQual = lhptee.getQualifiers(); 6762 Qualifiers rhQual = rhptee.getQualifiers(); 6763 6764 LangAS ResultAddrSpace = LangAS::Default; 6765 LangAS LAddrSpace = lhQual.getAddressSpace(); 6766 LangAS RAddrSpace = rhQual.getAddressSpace(); 6767 6768 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 6769 // spaces is disallowed. 6770 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 6771 ResultAddrSpace = LAddrSpace; 6772 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 6773 ResultAddrSpace = RAddrSpace; 6774 else { 6775 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 6776 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 6777 << RHS.get()->getSourceRange(); 6778 return QualType(); 6779 } 6780 6781 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6782 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 6783 lhQual.removeCVRQualifiers(); 6784 rhQual.removeCVRQualifiers(); 6785 6786 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 6787 // (C99 6.7.3) for address spaces. We assume that the check should behave in 6788 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 6789 // qual types are compatible iff 6790 // * corresponded types are compatible 6791 // * CVR qualifiers are equal 6792 // * address spaces are equal 6793 // Thus for conditional operator we merge CVR and address space unqualified 6794 // pointees and if there is a composite type we return a pointer to it with 6795 // merged qualifiers. 6796 LHSCastKind = 6797 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 6798 RHSCastKind = 6799 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 6800 lhQual.removeAddressSpace(); 6801 rhQual.removeAddressSpace(); 6802 6803 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 6804 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 6805 6806 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 6807 6808 if (CompositeTy.isNull()) { 6809 // In this situation, we assume void* type. No especially good 6810 // reason, but this is what gcc does, and we do have to pick 6811 // to get a consistent AST. 6812 QualType incompatTy; 6813 incompatTy = S.Context.getPointerType( 6814 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 6815 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 6816 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 6817 6818 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 6819 // for casts between types with incompatible address space qualifiers. 6820 // For the following code the compiler produces casts between global and 6821 // local address spaces of the corresponded innermost pointees: 6822 // local int *global *a; 6823 // global int *global *b; 6824 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 6825 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 6826 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6827 << RHS.get()->getSourceRange(); 6828 6829 return incompatTy; 6830 } 6831 6832 // The pointer types are compatible. 6833 // In case of OpenCL ResultTy should have the address space qualifier 6834 // which is a superset of address spaces of both the 2nd and the 3rd 6835 // operands of the conditional operator. 6836 QualType ResultTy = [&, ResultAddrSpace]() { 6837 if (S.getLangOpts().OpenCL) { 6838 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 6839 CompositeQuals.setAddressSpace(ResultAddrSpace); 6840 return S.Context 6841 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 6842 .withCVRQualifiers(MergedCVRQual); 6843 } 6844 return CompositeTy.withCVRQualifiers(MergedCVRQual); 6845 }(); 6846 if (IsBlockPointer) 6847 ResultTy = S.Context.getBlockPointerType(ResultTy); 6848 else 6849 ResultTy = S.Context.getPointerType(ResultTy); 6850 6851 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 6852 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 6853 return ResultTy; 6854 } 6855 6856 /// Return the resulting type when the operands are both block pointers. 6857 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 6858 ExprResult &LHS, 6859 ExprResult &RHS, 6860 SourceLocation Loc) { 6861 QualType LHSTy = LHS.get()->getType(); 6862 QualType RHSTy = RHS.get()->getType(); 6863 6864 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 6865 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 6866 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 6867 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6868 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6869 return destType; 6870 } 6871 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 6872 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6873 << RHS.get()->getSourceRange(); 6874 return QualType(); 6875 } 6876 6877 // We have 2 block pointer types. 6878 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6879 } 6880 6881 /// Return the resulting type when the operands are both pointers. 6882 static QualType 6883 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 6884 ExprResult &RHS, 6885 SourceLocation Loc) { 6886 // get the pointer types 6887 QualType LHSTy = LHS.get()->getType(); 6888 QualType RHSTy = RHS.get()->getType(); 6889 6890 // get the "pointed to" types 6891 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6892 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6893 6894 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 6895 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 6896 // Figure out necessary qualifiers (C99 6.5.15p6) 6897 QualType destPointee 6898 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6899 QualType destType = S.Context.getPointerType(destPointee); 6900 // Add qualifiers if necessary. 6901 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6902 // Promote to void*. 6903 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6904 return destType; 6905 } 6906 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 6907 QualType destPointee 6908 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6909 QualType destType = S.Context.getPointerType(destPointee); 6910 // Add qualifiers if necessary. 6911 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6912 // Promote to void*. 6913 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6914 return destType; 6915 } 6916 6917 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6918 } 6919 6920 /// Return false if the first expression is not an integer and the second 6921 /// expression is not a pointer, true otherwise. 6922 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 6923 Expr* PointerExpr, SourceLocation Loc, 6924 bool IsIntFirstExpr) { 6925 if (!PointerExpr->getType()->isPointerType() || 6926 !Int.get()->getType()->isIntegerType()) 6927 return false; 6928 6929 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 6930 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 6931 6932 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 6933 << Expr1->getType() << Expr2->getType() 6934 << Expr1->getSourceRange() << Expr2->getSourceRange(); 6935 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 6936 CK_IntegralToPointer); 6937 return true; 6938 } 6939 6940 /// Simple conversion between integer and floating point types. 6941 /// 6942 /// Used when handling the OpenCL conditional operator where the 6943 /// condition is a vector while the other operands are scalar. 6944 /// 6945 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 6946 /// types are either integer or floating type. Between the two 6947 /// operands, the type with the higher rank is defined as the "result 6948 /// type". The other operand needs to be promoted to the same type. No 6949 /// other type promotion is allowed. We cannot use 6950 /// UsualArithmeticConversions() for this purpose, since it always 6951 /// promotes promotable types. 6952 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 6953 ExprResult &RHS, 6954 SourceLocation QuestionLoc) { 6955 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 6956 if (LHS.isInvalid()) 6957 return QualType(); 6958 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 6959 if (RHS.isInvalid()) 6960 return QualType(); 6961 6962 // For conversion purposes, we ignore any qualifiers. 6963 // For example, "const float" and "float" are equivalent. 6964 QualType LHSType = 6965 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6966 QualType RHSType = 6967 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6968 6969 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 6970 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6971 << LHSType << LHS.get()->getSourceRange(); 6972 return QualType(); 6973 } 6974 6975 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 6976 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6977 << RHSType << RHS.get()->getSourceRange(); 6978 return QualType(); 6979 } 6980 6981 // If both types are identical, no conversion is needed. 6982 if (LHSType == RHSType) 6983 return LHSType; 6984 6985 // Now handle "real" floating types (i.e. float, double, long double). 6986 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 6987 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 6988 /*IsCompAssign = */ false); 6989 6990 // Finally, we have two differing integer types. 6991 return handleIntegerConversion<doIntegralCast, doIntegralCast> 6992 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 6993 } 6994 6995 /// Convert scalar operands to a vector that matches the 6996 /// condition in length. 6997 /// 6998 /// Used when handling the OpenCL conditional operator where the 6999 /// condition is a vector while the other operands are scalar. 7000 /// 7001 /// We first compute the "result type" for the scalar operands 7002 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 7003 /// into a vector of that type where the length matches the condition 7004 /// vector type. s6.11.6 requires that the element types of the result 7005 /// and the condition must have the same number of bits. 7006 static QualType 7007 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 7008 QualType CondTy, SourceLocation QuestionLoc) { 7009 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 7010 if (ResTy.isNull()) return QualType(); 7011 7012 const VectorType *CV = CondTy->getAs<VectorType>(); 7013 assert(CV); 7014 7015 // Determine the vector result type 7016 unsigned NumElements = CV->getNumElements(); 7017 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 7018 7019 // Ensure that all types have the same number of bits 7020 if (S.Context.getTypeSize(CV->getElementType()) 7021 != S.Context.getTypeSize(ResTy)) { 7022 // Since VectorTy is created internally, it does not pretty print 7023 // with an OpenCL name. Instead, we just print a description. 7024 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 7025 SmallString<64> Str; 7026 llvm::raw_svector_ostream OS(Str); 7027 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 7028 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 7029 << CondTy << OS.str(); 7030 return QualType(); 7031 } 7032 7033 // Convert operands to the vector result type 7034 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 7035 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 7036 7037 return VectorTy; 7038 } 7039 7040 /// Return false if this is a valid OpenCL condition vector 7041 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 7042 SourceLocation QuestionLoc) { 7043 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 7044 // integral type. 7045 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 7046 assert(CondTy); 7047 QualType EleTy = CondTy->getElementType(); 7048 if (EleTy->isIntegerType()) return false; 7049 7050 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7051 << Cond->getType() << Cond->getSourceRange(); 7052 return true; 7053 } 7054 7055 /// Return false if the vector condition type and the vector 7056 /// result type are compatible. 7057 /// 7058 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 7059 /// number of elements, and their element types have the same number 7060 /// of bits. 7061 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 7062 SourceLocation QuestionLoc) { 7063 const VectorType *CV = CondTy->getAs<VectorType>(); 7064 const VectorType *RV = VecResTy->getAs<VectorType>(); 7065 assert(CV && RV); 7066 7067 if (CV->getNumElements() != RV->getNumElements()) { 7068 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 7069 << CondTy << VecResTy; 7070 return true; 7071 } 7072 7073 QualType CVE = CV->getElementType(); 7074 QualType RVE = RV->getElementType(); 7075 7076 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 7077 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 7078 << CondTy << VecResTy; 7079 return true; 7080 } 7081 7082 return false; 7083 } 7084 7085 /// Return the resulting type for the conditional operator in 7086 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 7087 /// s6.3.i) when the condition is a vector type. 7088 static QualType 7089 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 7090 ExprResult &LHS, ExprResult &RHS, 7091 SourceLocation QuestionLoc) { 7092 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 7093 if (Cond.isInvalid()) 7094 return QualType(); 7095 QualType CondTy = Cond.get()->getType(); 7096 7097 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 7098 return QualType(); 7099 7100 // If either operand is a vector then find the vector type of the 7101 // result as specified in OpenCL v1.1 s6.3.i. 7102 if (LHS.get()->getType()->isVectorType() || 7103 RHS.get()->getType()->isVectorType()) { 7104 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 7105 /*isCompAssign*/false, 7106 /*AllowBothBool*/true, 7107 /*AllowBoolConversions*/false); 7108 if (VecResTy.isNull()) return QualType(); 7109 // The result type must match the condition type as specified in 7110 // OpenCL v1.1 s6.11.6. 7111 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 7112 return QualType(); 7113 return VecResTy; 7114 } 7115 7116 // Both operands are scalar. 7117 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 7118 } 7119 7120 /// Return true if the Expr is block type 7121 static bool checkBlockType(Sema &S, const Expr *E) { 7122 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 7123 QualType Ty = CE->getCallee()->getType(); 7124 if (Ty->isBlockPointerType()) { 7125 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 7126 return true; 7127 } 7128 } 7129 return false; 7130 } 7131 7132 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 7133 /// In that case, LHS = cond. 7134 /// C99 6.5.15 7135 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 7136 ExprResult &RHS, ExprValueKind &VK, 7137 ExprObjectKind &OK, 7138 SourceLocation QuestionLoc) { 7139 7140 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 7141 if (!LHSResult.isUsable()) return QualType(); 7142 LHS = LHSResult; 7143 7144 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 7145 if (!RHSResult.isUsable()) return QualType(); 7146 RHS = RHSResult; 7147 7148 // C++ is sufficiently different to merit its own checker. 7149 if (getLangOpts().CPlusPlus) 7150 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 7151 7152 VK = VK_RValue; 7153 OK = OK_Ordinary; 7154 7155 // The OpenCL operator with a vector condition is sufficiently 7156 // different to merit its own checker. 7157 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 7158 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 7159 7160 // First, check the condition. 7161 Cond = UsualUnaryConversions(Cond.get()); 7162 if (Cond.isInvalid()) 7163 return QualType(); 7164 if (checkCondition(*this, Cond.get(), QuestionLoc)) 7165 return QualType(); 7166 7167 // Now check the two expressions. 7168 if (LHS.get()->getType()->isVectorType() || 7169 RHS.get()->getType()->isVectorType()) 7170 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 7171 /*AllowBothBool*/true, 7172 /*AllowBoolConversions*/false); 7173 7174 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 7175 if (LHS.isInvalid() || RHS.isInvalid()) 7176 return QualType(); 7177 7178 QualType LHSTy = LHS.get()->getType(); 7179 QualType RHSTy = RHS.get()->getType(); 7180 7181 // Diagnose attempts to convert between __float128 and long double where 7182 // such conversions currently can't be handled. 7183 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 7184 Diag(QuestionLoc, 7185 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 7186 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7187 return QualType(); 7188 } 7189 7190 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 7191 // selection operator (?:). 7192 if (getLangOpts().OpenCL && 7193 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 7194 return QualType(); 7195 } 7196 7197 // If both operands have arithmetic type, do the usual arithmetic conversions 7198 // to find a common type: C99 6.5.15p3,5. 7199 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 7200 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 7201 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 7202 7203 return ResTy; 7204 } 7205 7206 // If both operands are the same structure or union type, the result is that 7207 // type. 7208 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 7209 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 7210 if (LHSRT->getDecl() == RHSRT->getDecl()) 7211 // "If both the operands have structure or union type, the result has 7212 // that type." This implies that CV qualifiers are dropped. 7213 return LHSTy.getUnqualifiedType(); 7214 // FIXME: Type of conditional expression must be complete in C mode. 7215 } 7216 7217 // C99 6.5.15p5: "If both operands have void type, the result has void type." 7218 // The following || allows only one side to be void (a GCC-ism). 7219 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 7220 return checkConditionalVoidType(*this, LHS, RHS); 7221 } 7222 7223 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 7224 // the type of the other operand." 7225 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 7226 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 7227 7228 // All objective-c pointer type analysis is done here. 7229 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 7230 QuestionLoc); 7231 if (LHS.isInvalid() || RHS.isInvalid()) 7232 return QualType(); 7233 if (!compositeType.isNull()) 7234 return compositeType; 7235 7236 7237 // Handle block pointer types. 7238 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 7239 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 7240 QuestionLoc); 7241 7242 // Check constraints for C object pointers types (C99 6.5.15p3,6). 7243 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 7244 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 7245 QuestionLoc); 7246 7247 // GCC compatibility: soften pointer/integer mismatch. Note that 7248 // null pointers have been filtered out by this point. 7249 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 7250 /*isIntFirstExpr=*/true)) 7251 return RHSTy; 7252 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 7253 /*isIntFirstExpr=*/false)) 7254 return LHSTy; 7255 7256 // Emit a better diagnostic if one of the expressions is a null pointer 7257 // constant and the other is not a pointer type. In this case, the user most 7258 // likely forgot to take the address of the other expression. 7259 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 7260 return QualType(); 7261 7262 // Otherwise, the operands are not compatible. 7263 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 7264 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7265 << RHS.get()->getSourceRange(); 7266 return QualType(); 7267 } 7268 7269 /// FindCompositeObjCPointerType - Helper method to find composite type of 7270 /// two objective-c pointer types of the two input expressions. 7271 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 7272 SourceLocation QuestionLoc) { 7273 QualType LHSTy = LHS.get()->getType(); 7274 QualType RHSTy = RHS.get()->getType(); 7275 7276 // Handle things like Class and struct objc_class*. Here we case the result 7277 // to the pseudo-builtin, because that will be implicitly cast back to the 7278 // redefinition type if an attempt is made to access its fields. 7279 if (LHSTy->isObjCClassType() && 7280 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 7281 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 7282 return LHSTy; 7283 } 7284 if (RHSTy->isObjCClassType() && 7285 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 7286 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 7287 return RHSTy; 7288 } 7289 // And the same for struct objc_object* / id 7290 if (LHSTy->isObjCIdType() && 7291 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 7292 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 7293 return LHSTy; 7294 } 7295 if (RHSTy->isObjCIdType() && 7296 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 7297 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 7298 return RHSTy; 7299 } 7300 // And the same for struct objc_selector* / SEL 7301 if (Context.isObjCSelType(LHSTy) && 7302 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 7303 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 7304 return LHSTy; 7305 } 7306 if (Context.isObjCSelType(RHSTy) && 7307 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 7308 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 7309 return RHSTy; 7310 } 7311 // Check constraints for Objective-C object pointers types. 7312 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 7313 7314 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 7315 // Two identical object pointer types are always compatible. 7316 return LHSTy; 7317 } 7318 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 7319 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 7320 QualType compositeType = LHSTy; 7321 7322 // If both operands are interfaces and either operand can be 7323 // assigned to the other, use that type as the composite 7324 // type. This allows 7325 // xxx ? (A*) a : (B*) b 7326 // where B is a subclass of A. 7327 // 7328 // Additionally, as for assignment, if either type is 'id' 7329 // allow silent coercion. Finally, if the types are 7330 // incompatible then make sure to use 'id' as the composite 7331 // type so the result is acceptable for sending messages to. 7332 7333 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 7334 // It could return the composite type. 7335 if (!(compositeType = 7336 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 7337 // Nothing more to do. 7338 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 7339 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 7340 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 7341 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 7342 } else if ((LHSTy->isObjCQualifiedIdType() || 7343 RHSTy->isObjCQualifiedIdType()) && 7344 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 7345 // Need to handle "id<xx>" explicitly. 7346 // GCC allows qualified id and any Objective-C type to devolve to 7347 // id. Currently localizing to here until clear this should be 7348 // part of ObjCQualifiedIdTypesAreCompatible. 7349 compositeType = Context.getObjCIdType(); 7350 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 7351 compositeType = Context.getObjCIdType(); 7352 } else { 7353 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 7354 << LHSTy << RHSTy 7355 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7356 QualType incompatTy = Context.getObjCIdType(); 7357 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 7358 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 7359 return incompatTy; 7360 } 7361 // The object pointer types are compatible. 7362 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 7363 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 7364 return compositeType; 7365 } 7366 // Check Objective-C object pointer types and 'void *' 7367 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 7368 if (getLangOpts().ObjCAutoRefCount) { 7369 // ARC forbids the implicit conversion of object pointers to 'void *', 7370 // so these types are not compatible. 7371 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7372 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7373 LHS = RHS = true; 7374 return QualType(); 7375 } 7376 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 7377 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 7378 QualType destPointee 7379 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7380 QualType destType = Context.getPointerType(destPointee); 7381 // Add qualifiers if necessary. 7382 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7383 // Promote to void*. 7384 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7385 return destType; 7386 } 7387 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 7388 if (getLangOpts().ObjCAutoRefCount) { 7389 // ARC forbids the implicit conversion of object pointers to 'void *', 7390 // so these types are not compatible. 7391 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7392 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7393 LHS = RHS = true; 7394 return QualType(); 7395 } 7396 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 7397 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 7398 QualType destPointee 7399 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7400 QualType destType = Context.getPointerType(destPointee); 7401 // Add qualifiers if necessary. 7402 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7403 // Promote to void*. 7404 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7405 return destType; 7406 } 7407 return QualType(); 7408 } 7409 7410 /// SuggestParentheses - Emit a note with a fixit hint that wraps 7411 /// ParenRange in parentheses. 7412 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 7413 const PartialDiagnostic &Note, 7414 SourceRange ParenRange) { 7415 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 7416 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 7417 EndLoc.isValid()) { 7418 Self.Diag(Loc, Note) 7419 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 7420 << FixItHint::CreateInsertion(EndLoc, ")"); 7421 } else { 7422 // We can't display the parentheses, so just show the bare note. 7423 Self.Diag(Loc, Note) << ParenRange; 7424 } 7425 } 7426 7427 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 7428 return BinaryOperator::isAdditiveOp(Opc) || 7429 BinaryOperator::isMultiplicativeOp(Opc) || 7430 BinaryOperator::isShiftOp(Opc); 7431 } 7432 7433 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 7434 /// expression, either using a built-in or overloaded operator, 7435 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 7436 /// expression. 7437 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 7438 Expr **RHSExprs) { 7439 // Don't strip parenthesis: we should not warn if E is in parenthesis. 7440 E = E->IgnoreImpCasts(); 7441 E = E->IgnoreConversionOperator(); 7442 E = E->IgnoreImpCasts(); 7443 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 7444 E = MTE->GetTemporaryExpr(); 7445 E = E->IgnoreImpCasts(); 7446 } 7447 7448 // Built-in binary operator. 7449 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 7450 if (IsArithmeticOp(OP->getOpcode())) { 7451 *Opcode = OP->getOpcode(); 7452 *RHSExprs = OP->getRHS(); 7453 return true; 7454 } 7455 } 7456 7457 // Overloaded operator. 7458 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 7459 if (Call->getNumArgs() != 2) 7460 return false; 7461 7462 // Make sure this is really a binary operator that is safe to pass into 7463 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 7464 OverloadedOperatorKind OO = Call->getOperator(); 7465 if (OO < OO_Plus || OO > OO_Arrow || 7466 OO == OO_PlusPlus || OO == OO_MinusMinus) 7467 return false; 7468 7469 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 7470 if (IsArithmeticOp(OpKind)) { 7471 *Opcode = OpKind; 7472 *RHSExprs = Call->getArg(1); 7473 return true; 7474 } 7475 } 7476 7477 return false; 7478 } 7479 7480 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 7481 /// or is a logical expression such as (x==y) which has int type, but is 7482 /// commonly interpreted as boolean. 7483 static bool ExprLooksBoolean(Expr *E) { 7484 E = E->IgnoreParenImpCasts(); 7485 7486 if (E->getType()->isBooleanType()) 7487 return true; 7488 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 7489 return OP->isComparisonOp() || OP->isLogicalOp(); 7490 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 7491 return OP->getOpcode() == UO_LNot; 7492 if (E->getType()->isPointerType()) 7493 return true; 7494 // FIXME: What about overloaded operator calls returning "unspecified boolean 7495 // type"s (commonly pointer-to-members)? 7496 7497 return false; 7498 } 7499 7500 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 7501 /// and binary operator are mixed in a way that suggests the programmer assumed 7502 /// the conditional operator has higher precedence, for example: 7503 /// "int x = a + someBinaryCondition ? 1 : 2". 7504 static void DiagnoseConditionalPrecedence(Sema &Self, 7505 SourceLocation OpLoc, 7506 Expr *Condition, 7507 Expr *LHSExpr, 7508 Expr *RHSExpr) { 7509 BinaryOperatorKind CondOpcode; 7510 Expr *CondRHS; 7511 7512 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 7513 return; 7514 if (!ExprLooksBoolean(CondRHS)) 7515 return; 7516 7517 // The condition is an arithmetic binary expression, with a right- 7518 // hand side that looks boolean, so warn. 7519 7520 Self.Diag(OpLoc, diag::warn_precedence_conditional) 7521 << Condition->getSourceRange() 7522 << BinaryOperator::getOpcodeStr(CondOpcode); 7523 7524 SuggestParentheses( 7525 Self, OpLoc, 7526 Self.PDiag(diag::note_precedence_silence) 7527 << BinaryOperator::getOpcodeStr(CondOpcode), 7528 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 7529 7530 SuggestParentheses(Self, OpLoc, 7531 Self.PDiag(diag::note_precedence_conditional_first), 7532 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 7533 } 7534 7535 /// Compute the nullability of a conditional expression. 7536 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 7537 QualType LHSTy, QualType RHSTy, 7538 ASTContext &Ctx) { 7539 if (!ResTy->isAnyPointerType()) 7540 return ResTy; 7541 7542 auto GetNullability = [&Ctx](QualType Ty) { 7543 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 7544 if (Kind) 7545 return *Kind; 7546 return NullabilityKind::Unspecified; 7547 }; 7548 7549 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 7550 NullabilityKind MergedKind; 7551 7552 // Compute nullability of a binary conditional expression. 7553 if (IsBin) { 7554 if (LHSKind == NullabilityKind::NonNull) 7555 MergedKind = NullabilityKind::NonNull; 7556 else 7557 MergedKind = RHSKind; 7558 // Compute nullability of a normal conditional expression. 7559 } else { 7560 if (LHSKind == NullabilityKind::Nullable || 7561 RHSKind == NullabilityKind::Nullable) 7562 MergedKind = NullabilityKind::Nullable; 7563 else if (LHSKind == NullabilityKind::NonNull) 7564 MergedKind = RHSKind; 7565 else if (RHSKind == NullabilityKind::NonNull) 7566 MergedKind = LHSKind; 7567 else 7568 MergedKind = NullabilityKind::Unspecified; 7569 } 7570 7571 // Return if ResTy already has the correct nullability. 7572 if (GetNullability(ResTy) == MergedKind) 7573 return ResTy; 7574 7575 // Strip all nullability from ResTy. 7576 while (ResTy->getNullability(Ctx)) 7577 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 7578 7579 // Create a new AttributedType with the new nullability kind. 7580 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 7581 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 7582 } 7583 7584 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7585 /// in the case of a the GNU conditional expr extension. 7586 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7587 SourceLocation ColonLoc, 7588 Expr *CondExpr, Expr *LHSExpr, 7589 Expr *RHSExpr) { 7590 if (!getLangOpts().CPlusPlus) { 7591 // C cannot handle TypoExpr nodes in the condition because it 7592 // doesn't handle dependent types properly, so make sure any TypoExprs have 7593 // been dealt with before checking the operands. 7594 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7595 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7596 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7597 7598 if (!CondResult.isUsable()) 7599 return ExprError(); 7600 7601 if (LHSExpr) { 7602 if (!LHSResult.isUsable()) 7603 return ExprError(); 7604 } 7605 7606 if (!RHSResult.isUsable()) 7607 return ExprError(); 7608 7609 CondExpr = CondResult.get(); 7610 LHSExpr = LHSResult.get(); 7611 RHSExpr = RHSResult.get(); 7612 } 7613 7614 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7615 // was the condition. 7616 OpaqueValueExpr *opaqueValue = nullptr; 7617 Expr *commonExpr = nullptr; 7618 if (!LHSExpr) { 7619 commonExpr = CondExpr; 7620 // Lower out placeholder types first. This is important so that we don't 7621 // try to capture a placeholder. This happens in few cases in C++; such 7622 // as Objective-C++'s dictionary subscripting syntax. 7623 if (commonExpr->hasPlaceholderType()) { 7624 ExprResult result = CheckPlaceholderExpr(commonExpr); 7625 if (!result.isUsable()) return ExprError(); 7626 commonExpr = result.get(); 7627 } 7628 // We usually want to apply unary conversions *before* saving, except 7629 // in the special case of a C++ l-value conditional. 7630 if (!(getLangOpts().CPlusPlus 7631 && !commonExpr->isTypeDependent() 7632 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7633 && commonExpr->isGLValue() 7634 && commonExpr->isOrdinaryOrBitFieldObject() 7635 && RHSExpr->isOrdinaryOrBitFieldObject() 7636 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7637 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7638 if (commonRes.isInvalid()) 7639 return ExprError(); 7640 commonExpr = commonRes.get(); 7641 } 7642 7643 // If the common expression is a class or array prvalue, materialize it 7644 // so that we can safely refer to it multiple times. 7645 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 7646 commonExpr->getType()->isArrayType())) { 7647 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 7648 if (MatExpr.isInvalid()) 7649 return ExprError(); 7650 commonExpr = MatExpr.get(); 7651 } 7652 7653 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7654 commonExpr->getType(), 7655 commonExpr->getValueKind(), 7656 commonExpr->getObjectKind(), 7657 commonExpr); 7658 LHSExpr = CondExpr = opaqueValue; 7659 } 7660 7661 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 7662 ExprValueKind VK = VK_RValue; 7663 ExprObjectKind OK = OK_Ordinary; 7664 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7665 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7666 VK, OK, QuestionLoc); 7667 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7668 RHS.isInvalid()) 7669 return ExprError(); 7670 7671 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7672 RHS.get()); 7673 7674 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 7675 7676 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 7677 Context); 7678 7679 if (!commonExpr) 7680 return new (Context) 7681 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 7682 RHS.get(), result, VK, OK); 7683 7684 return new (Context) BinaryConditionalOperator( 7685 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 7686 ColonLoc, result, VK, OK); 7687 } 7688 7689 // checkPointerTypesForAssignment - This is a very tricky routine (despite 7690 // being closely modeled after the C99 spec:-). The odd characteristic of this 7691 // routine is it effectively iqnores the qualifiers on the top level pointee. 7692 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 7693 // FIXME: add a couple examples in this comment. 7694 static Sema::AssignConvertType 7695 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 7696 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7697 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7698 7699 // get the "pointed to" type (ignoring qualifiers at the top level) 7700 const Type *lhptee, *rhptee; 7701 Qualifiers lhq, rhq; 7702 std::tie(lhptee, lhq) = 7703 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 7704 std::tie(rhptee, rhq) = 7705 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 7706 7707 Sema::AssignConvertType ConvTy = Sema::Compatible; 7708 7709 // C99 6.5.16.1p1: This following citation is common to constraints 7710 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 7711 // qualifiers of the type *pointed to* by the right; 7712 7713 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 7714 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 7715 lhq.compatiblyIncludesObjCLifetime(rhq)) { 7716 // Ignore lifetime for further calculation. 7717 lhq.removeObjCLifetime(); 7718 rhq.removeObjCLifetime(); 7719 } 7720 7721 if (!lhq.compatiblyIncludes(rhq)) { 7722 // Treat address-space mismatches as fatal. TODO: address subspaces 7723 if (!lhq.isAddressSpaceSupersetOf(rhq)) 7724 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7725 7726 // It's okay to add or remove GC or lifetime qualifiers when converting to 7727 // and from void*. 7728 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 7729 .compatiblyIncludes( 7730 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 7731 && (lhptee->isVoidType() || rhptee->isVoidType())) 7732 ; // keep old 7733 7734 // Treat lifetime mismatches as fatal. 7735 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 7736 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7737 7738 // For GCC/MS compatibility, other qualifier mismatches are treated 7739 // as still compatible in C. 7740 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7741 } 7742 7743 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 7744 // incomplete type and the other is a pointer to a qualified or unqualified 7745 // version of void... 7746 if (lhptee->isVoidType()) { 7747 if (rhptee->isIncompleteOrObjectType()) 7748 return ConvTy; 7749 7750 // As an extension, we allow cast to/from void* to function pointer. 7751 assert(rhptee->isFunctionType()); 7752 return Sema::FunctionVoidPointer; 7753 } 7754 7755 if (rhptee->isVoidType()) { 7756 if (lhptee->isIncompleteOrObjectType()) 7757 return ConvTy; 7758 7759 // As an extension, we allow cast to/from void* to function pointer. 7760 assert(lhptee->isFunctionType()); 7761 return Sema::FunctionVoidPointer; 7762 } 7763 7764 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7765 // unqualified versions of compatible types, ... 7766 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7767 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7768 // Check if the pointee types are compatible ignoring the sign. 7769 // We explicitly check for char so that we catch "char" vs 7770 // "unsigned char" on systems where "char" is unsigned. 7771 if (lhptee->isCharType()) 7772 ltrans = S.Context.UnsignedCharTy; 7773 else if (lhptee->hasSignedIntegerRepresentation()) 7774 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7775 7776 if (rhptee->isCharType()) 7777 rtrans = S.Context.UnsignedCharTy; 7778 else if (rhptee->hasSignedIntegerRepresentation()) 7779 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 7780 7781 if (ltrans == rtrans) { 7782 // Types are compatible ignoring the sign. Qualifier incompatibility 7783 // takes priority over sign incompatibility because the sign 7784 // warning can be disabled. 7785 if (ConvTy != Sema::Compatible) 7786 return ConvTy; 7787 7788 return Sema::IncompatiblePointerSign; 7789 } 7790 7791 // If we are a multi-level pointer, it's possible that our issue is simply 7792 // one of qualification - e.g. char ** -> const char ** is not allowed. If 7793 // the eventual target type is the same and the pointers have the same 7794 // level of indirection, this must be the issue. 7795 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 7796 do { 7797 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 7798 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 7799 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 7800 7801 if (lhptee == rhptee) 7802 return Sema::IncompatibleNestedPointerQualifiers; 7803 } 7804 7805 // General pointer incompatibility takes priority over qualifiers. 7806 return Sema::IncompatiblePointer; 7807 } 7808 if (!S.getLangOpts().CPlusPlus && 7809 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 7810 return Sema::IncompatiblePointer; 7811 return ConvTy; 7812 } 7813 7814 /// checkBlockPointerTypesForAssignment - This routine determines whether two 7815 /// block pointer types are compatible or whether a block and normal pointer 7816 /// are compatible. It is more restrict than comparing two function pointer 7817 // types. 7818 static Sema::AssignConvertType 7819 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 7820 QualType RHSType) { 7821 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7822 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7823 7824 QualType lhptee, rhptee; 7825 7826 // get the "pointed to" type (ignoring qualifiers at the top level) 7827 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 7828 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 7829 7830 // In C++, the types have to match exactly. 7831 if (S.getLangOpts().CPlusPlus) 7832 return Sema::IncompatibleBlockPointer; 7833 7834 Sema::AssignConvertType ConvTy = Sema::Compatible; 7835 7836 // For blocks we enforce that qualifiers are identical. 7837 Qualifiers LQuals = lhptee.getLocalQualifiers(); 7838 Qualifiers RQuals = rhptee.getLocalQualifiers(); 7839 if (S.getLangOpts().OpenCL) { 7840 LQuals.removeAddressSpace(); 7841 RQuals.removeAddressSpace(); 7842 } 7843 if (LQuals != RQuals) 7844 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7845 7846 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 7847 // assignment. 7848 // The current behavior is similar to C++ lambdas. A block might be 7849 // assigned to a variable iff its return type and parameters are compatible 7850 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 7851 // an assignment. Presumably it should behave in way that a function pointer 7852 // assignment does in C, so for each parameter and return type: 7853 // * CVR and address space of LHS should be a superset of CVR and address 7854 // space of RHS. 7855 // * unqualified types should be compatible. 7856 if (S.getLangOpts().OpenCL) { 7857 if (!S.Context.typesAreBlockPointerCompatible( 7858 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 7859 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 7860 return Sema::IncompatibleBlockPointer; 7861 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 7862 return Sema::IncompatibleBlockPointer; 7863 7864 return ConvTy; 7865 } 7866 7867 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 7868 /// for assignment compatibility. 7869 static Sema::AssignConvertType 7870 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 7871 QualType RHSType) { 7872 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 7873 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 7874 7875 if (LHSType->isObjCBuiltinType()) { 7876 // Class is not compatible with ObjC object pointers. 7877 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 7878 !RHSType->isObjCQualifiedClassType()) 7879 return Sema::IncompatiblePointer; 7880 return Sema::Compatible; 7881 } 7882 if (RHSType->isObjCBuiltinType()) { 7883 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 7884 !LHSType->isObjCQualifiedClassType()) 7885 return Sema::IncompatiblePointer; 7886 return Sema::Compatible; 7887 } 7888 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7889 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7890 7891 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 7892 // make an exception for id<P> 7893 !LHSType->isObjCQualifiedIdType()) 7894 return Sema::CompatiblePointerDiscardsQualifiers; 7895 7896 if (S.Context.typesAreCompatible(LHSType, RHSType)) 7897 return Sema::Compatible; 7898 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 7899 return Sema::IncompatibleObjCQualifiedId; 7900 return Sema::IncompatiblePointer; 7901 } 7902 7903 Sema::AssignConvertType 7904 Sema::CheckAssignmentConstraints(SourceLocation Loc, 7905 QualType LHSType, QualType RHSType) { 7906 // Fake up an opaque expression. We don't actually care about what 7907 // cast operations are required, so if CheckAssignmentConstraints 7908 // adds casts to this they'll be wasted, but fortunately that doesn't 7909 // usually happen on valid code. 7910 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 7911 ExprResult RHSPtr = &RHSExpr; 7912 CastKind K; 7913 7914 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 7915 } 7916 7917 /// This helper function returns true if QT is a vector type that has element 7918 /// type ElementType. 7919 static bool isVector(QualType QT, QualType ElementType) { 7920 if (const VectorType *VT = QT->getAs<VectorType>()) 7921 return VT->getElementType() == ElementType; 7922 return false; 7923 } 7924 7925 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 7926 /// has code to accommodate several GCC extensions when type checking 7927 /// pointers. Here are some objectionable examples that GCC considers warnings: 7928 /// 7929 /// int a, *pint; 7930 /// short *pshort; 7931 /// struct foo *pfoo; 7932 /// 7933 /// pint = pshort; // warning: assignment from incompatible pointer type 7934 /// a = pint; // warning: assignment makes integer from pointer without a cast 7935 /// pint = a; // warning: assignment makes pointer from integer without a cast 7936 /// pint = pfoo; // warning: assignment from incompatible pointer type 7937 /// 7938 /// As a result, the code for dealing with pointers is more complex than the 7939 /// C99 spec dictates. 7940 /// 7941 /// Sets 'Kind' for any result kind except Incompatible. 7942 Sema::AssignConvertType 7943 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 7944 CastKind &Kind, bool ConvertRHS) { 7945 QualType RHSType = RHS.get()->getType(); 7946 QualType OrigLHSType = LHSType; 7947 7948 // Get canonical types. We're not formatting these types, just comparing 7949 // them. 7950 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 7951 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 7952 7953 // Common case: no conversion required. 7954 if (LHSType == RHSType) { 7955 Kind = CK_NoOp; 7956 return Compatible; 7957 } 7958 7959 // If we have an atomic type, try a non-atomic assignment, then just add an 7960 // atomic qualification step. 7961 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 7962 Sema::AssignConvertType result = 7963 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 7964 if (result != Compatible) 7965 return result; 7966 if (Kind != CK_NoOp && ConvertRHS) 7967 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 7968 Kind = CK_NonAtomicToAtomic; 7969 return Compatible; 7970 } 7971 7972 // If the left-hand side is a reference type, then we are in a 7973 // (rare!) case where we've allowed the use of references in C, 7974 // e.g., as a parameter type in a built-in function. In this case, 7975 // just make sure that the type referenced is compatible with the 7976 // right-hand side type. The caller is responsible for adjusting 7977 // LHSType so that the resulting expression does not have reference 7978 // type. 7979 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 7980 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 7981 Kind = CK_LValueBitCast; 7982 return Compatible; 7983 } 7984 return Incompatible; 7985 } 7986 7987 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 7988 // to the same ExtVector type. 7989 if (LHSType->isExtVectorType()) { 7990 if (RHSType->isExtVectorType()) 7991 return Incompatible; 7992 if (RHSType->isArithmeticType()) { 7993 // CK_VectorSplat does T -> vector T, so first cast to the element type. 7994 if (ConvertRHS) 7995 RHS = prepareVectorSplat(LHSType, RHS.get()); 7996 Kind = CK_VectorSplat; 7997 return Compatible; 7998 } 7999 } 8000 8001 // Conversions to or from vector type. 8002 if (LHSType->isVectorType() || RHSType->isVectorType()) { 8003 if (LHSType->isVectorType() && RHSType->isVectorType()) { 8004 // Allow assignments of an AltiVec vector type to an equivalent GCC 8005 // vector type and vice versa 8006 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8007 Kind = CK_BitCast; 8008 return Compatible; 8009 } 8010 8011 // If we are allowing lax vector conversions, and LHS and RHS are both 8012 // vectors, the total size only needs to be the same. This is a bitcast; 8013 // no bits are changed but the result type is different. 8014 if (isLaxVectorConversion(RHSType, LHSType)) { 8015 Kind = CK_BitCast; 8016 return IncompatibleVectors; 8017 } 8018 } 8019 8020 // When the RHS comes from another lax conversion (e.g. binops between 8021 // scalars and vectors) the result is canonicalized as a vector. When the 8022 // LHS is also a vector, the lax is allowed by the condition above. Handle 8023 // the case where LHS is a scalar. 8024 if (LHSType->isScalarType()) { 8025 const VectorType *VecType = RHSType->getAs<VectorType>(); 8026 if (VecType && VecType->getNumElements() == 1 && 8027 isLaxVectorConversion(RHSType, LHSType)) { 8028 ExprResult *VecExpr = &RHS; 8029 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 8030 Kind = CK_BitCast; 8031 return Compatible; 8032 } 8033 } 8034 8035 return Incompatible; 8036 } 8037 8038 // Diagnose attempts to convert between __float128 and long double where 8039 // such conversions currently can't be handled. 8040 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 8041 return Incompatible; 8042 8043 // Disallow assigning a _Complex to a real type in C++ mode since it simply 8044 // discards the imaginary part. 8045 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 8046 !LHSType->getAs<ComplexType>()) 8047 return Incompatible; 8048 8049 // Arithmetic conversions. 8050 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 8051 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 8052 if (ConvertRHS) 8053 Kind = PrepareScalarCast(RHS, LHSType); 8054 return Compatible; 8055 } 8056 8057 // Conversions to normal pointers. 8058 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 8059 // U* -> T* 8060 if (isa<PointerType>(RHSType)) { 8061 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 8062 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 8063 if (AddrSpaceL != AddrSpaceR) 8064 Kind = CK_AddressSpaceConversion; 8065 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 8066 Kind = CK_NoOp; 8067 else 8068 Kind = CK_BitCast; 8069 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 8070 } 8071 8072 // int -> T* 8073 if (RHSType->isIntegerType()) { 8074 Kind = CK_IntegralToPointer; // FIXME: null? 8075 return IntToPointer; 8076 } 8077 8078 // C pointers are not compatible with ObjC object pointers, 8079 // with two exceptions: 8080 if (isa<ObjCObjectPointerType>(RHSType)) { 8081 // - conversions to void* 8082 if (LHSPointer->getPointeeType()->isVoidType()) { 8083 Kind = CK_BitCast; 8084 return Compatible; 8085 } 8086 8087 // - conversions from 'Class' to the redefinition type 8088 if (RHSType->isObjCClassType() && 8089 Context.hasSameType(LHSType, 8090 Context.getObjCClassRedefinitionType())) { 8091 Kind = CK_BitCast; 8092 return Compatible; 8093 } 8094 8095 Kind = CK_BitCast; 8096 return IncompatiblePointer; 8097 } 8098 8099 // U^ -> void* 8100 if (RHSType->getAs<BlockPointerType>()) { 8101 if (LHSPointer->getPointeeType()->isVoidType()) { 8102 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 8103 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 8104 ->getPointeeType() 8105 .getAddressSpace(); 8106 Kind = 8107 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 8108 return Compatible; 8109 } 8110 } 8111 8112 return Incompatible; 8113 } 8114 8115 // Conversions to block pointers. 8116 if (isa<BlockPointerType>(LHSType)) { 8117 // U^ -> T^ 8118 if (RHSType->isBlockPointerType()) { 8119 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 8120 ->getPointeeType() 8121 .getAddressSpace(); 8122 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 8123 ->getPointeeType() 8124 .getAddressSpace(); 8125 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 8126 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 8127 } 8128 8129 // int or null -> T^ 8130 if (RHSType->isIntegerType()) { 8131 Kind = CK_IntegralToPointer; // FIXME: null 8132 return IntToBlockPointer; 8133 } 8134 8135 // id -> T^ 8136 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 8137 Kind = CK_AnyPointerToBlockPointerCast; 8138 return Compatible; 8139 } 8140 8141 // void* -> T^ 8142 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 8143 if (RHSPT->getPointeeType()->isVoidType()) { 8144 Kind = CK_AnyPointerToBlockPointerCast; 8145 return Compatible; 8146 } 8147 8148 return Incompatible; 8149 } 8150 8151 // Conversions to Objective-C pointers. 8152 if (isa<ObjCObjectPointerType>(LHSType)) { 8153 // A* -> B* 8154 if (RHSType->isObjCObjectPointerType()) { 8155 Kind = CK_BitCast; 8156 Sema::AssignConvertType result = 8157 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 8158 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8159 result == Compatible && 8160 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 8161 result = IncompatibleObjCWeakRef; 8162 return result; 8163 } 8164 8165 // int or null -> A* 8166 if (RHSType->isIntegerType()) { 8167 Kind = CK_IntegralToPointer; // FIXME: null 8168 return IntToPointer; 8169 } 8170 8171 // In general, C pointers are not compatible with ObjC object pointers, 8172 // with two exceptions: 8173 if (isa<PointerType>(RHSType)) { 8174 Kind = CK_CPointerToObjCPointerCast; 8175 8176 // - conversions from 'void*' 8177 if (RHSType->isVoidPointerType()) { 8178 return Compatible; 8179 } 8180 8181 // - conversions to 'Class' from its redefinition type 8182 if (LHSType->isObjCClassType() && 8183 Context.hasSameType(RHSType, 8184 Context.getObjCClassRedefinitionType())) { 8185 return Compatible; 8186 } 8187 8188 return IncompatiblePointer; 8189 } 8190 8191 // Only under strict condition T^ is compatible with an Objective-C pointer. 8192 if (RHSType->isBlockPointerType() && 8193 LHSType->isBlockCompatibleObjCPointerType(Context)) { 8194 if (ConvertRHS) 8195 maybeExtendBlockObject(RHS); 8196 Kind = CK_BlockPointerToObjCPointerCast; 8197 return Compatible; 8198 } 8199 8200 return Incompatible; 8201 } 8202 8203 // Conversions from pointers that are not covered by the above. 8204 if (isa<PointerType>(RHSType)) { 8205 // T* -> _Bool 8206 if (LHSType == Context.BoolTy) { 8207 Kind = CK_PointerToBoolean; 8208 return Compatible; 8209 } 8210 8211 // T* -> int 8212 if (LHSType->isIntegerType()) { 8213 Kind = CK_PointerToIntegral; 8214 return PointerToInt; 8215 } 8216 8217 return Incompatible; 8218 } 8219 8220 // Conversions from Objective-C pointers that are not covered by the above. 8221 if (isa<ObjCObjectPointerType>(RHSType)) { 8222 // T* -> _Bool 8223 if (LHSType == Context.BoolTy) { 8224 Kind = CK_PointerToBoolean; 8225 return Compatible; 8226 } 8227 8228 // T* -> int 8229 if (LHSType->isIntegerType()) { 8230 Kind = CK_PointerToIntegral; 8231 return PointerToInt; 8232 } 8233 8234 return Incompatible; 8235 } 8236 8237 // struct A -> struct B 8238 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 8239 if (Context.typesAreCompatible(LHSType, RHSType)) { 8240 Kind = CK_NoOp; 8241 return Compatible; 8242 } 8243 } 8244 8245 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 8246 Kind = CK_IntToOCLSampler; 8247 return Compatible; 8248 } 8249 8250 return Incompatible; 8251 } 8252 8253 /// Constructs a transparent union from an expression that is 8254 /// used to initialize the transparent union. 8255 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 8256 ExprResult &EResult, QualType UnionType, 8257 FieldDecl *Field) { 8258 // Build an initializer list that designates the appropriate member 8259 // of the transparent union. 8260 Expr *E = EResult.get(); 8261 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 8262 E, SourceLocation()); 8263 Initializer->setType(UnionType); 8264 Initializer->setInitializedFieldInUnion(Field); 8265 8266 // Build a compound literal constructing a value of the transparent 8267 // union type from this initializer list. 8268 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 8269 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 8270 VK_RValue, Initializer, false); 8271 } 8272 8273 Sema::AssignConvertType 8274 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 8275 ExprResult &RHS) { 8276 QualType RHSType = RHS.get()->getType(); 8277 8278 // If the ArgType is a Union type, we want to handle a potential 8279 // transparent_union GCC extension. 8280 const RecordType *UT = ArgType->getAsUnionType(); 8281 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 8282 return Incompatible; 8283 8284 // The field to initialize within the transparent union. 8285 RecordDecl *UD = UT->getDecl(); 8286 FieldDecl *InitField = nullptr; 8287 // It's compatible if the expression matches any of the fields. 8288 for (auto *it : UD->fields()) { 8289 if (it->getType()->isPointerType()) { 8290 // If the transparent union contains a pointer type, we allow: 8291 // 1) void pointer 8292 // 2) null pointer constant 8293 if (RHSType->isPointerType()) 8294 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 8295 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 8296 InitField = it; 8297 break; 8298 } 8299 8300 if (RHS.get()->isNullPointerConstant(Context, 8301 Expr::NPC_ValueDependentIsNull)) { 8302 RHS = ImpCastExprToType(RHS.get(), it->getType(), 8303 CK_NullToPointer); 8304 InitField = it; 8305 break; 8306 } 8307 } 8308 8309 CastKind Kind; 8310 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 8311 == Compatible) { 8312 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 8313 InitField = it; 8314 break; 8315 } 8316 } 8317 8318 if (!InitField) 8319 return Incompatible; 8320 8321 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 8322 return Compatible; 8323 } 8324 8325 Sema::AssignConvertType 8326 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 8327 bool Diagnose, 8328 bool DiagnoseCFAudited, 8329 bool ConvertRHS) { 8330 // We need to be able to tell the caller whether we diagnosed a problem, if 8331 // they ask us to issue diagnostics. 8332 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 8333 8334 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 8335 // we can't avoid *all* modifications at the moment, so we need some somewhere 8336 // to put the updated value. 8337 ExprResult LocalRHS = CallerRHS; 8338 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 8339 8340 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 8341 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 8342 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 8343 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 8344 Diag(RHS.get()->getExprLoc(), 8345 diag::warn_noderef_to_dereferenceable_pointer) 8346 << RHS.get()->getSourceRange(); 8347 } 8348 } 8349 } 8350 8351 if (getLangOpts().CPlusPlus) { 8352 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 8353 // C++ 5.17p3: If the left operand is not of class type, the 8354 // expression is implicitly converted (C++ 4) to the 8355 // cv-unqualified type of the left operand. 8356 QualType RHSType = RHS.get()->getType(); 8357 if (Diagnose) { 8358 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8359 AA_Assigning); 8360 } else { 8361 ImplicitConversionSequence ICS = 8362 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8363 /*SuppressUserConversions=*/false, 8364 /*AllowExplicit=*/false, 8365 /*InOverloadResolution=*/false, 8366 /*CStyle=*/false, 8367 /*AllowObjCWritebackConversion=*/false); 8368 if (ICS.isFailure()) 8369 return Incompatible; 8370 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8371 ICS, AA_Assigning); 8372 } 8373 if (RHS.isInvalid()) 8374 return Incompatible; 8375 Sema::AssignConvertType result = Compatible; 8376 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8377 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 8378 result = IncompatibleObjCWeakRef; 8379 return result; 8380 } 8381 8382 // FIXME: Currently, we fall through and treat C++ classes like C 8383 // structures. 8384 // FIXME: We also fall through for atomics; not sure what should 8385 // happen there, though. 8386 } else if (RHS.get()->getType() == Context.OverloadTy) { 8387 // As a set of extensions to C, we support overloading on functions. These 8388 // functions need to be resolved here. 8389 DeclAccessPair DAP; 8390 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 8391 RHS.get(), LHSType, /*Complain=*/false, DAP)) 8392 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 8393 else 8394 return Incompatible; 8395 } 8396 8397 // C99 6.5.16.1p1: the left operand is a pointer and the right is 8398 // a null pointer constant. 8399 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 8400 LHSType->isBlockPointerType()) && 8401 RHS.get()->isNullPointerConstant(Context, 8402 Expr::NPC_ValueDependentIsNull)) { 8403 if (Diagnose || ConvertRHS) { 8404 CastKind Kind; 8405 CXXCastPath Path; 8406 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 8407 /*IgnoreBaseAccess=*/false, Diagnose); 8408 if (ConvertRHS) 8409 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 8410 } 8411 return Compatible; 8412 } 8413 8414 // OpenCL queue_t type assignment. 8415 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 8416 Context, Expr::NPC_ValueDependentIsNull)) { 8417 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 8418 return Compatible; 8419 } 8420 8421 // This check seems unnatural, however it is necessary to ensure the proper 8422 // conversion of functions/arrays. If the conversion were done for all 8423 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 8424 // expressions that suppress this implicit conversion (&, sizeof). 8425 // 8426 // Suppress this for references: C++ 8.5.3p5. 8427 if (!LHSType->isReferenceType()) { 8428 // FIXME: We potentially allocate here even if ConvertRHS is false. 8429 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 8430 if (RHS.isInvalid()) 8431 return Incompatible; 8432 } 8433 CastKind Kind; 8434 Sema::AssignConvertType result = 8435 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 8436 8437 // C99 6.5.16.1p2: The value of the right operand is converted to the 8438 // type of the assignment expression. 8439 // CheckAssignmentConstraints allows the left-hand side to be a reference, 8440 // so that we can use references in built-in functions even in C. 8441 // The getNonReferenceType() call makes sure that the resulting expression 8442 // does not have reference type. 8443 if (result != Incompatible && RHS.get()->getType() != LHSType) { 8444 QualType Ty = LHSType.getNonLValueExprType(Context); 8445 Expr *E = RHS.get(); 8446 8447 // Check for various Objective-C errors. If we are not reporting 8448 // diagnostics and just checking for errors, e.g., during overload 8449 // resolution, return Incompatible to indicate the failure. 8450 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8451 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 8452 Diagnose, DiagnoseCFAudited) != ACR_okay) { 8453 if (!Diagnose) 8454 return Incompatible; 8455 } 8456 if (getLangOpts().ObjC && 8457 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 8458 E->getType(), E, Diagnose) || 8459 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 8460 if (!Diagnose) 8461 return Incompatible; 8462 // Replace the expression with a corrected version and continue so we 8463 // can find further errors. 8464 RHS = E; 8465 return Compatible; 8466 } 8467 8468 if (ConvertRHS) 8469 RHS = ImpCastExprToType(E, Ty, Kind); 8470 } 8471 8472 return result; 8473 } 8474 8475 namespace { 8476 /// The original operand to an operator, prior to the application of the usual 8477 /// arithmetic conversions and converting the arguments of a builtin operator 8478 /// candidate. 8479 struct OriginalOperand { 8480 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 8481 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 8482 Op = MTE->GetTemporaryExpr(); 8483 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 8484 Op = BTE->getSubExpr(); 8485 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 8486 Orig = ICE->getSubExprAsWritten(); 8487 Conversion = ICE->getConversionFunction(); 8488 } 8489 } 8490 8491 QualType getType() const { return Orig->getType(); } 8492 8493 Expr *Orig; 8494 NamedDecl *Conversion; 8495 }; 8496 } 8497 8498 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 8499 ExprResult &RHS) { 8500 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 8501 8502 Diag(Loc, diag::err_typecheck_invalid_operands) 8503 << OrigLHS.getType() << OrigRHS.getType() 8504 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8505 8506 // If a user-defined conversion was applied to either of the operands prior 8507 // to applying the built-in operator rules, tell the user about it. 8508 if (OrigLHS.Conversion) { 8509 Diag(OrigLHS.Conversion->getLocation(), 8510 diag::note_typecheck_invalid_operands_converted) 8511 << 0 << LHS.get()->getType(); 8512 } 8513 if (OrigRHS.Conversion) { 8514 Diag(OrigRHS.Conversion->getLocation(), 8515 diag::note_typecheck_invalid_operands_converted) 8516 << 1 << RHS.get()->getType(); 8517 } 8518 8519 return QualType(); 8520 } 8521 8522 // Diagnose cases where a scalar was implicitly converted to a vector and 8523 // diagnose the underlying types. Otherwise, diagnose the error 8524 // as invalid vector logical operands for non-C++ cases. 8525 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 8526 ExprResult &RHS) { 8527 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 8528 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 8529 8530 bool LHSNatVec = LHSType->isVectorType(); 8531 bool RHSNatVec = RHSType->isVectorType(); 8532 8533 if (!(LHSNatVec && RHSNatVec)) { 8534 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 8535 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 8536 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8537 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 8538 << Vector->getSourceRange(); 8539 return QualType(); 8540 } 8541 8542 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8543 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 8544 << RHS.get()->getSourceRange(); 8545 8546 return QualType(); 8547 } 8548 8549 /// Try to convert a value of non-vector type to a vector type by converting 8550 /// the type to the element type of the vector and then performing a splat. 8551 /// If the language is OpenCL, we only use conversions that promote scalar 8552 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 8553 /// for float->int. 8554 /// 8555 /// OpenCL V2.0 6.2.6.p2: 8556 /// An error shall occur if any scalar operand type has greater rank 8557 /// than the type of the vector element. 8558 /// 8559 /// \param scalar - if non-null, actually perform the conversions 8560 /// \return true if the operation fails (but without diagnosing the failure) 8561 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 8562 QualType scalarTy, 8563 QualType vectorEltTy, 8564 QualType vectorTy, 8565 unsigned &DiagID) { 8566 // The conversion to apply to the scalar before splatting it, 8567 // if necessary. 8568 CastKind scalarCast = CK_NoOp; 8569 8570 if (vectorEltTy->isIntegralType(S.Context)) { 8571 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 8572 (scalarTy->isIntegerType() && 8573 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 8574 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8575 return true; 8576 } 8577 if (!scalarTy->isIntegralType(S.Context)) 8578 return true; 8579 scalarCast = CK_IntegralCast; 8580 } else if (vectorEltTy->isRealFloatingType()) { 8581 if (scalarTy->isRealFloatingType()) { 8582 if (S.getLangOpts().OpenCL && 8583 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 8584 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8585 return true; 8586 } 8587 scalarCast = CK_FloatingCast; 8588 } 8589 else if (scalarTy->isIntegralType(S.Context)) 8590 scalarCast = CK_IntegralToFloating; 8591 else 8592 return true; 8593 } else { 8594 return true; 8595 } 8596 8597 // Adjust scalar if desired. 8598 if (scalar) { 8599 if (scalarCast != CK_NoOp) 8600 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 8601 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 8602 } 8603 return false; 8604 } 8605 8606 /// Convert vector E to a vector with the same number of elements but different 8607 /// element type. 8608 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 8609 const auto *VecTy = E->getType()->getAs<VectorType>(); 8610 assert(VecTy && "Expression E must be a vector"); 8611 QualType NewVecTy = S.Context.getVectorType(ElementType, 8612 VecTy->getNumElements(), 8613 VecTy->getVectorKind()); 8614 8615 // Look through the implicit cast. Return the subexpression if its type is 8616 // NewVecTy. 8617 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 8618 if (ICE->getSubExpr()->getType() == NewVecTy) 8619 return ICE->getSubExpr(); 8620 8621 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 8622 return S.ImpCastExprToType(E, NewVecTy, Cast); 8623 } 8624 8625 /// Test if a (constant) integer Int can be casted to another integer type 8626 /// IntTy without losing precision. 8627 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 8628 QualType OtherIntTy) { 8629 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8630 8631 // Reject cases where the value of the Int is unknown as that would 8632 // possibly cause truncation, but accept cases where the scalar can be 8633 // demoted without loss of precision. 8634 Expr::EvalResult EVResult; 8635 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 8636 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 8637 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 8638 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 8639 8640 if (CstInt) { 8641 // If the scalar is constant and is of a higher order and has more active 8642 // bits that the vector element type, reject it. 8643 llvm::APSInt Result = EVResult.Val.getInt(); 8644 unsigned NumBits = IntSigned 8645 ? (Result.isNegative() ? Result.getMinSignedBits() 8646 : Result.getActiveBits()) 8647 : Result.getActiveBits(); 8648 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 8649 return true; 8650 8651 // If the signedness of the scalar type and the vector element type 8652 // differs and the number of bits is greater than that of the vector 8653 // element reject it. 8654 return (IntSigned != OtherIntSigned && 8655 NumBits > S.Context.getIntWidth(OtherIntTy)); 8656 } 8657 8658 // Reject cases where the value of the scalar is not constant and it's 8659 // order is greater than that of the vector element type. 8660 return (Order < 0); 8661 } 8662 8663 /// Test if a (constant) integer Int can be casted to floating point type 8664 /// FloatTy without losing precision. 8665 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 8666 QualType FloatTy) { 8667 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8668 8669 // Determine if the integer constant can be expressed as a floating point 8670 // number of the appropriate type. 8671 Expr::EvalResult EVResult; 8672 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 8673 8674 uint64_t Bits = 0; 8675 if (CstInt) { 8676 // Reject constants that would be truncated if they were converted to 8677 // the floating point type. Test by simple to/from conversion. 8678 // FIXME: Ideally the conversion to an APFloat and from an APFloat 8679 // could be avoided if there was a convertFromAPInt method 8680 // which could signal back if implicit truncation occurred. 8681 llvm::APSInt Result = EVResult.Val.getInt(); 8682 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 8683 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 8684 llvm::APFloat::rmTowardZero); 8685 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 8686 !IntTy->hasSignedIntegerRepresentation()); 8687 bool Ignored = false; 8688 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 8689 &Ignored); 8690 if (Result != ConvertBack) 8691 return true; 8692 } else { 8693 // Reject types that cannot be fully encoded into the mantissa of 8694 // the float. 8695 Bits = S.Context.getTypeSize(IntTy); 8696 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 8697 S.Context.getFloatTypeSemantics(FloatTy)); 8698 if (Bits > FloatPrec) 8699 return true; 8700 } 8701 8702 return false; 8703 } 8704 8705 /// Attempt to convert and splat Scalar into a vector whose types matches 8706 /// Vector following GCC conversion rules. The rule is that implicit 8707 /// conversion can occur when Scalar can be casted to match Vector's element 8708 /// type without causing truncation of Scalar. 8709 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 8710 ExprResult *Vector) { 8711 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 8712 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 8713 const VectorType *VT = VectorTy->getAs<VectorType>(); 8714 8715 assert(!isa<ExtVectorType>(VT) && 8716 "ExtVectorTypes should not be handled here!"); 8717 8718 QualType VectorEltTy = VT->getElementType(); 8719 8720 // Reject cases where the vector element type or the scalar element type are 8721 // not integral or floating point types. 8722 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 8723 return true; 8724 8725 // The conversion to apply to the scalar before splatting it, 8726 // if necessary. 8727 CastKind ScalarCast = CK_NoOp; 8728 8729 // Accept cases where the vector elements are integers and the scalar is 8730 // an integer. 8731 // FIXME: Notionally if the scalar was a floating point value with a precise 8732 // integral representation, we could cast it to an appropriate integer 8733 // type and then perform the rest of the checks here. GCC will perform 8734 // this conversion in some cases as determined by the input language. 8735 // We should accept it on a language independent basis. 8736 if (VectorEltTy->isIntegralType(S.Context) && 8737 ScalarTy->isIntegralType(S.Context) && 8738 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 8739 8740 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 8741 return true; 8742 8743 ScalarCast = CK_IntegralCast; 8744 } else if (VectorEltTy->isRealFloatingType()) { 8745 if (ScalarTy->isRealFloatingType()) { 8746 8747 // Reject cases where the scalar type is not a constant and has a higher 8748 // Order than the vector element type. 8749 llvm::APFloat Result(0.0); 8750 bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context); 8751 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 8752 if (!CstScalar && Order < 0) 8753 return true; 8754 8755 // If the scalar cannot be safely casted to the vector element type, 8756 // reject it. 8757 if (CstScalar) { 8758 bool Truncated = false; 8759 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 8760 llvm::APFloat::rmNearestTiesToEven, &Truncated); 8761 if (Truncated) 8762 return true; 8763 } 8764 8765 ScalarCast = CK_FloatingCast; 8766 } else if (ScalarTy->isIntegralType(S.Context)) { 8767 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 8768 return true; 8769 8770 ScalarCast = CK_IntegralToFloating; 8771 } else 8772 return true; 8773 } 8774 8775 // Adjust scalar if desired. 8776 if (Scalar) { 8777 if (ScalarCast != CK_NoOp) 8778 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 8779 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 8780 } 8781 return false; 8782 } 8783 8784 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 8785 SourceLocation Loc, bool IsCompAssign, 8786 bool AllowBothBool, 8787 bool AllowBoolConversions) { 8788 if (!IsCompAssign) { 8789 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 8790 if (LHS.isInvalid()) 8791 return QualType(); 8792 } 8793 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 8794 if (RHS.isInvalid()) 8795 return QualType(); 8796 8797 // For conversion purposes, we ignore any qualifiers. 8798 // For example, "const float" and "float" are equivalent. 8799 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 8800 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 8801 8802 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 8803 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 8804 assert(LHSVecType || RHSVecType); 8805 8806 // AltiVec-style "vector bool op vector bool" combinations are allowed 8807 // for some operators but not others. 8808 if (!AllowBothBool && 8809 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8810 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8811 return InvalidOperands(Loc, LHS, RHS); 8812 8813 // If the vector types are identical, return. 8814 if (Context.hasSameType(LHSType, RHSType)) 8815 return LHSType; 8816 8817 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 8818 if (LHSVecType && RHSVecType && 8819 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8820 if (isa<ExtVectorType>(LHSVecType)) { 8821 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8822 return LHSType; 8823 } 8824 8825 if (!IsCompAssign) 8826 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8827 return RHSType; 8828 } 8829 8830 // AllowBoolConversions says that bool and non-bool AltiVec vectors 8831 // can be mixed, with the result being the non-bool type. The non-bool 8832 // operand must have integer element type. 8833 if (AllowBoolConversions && LHSVecType && RHSVecType && 8834 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 8835 (Context.getTypeSize(LHSVecType->getElementType()) == 8836 Context.getTypeSize(RHSVecType->getElementType()))) { 8837 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 8838 LHSVecType->getElementType()->isIntegerType() && 8839 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 8840 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8841 return LHSType; 8842 } 8843 if (!IsCompAssign && 8844 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8845 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 8846 RHSVecType->getElementType()->isIntegerType()) { 8847 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8848 return RHSType; 8849 } 8850 } 8851 8852 // If there's a vector type and a scalar, try to convert the scalar to 8853 // the vector element type and splat. 8854 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 8855 if (!RHSVecType) { 8856 if (isa<ExtVectorType>(LHSVecType)) { 8857 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 8858 LHSVecType->getElementType(), LHSType, 8859 DiagID)) 8860 return LHSType; 8861 } else { 8862 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 8863 return LHSType; 8864 } 8865 } 8866 if (!LHSVecType) { 8867 if (isa<ExtVectorType>(RHSVecType)) { 8868 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 8869 LHSType, RHSVecType->getElementType(), 8870 RHSType, DiagID)) 8871 return RHSType; 8872 } else { 8873 if (LHS.get()->getValueKind() == VK_LValue || 8874 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 8875 return RHSType; 8876 } 8877 } 8878 8879 // FIXME: The code below also handles conversion between vectors and 8880 // non-scalars, we should break this down into fine grained specific checks 8881 // and emit proper diagnostics. 8882 QualType VecType = LHSVecType ? LHSType : RHSType; 8883 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 8884 QualType OtherType = LHSVecType ? RHSType : LHSType; 8885 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 8886 if (isLaxVectorConversion(OtherType, VecType)) { 8887 // If we're allowing lax vector conversions, only the total (data) size 8888 // needs to be the same. For non compound assignment, if one of the types is 8889 // scalar, the result is always the vector type. 8890 if (!IsCompAssign) { 8891 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 8892 return VecType; 8893 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 8894 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 8895 // type. Note that this is already done by non-compound assignments in 8896 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 8897 // <1 x T> -> T. The result is also a vector type. 8898 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 8899 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 8900 ExprResult *RHSExpr = &RHS; 8901 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 8902 return VecType; 8903 } 8904 } 8905 8906 // Okay, the expression is invalid. 8907 8908 // If there's a non-vector, non-real operand, diagnose that. 8909 if ((!RHSVecType && !RHSType->isRealType()) || 8910 (!LHSVecType && !LHSType->isRealType())) { 8911 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 8912 << LHSType << RHSType 8913 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8914 return QualType(); 8915 } 8916 8917 // OpenCL V1.1 6.2.6.p1: 8918 // If the operands are of more than one vector type, then an error shall 8919 // occur. Implicit conversions between vector types are not permitted, per 8920 // section 6.2.1. 8921 if (getLangOpts().OpenCL && 8922 RHSVecType && isa<ExtVectorType>(RHSVecType) && 8923 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 8924 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 8925 << RHSType; 8926 return QualType(); 8927 } 8928 8929 8930 // If there is a vector type that is not a ExtVector and a scalar, we reach 8931 // this point if scalar could not be converted to the vector's element type 8932 // without truncation. 8933 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 8934 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 8935 QualType Scalar = LHSVecType ? RHSType : LHSType; 8936 QualType Vector = LHSVecType ? LHSType : RHSType; 8937 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 8938 Diag(Loc, 8939 diag::err_typecheck_vector_not_convertable_implict_truncation) 8940 << ScalarOrVector << Scalar << Vector; 8941 8942 return QualType(); 8943 } 8944 8945 // Otherwise, use the generic diagnostic. 8946 Diag(Loc, DiagID) 8947 << LHSType << RHSType 8948 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8949 return QualType(); 8950 } 8951 8952 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 8953 // expression. These are mainly cases where the null pointer is used as an 8954 // integer instead of a pointer. 8955 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 8956 SourceLocation Loc, bool IsCompare) { 8957 // The canonical way to check for a GNU null is with isNullPointerConstant, 8958 // but we use a bit of a hack here for speed; this is a relatively 8959 // hot path, and isNullPointerConstant is slow. 8960 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 8961 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 8962 8963 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 8964 8965 // Avoid analyzing cases where the result will either be invalid (and 8966 // diagnosed as such) or entirely valid and not something to warn about. 8967 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 8968 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 8969 return; 8970 8971 // Comparison operations would not make sense with a null pointer no matter 8972 // what the other expression is. 8973 if (!IsCompare) { 8974 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 8975 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 8976 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 8977 return; 8978 } 8979 8980 // The rest of the operations only make sense with a null pointer 8981 // if the other expression is a pointer. 8982 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 8983 NonNullType->canDecayToPointerType()) 8984 return; 8985 8986 S.Diag(Loc, diag::warn_null_in_comparison_operation) 8987 << LHSNull /* LHS is NULL */ << NonNullType 8988 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8989 } 8990 8991 static void DiagnoseDivisionSizeofPointer(Sema &S, Expr *LHS, Expr *RHS, 8992 SourceLocation Loc) { 8993 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 8994 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 8995 if (!LUE || !RUE) 8996 return; 8997 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 8998 RUE->getKind() != UETT_SizeOf) 8999 return; 9000 9001 QualType LHSTy = LUE->getArgumentExpr()->IgnoreParens()->getType(); 9002 QualType RHSTy; 9003 9004 if (RUE->isArgumentType()) 9005 RHSTy = RUE->getArgumentType(); 9006 else 9007 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 9008 9009 if (!LHSTy->isPointerType() || RHSTy->isPointerType()) 9010 return; 9011 if (LHSTy->getPointeeType() != RHSTy) 9012 return; 9013 9014 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 9015 } 9016 9017 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 9018 ExprResult &RHS, 9019 SourceLocation Loc, bool IsDiv) { 9020 // Check for division/remainder by zero. 9021 Expr::EvalResult RHSValue; 9022 if (!RHS.get()->isValueDependent() && 9023 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 9024 RHSValue.Val.getInt() == 0) 9025 S.DiagRuntimeBehavior(Loc, RHS.get(), 9026 S.PDiag(diag::warn_remainder_division_by_zero) 9027 << IsDiv << RHS.get()->getSourceRange()); 9028 } 9029 9030 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 9031 SourceLocation Loc, 9032 bool IsCompAssign, bool IsDiv) { 9033 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9034 9035 if (LHS.get()->getType()->isVectorType() || 9036 RHS.get()->getType()->isVectorType()) 9037 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9038 /*AllowBothBool*/getLangOpts().AltiVec, 9039 /*AllowBoolConversions*/false); 9040 9041 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 9042 if (LHS.isInvalid() || RHS.isInvalid()) 9043 return QualType(); 9044 9045 9046 if (compType.isNull() || !compType->isArithmeticType()) 9047 return InvalidOperands(Loc, LHS, RHS); 9048 if (IsDiv) { 9049 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 9050 DiagnoseDivisionSizeofPointer(*this, LHS.get(), RHS.get(), Loc); 9051 } 9052 return compType; 9053 } 9054 9055 QualType Sema::CheckRemainderOperands( 9056 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 9057 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9058 9059 if (LHS.get()->getType()->isVectorType() || 9060 RHS.get()->getType()->isVectorType()) { 9061 if (LHS.get()->getType()->hasIntegerRepresentation() && 9062 RHS.get()->getType()->hasIntegerRepresentation()) 9063 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9064 /*AllowBothBool*/getLangOpts().AltiVec, 9065 /*AllowBoolConversions*/false); 9066 return InvalidOperands(Loc, LHS, RHS); 9067 } 9068 9069 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 9070 if (LHS.isInvalid() || RHS.isInvalid()) 9071 return QualType(); 9072 9073 if (compType.isNull() || !compType->isIntegerType()) 9074 return InvalidOperands(Loc, LHS, RHS); 9075 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 9076 return compType; 9077 } 9078 9079 /// Diagnose invalid arithmetic on two void pointers. 9080 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 9081 Expr *LHSExpr, Expr *RHSExpr) { 9082 S.Diag(Loc, S.getLangOpts().CPlusPlus 9083 ? diag::err_typecheck_pointer_arith_void_type 9084 : diag::ext_gnu_void_ptr) 9085 << 1 /* two pointers */ << LHSExpr->getSourceRange() 9086 << RHSExpr->getSourceRange(); 9087 } 9088 9089 /// Diagnose invalid arithmetic on a void pointer. 9090 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 9091 Expr *Pointer) { 9092 S.Diag(Loc, S.getLangOpts().CPlusPlus 9093 ? diag::err_typecheck_pointer_arith_void_type 9094 : diag::ext_gnu_void_ptr) 9095 << 0 /* one pointer */ << Pointer->getSourceRange(); 9096 } 9097 9098 /// Diagnose invalid arithmetic on a null pointer. 9099 /// 9100 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 9101 /// idiom, which we recognize as a GNU extension. 9102 /// 9103 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 9104 Expr *Pointer, bool IsGNUIdiom) { 9105 if (IsGNUIdiom) 9106 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 9107 << Pointer->getSourceRange(); 9108 else 9109 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 9110 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 9111 } 9112 9113 /// Diagnose invalid arithmetic on two function pointers. 9114 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 9115 Expr *LHS, Expr *RHS) { 9116 assert(LHS->getType()->isAnyPointerType()); 9117 assert(RHS->getType()->isAnyPointerType()); 9118 S.Diag(Loc, S.getLangOpts().CPlusPlus 9119 ? diag::err_typecheck_pointer_arith_function_type 9120 : diag::ext_gnu_ptr_func_arith) 9121 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 9122 // We only show the second type if it differs from the first. 9123 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 9124 RHS->getType()) 9125 << RHS->getType()->getPointeeType() 9126 << LHS->getSourceRange() << RHS->getSourceRange(); 9127 } 9128 9129 /// Diagnose invalid arithmetic on a function pointer. 9130 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 9131 Expr *Pointer) { 9132 assert(Pointer->getType()->isAnyPointerType()); 9133 S.Diag(Loc, S.getLangOpts().CPlusPlus 9134 ? diag::err_typecheck_pointer_arith_function_type 9135 : diag::ext_gnu_ptr_func_arith) 9136 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 9137 << 0 /* one pointer, so only one type */ 9138 << Pointer->getSourceRange(); 9139 } 9140 9141 /// Emit error if Operand is incomplete pointer type 9142 /// 9143 /// \returns True if pointer has incomplete type 9144 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 9145 Expr *Operand) { 9146 QualType ResType = Operand->getType(); 9147 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 9148 ResType = ResAtomicType->getValueType(); 9149 9150 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 9151 QualType PointeeTy = ResType->getPointeeType(); 9152 return S.RequireCompleteType(Loc, PointeeTy, 9153 diag::err_typecheck_arithmetic_incomplete_type, 9154 PointeeTy, Operand->getSourceRange()); 9155 } 9156 9157 /// Check the validity of an arithmetic pointer operand. 9158 /// 9159 /// If the operand has pointer type, this code will check for pointer types 9160 /// which are invalid in arithmetic operations. These will be diagnosed 9161 /// appropriately, including whether or not the use is supported as an 9162 /// extension. 9163 /// 9164 /// \returns True when the operand is valid to use (even if as an extension). 9165 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 9166 Expr *Operand) { 9167 QualType ResType = Operand->getType(); 9168 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 9169 ResType = ResAtomicType->getValueType(); 9170 9171 if (!ResType->isAnyPointerType()) return true; 9172 9173 QualType PointeeTy = ResType->getPointeeType(); 9174 if (PointeeTy->isVoidType()) { 9175 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 9176 return !S.getLangOpts().CPlusPlus; 9177 } 9178 if (PointeeTy->isFunctionType()) { 9179 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 9180 return !S.getLangOpts().CPlusPlus; 9181 } 9182 9183 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 9184 9185 return true; 9186 } 9187 9188 /// Check the validity of a binary arithmetic operation w.r.t. pointer 9189 /// operands. 9190 /// 9191 /// This routine will diagnose any invalid arithmetic on pointer operands much 9192 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 9193 /// for emitting a single diagnostic even for operations where both LHS and RHS 9194 /// are (potentially problematic) pointers. 9195 /// 9196 /// \returns True when the operand is valid to use (even if as an extension). 9197 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 9198 Expr *LHSExpr, Expr *RHSExpr) { 9199 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 9200 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 9201 if (!isLHSPointer && !isRHSPointer) return true; 9202 9203 QualType LHSPointeeTy, RHSPointeeTy; 9204 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 9205 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 9206 9207 // if both are pointers check if operation is valid wrt address spaces 9208 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 9209 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 9210 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 9211 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 9212 S.Diag(Loc, 9213 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 9214 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 9215 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 9216 return false; 9217 } 9218 } 9219 9220 // Check for arithmetic on pointers to incomplete types. 9221 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 9222 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 9223 if (isLHSVoidPtr || isRHSVoidPtr) { 9224 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 9225 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 9226 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 9227 9228 return !S.getLangOpts().CPlusPlus; 9229 } 9230 9231 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 9232 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 9233 if (isLHSFuncPtr || isRHSFuncPtr) { 9234 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 9235 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 9236 RHSExpr); 9237 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 9238 9239 return !S.getLangOpts().CPlusPlus; 9240 } 9241 9242 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 9243 return false; 9244 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 9245 return false; 9246 9247 return true; 9248 } 9249 9250 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 9251 /// literal. 9252 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 9253 Expr *LHSExpr, Expr *RHSExpr) { 9254 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 9255 Expr* IndexExpr = RHSExpr; 9256 if (!StrExpr) { 9257 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 9258 IndexExpr = LHSExpr; 9259 } 9260 9261 bool IsStringPlusInt = StrExpr && 9262 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 9263 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 9264 return; 9265 9266 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 9267 Self.Diag(OpLoc, diag::warn_string_plus_int) 9268 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 9269 9270 // Only print a fixit for "str" + int, not for int + "str". 9271 if (IndexExpr == RHSExpr) { 9272 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 9273 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 9274 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 9275 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 9276 << FixItHint::CreateInsertion(EndLoc, "]"); 9277 } else 9278 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 9279 } 9280 9281 /// Emit a warning when adding a char literal to a string. 9282 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 9283 Expr *LHSExpr, Expr *RHSExpr) { 9284 const Expr *StringRefExpr = LHSExpr; 9285 const CharacterLiteral *CharExpr = 9286 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 9287 9288 if (!CharExpr) { 9289 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 9290 StringRefExpr = RHSExpr; 9291 } 9292 9293 if (!CharExpr || !StringRefExpr) 9294 return; 9295 9296 const QualType StringType = StringRefExpr->getType(); 9297 9298 // Return if not a PointerType. 9299 if (!StringType->isAnyPointerType()) 9300 return; 9301 9302 // Return if not a CharacterType. 9303 if (!StringType->getPointeeType()->isAnyCharacterType()) 9304 return; 9305 9306 ASTContext &Ctx = Self.getASTContext(); 9307 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 9308 9309 const QualType CharType = CharExpr->getType(); 9310 if (!CharType->isAnyCharacterType() && 9311 CharType->isIntegerType() && 9312 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 9313 Self.Diag(OpLoc, diag::warn_string_plus_char) 9314 << DiagRange << Ctx.CharTy; 9315 } else { 9316 Self.Diag(OpLoc, diag::warn_string_plus_char) 9317 << DiagRange << CharExpr->getType(); 9318 } 9319 9320 // Only print a fixit for str + char, not for char + str. 9321 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 9322 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 9323 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 9324 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 9325 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 9326 << FixItHint::CreateInsertion(EndLoc, "]"); 9327 } else { 9328 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 9329 } 9330 } 9331 9332 /// Emit error when two pointers are incompatible. 9333 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 9334 Expr *LHSExpr, Expr *RHSExpr) { 9335 assert(LHSExpr->getType()->isAnyPointerType()); 9336 assert(RHSExpr->getType()->isAnyPointerType()); 9337 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 9338 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 9339 << RHSExpr->getSourceRange(); 9340 } 9341 9342 // C99 6.5.6 9343 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 9344 SourceLocation Loc, BinaryOperatorKind Opc, 9345 QualType* CompLHSTy) { 9346 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9347 9348 if (LHS.get()->getType()->isVectorType() || 9349 RHS.get()->getType()->isVectorType()) { 9350 QualType compType = CheckVectorOperands( 9351 LHS, RHS, Loc, CompLHSTy, 9352 /*AllowBothBool*/getLangOpts().AltiVec, 9353 /*AllowBoolConversions*/getLangOpts().ZVector); 9354 if (CompLHSTy) *CompLHSTy = compType; 9355 return compType; 9356 } 9357 9358 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 9359 if (LHS.isInvalid() || RHS.isInvalid()) 9360 return QualType(); 9361 9362 // Diagnose "string literal" '+' int and string '+' "char literal". 9363 if (Opc == BO_Add) { 9364 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 9365 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 9366 } 9367 9368 // handle the common case first (both operands are arithmetic). 9369 if (!compType.isNull() && compType->isArithmeticType()) { 9370 if (CompLHSTy) *CompLHSTy = compType; 9371 return compType; 9372 } 9373 9374 // Type-checking. Ultimately the pointer's going to be in PExp; 9375 // note that we bias towards the LHS being the pointer. 9376 Expr *PExp = LHS.get(), *IExp = RHS.get(); 9377 9378 bool isObjCPointer; 9379 if (PExp->getType()->isPointerType()) { 9380 isObjCPointer = false; 9381 } else if (PExp->getType()->isObjCObjectPointerType()) { 9382 isObjCPointer = true; 9383 } else { 9384 std::swap(PExp, IExp); 9385 if (PExp->getType()->isPointerType()) { 9386 isObjCPointer = false; 9387 } else if (PExp->getType()->isObjCObjectPointerType()) { 9388 isObjCPointer = true; 9389 } else { 9390 return InvalidOperands(Loc, LHS, RHS); 9391 } 9392 } 9393 assert(PExp->getType()->isAnyPointerType()); 9394 9395 if (!IExp->getType()->isIntegerType()) 9396 return InvalidOperands(Loc, LHS, RHS); 9397 9398 // Adding to a null pointer results in undefined behavior. 9399 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 9400 Context, Expr::NPC_ValueDependentIsNotNull)) { 9401 // In C++ adding zero to a null pointer is defined. 9402 Expr::EvalResult KnownVal; 9403 if (!getLangOpts().CPlusPlus || 9404 (!IExp->isValueDependent() && 9405 (!IExp->EvaluateAsInt(KnownVal, Context) || 9406 KnownVal.Val.getInt() != 0))) { 9407 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 9408 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 9409 Context, BO_Add, PExp, IExp); 9410 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 9411 } 9412 } 9413 9414 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 9415 return QualType(); 9416 9417 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 9418 return QualType(); 9419 9420 // Check array bounds for pointer arithemtic 9421 CheckArrayAccess(PExp, IExp); 9422 9423 if (CompLHSTy) { 9424 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 9425 if (LHSTy.isNull()) { 9426 LHSTy = LHS.get()->getType(); 9427 if (LHSTy->isPromotableIntegerType()) 9428 LHSTy = Context.getPromotedIntegerType(LHSTy); 9429 } 9430 *CompLHSTy = LHSTy; 9431 } 9432 9433 return PExp->getType(); 9434 } 9435 9436 // C99 6.5.6 9437 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 9438 SourceLocation Loc, 9439 QualType* CompLHSTy) { 9440 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9441 9442 if (LHS.get()->getType()->isVectorType() || 9443 RHS.get()->getType()->isVectorType()) { 9444 QualType compType = CheckVectorOperands( 9445 LHS, RHS, Loc, CompLHSTy, 9446 /*AllowBothBool*/getLangOpts().AltiVec, 9447 /*AllowBoolConversions*/getLangOpts().ZVector); 9448 if (CompLHSTy) *CompLHSTy = compType; 9449 return compType; 9450 } 9451 9452 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 9453 if (LHS.isInvalid() || RHS.isInvalid()) 9454 return QualType(); 9455 9456 // Enforce type constraints: C99 6.5.6p3. 9457 9458 // Handle the common case first (both operands are arithmetic). 9459 if (!compType.isNull() && compType->isArithmeticType()) { 9460 if (CompLHSTy) *CompLHSTy = compType; 9461 return compType; 9462 } 9463 9464 // Either ptr - int or ptr - ptr. 9465 if (LHS.get()->getType()->isAnyPointerType()) { 9466 QualType lpointee = LHS.get()->getType()->getPointeeType(); 9467 9468 // Diagnose bad cases where we step over interface counts. 9469 if (LHS.get()->getType()->isObjCObjectPointerType() && 9470 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 9471 return QualType(); 9472 9473 // The result type of a pointer-int computation is the pointer type. 9474 if (RHS.get()->getType()->isIntegerType()) { 9475 // Subtracting from a null pointer should produce a warning. 9476 // The last argument to the diagnose call says this doesn't match the 9477 // GNU int-to-pointer idiom. 9478 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 9479 Expr::NPC_ValueDependentIsNotNull)) { 9480 // In C++ adding zero to a null pointer is defined. 9481 Expr::EvalResult KnownVal; 9482 if (!getLangOpts().CPlusPlus || 9483 (!RHS.get()->isValueDependent() && 9484 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 9485 KnownVal.Val.getInt() != 0))) { 9486 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 9487 } 9488 } 9489 9490 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 9491 return QualType(); 9492 9493 // Check array bounds for pointer arithemtic 9494 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 9495 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 9496 9497 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9498 return LHS.get()->getType(); 9499 } 9500 9501 // Handle pointer-pointer subtractions. 9502 if (const PointerType *RHSPTy 9503 = RHS.get()->getType()->getAs<PointerType>()) { 9504 QualType rpointee = RHSPTy->getPointeeType(); 9505 9506 if (getLangOpts().CPlusPlus) { 9507 // Pointee types must be the same: C++ [expr.add] 9508 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 9509 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9510 } 9511 } else { 9512 // Pointee types must be compatible C99 6.5.6p3 9513 if (!Context.typesAreCompatible( 9514 Context.getCanonicalType(lpointee).getUnqualifiedType(), 9515 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 9516 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9517 return QualType(); 9518 } 9519 } 9520 9521 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 9522 LHS.get(), RHS.get())) 9523 return QualType(); 9524 9525 // FIXME: Add warnings for nullptr - ptr. 9526 9527 // The pointee type may have zero size. As an extension, a structure or 9528 // union may have zero size or an array may have zero length. In this 9529 // case subtraction does not make sense. 9530 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 9531 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 9532 if (ElementSize.isZero()) { 9533 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 9534 << rpointee.getUnqualifiedType() 9535 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9536 } 9537 } 9538 9539 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9540 return Context.getPointerDiffType(); 9541 } 9542 } 9543 9544 return InvalidOperands(Loc, LHS, RHS); 9545 } 9546 9547 static bool isScopedEnumerationType(QualType T) { 9548 if (const EnumType *ET = T->getAs<EnumType>()) 9549 return ET->getDecl()->isScoped(); 9550 return false; 9551 } 9552 9553 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 9554 SourceLocation Loc, BinaryOperatorKind Opc, 9555 QualType LHSType) { 9556 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 9557 // so skip remaining warnings as we don't want to modify values within Sema. 9558 if (S.getLangOpts().OpenCL) 9559 return; 9560 9561 // Check right/shifter operand 9562 Expr::EvalResult RHSResult; 9563 if (RHS.get()->isValueDependent() || 9564 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 9565 return; 9566 llvm::APSInt Right = RHSResult.Val.getInt(); 9567 9568 if (Right.isNegative()) { 9569 S.DiagRuntimeBehavior(Loc, RHS.get(), 9570 S.PDiag(diag::warn_shift_negative) 9571 << RHS.get()->getSourceRange()); 9572 return; 9573 } 9574 llvm::APInt LeftBits(Right.getBitWidth(), 9575 S.Context.getTypeSize(LHS.get()->getType())); 9576 if (Right.uge(LeftBits)) { 9577 S.DiagRuntimeBehavior(Loc, RHS.get(), 9578 S.PDiag(diag::warn_shift_gt_typewidth) 9579 << RHS.get()->getSourceRange()); 9580 return; 9581 } 9582 if (Opc != BO_Shl) 9583 return; 9584 9585 // When left shifting an ICE which is signed, we can check for overflow which 9586 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 9587 // integers have defined behavior modulo one more than the maximum value 9588 // representable in the result type, so never warn for those. 9589 Expr::EvalResult LHSResult; 9590 if (LHS.get()->isValueDependent() || 9591 LHSType->hasUnsignedIntegerRepresentation() || 9592 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 9593 return; 9594 llvm::APSInt Left = LHSResult.Val.getInt(); 9595 9596 // If LHS does not have a signed type and non-negative value 9597 // then, the behavior is undefined. Warn about it. 9598 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) { 9599 S.DiagRuntimeBehavior(Loc, LHS.get(), 9600 S.PDiag(diag::warn_shift_lhs_negative) 9601 << LHS.get()->getSourceRange()); 9602 return; 9603 } 9604 9605 llvm::APInt ResultBits = 9606 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 9607 if (LeftBits.uge(ResultBits)) 9608 return; 9609 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 9610 Result = Result.shl(Right); 9611 9612 // Print the bit representation of the signed integer as an unsigned 9613 // hexadecimal number. 9614 SmallString<40> HexResult; 9615 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 9616 9617 // If we are only missing a sign bit, this is less likely to result in actual 9618 // bugs -- if the result is cast back to an unsigned type, it will have the 9619 // expected value. Thus we place this behind a different warning that can be 9620 // turned off separately if needed. 9621 if (LeftBits == ResultBits - 1) { 9622 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 9623 << HexResult << LHSType 9624 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9625 return; 9626 } 9627 9628 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 9629 << HexResult.str() << Result.getMinSignedBits() << LHSType 9630 << Left.getBitWidth() << LHS.get()->getSourceRange() 9631 << RHS.get()->getSourceRange(); 9632 } 9633 9634 /// Return the resulting type when a vector is shifted 9635 /// by a scalar or vector shift amount. 9636 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 9637 SourceLocation Loc, bool IsCompAssign) { 9638 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 9639 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 9640 !LHS.get()->getType()->isVectorType()) { 9641 S.Diag(Loc, diag::err_shift_rhs_only_vector) 9642 << RHS.get()->getType() << LHS.get()->getType() 9643 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9644 return QualType(); 9645 } 9646 9647 if (!IsCompAssign) { 9648 LHS = S.UsualUnaryConversions(LHS.get()); 9649 if (LHS.isInvalid()) return QualType(); 9650 } 9651 9652 RHS = S.UsualUnaryConversions(RHS.get()); 9653 if (RHS.isInvalid()) return QualType(); 9654 9655 QualType LHSType = LHS.get()->getType(); 9656 // Note that LHS might be a scalar because the routine calls not only in 9657 // OpenCL case. 9658 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 9659 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 9660 9661 // Note that RHS might not be a vector. 9662 QualType RHSType = RHS.get()->getType(); 9663 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 9664 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 9665 9666 // The operands need to be integers. 9667 if (!LHSEleType->isIntegerType()) { 9668 S.Diag(Loc, diag::err_typecheck_expect_int) 9669 << LHS.get()->getType() << LHS.get()->getSourceRange(); 9670 return QualType(); 9671 } 9672 9673 if (!RHSEleType->isIntegerType()) { 9674 S.Diag(Loc, diag::err_typecheck_expect_int) 9675 << RHS.get()->getType() << RHS.get()->getSourceRange(); 9676 return QualType(); 9677 } 9678 9679 if (!LHSVecTy) { 9680 assert(RHSVecTy); 9681 if (IsCompAssign) 9682 return RHSType; 9683 if (LHSEleType != RHSEleType) { 9684 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 9685 LHSEleType = RHSEleType; 9686 } 9687 QualType VecTy = 9688 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 9689 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 9690 LHSType = VecTy; 9691 } else if (RHSVecTy) { 9692 // OpenCL v1.1 s6.3.j says that for vector types, the operators 9693 // are applied component-wise. So if RHS is a vector, then ensure 9694 // that the number of elements is the same as LHS... 9695 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 9696 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 9697 << LHS.get()->getType() << RHS.get()->getType() 9698 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9699 return QualType(); 9700 } 9701 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 9702 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 9703 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 9704 if (LHSBT != RHSBT && 9705 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 9706 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 9707 << LHS.get()->getType() << RHS.get()->getType() 9708 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9709 } 9710 } 9711 } else { 9712 // ...else expand RHS to match the number of elements in LHS. 9713 QualType VecTy = 9714 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 9715 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 9716 } 9717 9718 return LHSType; 9719 } 9720 9721 // C99 6.5.7 9722 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 9723 SourceLocation Loc, BinaryOperatorKind Opc, 9724 bool IsCompAssign) { 9725 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9726 9727 // Vector shifts promote their scalar inputs to vector type. 9728 if (LHS.get()->getType()->isVectorType() || 9729 RHS.get()->getType()->isVectorType()) { 9730 if (LangOpts.ZVector) { 9731 // The shift operators for the z vector extensions work basically 9732 // like general shifts, except that neither the LHS nor the RHS is 9733 // allowed to be a "vector bool". 9734 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 9735 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 9736 return InvalidOperands(Loc, LHS, RHS); 9737 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 9738 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9739 return InvalidOperands(Loc, LHS, RHS); 9740 } 9741 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 9742 } 9743 9744 // Shifts don't perform usual arithmetic conversions, they just do integer 9745 // promotions on each operand. C99 6.5.7p3 9746 9747 // For the LHS, do usual unary conversions, but then reset them away 9748 // if this is a compound assignment. 9749 ExprResult OldLHS = LHS; 9750 LHS = UsualUnaryConversions(LHS.get()); 9751 if (LHS.isInvalid()) 9752 return QualType(); 9753 QualType LHSType = LHS.get()->getType(); 9754 if (IsCompAssign) LHS = OldLHS; 9755 9756 // The RHS is simpler. 9757 RHS = UsualUnaryConversions(RHS.get()); 9758 if (RHS.isInvalid()) 9759 return QualType(); 9760 QualType RHSType = RHS.get()->getType(); 9761 9762 // C99 6.5.7p2: Each of the operands shall have integer type. 9763 if (!LHSType->hasIntegerRepresentation() || 9764 !RHSType->hasIntegerRepresentation()) 9765 return InvalidOperands(Loc, LHS, RHS); 9766 9767 // C++0x: Don't allow scoped enums. FIXME: Use something better than 9768 // hasIntegerRepresentation() above instead of this. 9769 if (isScopedEnumerationType(LHSType) || 9770 isScopedEnumerationType(RHSType)) { 9771 return InvalidOperands(Loc, LHS, RHS); 9772 } 9773 // Sanity-check shift operands 9774 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 9775 9776 // "The type of the result is that of the promoted left operand." 9777 return LHSType; 9778 } 9779 9780 /// If two different enums are compared, raise a warning. 9781 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 9782 Expr *RHS) { 9783 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 9784 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 9785 9786 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 9787 if (!LHSEnumType) 9788 return; 9789 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 9790 if (!RHSEnumType) 9791 return; 9792 9793 // Ignore anonymous enums. 9794 if (!LHSEnumType->getDecl()->getIdentifier() && 9795 !LHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 9796 return; 9797 if (!RHSEnumType->getDecl()->getIdentifier() && 9798 !RHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 9799 return; 9800 9801 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 9802 return; 9803 9804 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 9805 << LHSStrippedType << RHSStrippedType 9806 << LHS->getSourceRange() << RHS->getSourceRange(); 9807 } 9808 9809 /// Diagnose bad pointer comparisons. 9810 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 9811 ExprResult &LHS, ExprResult &RHS, 9812 bool IsError) { 9813 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 9814 : diag::ext_typecheck_comparison_of_distinct_pointers) 9815 << LHS.get()->getType() << RHS.get()->getType() 9816 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9817 } 9818 9819 /// Returns false if the pointers are converted to a composite type, 9820 /// true otherwise. 9821 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 9822 ExprResult &LHS, ExprResult &RHS) { 9823 // C++ [expr.rel]p2: 9824 // [...] Pointer conversions (4.10) and qualification 9825 // conversions (4.4) are performed on pointer operands (or on 9826 // a pointer operand and a null pointer constant) to bring 9827 // them to their composite pointer type. [...] 9828 // 9829 // C++ [expr.eq]p1 uses the same notion for (in)equality 9830 // comparisons of pointers. 9831 9832 QualType LHSType = LHS.get()->getType(); 9833 QualType RHSType = RHS.get()->getType(); 9834 assert(LHSType->isPointerType() || RHSType->isPointerType() || 9835 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 9836 9837 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 9838 if (T.isNull()) { 9839 if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) && 9840 (RHSType->isPointerType() || RHSType->isMemberPointerType())) 9841 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 9842 else 9843 S.InvalidOperands(Loc, LHS, RHS); 9844 return true; 9845 } 9846 9847 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 9848 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 9849 return false; 9850 } 9851 9852 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 9853 ExprResult &LHS, 9854 ExprResult &RHS, 9855 bool IsError) { 9856 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 9857 : diag::ext_typecheck_comparison_of_fptr_to_void) 9858 << LHS.get()->getType() << RHS.get()->getType() 9859 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9860 } 9861 9862 static bool isObjCObjectLiteral(ExprResult &E) { 9863 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 9864 case Stmt::ObjCArrayLiteralClass: 9865 case Stmt::ObjCDictionaryLiteralClass: 9866 case Stmt::ObjCStringLiteralClass: 9867 case Stmt::ObjCBoxedExprClass: 9868 return true; 9869 default: 9870 // Note that ObjCBoolLiteral is NOT an object literal! 9871 return false; 9872 } 9873 } 9874 9875 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 9876 const ObjCObjectPointerType *Type = 9877 LHS->getType()->getAs<ObjCObjectPointerType>(); 9878 9879 // If this is not actually an Objective-C object, bail out. 9880 if (!Type) 9881 return false; 9882 9883 // Get the LHS object's interface type. 9884 QualType InterfaceType = Type->getPointeeType(); 9885 9886 // If the RHS isn't an Objective-C object, bail out. 9887 if (!RHS->getType()->isObjCObjectPointerType()) 9888 return false; 9889 9890 // Try to find the -isEqual: method. 9891 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 9892 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 9893 InterfaceType, 9894 /*instance=*/true); 9895 if (!Method) { 9896 if (Type->isObjCIdType()) { 9897 // For 'id', just check the global pool. 9898 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 9899 /*receiverId=*/true); 9900 } else { 9901 // Check protocols. 9902 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 9903 /*instance=*/true); 9904 } 9905 } 9906 9907 if (!Method) 9908 return false; 9909 9910 QualType T = Method->parameters()[0]->getType(); 9911 if (!T->isObjCObjectPointerType()) 9912 return false; 9913 9914 QualType R = Method->getReturnType(); 9915 if (!R->isScalarType()) 9916 return false; 9917 9918 return true; 9919 } 9920 9921 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 9922 FromE = FromE->IgnoreParenImpCasts(); 9923 switch (FromE->getStmtClass()) { 9924 default: 9925 break; 9926 case Stmt::ObjCStringLiteralClass: 9927 // "string literal" 9928 return LK_String; 9929 case Stmt::ObjCArrayLiteralClass: 9930 // "array literal" 9931 return LK_Array; 9932 case Stmt::ObjCDictionaryLiteralClass: 9933 // "dictionary literal" 9934 return LK_Dictionary; 9935 case Stmt::BlockExprClass: 9936 return LK_Block; 9937 case Stmt::ObjCBoxedExprClass: { 9938 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 9939 switch (Inner->getStmtClass()) { 9940 case Stmt::IntegerLiteralClass: 9941 case Stmt::FloatingLiteralClass: 9942 case Stmt::CharacterLiteralClass: 9943 case Stmt::ObjCBoolLiteralExprClass: 9944 case Stmt::CXXBoolLiteralExprClass: 9945 // "numeric literal" 9946 return LK_Numeric; 9947 case Stmt::ImplicitCastExprClass: { 9948 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 9949 // Boolean literals can be represented by implicit casts. 9950 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 9951 return LK_Numeric; 9952 break; 9953 } 9954 default: 9955 break; 9956 } 9957 return LK_Boxed; 9958 } 9959 } 9960 return LK_None; 9961 } 9962 9963 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 9964 ExprResult &LHS, ExprResult &RHS, 9965 BinaryOperator::Opcode Opc){ 9966 Expr *Literal; 9967 Expr *Other; 9968 if (isObjCObjectLiteral(LHS)) { 9969 Literal = LHS.get(); 9970 Other = RHS.get(); 9971 } else { 9972 Literal = RHS.get(); 9973 Other = LHS.get(); 9974 } 9975 9976 // Don't warn on comparisons against nil. 9977 Other = Other->IgnoreParenCasts(); 9978 if (Other->isNullPointerConstant(S.getASTContext(), 9979 Expr::NPC_ValueDependentIsNotNull)) 9980 return; 9981 9982 // This should be kept in sync with warn_objc_literal_comparison. 9983 // LK_String should always be after the other literals, since it has its own 9984 // warning flag. 9985 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 9986 assert(LiteralKind != Sema::LK_Block); 9987 if (LiteralKind == Sema::LK_None) { 9988 llvm_unreachable("Unknown Objective-C object literal kind"); 9989 } 9990 9991 if (LiteralKind == Sema::LK_String) 9992 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 9993 << Literal->getSourceRange(); 9994 else 9995 S.Diag(Loc, diag::warn_objc_literal_comparison) 9996 << LiteralKind << Literal->getSourceRange(); 9997 9998 if (BinaryOperator::isEqualityOp(Opc) && 9999 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 10000 SourceLocation Start = LHS.get()->getBeginLoc(); 10001 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 10002 CharSourceRange OpRange = 10003 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 10004 10005 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 10006 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 10007 << FixItHint::CreateReplacement(OpRange, " isEqual:") 10008 << FixItHint::CreateInsertion(End, "]"); 10009 } 10010 } 10011 10012 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 10013 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 10014 ExprResult &RHS, SourceLocation Loc, 10015 BinaryOperatorKind Opc) { 10016 // Check that left hand side is !something. 10017 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 10018 if (!UO || UO->getOpcode() != UO_LNot) return; 10019 10020 // Only check if the right hand side is non-bool arithmetic type. 10021 if (RHS.get()->isKnownToHaveBooleanValue()) return; 10022 10023 // Make sure that the something in !something is not bool. 10024 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 10025 if (SubExpr->isKnownToHaveBooleanValue()) return; 10026 10027 // Emit warning. 10028 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 10029 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 10030 << Loc << IsBitwiseOp; 10031 10032 // First note suggest !(x < y) 10033 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 10034 SourceLocation FirstClose = RHS.get()->getEndLoc(); 10035 FirstClose = S.getLocForEndOfToken(FirstClose); 10036 if (FirstClose.isInvalid()) 10037 FirstOpen = SourceLocation(); 10038 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 10039 << IsBitwiseOp 10040 << FixItHint::CreateInsertion(FirstOpen, "(") 10041 << FixItHint::CreateInsertion(FirstClose, ")"); 10042 10043 // Second note suggests (!x) < y 10044 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 10045 SourceLocation SecondClose = LHS.get()->getEndLoc(); 10046 SecondClose = S.getLocForEndOfToken(SecondClose); 10047 if (SecondClose.isInvalid()) 10048 SecondOpen = SourceLocation(); 10049 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 10050 << FixItHint::CreateInsertion(SecondOpen, "(") 10051 << FixItHint::CreateInsertion(SecondClose, ")"); 10052 } 10053 10054 // Get the decl for a simple expression: a reference to a variable, 10055 // an implicit C++ field reference, or an implicit ObjC ivar reference. 10056 static ValueDecl *getCompareDecl(Expr *E) { 10057 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) 10058 return DR->getDecl(); 10059 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 10060 if (Ivar->isFreeIvar()) 10061 return Ivar->getDecl(); 10062 } 10063 if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 10064 if (Mem->isImplicitAccess()) 10065 return Mem->getMemberDecl(); 10066 } 10067 return nullptr; 10068 } 10069 10070 /// Diagnose some forms of syntactically-obvious tautological comparison. 10071 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 10072 Expr *LHS, Expr *RHS, 10073 BinaryOperatorKind Opc) { 10074 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 10075 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 10076 10077 QualType LHSType = LHS->getType(); 10078 QualType RHSType = RHS->getType(); 10079 if (LHSType->hasFloatingRepresentation() || 10080 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 10081 LHS->getBeginLoc().isMacroID() || RHS->getBeginLoc().isMacroID() || 10082 S.inTemplateInstantiation()) 10083 return; 10084 10085 // Comparisons between two array types are ill-formed for operator<=>, so 10086 // we shouldn't emit any additional warnings about it. 10087 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 10088 return; 10089 10090 // For non-floating point types, check for self-comparisons of the form 10091 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 10092 // often indicate logic errors in the program. 10093 // 10094 // NOTE: Don't warn about comparison expressions resulting from macro 10095 // expansion. Also don't warn about comparisons which are only self 10096 // comparisons within a template instantiation. The warnings should catch 10097 // obvious cases in the definition of the template anyways. The idea is to 10098 // warn when the typed comparison operator will always evaluate to the same 10099 // result. 10100 ValueDecl *DL = getCompareDecl(LHSStripped); 10101 ValueDecl *DR = getCompareDecl(RHSStripped); 10102 if (DL && DR && declaresSameEntity(DL, DR)) { 10103 StringRef Result; 10104 switch (Opc) { 10105 case BO_EQ: case BO_LE: case BO_GE: 10106 Result = "true"; 10107 break; 10108 case BO_NE: case BO_LT: case BO_GT: 10109 Result = "false"; 10110 break; 10111 case BO_Cmp: 10112 Result = "'std::strong_ordering::equal'"; 10113 break; 10114 default: 10115 break; 10116 } 10117 S.DiagRuntimeBehavior(Loc, nullptr, 10118 S.PDiag(diag::warn_comparison_always) 10119 << 0 /*self-comparison*/ << !Result.empty() 10120 << Result); 10121 } else if (DL && DR && 10122 DL->getType()->isArrayType() && DR->getType()->isArrayType() && 10123 !DL->isWeak() && !DR->isWeak()) { 10124 // What is it always going to evaluate to? 10125 StringRef Result; 10126 switch(Opc) { 10127 case BO_EQ: // e.g. array1 == array2 10128 Result = "false"; 10129 break; 10130 case BO_NE: // e.g. array1 != array2 10131 Result = "true"; 10132 break; 10133 default: // e.g. array1 <= array2 10134 // The best we can say is 'a constant' 10135 break; 10136 } 10137 S.DiagRuntimeBehavior(Loc, nullptr, 10138 S.PDiag(diag::warn_comparison_always) 10139 << 1 /*array comparison*/ 10140 << !Result.empty() << Result); 10141 } 10142 10143 if (isa<CastExpr>(LHSStripped)) 10144 LHSStripped = LHSStripped->IgnoreParenCasts(); 10145 if (isa<CastExpr>(RHSStripped)) 10146 RHSStripped = RHSStripped->IgnoreParenCasts(); 10147 10148 // Warn about comparisons against a string constant (unless the other 10149 // operand is null); the user probably wants strcmp. 10150 Expr *LiteralString = nullptr; 10151 Expr *LiteralStringStripped = nullptr; 10152 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 10153 !RHSStripped->isNullPointerConstant(S.Context, 10154 Expr::NPC_ValueDependentIsNull)) { 10155 LiteralString = LHS; 10156 LiteralStringStripped = LHSStripped; 10157 } else if ((isa<StringLiteral>(RHSStripped) || 10158 isa<ObjCEncodeExpr>(RHSStripped)) && 10159 !LHSStripped->isNullPointerConstant(S.Context, 10160 Expr::NPC_ValueDependentIsNull)) { 10161 LiteralString = RHS; 10162 LiteralStringStripped = RHSStripped; 10163 } 10164 10165 if (LiteralString) { 10166 S.DiagRuntimeBehavior(Loc, nullptr, 10167 S.PDiag(diag::warn_stringcompare) 10168 << isa<ObjCEncodeExpr>(LiteralStringStripped) 10169 << LiteralString->getSourceRange()); 10170 } 10171 } 10172 10173 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 10174 switch (CK) { 10175 default: { 10176 #ifndef NDEBUG 10177 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 10178 << "\n"; 10179 #endif 10180 llvm_unreachable("unhandled cast kind"); 10181 } 10182 case CK_UserDefinedConversion: 10183 return ICK_Identity; 10184 case CK_LValueToRValue: 10185 return ICK_Lvalue_To_Rvalue; 10186 case CK_ArrayToPointerDecay: 10187 return ICK_Array_To_Pointer; 10188 case CK_FunctionToPointerDecay: 10189 return ICK_Function_To_Pointer; 10190 case CK_IntegralCast: 10191 return ICK_Integral_Conversion; 10192 case CK_FloatingCast: 10193 return ICK_Floating_Conversion; 10194 case CK_IntegralToFloating: 10195 case CK_FloatingToIntegral: 10196 return ICK_Floating_Integral; 10197 case CK_IntegralComplexCast: 10198 case CK_FloatingComplexCast: 10199 case CK_FloatingComplexToIntegralComplex: 10200 case CK_IntegralComplexToFloatingComplex: 10201 return ICK_Complex_Conversion; 10202 case CK_FloatingComplexToReal: 10203 case CK_FloatingRealToComplex: 10204 case CK_IntegralComplexToReal: 10205 case CK_IntegralRealToComplex: 10206 return ICK_Complex_Real; 10207 } 10208 } 10209 10210 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 10211 QualType FromType, 10212 SourceLocation Loc) { 10213 // Check for a narrowing implicit conversion. 10214 StandardConversionSequence SCS; 10215 SCS.setAsIdentityConversion(); 10216 SCS.setToType(0, FromType); 10217 SCS.setToType(1, ToType); 10218 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 10219 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 10220 10221 APValue PreNarrowingValue; 10222 QualType PreNarrowingType; 10223 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 10224 PreNarrowingType, 10225 /*IgnoreFloatToIntegralConversion*/ true)) { 10226 case NK_Dependent_Narrowing: 10227 // Implicit conversion to a narrower type, but the expression is 10228 // value-dependent so we can't tell whether it's actually narrowing. 10229 case NK_Not_Narrowing: 10230 return false; 10231 10232 case NK_Constant_Narrowing: 10233 // Implicit conversion to a narrower type, and the value is not a constant 10234 // expression. 10235 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 10236 << /*Constant*/ 1 10237 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 10238 return true; 10239 10240 case NK_Variable_Narrowing: 10241 // Implicit conversion to a narrower type, and the value is not a constant 10242 // expression. 10243 case NK_Type_Narrowing: 10244 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 10245 << /*Constant*/ 0 << FromType << ToType; 10246 // TODO: It's not a constant expression, but what if the user intended it 10247 // to be? Can we produce notes to help them figure out why it isn't? 10248 return true; 10249 } 10250 llvm_unreachable("unhandled case in switch"); 10251 } 10252 10253 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 10254 ExprResult &LHS, 10255 ExprResult &RHS, 10256 SourceLocation Loc) { 10257 using CCT = ComparisonCategoryType; 10258 10259 QualType LHSType = LHS.get()->getType(); 10260 QualType RHSType = RHS.get()->getType(); 10261 // Dig out the original argument type and expression before implicit casts 10262 // were applied. These are the types/expressions we need to check the 10263 // [expr.spaceship] requirements against. 10264 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 10265 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 10266 QualType LHSStrippedType = LHSStripped.get()->getType(); 10267 QualType RHSStrippedType = RHSStripped.get()->getType(); 10268 10269 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 10270 // other is not, the program is ill-formed. 10271 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 10272 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 10273 return QualType(); 10274 } 10275 10276 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 10277 RHSStrippedType->isEnumeralType(); 10278 if (NumEnumArgs == 1) { 10279 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 10280 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 10281 if (OtherTy->hasFloatingRepresentation()) { 10282 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 10283 return QualType(); 10284 } 10285 } 10286 if (NumEnumArgs == 2) { 10287 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 10288 // type E, the operator yields the result of converting the operands 10289 // to the underlying type of E and applying <=> to the converted operands. 10290 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 10291 S.InvalidOperands(Loc, LHS, RHS); 10292 return QualType(); 10293 } 10294 QualType IntType = 10295 LHSStrippedType->getAs<EnumType>()->getDecl()->getIntegerType(); 10296 assert(IntType->isArithmeticType()); 10297 10298 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 10299 // promote the boolean type, and all other promotable integer types, to 10300 // avoid this. 10301 if (IntType->isPromotableIntegerType()) 10302 IntType = S.Context.getPromotedIntegerType(IntType); 10303 10304 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 10305 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 10306 LHSType = RHSType = IntType; 10307 } 10308 10309 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 10310 // usual arithmetic conversions are applied to the operands. 10311 QualType Type = S.UsualArithmeticConversions(LHS, RHS); 10312 if (LHS.isInvalid() || RHS.isInvalid()) 10313 return QualType(); 10314 if (Type.isNull()) 10315 return S.InvalidOperands(Loc, LHS, RHS); 10316 assert(Type->isArithmeticType() || Type->isEnumeralType()); 10317 10318 bool HasNarrowing = checkThreeWayNarrowingConversion( 10319 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 10320 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 10321 RHS.get()->getBeginLoc()); 10322 if (HasNarrowing) 10323 return QualType(); 10324 10325 assert(!Type.isNull() && "composite type for <=> has not been set"); 10326 10327 auto TypeKind = [&]() { 10328 if (const ComplexType *CT = Type->getAs<ComplexType>()) { 10329 if (CT->getElementType()->hasFloatingRepresentation()) 10330 return CCT::WeakEquality; 10331 return CCT::StrongEquality; 10332 } 10333 if (Type->isIntegralOrEnumerationType()) 10334 return CCT::StrongOrdering; 10335 if (Type->hasFloatingRepresentation()) 10336 return CCT::PartialOrdering; 10337 llvm_unreachable("other types are unimplemented"); 10338 }(); 10339 10340 return S.CheckComparisonCategoryType(TypeKind, Loc); 10341 } 10342 10343 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 10344 ExprResult &RHS, 10345 SourceLocation Loc, 10346 BinaryOperatorKind Opc) { 10347 if (Opc == BO_Cmp) 10348 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 10349 10350 // C99 6.5.8p3 / C99 6.5.9p4 10351 QualType Type = S.UsualArithmeticConversions(LHS, RHS); 10352 if (LHS.isInvalid() || RHS.isInvalid()) 10353 return QualType(); 10354 if (Type.isNull()) 10355 return S.InvalidOperands(Loc, LHS, RHS); 10356 assert(Type->isArithmeticType() || Type->isEnumeralType()); 10357 10358 checkEnumComparison(S, Loc, LHS.get(), RHS.get()); 10359 10360 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 10361 return S.InvalidOperands(Loc, LHS, RHS); 10362 10363 // Check for comparisons of floating point operands using != and ==. 10364 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 10365 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 10366 10367 // The result of comparisons is 'bool' in C++, 'int' in C. 10368 return S.Context.getLogicalOperationType(); 10369 } 10370 10371 // C99 6.5.8, C++ [expr.rel] 10372 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 10373 SourceLocation Loc, 10374 BinaryOperatorKind Opc) { 10375 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 10376 bool IsThreeWay = Opc == BO_Cmp; 10377 auto IsAnyPointerType = [](ExprResult E) { 10378 QualType Ty = E.get()->getType(); 10379 return Ty->isPointerType() || Ty->isMemberPointerType(); 10380 }; 10381 10382 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 10383 // type, array-to-pointer, ..., conversions are performed on both operands to 10384 // bring them to their composite type. 10385 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 10386 // any type-related checks. 10387 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 10388 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10389 if (LHS.isInvalid()) 10390 return QualType(); 10391 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10392 if (RHS.isInvalid()) 10393 return QualType(); 10394 } else { 10395 LHS = DefaultLvalueConversion(LHS.get()); 10396 if (LHS.isInvalid()) 10397 return QualType(); 10398 RHS = DefaultLvalueConversion(RHS.get()); 10399 if (RHS.isInvalid()) 10400 return QualType(); 10401 } 10402 10403 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 10404 10405 // Handle vector comparisons separately. 10406 if (LHS.get()->getType()->isVectorType() || 10407 RHS.get()->getType()->isVectorType()) 10408 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 10409 10410 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 10411 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 10412 10413 QualType LHSType = LHS.get()->getType(); 10414 QualType RHSType = RHS.get()->getType(); 10415 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 10416 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 10417 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 10418 10419 const Expr::NullPointerConstantKind LHSNullKind = 10420 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 10421 const Expr::NullPointerConstantKind RHSNullKind = 10422 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 10423 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 10424 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 10425 10426 auto computeResultTy = [&]() { 10427 if (Opc != BO_Cmp) 10428 return Context.getLogicalOperationType(); 10429 assert(getLangOpts().CPlusPlus); 10430 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 10431 10432 QualType CompositeTy = LHS.get()->getType(); 10433 assert(!CompositeTy->isReferenceType()); 10434 10435 auto buildResultTy = [&](ComparisonCategoryType Kind) { 10436 return CheckComparisonCategoryType(Kind, Loc); 10437 }; 10438 10439 // C++2a [expr.spaceship]p7: If the composite pointer type is a function 10440 // pointer type, a pointer-to-member type, or std::nullptr_t, the 10441 // result is of type std::strong_equality 10442 if (CompositeTy->isFunctionPointerType() || 10443 CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType()) 10444 // FIXME: consider making the function pointer case produce 10445 // strong_ordering not strong_equality, per P0946R0-Jax18 discussion 10446 // and direction polls 10447 return buildResultTy(ComparisonCategoryType::StrongEquality); 10448 10449 // C++2a [expr.spaceship]p8: If the composite pointer type is an object 10450 // pointer type, p <=> q is of type std::strong_ordering. 10451 if (CompositeTy->isPointerType()) { 10452 // P0946R0: Comparisons between a null pointer constant and an object 10453 // pointer result in std::strong_equality 10454 if (LHSIsNull != RHSIsNull) 10455 return buildResultTy(ComparisonCategoryType::StrongEquality); 10456 return buildResultTy(ComparisonCategoryType::StrongOrdering); 10457 } 10458 // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed. 10459 // TODO: Extend support for operator<=> to ObjC types. 10460 return InvalidOperands(Loc, LHS, RHS); 10461 }; 10462 10463 10464 if (!IsRelational && LHSIsNull != RHSIsNull) { 10465 bool IsEquality = Opc == BO_EQ; 10466 if (RHSIsNull) 10467 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 10468 RHS.get()->getSourceRange()); 10469 else 10470 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 10471 LHS.get()->getSourceRange()); 10472 } 10473 10474 if ((LHSType->isIntegerType() && !LHSIsNull) || 10475 (RHSType->isIntegerType() && !RHSIsNull)) { 10476 // Skip normal pointer conversion checks in this case; we have better 10477 // diagnostics for this below. 10478 } else if (getLangOpts().CPlusPlus) { 10479 // Equality comparison of a function pointer to a void pointer is invalid, 10480 // but we allow it as an extension. 10481 // FIXME: If we really want to allow this, should it be part of composite 10482 // pointer type computation so it works in conditionals too? 10483 if (!IsRelational && 10484 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 10485 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 10486 // This is a gcc extension compatibility comparison. 10487 // In a SFINAE context, we treat this as a hard error to maintain 10488 // conformance with the C++ standard. 10489 diagnoseFunctionPointerToVoidComparison( 10490 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 10491 10492 if (isSFINAEContext()) 10493 return QualType(); 10494 10495 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10496 return computeResultTy(); 10497 } 10498 10499 // C++ [expr.eq]p2: 10500 // If at least one operand is a pointer [...] bring them to their 10501 // composite pointer type. 10502 // C++ [expr.spaceship]p6 10503 // If at least one of the operands is of pointer type, [...] bring them 10504 // to their composite pointer type. 10505 // C++ [expr.rel]p2: 10506 // If both operands are pointers, [...] bring them to their composite 10507 // pointer type. 10508 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 10509 (IsRelational ? 2 : 1) && 10510 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 10511 RHSType->isObjCObjectPointerType()))) { 10512 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 10513 return QualType(); 10514 return computeResultTy(); 10515 } 10516 } else if (LHSType->isPointerType() && 10517 RHSType->isPointerType()) { // C99 6.5.8p2 10518 // All of the following pointer-related warnings are GCC extensions, except 10519 // when handling null pointer constants. 10520 QualType LCanPointeeTy = 10521 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 10522 QualType RCanPointeeTy = 10523 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 10524 10525 // C99 6.5.9p2 and C99 6.5.8p2 10526 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 10527 RCanPointeeTy.getUnqualifiedType())) { 10528 // Valid unless a relational comparison of function pointers 10529 if (IsRelational && LCanPointeeTy->isFunctionType()) { 10530 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 10531 << LHSType << RHSType << LHS.get()->getSourceRange() 10532 << RHS.get()->getSourceRange(); 10533 } 10534 } else if (!IsRelational && 10535 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 10536 // Valid unless comparison between non-null pointer and function pointer 10537 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 10538 && !LHSIsNull && !RHSIsNull) 10539 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 10540 /*isError*/false); 10541 } else { 10542 // Invalid 10543 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 10544 } 10545 if (LCanPointeeTy != RCanPointeeTy) { 10546 // Treat NULL constant as a special case in OpenCL. 10547 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 10548 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 10549 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 10550 Diag(Loc, 10551 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10552 << LHSType << RHSType << 0 /* comparison */ 10553 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10554 } 10555 } 10556 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 10557 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 10558 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 10559 : CK_BitCast; 10560 if (LHSIsNull && !RHSIsNull) 10561 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 10562 else 10563 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 10564 } 10565 return computeResultTy(); 10566 } 10567 10568 if (getLangOpts().CPlusPlus) { 10569 // C++ [expr.eq]p4: 10570 // Two operands of type std::nullptr_t or one operand of type 10571 // std::nullptr_t and the other a null pointer constant compare equal. 10572 if (!IsRelational && LHSIsNull && RHSIsNull) { 10573 if (LHSType->isNullPtrType()) { 10574 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10575 return computeResultTy(); 10576 } 10577 if (RHSType->isNullPtrType()) { 10578 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10579 return computeResultTy(); 10580 } 10581 } 10582 10583 // Comparison of Objective-C pointers and block pointers against nullptr_t. 10584 // These aren't covered by the composite pointer type rules. 10585 if (!IsRelational && RHSType->isNullPtrType() && 10586 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 10587 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10588 return computeResultTy(); 10589 } 10590 if (!IsRelational && LHSType->isNullPtrType() && 10591 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 10592 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10593 return computeResultTy(); 10594 } 10595 10596 if (IsRelational && 10597 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 10598 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 10599 // HACK: Relational comparison of nullptr_t against a pointer type is 10600 // invalid per DR583, but we allow it within std::less<> and friends, 10601 // since otherwise common uses of it break. 10602 // FIXME: Consider removing this hack once LWG fixes std::less<> and 10603 // friends to have std::nullptr_t overload candidates. 10604 DeclContext *DC = CurContext; 10605 if (isa<FunctionDecl>(DC)) 10606 DC = DC->getParent(); 10607 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 10608 if (CTSD->isInStdNamespace() && 10609 llvm::StringSwitch<bool>(CTSD->getName()) 10610 .Cases("less", "less_equal", "greater", "greater_equal", true) 10611 .Default(false)) { 10612 if (RHSType->isNullPtrType()) 10613 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10614 else 10615 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10616 return computeResultTy(); 10617 } 10618 } 10619 } 10620 10621 // C++ [expr.eq]p2: 10622 // If at least one operand is a pointer to member, [...] bring them to 10623 // their composite pointer type. 10624 if (!IsRelational && 10625 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 10626 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 10627 return QualType(); 10628 else 10629 return computeResultTy(); 10630 } 10631 } 10632 10633 // Handle block pointer types. 10634 if (!IsRelational && LHSType->isBlockPointerType() && 10635 RHSType->isBlockPointerType()) { 10636 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 10637 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 10638 10639 if (!LHSIsNull && !RHSIsNull && 10640 !Context.typesAreCompatible(lpointee, rpointee)) { 10641 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 10642 << LHSType << RHSType << LHS.get()->getSourceRange() 10643 << RHS.get()->getSourceRange(); 10644 } 10645 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10646 return computeResultTy(); 10647 } 10648 10649 // Allow block pointers to be compared with null pointer constants. 10650 if (!IsRelational 10651 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 10652 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 10653 if (!LHSIsNull && !RHSIsNull) { 10654 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 10655 ->getPointeeType()->isVoidType()) 10656 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 10657 ->getPointeeType()->isVoidType()))) 10658 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 10659 << LHSType << RHSType << LHS.get()->getSourceRange() 10660 << RHS.get()->getSourceRange(); 10661 } 10662 if (LHSIsNull && !RHSIsNull) 10663 LHS = ImpCastExprToType(LHS.get(), RHSType, 10664 RHSType->isPointerType() ? CK_BitCast 10665 : CK_AnyPointerToBlockPointerCast); 10666 else 10667 RHS = ImpCastExprToType(RHS.get(), LHSType, 10668 LHSType->isPointerType() ? CK_BitCast 10669 : CK_AnyPointerToBlockPointerCast); 10670 return computeResultTy(); 10671 } 10672 10673 if (LHSType->isObjCObjectPointerType() || 10674 RHSType->isObjCObjectPointerType()) { 10675 const PointerType *LPT = LHSType->getAs<PointerType>(); 10676 const PointerType *RPT = RHSType->getAs<PointerType>(); 10677 if (LPT || RPT) { 10678 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 10679 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 10680 10681 if (!LPtrToVoid && !RPtrToVoid && 10682 !Context.typesAreCompatible(LHSType, RHSType)) { 10683 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 10684 /*isError*/false); 10685 } 10686 if (LHSIsNull && !RHSIsNull) { 10687 Expr *E = LHS.get(); 10688 if (getLangOpts().ObjCAutoRefCount) 10689 CheckObjCConversion(SourceRange(), RHSType, E, 10690 CCK_ImplicitConversion); 10691 LHS = ImpCastExprToType(E, RHSType, 10692 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 10693 } 10694 else { 10695 Expr *E = RHS.get(); 10696 if (getLangOpts().ObjCAutoRefCount) 10697 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 10698 /*Diagnose=*/true, 10699 /*DiagnoseCFAudited=*/false, Opc); 10700 RHS = ImpCastExprToType(E, LHSType, 10701 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 10702 } 10703 return computeResultTy(); 10704 } 10705 if (LHSType->isObjCObjectPointerType() && 10706 RHSType->isObjCObjectPointerType()) { 10707 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 10708 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 10709 /*isError*/false); 10710 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 10711 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 10712 10713 if (LHSIsNull && !RHSIsNull) 10714 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10715 else 10716 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10717 return computeResultTy(); 10718 } 10719 10720 if (!IsRelational && LHSType->isBlockPointerType() && 10721 RHSType->isBlockCompatibleObjCPointerType(Context)) { 10722 LHS = ImpCastExprToType(LHS.get(), RHSType, 10723 CK_BlockPointerToObjCPointerCast); 10724 return computeResultTy(); 10725 } else if (!IsRelational && 10726 LHSType->isBlockCompatibleObjCPointerType(Context) && 10727 RHSType->isBlockPointerType()) { 10728 RHS = ImpCastExprToType(RHS.get(), LHSType, 10729 CK_BlockPointerToObjCPointerCast); 10730 return computeResultTy(); 10731 } 10732 } 10733 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 10734 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 10735 unsigned DiagID = 0; 10736 bool isError = false; 10737 if (LangOpts.DebuggerSupport) { 10738 // Under a debugger, allow the comparison of pointers to integers, 10739 // since users tend to want to compare addresses. 10740 } else if ((LHSIsNull && LHSType->isIntegerType()) || 10741 (RHSIsNull && RHSType->isIntegerType())) { 10742 if (IsRelational) { 10743 isError = getLangOpts().CPlusPlus; 10744 DiagID = 10745 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 10746 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 10747 } 10748 } else if (getLangOpts().CPlusPlus) { 10749 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 10750 isError = true; 10751 } else if (IsRelational) 10752 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 10753 else 10754 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 10755 10756 if (DiagID) { 10757 Diag(Loc, DiagID) 10758 << LHSType << RHSType << LHS.get()->getSourceRange() 10759 << RHS.get()->getSourceRange(); 10760 if (isError) 10761 return QualType(); 10762 } 10763 10764 if (LHSType->isIntegerType()) 10765 LHS = ImpCastExprToType(LHS.get(), RHSType, 10766 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 10767 else 10768 RHS = ImpCastExprToType(RHS.get(), LHSType, 10769 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 10770 return computeResultTy(); 10771 } 10772 10773 // Handle block pointers. 10774 if (!IsRelational && RHSIsNull 10775 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 10776 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10777 return computeResultTy(); 10778 } 10779 if (!IsRelational && LHSIsNull 10780 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 10781 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10782 return computeResultTy(); 10783 } 10784 10785 if (getLangOpts().OpenCLVersion >= 200) { 10786 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 10787 return computeResultTy(); 10788 } 10789 10790 if (LHSType->isQueueT() && RHSType->isQueueT()) { 10791 return computeResultTy(); 10792 } 10793 10794 if (LHSIsNull && RHSType->isQueueT()) { 10795 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10796 return computeResultTy(); 10797 } 10798 10799 if (LHSType->isQueueT() && RHSIsNull) { 10800 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10801 return computeResultTy(); 10802 } 10803 } 10804 10805 return InvalidOperands(Loc, LHS, RHS); 10806 } 10807 10808 // Return a signed ext_vector_type that is of identical size and number of 10809 // elements. For floating point vectors, return an integer type of identical 10810 // size and number of elements. In the non ext_vector_type case, search from 10811 // the largest type to the smallest type to avoid cases where long long == long, 10812 // where long gets picked over long long. 10813 QualType Sema::GetSignedVectorType(QualType V) { 10814 const VectorType *VTy = V->getAs<VectorType>(); 10815 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 10816 10817 if (isa<ExtVectorType>(VTy)) { 10818 if (TypeSize == Context.getTypeSize(Context.CharTy)) 10819 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 10820 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 10821 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 10822 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 10823 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 10824 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 10825 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 10826 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 10827 "Unhandled vector element size in vector compare"); 10828 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 10829 } 10830 10831 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 10832 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 10833 VectorType::GenericVector); 10834 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 10835 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 10836 VectorType::GenericVector); 10837 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 10838 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 10839 VectorType::GenericVector); 10840 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 10841 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 10842 VectorType::GenericVector); 10843 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 10844 "Unhandled vector element size in vector compare"); 10845 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 10846 VectorType::GenericVector); 10847 } 10848 10849 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 10850 /// operates on extended vector types. Instead of producing an IntTy result, 10851 /// like a scalar comparison, a vector comparison produces a vector of integer 10852 /// types. 10853 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 10854 SourceLocation Loc, 10855 BinaryOperatorKind Opc) { 10856 // Check to make sure we're operating on vectors of the same type and width, 10857 // Allowing one side to be a scalar of element type. 10858 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 10859 /*AllowBothBool*/true, 10860 /*AllowBoolConversions*/getLangOpts().ZVector); 10861 if (vType.isNull()) 10862 return vType; 10863 10864 QualType LHSType = LHS.get()->getType(); 10865 10866 // If AltiVec, the comparison results in a numeric type, i.e. 10867 // bool for C++, int for C 10868 if (getLangOpts().AltiVec && 10869 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 10870 return Context.getLogicalOperationType(); 10871 10872 // For non-floating point types, check for self-comparisons of the form 10873 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 10874 // often indicate logic errors in the program. 10875 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 10876 10877 // Check for comparisons of floating point operands using != and ==. 10878 if (BinaryOperator::isEqualityOp(Opc) && 10879 LHSType->hasFloatingRepresentation()) { 10880 assert(RHS.get()->getType()->hasFloatingRepresentation()); 10881 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 10882 } 10883 10884 // Return a signed type for the vector. 10885 return GetSignedVectorType(vType); 10886 } 10887 10888 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 10889 SourceLocation Loc) { 10890 // Ensure that either both operands are of the same vector type, or 10891 // one operand is of a vector type and the other is of its element type. 10892 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 10893 /*AllowBothBool*/true, 10894 /*AllowBoolConversions*/false); 10895 if (vType.isNull()) 10896 return InvalidOperands(Loc, LHS, RHS); 10897 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 10898 vType->hasFloatingRepresentation()) 10899 return InvalidOperands(Loc, LHS, RHS); 10900 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 10901 // usage of the logical operators && and || with vectors in C. This 10902 // check could be notionally dropped. 10903 if (!getLangOpts().CPlusPlus && 10904 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 10905 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 10906 10907 return GetSignedVectorType(LHS.get()->getType()); 10908 } 10909 10910 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 10911 SourceLocation Loc, 10912 BinaryOperatorKind Opc) { 10913 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 10914 10915 bool IsCompAssign = 10916 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 10917 10918 if (LHS.get()->getType()->isVectorType() || 10919 RHS.get()->getType()->isVectorType()) { 10920 if (LHS.get()->getType()->hasIntegerRepresentation() && 10921 RHS.get()->getType()->hasIntegerRepresentation()) 10922 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10923 /*AllowBothBool*/true, 10924 /*AllowBoolConversions*/getLangOpts().ZVector); 10925 return InvalidOperands(Loc, LHS, RHS); 10926 } 10927 10928 if (Opc == BO_And) 10929 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 10930 10931 ExprResult LHSResult = LHS, RHSResult = RHS; 10932 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 10933 IsCompAssign); 10934 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 10935 return QualType(); 10936 LHS = LHSResult.get(); 10937 RHS = RHSResult.get(); 10938 10939 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 10940 return compType; 10941 return InvalidOperands(Loc, LHS, RHS); 10942 } 10943 10944 // C99 6.5.[13,14] 10945 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 10946 SourceLocation Loc, 10947 BinaryOperatorKind Opc) { 10948 // Check vector operands differently. 10949 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 10950 return CheckVectorLogicalOperands(LHS, RHS, Loc); 10951 10952 // Diagnose cases where the user write a logical and/or but probably meant a 10953 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 10954 // is a constant. 10955 if (LHS.get()->getType()->isIntegerType() && 10956 !LHS.get()->getType()->isBooleanType() && 10957 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 10958 // Don't warn in macros or template instantiations. 10959 !Loc.isMacroID() && !inTemplateInstantiation()) { 10960 // If the RHS can be constant folded, and if it constant folds to something 10961 // that isn't 0 or 1 (which indicate a potential logical operation that 10962 // happened to fold to true/false) then warn. 10963 // Parens on the RHS are ignored. 10964 Expr::EvalResult EVResult; 10965 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 10966 llvm::APSInt Result = EVResult.Val.getInt(); 10967 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 10968 !RHS.get()->getExprLoc().isMacroID()) || 10969 (Result != 0 && Result != 1)) { 10970 Diag(Loc, diag::warn_logical_instead_of_bitwise) 10971 << RHS.get()->getSourceRange() 10972 << (Opc == BO_LAnd ? "&&" : "||"); 10973 // Suggest replacing the logical operator with the bitwise version 10974 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 10975 << (Opc == BO_LAnd ? "&" : "|") 10976 << FixItHint::CreateReplacement(SourceRange( 10977 Loc, getLocForEndOfToken(Loc)), 10978 Opc == BO_LAnd ? "&" : "|"); 10979 if (Opc == BO_LAnd) 10980 // Suggest replacing "Foo() && kNonZero" with "Foo()" 10981 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 10982 << FixItHint::CreateRemoval( 10983 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 10984 RHS.get()->getEndLoc())); 10985 } 10986 } 10987 } 10988 10989 if (!Context.getLangOpts().CPlusPlus) { 10990 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 10991 // not operate on the built-in scalar and vector float types. 10992 if (Context.getLangOpts().OpenCL && 10993 Context.getLangOpts().OpenCLVersion < 120) { 10994 if (LHS.get()->getType()->isFloatingType() || 10995 RHS.get()->getType()->isFloatingType()) 10996 return InvalidOperands(Loc, LHS, RHS); 10997 } 10998 10999 LHS = UsualUnaryConversions(LHS.get()); 11000 if (LHS.isInvalid()) 11001 return QualType(); 11002 11003 RHS = UsualUnaryConversions(RHS.get()); 11004 if (RHS.isInvalid()) 11005 return QualType(); 11006 11007 if (!LHS.get()->getType()->isScalarType() || 11008 !RHS.get()->getType()->isScalarType()) 11009 return InvalidOperands(Loc, LHS, RHS); 11010 11011 return Context.IntTy; 11012 } 11013 11014 // The following is safe because we only use this method for 11015 // non-overloadable operands. 11016 11017 // C++ [expr.log.and]p1 11018 // C++ [expr.log.or]p1 11019 // The operands are both contextually converted to type bool. 11020 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 11021 if (LHSRes.isInvalid()) 11022 return InvalidOperands(Loc, LHS, RHS); 11023 LHS = LHSRes; 11024 11025 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 11026 if (RHSRes.isInvalid()) 11027 return InvalidOperands(Loc, LHS, RHS); 11028 RHS = RHSRes; 11029 11030 // C++ [expr.log.and]p2 11031 // C++ [expr.log.or]p2 11032 // The result is a bool. 11033 return Context.BoolTy; 11034 } 11035 11036 static bool IsReadonlyMessage(Expr *E, Sema &S) { 11037 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 11038 if (!ME) return false; 11039 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 11040 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 11041 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 11042 if (!Base) return false; 11043 return Base->getMethodDecl() != nullptr; 11044 } 11045 11046 /// Is the given expression (which must be 'const') a reference to a 11047 /// variable which was originally non-const, but which has become 11048 /// 'const' due to being captured within a block? 11049 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 11050 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 11051 assert(E->isLValue() && E->getType().isConstQualified()); 11052 E = E->IgnoreParens(); 11053 11054 // Must be a reference to a declaration from an enclosing scope. 11055 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 11056 if (!DRE) return NCCK_None; 11057 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 11058 11059 // The declaration must be a variable which is not declared 'const'. 11060 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 11061 if (!var) return NCCK_None; 11062 if (var->getType().isConstQualified()) return NCCK_None; 11063 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 11064 11065 // Decide whether the first capture was for a block or a lambda. 11066 DeclContext *DC = S.CurContext, *Prev = nullptr; 11067 // Decide whether the first capture was for a block or a lambda. 11068 while (DC) { 11069 // For init-capture, it is possible that the variable belongs to the 11070 // template pattern of the current context. 11071 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 11072 if (var->isInitCapture() && 11073 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 11074 break; 11075 if (DC == var->getDeclContext()) 11076 break; 11077 Prev = DC; 11078 DC = DC->getParent(); 11079 } 11080 // Unless we have an init-capture, we've gone one step too far. 11081 if (!var->isInitCapture()) 11082 DC = Prev; 11083 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 11084 } 11085 11086 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 11087 Ty = Ty.getNonReferenceType(); 11088 if (IsDereference && Ty->isPointerType()) 11089 Ty = Ty->getPointeeType(); 11090 return !Ty.isConstQualified(); 11091 } 11092 11093 // Update err_typecheck_assign_const and note_typecheck_assign_const 11094 // when this enum is changed. 11095 enum { 11096 ConstFunction, 11097 ConstVariable, 11098 ConstMember, 11099 ConstMethod, 11100 NestedConstMember, 11101 ConstUnknown, // Keep as last element 11102 }; 11103 11104 /// Emit the "read-only variable not assignable" error and print notes to give 11105 /// more information about why the variable is not assignable, such as pointing 11106 /// to the declaration of a const variable, showing that a method is const, or 11107 /// that the function is returning a const reference. 11108 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 11109 SourceLocation Loc) { 11110 SourceRange ExprRange = E->getSourceRange(); 11111 11112 // Only emit one error on the first const found. All other consts will emit 11113 // a note to the error. 11114 bool DiagnosticEmitted = false; 11115 11116 // Track if the current expression is the result of a dereference, and if the 11117 // next checked expression is the result of a dereference. 11118 bool IsDereference = false; 11119 bool NextIsDereference = false; 11120 11121 // Loop to process MemberExpr chains. 11122 while (true) { 11123 IsDereference = NextIsDereference; 11124 11125 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 11126 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 11127 NextIsDereference = ME->isArrow(); 11128 const ValueDecl *VD = ME->getMemberDecl(); 11129 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 11130 // Mutable fields can be modified even if the class is const. 11131 if (Field->isMutable()) { 11132 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 11133 break; 11134 } 11135 11136 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 11137 if (!DiagnosticEmitted) { 11138 S.Diag(Loc, diag::err_typecheck_assign_const) 11139 << ExprRange << ConstMember << false /*static*/ << Field 11140 << Field->getType(); 11141 DiagnosticEmitted = true; 11142 } 11143 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11144 << ConstMember << false /*static*/ << Field << Field->getType() 11145 << Field->getSourceRange(); 11146 } 11147 E = ME->getBase(); 11148 continue; 11149 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 11150 if (VDecl->getType().isConstQualified()) { 11151 if (!DiagnosticEmitted) { 11152 S.Diag(Loc, diag::err_typecheck_assign_const) 11153 << ExprRange << ConstMember << true /*static*/ << VDecl 11154 << VDecl->getType(); 11155 DiagnosticEmitted = true; 11156 } 11157 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11158 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 11159 << VDecl->getSourceRange(); 11160 } 11161 // Static fields do not inherit constness from parents. 11162 break; 11163 } 11164 break; // End MemberExpr 11165 } else if (const ArraySubscriptExpr *ASE = 11166 dyn_cast<ArraySubscriptExpr>(E)) { 11167 E = ASE->getBase()->IgnoreParenImpCasts(); 11168 continue; 11169 } else if (const ExtVectorElementExpr *EVE = 11170 dyn_cast<ExtVectorElementExpr>(E)) { 11171 E = EVE->getBase()->IgnoreParenImpCasts(); 11172 continue; 11173 } 11174 break; 11175 } 11176 11177 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 11178 // Function calls 11179 const FunctionDecl *FD = CE->getDirectCallee(); 11180 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 11181 if (!DiagnosticEmitted) { 11182 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 11183 << ConstFunction << FD; 11184 DiagnosticEmitted = true; 11185 } 11186 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 11187 diag::note_typecheck_assign_const) 11188 << ConstFunction << FD << FD->getReturnType() 11189 << FD->getReturnTypeSourceRange(); 11190 } 11191 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11192 // Point to variable declaration. 11193 if (const ValueDecl *VD = DRE->getDecl()) { 11194 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 11195 if (!DiagnosticEmitted) { 11196 S.Diag(Loc, diag::err_typecheck_assign_const) 11197 << ExprRange << ConstVariable << VD << VD->getType(); 11198 DiagnosticEmitted = true; 11199 } 11200 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11201 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 11202 } 11203 } 11204 } else if (isa<CXXThisExpr>(E)) { 11205 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 11206 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 11207 if (MD->isConst()) { 11208 if (!DiagnosticEmitted) { 11209 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 11210 << ConstMethod << MD; 11211 DiagnosticEmitted = true; 11212 } 11213 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 11214 << ConstMethod << MD << MD->getSourceRange(); 11215 } 11216 } 11217 } 11218 } 11219 11220 if (DiagnosticEmitted) 11221 return; 11222 11223 // Can't determine a more specific message, so display the generic error. 11224 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 11225 } 11226 11227 enum OriginalExprKind { 11228 OEK_Variable, 11229 OEK_Member, 11230 OEK_LValue 11231 }; 11232 11233 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 11234 const RecordType *Ty, 11235 SourceLocation Loc, SourceRange Range, 11236 OriginalExprKind OEK, 11237 bool &DiagnosticEmitted) { 11238 std::vector<const RecordType *> RecordTypeList; 11239 RecordTypeList.push_back(Ty); 11240 unsigned NextToCheckIndex = 0; 11241 // We walk the record hierarchy breadth-first to ensure that we print 11242 // diagnostics in field nesting order. 11243 while (RecordTypeList.size() > NextToCheckIndex) { 11244 bool IsNested = NextToCheckIndex > 0; 11245 for (const FieldDecl *Field : 11246 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 11247 // First, check every field for constness. 11248 QualType FieldTy = Field->getType(); 11249 if (FieldTy.isConstQualified()) { 11250 if (!DiagnosticEmitted) { 11251 S.Diag(Loc, diag::err_typecheck_assign_const) 11252 << Range << NestedConstMember << OEK << VD 11253 << IsNested << Field; 11254 DiagnosticEmitted = true; 11255 } 11256 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 11257 << NestedConstMember << IsNested << Field 11258 << FieldTy << Field->getSourceRange(); 11259 } 11260 11261 // Then we append it to the list to check next in order. 11262 FieldTy = FieldTy.getCanonicalType(); 11263 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 11264 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) 11265 RecordTypeList.push_back(FieldRecTy); 11266 } 11267 } 11268 ++NextToCheckIndex; 11269 } 11270 } 11271 11272 /// Emit an error for the case where a record we are trying to assign to has a 11273 /// const-qualified field somewhere in its hierarchy. 11274 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 11275 SourceLocation Loc) { 11276 QualType Ty = E->getType(); 11277 assert(Ty->isRecordType() && "lvalue was not record?"); 11278 SourceRange Range = E->getSourceRange(); 11279 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 11280 bool DiagEmitted = false; 11281 11282 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 11283 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 11284 Range, OEK_Member, DiagEmitted); 11285 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11286 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 11287 Range, OEK_Variable, DiagEmitted); 11288 else 11289 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 11290 Range, OEK_LValue, DiagEmitted); 11291 if (!DiagEmitted) 11292 DiagnoseConstAssignment(S, E, Loc); 11293 } 11294 11295 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 11296 /// emit an error and return true. If so, return false. 11297 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 11298 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 11299 11300 S.CheckShadowingDeclModification(E, Loc); 11301 11302 SourceLocation OrigLoc = Loc; 11303 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 11304 &Loc); 11305 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 11306 IsLV = Expr::MLV_InvalidMessageExpression; 11307 if (IsLV == Expr::MLV_Valid) 11308 return false; 11309 11310 unsigned DiagID = 0; 11311 bool NeedType = false; 11312 switch (IsLV) { // C99 6.5.16p2 11313 case Expr::MLV_ConstQualified: 11314 // Use a specialized diagnostic when we're assigning to an object 11315 // from an enclosing function or block. 11316 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 11317 if (NCCK == NCCK_Block) 11318 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 11319 else 11320 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 11321 break; 11322 } 11323 11324 // In ARC, use some specialized diagnostics for occasions where we 11325 // infer 'const'. These are always pseudo-strong variables. 11326 if (S.getLangOpts().ObjCAutoRefCount) { 11327 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 11328 if (declRef && isa<VarDecl>(declRef->getDecl())) { 11329 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 11330 11331 // Use the normal diagnostic if it's pseudo-__strong but the 11332 // user actually wrote 'const'. 11333 if (var->isARCPseudoStrong() && 11334 (!var->getTypeSourceInfo() || 11335 !var->getTypeSourceInfo()->getType().isConstQualified())) { 11336 // There are three pseudo-strong cases: 11337 // - self 11338 ObjCMethodDecl *method = S.getCurMethodDecl(); 11339 if (method && var == method->getSelfDecl()) { 11340 DiagID = method->isClassMethod() 11341 ? diag::err_typecheck_arc_assign_self_class_method 11342 : diag::err_typecheck_arc_assign_self; 11343 11344 // - Objective-C externally_retained attribute. 11345 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 11346 isa<ParmVarDecl>(var)) { 11347 DiagID = diag::err_typecheck_arc_assign_externally_retained; 11348 11349 // - fast enumeration variables 11350 } else { 11351 DiagID = diag::err_typecheck_arr_assign_enumeration; 11352 } 11353 11354 SourceRange Assign; 11355 if (Loc != OrigLoc) 11356 Assign = SourceRange(OrigLoc, OrigLoc); 11357 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 11358 // We need to preserve the AST regardless, so migration tool 11359 // can do its job. 11360 return false; 11361 } 11362 } 11363 } 11364 11365 // If none of the special cases above are triggered, then this is a 11366 // simple const assignment. 11367 if (DiagID == 0) { 11368 DiagnoseConstAssignment(S, E, Loc); 11369 return true; 11370 } 11371 11372 break; 11373 case Expr::MLV_ConstAddrSpace: 11374 DiagnoseConstAssignment(S, E, Loc); 11375 return true; 11376 case Expr::MLV_ConstQualifiedField: 11377 DiagnoseRecursiveConstFields(S, E, Loc); 11378 return true; 11379 case Expr::MLV_ArrayType: 11380 case Expr::MLV_ArrayTemporary: 11381 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 11382 NeedType = true; 11383 break; 11384 case Expr::MLV_NotObjectType: 11385 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 11386 NeedType = true; 11387 break; 11388 case Expr::MLV_LValueCast: 11389 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 11390 break; 11391 case Expr::MLV_Valid: 11392 llvm_unreachable("did not take early return for MLV_Valid"); 11393 case Expr::MLV_InvalidExpression: 11394 case Expr::MLV_MemberFunction: 11395 case Expr::MLV_ClassTemporary: 11396 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 11397 break; 11398 case Expr::MLV_IncompleteType: 11399 case Expr::MLV_IncompleteVoidType: 11400 return S.RequireCompleteType(Loc, E->getType(), 11401 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 11402 case Expr::MLV_DuplicateVectorComponents: 11403 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 11404 break; 11405 case Expr::MLV_NoSetterProperty: 11406 llvm_unreachable("readonly properties should be processed differently"); 11407 case Expr::MLV_InvalidMessageExpression: 11408 DiagID = diag::err_readonly_message_assignment; 11409 break; 11410 case Expr::MLV_SubObjCPropertySetting: 11411 DiagID = diag::err_no_subobject_property_setting; 11412 break; 11413 } 11414 11415 SourceRange Assign; 11416 if (Loc != OrigLoc) 11417 Assign = SourceRange(OrigLoc, OrigLoc); 11418 if (NeedType) 11419 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 11420 else 11421 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 11422 return true; 11423 } 11424 11425 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 11426 SourceLocation Loc, 11427 Sema &Sema) { 11428 if (Sema.inTemplateInstantiation()) 11429 return; 11430 if (Sema.isUnevaluatedContext()) 11431 return; 11432 if (Loc.isInvalid() || Loc.isMacroID()) 11433 return; 11434 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 11435 return; 11436 11437 // C / C++ fields 11438 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 11439 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 11440 if (ML && MR) { 11441 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 11442 return; 11443 const ValueDecl *LHSDecl = 11444 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 11445 const ValueDecl *RHSDecl = 11446 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 11447 if (LHSDecl != RHSDecl) 11448 return; 11449 if (LHSDecl->getType().isVolatileQualified()) 11450 return; 11451 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 11452 if (RefTy->getPointeeType().isVolatileQualified()) 11453 return; 11454 11455 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 11456 } 11457 11458 // Objective-C instance variables 11459 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 11460 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 11461 if (OL && OR && OL->getDecl() == OR->getDecl()) { 11462 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 11463 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 11464 if (RL && RR && RL->getDecl() == RR->getDecl()) 11465 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 11466 } 11467 } 11468 11469 // C99 6.5.16.1 11470 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 11471 SourceLocation Loc, 11472 QualType CompoundType) { 11473 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 11474 11475 // Verify that LHS is a modifiable lvalue, and emit error if not. 11476 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 11477 return QualType(); 11478 11479 QualType LHSType = LHSExpr->getType(); 11480 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 11481 CompoundType; 11482 // OpenCL v1.2 s6.1.1.1 p2: 11483 // The half data type can only be used to declare a pointer to a buffer that 11484 // contains half values 11485 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 11486 LHSType->isHalfType()) { 11487 Diag(Loc, diag::err_opencl_half_load_store) << 1 11488 << LHSType.getUnqualifiedType(); 11489 return QualType(); 11490 } 11491 11492 AssignConvertType ConvTy; 11493 if (CompoundType.isNull()) { 11494 Expr *RHSCheck = RHS.get(); 11495 11496 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 11497 11498 QualType LHSTy(LHSType); 11499 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 11500 if (RHS.isInvalid()) 11501 return QualType(); 11502 // Special case of NSObject attributes on c-style pointer types. 11503 if (ConvTy == IncompatiblePointer && 11504 ((Context.isObjCNSObjectType(LHSType) && 11505 RHSType->isObjCObjectPointerType()) || 11506 (Context.isObjCNSObjectType(RHSType) && 11507 LHSType->isObjCObjectPointerType()))) 11508 ConvTy = Compatible; 11509 11510 if (ConvTy == Compatible && 11511 LHSType->isObjCObjectType()) 11512 Diag(Loc, diag::err_objc_object_assignment) 11513 << LHSType; 11514 11515 // If the RHS is a unary plus or minus, check to see if they = and + are 11516 // right next to each other. If so, the user may have typo'd "x =+ 4" 11517 // instead of "x += 4". 11518 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 11519 RHSCheck = ICE->getSubExpr(); 11520 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 11521 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 11522 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 11523 // Only if the two operators are exactly adjacent. 11524 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 11525 // And there is a space or other character before the subexpr of the 11526 // unary +/-. We don't want to warn on "x=-1". 11527 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 11528 UO->getSubExpr()->getBeginLoc().isFileID()) { 11529 Diag(Loc, diag::warn_not_compound_assign) 11530 << (UO->getOpcode() == UO_Plus ? "+" : "-") 11531 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 11532 } 11533 } 11534 11535 if (ConvTy == Compatible) { 11536 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 11537 // Warn about retain cycles where a block captures the LHS, but 11538 // not if the LHS is a simple variable into which the block is 11539 // being stored...unless that variable can be captured by reference! 11540 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 11541 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 11542 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 11543 checkRetainCycles(LHSExpr, RHS.get()); 11544 } 11545 11546 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 11547 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 11548 // It is safe to assign a weak reference into a strong variable. 11549 // Although this code can still have problems: 11550 // id x = self.weakProp; 11551 // id y = self.weakProp; 11552 // we do not warn to warn spuriously when 'x' and 'y' are on separate 11553 // paths through the function. This should be revisited if 11554 // -Wrepeated-use-of-weak is made flow-sensitive. 11555 // For ObjCWeak only, we do not warn if the assign is to a non-weak 11556 // variable, which will be valid for the current autorelease scope. 11557 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 11558 RHS.get()->getBeginLoc())) 11559 getCurFunction()->markSafeWeakUse(RHS.get()); 11560 11561 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 11562 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 11563 } 11564 } 11565 } else { 11566 // Compound assignment "x += y" 11567 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 11568 } 11569 11570 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 11571 RHS.get(), AA_Assigning)) 11572 return QualType(); 11573 11574 CheckForNullPointerDereference(*this, LHSExpr); 11575 11576 // C99 6.5.16p3: The type of an assignment expression is the type of the 11577 // left operand unless the left operand has qualified type, in which case 11578 // it is the unqualified version of the type of the left operand. 11579 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 11580 // is converted to the type of the assignment expression (above). 11581 // C++ 5.17p1: the type of the assignment expression is that of its left 11582 // operand. 11583 return (getLangOpts().CPlusPlus 11584 ? LHSType : LHSType.getUnqualifiedType()); 11585 } 11586 11587 // Only ignore explicit casts to void. 11588 static bool IgnoreCommaOperand(const Expr *E) { 11589 E = E->IgnoreParens(); 11590 11591 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 11592 if (CE->getCastKind() == CK_ToVoid) { 11593 return true; 11594 } 11595 11596 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 11597 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 11598 CE->getSubExpr()->getType()->isDependentType()) { 11599 return true; 11600 } 11601 } 11602 11603 return false; 11604 } 11605 11606 // Look for instances where it is likely the comma operator is confused with 11607 // another operator. There is a whitelist of acceptable expressions for the 11608 // left hand side of the comma operator, otherwise emit a warning. 11609 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 11610 // No warnings in macros 11611 if (Loc.isMacroID()) 11612 return; 11613 11614 // Don't warn in template instantiations. 11615 if (inTemplateInstantiation()) 11616 return; 11617 11618 // Scope isn't fine-grained enough to whitelist the specific cases, so 11619 // instead, skip more than needed, then call back into here with the 11620 // CommaVisitor in SemaStmt.cpp. 11621 // The whitelisted locations are the initialization and increment portions 11622 // of a for loop. The additional checks are on the condition of 11623 // if statements, do/while loops, and for loops. 11624 // Differences in scope flags for C89 mode requires the extra logic. 11625 const unsigned ForIncrementFlags = 11626 getLangOpts().C99 || getLangOpts().CPlusPlus 11627 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 11628 : Scope::ContinueScope | Scope::BreakScope; 11629 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 11630 const unsigned ScopeFlags = getCurScope()->getFlags(); 11631 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 11632 (ScopeFlags & ForInitFlags) == ForInitFlags) 11633 return; 11634 11635 // If there are multiple comma operators used together, get the RHS of the 11636 // of the comma operator as the LHS. 11637 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 11638 if (BO->getOpcode() != BO_Comma) 11639 break; 11640 LHS = BO->getRHS(); 11641 } 11642 11643 // Only allow some expressions on LHS to not warn. 11644 if (IgnoreCommaOperand(LHS)) 11645 return; 11646 11647 Diag(Loc, diag::warn_comma_operator); 11648 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 11649 << LHS->getSourceRange() 11650 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 11651 LangOpts.CPlusPlus ? "static_cast<void>(" 11652 : "(void)(") 11653 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 11654 ")"); 11655 } 11656 11657 // C99 6.5.17 11658 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 11659 SourceLocation Loc) { 11660 LHS = S.CheckPlaceholderExpr(LHS.get()); 11661 RHS = S.CheckPlaceholderExpr(RHS.get()); 11662 if (LHS.isInvalid() || RHS.isInvalid()) 11663 return QualType(); 11664 11665 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 11666 // operands, but not unary promotions. 11667 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 11668 11669 // So we treat the LHS as a ignored value, and in C++ we allow the 11670 // containing site to determine what should be done with the RHS. 11671 LHS = S.IgnoredValueConversions(LHS.get()); 11672 if (LHS.isInvalid()) 11673 return QualType(); 11674 11675 S.DiagnoseUnusedExprResult(LHS.get()); 11676 11677 if (!S.getLangOpts().CPlusPlus) { 11678 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 11679 if (RHS.isInvalid()) 11680 return QualType(); 11681 if (!RHS.get()->getType()->isVoidType()) 11682 S.RequireCompleteType(Loc, RHS.get()->getType(), 11683 diag::err_incomplete_type); 11684 } 11685 11686 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 11687 S.DiagnoseCommaOperator(LHS.get(), Loc); 11688 11689 return RHS.get()->getType(); 11690 } 11691 11692 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 11693 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 11694 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 11695 ExprValueKind &VK, 11696 ExprObjectKind &OK, 11697 SourceLocation OpLoc, 11698 bool IsInc, bool IsPrefix) { 11699 if (Op->isTypeDependent()) 11700 return S.Context.DependentTy; 11701 11702 QualType ResType = Op->getType(); 11703 // Atomic types can be used for increment / decrement where the non-atomic 11704 // versions can, so ignore the _Atomic() specifier for the purpose of 11705 // checking. 11706 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 11707 ResType = ResAtomicType->getValueType(); 11708 11709 assert(!ResType.isNull() && "no type for increment/decrement expression"); 11710 11711 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 11712 // Decrement of bool is not allowed. 11713 if (!IsInc) { 11714 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 11715 return QualType(); 11716 } 11717 // Increment of bool sets it to true, but is deprecated. 11718 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 11719 : diag::warn_increment_bool) 11720 << Op->getSourceRange(); 11721 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 11722 // Error on enum increments and decrements in C++ mode 11723 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 11724 return QualType(); 11725 } else if (ResType->isRealType()) { 11726 // OK! 11727 } else if (ResType->isPointerType()) { 11728 // C99 6.5.2.4p2, 6.5.6p2 11729 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 11730 return QualType(); 11731 } else if (ResType->isObjCObjectPointerType()) { 11732 // On modern runtimes, ObjC pointer arithmetic is forbidden. 11733 // Otherwise, we just need a complete type. 11734 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 11735 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 11736 return QualType(); 11737 } else if (ResType->isAnyComplexType()) { 11738 // C99 does not support ++/-- on complex types, we allow as an extension. 11739 S.Diag(OpLoc, diag::ext_integer_increment_complex) 11740 << ResType << Op->getSourceRange(); 11741 } else if (ResType->isPlaceholderType()) { 11742 ExprResult PR = S.CheckPlaceholderExpr(Op); 11743 if (PR.isInvalid()) return QualType(); 11744 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 11745 IsInc, IsPrefix); 11746 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 11747 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 11748 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 11749 (ResType->getAs<VectorType>()->getVectorKind() != 11750 VectorType::AltiVecBool)) { 11751 // The z vector extensions allow ++ and -- for non-bool vectors. 11752 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 11753 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 11754 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 11755 } else { 11756 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 11757 << ResType << int(IsInc) << Op->getSourceRange(); 11758 return QualType(); 11759 } 11760 // At this point, we know we have a real, complex or pointer type. 11761 // Now make sure the operand is a modifiable lvalue. 11762 if (CheckForModifiableLvalue(Op, OpLoc, S)) 11763 return QualType(); 11764 // In C++, a prefix increment is the same type as the operand. Otherwise 11765 // (in C or with postfix), the increment is the unqualified type of the 11766 // operand. 11767 if (IsPrefix && S.getLangOpts().CPlusPlus) { 11768 VK = VK_LValue; 11769 OK = Op->getObjectKind(); 11770 return ResType; 11771 } else { 11772 VK = VK_RValue; 11773 return ResType.getUnqualifiedType(); 11774 } 11775 } 11776 11777 11778 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 11779 /// This routine allows us to typecheck complex/recursive expressions 11780 /// where the declaration is needed for type checking. We only need to 11781 /// handle cases when the expression references a function designator 11782 /// or is an lvalue. Here are some examples: 11783 /// - &(x) => x 11784 /// - &*****f => f for f a function designator. 11785 /// - &s.xx => s 11786 /// - &s.zz[1].yy -> s, if zz is an array 11787 /// - *(x + 1) -> x, if x is an array 11788 /// - &"123"[2] -> 0 11789 /// - & __real__ x -> x 11790 static ValueDecl *getPrimaryDecl(Expr *E) { 11791 switch (E->getStmtClass()) { 11792 case Stmt::DeclRefExprClass: 11793 return cast<DeclRefExpr>(E)->getDecl(); 11794 case Stmt::MemberExprClass: 11795 // If this is an arrow operator, the address is an offset from 11796 // the base's value, so the object the base refers to is 11797 // irrelevant. 11798 if (cast<MemberExpr>(E)->isArrow()) 11799 return nullptr; 11800 // Otherwise, the expression refers to a part of the base 11801 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 11802 case Stmt::ArraySubscriptExprClass: { 11803 // FIXME: This code shouldn't be necessary! We should catch the implicit 11804 // promotion of register arrays earlier. 11805 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 11806 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 11807 if (ICE->getSubExpr()->getType()->isArrayType()) 11808 return getPrimaryDecl(ICE->getSubExpr()); 11809 } 11810 return nullptr; 11811 } 11812 case Stmt::UnaryOperatorClass: { 11813 UnaryOperator *UO = cast<UnaryOperator>(E); 11814 11815 switch(UO->getOpcode()) { 11816 case UO_Real: 11817 case UO_Imag: 11818 case UO_Extension: 11819 return getPrimaryDecl(UO->getSubExpr()); 11820 default: 11821 return nullptr; 11822 } 11823 } 11824 case Stmt::ParenExprClass: 11825 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 11826 case Stmt::ImplicitCastExprClass: 11827 // If the result of an implicit cast is an l-value, we care about 11828 // the sub-expression; otherwise, the result here doesn't matter. 11829 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 11830 default: 11831 return nullptr; 11832 } 11833 } 11834 11835 namespace { 11836 enum { 11837 AO_Bit_Field = 0, 11838 AO_Vector_Element = 1, 11839 AO_Property_Expansion = 2, 11840 AO_Register_Variable = 3, 11841 AO_No_Error = 4 11842 }; 11843 } 11844 /// Diagnose invalid operand for address of operations. 11845 /// 11846 /// \param Type The type of operand which cannot have its address taken. 11847 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 11848 Expr *E, unsigned Type) { 11849 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 11850 } 11851 11852 /// CheckAddressOfOperand - The operand of & must be either a function 11853 /// designator or an lvalue designating an object. If it is an lvalue, the 11854 /// object cannot be declared with storage class register or be a bit field. 11855 /// Note: The usual conversions are *not* applied to the operand of the & 11856 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 11857 /// In C++, the operand might be an overloaded function name, in which case 11858 /// we allow the '&' but retain the overloaded-function type. 11859 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 11860 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 11861 if (PTy->getKind() == BuiltinType::Overload) { 11862 Expr *E = OrigOp.get()->IgnoreParens(); 11863 if (!isa<OverloadExpr>(E)) { 11864 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 11865 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 11866 << OrigOp.get()->getSourceRange(); 11867 return QualType(); 11868 } 11869 11870 OverloadExpr *Ovl = cast<OverloadExpr>(E); 11871 if (isa<UnresolvedMemberExpr>(Ovl)) 11872 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 11873 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11874 << OrigOp.get()->getSourceRange(); 11875 return QualType(); 11876 } 11877 11878 return Context.OverloadTy; 11879 } 11880 11881 if (PTy->getKind() == BuiltinType::UnknownAny) 11882 return Context.UnknownAnyTy; 11883 11884 if (PTy->getKind() == BuiltinType::BoundMember) { 11885 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11886 << OrigOp.get()->getSourceRange(); 11887 return QualType(); 11888 } 11889 11890 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 11891 if (OrigOp.isInvalid()) return QualType(); 11892 } 11893 11894 if (OrigOp.get()->isTypeDependent()) 11895 return Context.DependentTy; 11896 11897 assert(!OrigOp.get()->getType()->isPlaceholderType()); 11898 11899 // Make sure to ignore parentheses in subsequent checks 11900 Expr *op = OrigOp.get()->IgnoreParens(); 11901 11902 // In OpenCL captures for blocks called as lambda functions 11903 // are located in the private address space. Blocks used in 11904 // enqueue_kernel can be located in a different address space 11905 // depending on a vendor implementation. Thus preventing 11906 // taking an address of the capture to avoid invalid AS casts. 11907 if (LangOpts.OpenCL) { 11908 auto* VarRef = dyn_cast<DeclRefExpr>(op); 11909 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 11910 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 11911 return QualType(); 11912 } 11913 } 11914 11915 if (getLangOpts().C99) { 11916 // Implement C99-only parts of addressof rules. 11917 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 11918 if (uOp->getOpcode() == UO_Deref) 11919 // Per C99 6.5.3.2, the address of a deref always returns a valid result 11920 // (assuming the deref expression is valid). 11921 return uOp->getSubExpr()->getType(); 11922 } 11923 // Technically, there should be a check for array subscript 11924 // expressions here, but the result of one is always an lvalue anyway. 11925 } 11926 ValueDecl *dcl = getPrimaryDecl(op); 11927 11928 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 11929 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 11930 op->getBeginLoc())) 11931 return QualType(); 11932 11933 Expr::LValueClassification lval = op->ClassifyLValue(Context); 11934 unsigned AddressOfError = AO_No_Error; 11935 11936 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 11937 bool sfinae = (bool)isSFINAEContext(); 11938 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 11939 : diag::ext_typecheck_addrof_temporary) 11940 << op->getType() << op->getSourceRange(); 11941 if (sfinae) 11942 return QualType(); 11943 // Materialize the temporary as an lvalue so that we can take its address. 11944 OrigOp = op = 11945 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 11946 } else if (isa<ObjCSelectorExpr>(op)) { 11947 return Context.getPointerType(op->getType()); 11948 } else if (lval == Expr::LV_MemberFunction) { 11949 // If it's an instance method, make a member pointer. 11950 // The expression must have exactly the form &A::foo. 11951 11952 // If the underlying expression isn't a decl ref, give up. 11953 if (!isa<DeclRefExpr>(op)) { 11954 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11955 << OrigOp.get()->getSourceRange(); 11956 return QualType(); 11957 } 11958 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 11959 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 11960 11961 // The id-expression was parenthesized. 11962 if (OrigOp.get() != DRE) { 11963 Diag(OpLoc, diag::err_parens_pointer_member_function) 11964 << OrigOp.get()->getSourceRange(); 11965 11966 // The method was named without a qualifier. 11967 } else if (!DRE->getQualifier()) { 11968 if (MD->getParent()->getName().empty()) 11969 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 11970 << op->getSourceRange(); 11971 else { 11972 SmallString<32> Str; 11973 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 11974 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 11975 << op->getSourceRange() 11976 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 11977 } 11978 } 11979 11980 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 11981 if (isa<CXXDestructorDecl>(MD)) 11982 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 11983 11984 QualType MPTy = Context.getMemberPointerType( 11985 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 11986 // Under the MS ABI, lock down the inheritance model now. 11987 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11988 (void)isCompleteType(OpLoc, MPTy); 11989 return MPTy; 11990 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 11991 // C99 6.5.3.2p1 11992 // The operand must be either an l-value or a function designator 11993 if (!op->getType()->isFunctionType()) { 11994 // Use a special diagnostic for loads from property references. 11995 if (isa<PseudoObjectExpr>(op)) { 11996 AddressOfError = AO_Property_Expansion; 11997 } else { 11998 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 11999 << op->getType() << op->getSourceRange(); 12000 return QualType(); 12001 } 12002 } 12003 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 12004 // The operand cannot be a bit-field 12005 AddressOfError = AO_Bit_Field; 12006 } else if (op->getObjectKind() == OK_VectorComponent) { 12007 // The operand cannot be an element of a vector 12008 AddressOfError = AO_Vector_Element; 12009 } else if (dcl) { // C99 6.5.3.2p1 12010 // We have an lvalue with a decl. Make sure the decl is not declared 12011 // with the register storage-class specifier. 12012 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 12013 // in C++ it is not error to take address of a register 12014 // variable (c++03 7.1.1P3) 12015 if (vd->getStorageClass() == SC_Register && 12016 !getLangOpts().CPlusPlus) { 12017 AddressOfError = AO_Register_Variable; 12018 } 12019 } else if (isa<MSPropertyDecl>(dcl)) { 12020 AddressOfError = AO_Property_Expansion; 12021 } else if (isa<FunctionTemplateDecl>(dcl)) { 12022 return Context.OverloadTy; 12023 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 12024 // Okay: we can take the address of a field. 12025 // Could be a pointer to member, though, if there is an explicit 12026 // scope qualifier for the class. 12027 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 12028 DeclContext *Ctx = dcl->getDeclContext(); 12029 if (Ctx && Ctx->isRecord()) { 12030 if (dcl->getType()->isReferenceType()) { 12031 Diag(OpLoc, 12032 diag::err_cannot_form_pointer_to_member_of_reference_type) 12033 << dcl->getDeclName() << dcl->getType(); 12034 return QualType(); 12035 } 12036 12037 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 12038 Ctx = Ctx->getParent(); 12039 12040 QualType MPTy = Context.getMemberPointerType( 12041 op->getType(), 12042 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 12043 // Under the MS ABI, lock down the inheritance model now. 12044 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 12045 (void)isCompleteType(OpLoc, MPTy); 12046 return MPTy; 12047 } 12048 } 12049 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 12050 !isa<BindingDecl>(dcl)) 12051 llvm_unreachable("Unknown/unexpected decl type"); 12052 } 12053 12054 if (AddressOfError != AO_No_Error) { 12055 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 12056 return QualType(); 12057 } 12058 12059 if (lval == Expr::LV_IncompleteVoidType) { 12060 // Taking the address of a void variable is technically illegal, but we 12061 // allow it in cases which are otherwise valid. 12062 // Example: "extern void x; void* y = &x;". 12063 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 12064 } 12065 12066 // If the operand has type "type", the result has type "pointer to type". 12067 if (op->getType()->isObjCObjectType()) 12068 return Context.getObjCObjectPointerType(op->getType()); 12069 12070 CheckAddressOfPackedMember(op); 12071 12072 return Context.getPointerType(op->getType()); 12073 } 12074 12075 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 12076 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 12077 if (!DRE) 12078 return; 12079 const Decl *D = DRE->getDecl(); 12080 if (!D) 12081 return; 12082 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 12083 if (!Param) 12084 return; 12085 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 12086 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 12087 return; 12088 if (FunctionScopeInfo *FD = S.getCurFunction()) 12089 if (!FD->ModifiedNonNullParams.count(Param)) 12090 FD->ModifiedNonNullParams.insert(Param); 12091 } 12092 12093 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 12094 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 12095 SourceLocation OpLoc) { 12096 if (Op->isTypeDependent()) 12097 return S.Context.DependentTy; 12098 12099 ExprResult ConvResult = S.UsualUnaryConversions(Op); 12100 if (ConvResult.isInvalid()) 12101 return QualType(); 12102 Op = ConvResult.get(); 12103 QualType OpTy = Op->getType(); 12104 QualType Result; 12105 12106 if (isa<CXXReinterpretCastExpr>(Op)) { 12107 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 12108 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 12109 Op->getSourceRange()); 12110 } 12111 12112 if (const PointerType *PT = OpTy->getAs<PointerType>()) 12113 { 12114 Result = PT->getPointeeType(); 12115 } 12116 else if (const ObjCObjectPointerType *OPT = 12117 OpTy->getAs<ObjCObjectPointerType>()) 12118 Result = OPT->getPointeeType(); 12119 else { 12120 ExprResult PR = S.CheckPlaceholderExpr(Op); 12121 if (PR.isInvalid()) return QualType(); 12122 if (PR.get() != Op) 12123 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 12124 } 12125 12126 if (Result.isNull()) { 12127 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 12128 << OpTy << Op->getSourceRange(); 12129 return QualType(); 12130 } 12131 12132 // Note that per both C89 and C99, indirection is always legal, even if Result 12133 // is an incomplete type or void. It would be possible to warn about 12134 // dereferencing a void pointer, but it's completely well-defined, and such a 12135 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 12136 // for pointers to 'void' but is fine for any other pointer type: 12137 // 12138 // C++ [expr.unary.op]p1: 12139 // [...] the expression to which [the unary * operator] is applied shall 12140 // be a pointer to an object type, or a pointer to a function type 12141 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 12142 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 12143 << OpTy << Op->getSourceRange(); 12144 12145 // Dereferences are usually l-values... 12146 VK = VK_LValue; 12147 12148 // ...except that certain expressions are never l-values in C. 12149 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 12150 VK = VK_RValue; 12151 12152 return Result; 12153 } 12154 12155 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 12156 BinaryOperatorKind Opc; 12157 switch (Kind) { 12158 default: llvm_unreachable("Unknown binop!"); 12159 case tok::periodstar: Opc = BO_PtrMemD; break; 12160 case tok::arrowstar: Opc = BO_PtrMemI; break; 12161 case tok::star: Opc = BO_Mul; break; 12162 case tok::slash: Opc = BO_Div; break; 12163 case tok::percent: Opc = BO_Rem; break; 12164 case tok::plus: Opc = BO_Add; break; 12165 case tok::minus: Opc = BO_Sub; break; 12166 case tok::lessless: Opc = BO_Shl; break; 12167 case tok::greatergreater: Opc = BO_Shr; break; 12168 case tok::lessequal: Opc = BO_LE; break; 12169 case tok::less: Opc = BO_LT; break; 12170 case tok::greaterequal: Opc = BO_GE; break; 12171 case tok::greater: Opc = BO_GT; break; 12172 case tok::exclaimequal: Opc = BO_NE; break; 12173 case tok::equalequal: Opc = BO_EQ; break; 12174 case tok::spaceship: Opc = BO_Cmp; break; 12175 case tok::amp: Opc = BO_And; break; 12176 case tok::caret: Opc = BO_Xor; break; 12177 case tok::pipe: Opc = BO_Or; break; 12178 case tok::ampamp: Opc = BO_LAnd; break; 12179 case tok::pipepipe: Opc = BO_LOr; break; 12180 case tok::equal: Opc = BO_Assign; break; 12181 case tok::starequal: Opc = BO_MulAssign; break; 12182 case tok::slashequal: Opc = BO_DivAssign; break; 12183 case tok::percentequal: Opc = BO_RemAssign; break; 12184 case tok::plusequal: Opc = BO_AddAssign; break; 12185 case tok::minusequal: Opc = BO_SubAssign; break; 12186 case tok::lesslessequal: Opc = BO_ShlAssign; break; 12187 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 12188 case tok::ampequal: Opc = BO_AndAssign; break; 12189 case tok::caretequal: Opc = BO_XorAssign; break; 12190 case tok::pipeequal: Opc = BO_OrAssign; break; 12191 case tok::comma: Opc = BO_Comma; break; 12192 } 12193 return Opc; 12194 } 12195 12196 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 12197 tok::TokenKind Kind) { 12198 UnaryOperatorKind Opc; 12199 switch (Kind) { 12200 default: llvm_unreachable("Unknown unary op!"); 12201 case tok::plusplus: Opc = UO_PreInc; break; 12202 case tok::minusminus: Opc = UO_PreDec; break; 12203 case tok::amp: Opc = UO_AddrOf; break; 12204 case tok::star: Opc = UO_Deref; break; 12205 case tok::plus: Opc = UO_Plus; break; 12206 case tok::minus: Opc = UO_Minus; break; 12207 case tok::tilde: Opc = UO_Not; break; 12208 case tok::exclaim: Opc = UO_LNot; break; 12209 case tok::kw___real: Opc = UO_Real; break; 12210 case tok::kw___imag: Opc = UO_Imag; break; 12211 case tok::kw___extension__: Opc = UO_Extension; break; 12212 } 12213 return Opc; 12214 } 12215 12216 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 12217 /// This warning suppressed in the event of macro expansions. 12218 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 12219 SourceLocation OpLoc, bool IsBuiltin) { 12220 if (S.inTemplateInstantiation()) 12221 return; 12222 if (S.isUnevaluatedContext()) 12223 return; 12224 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 12225 return; 12226 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 12227 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 12228 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 12229 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 12230 if (!LHSDeclRef || !RHSDeclRef || 12231 LHSDeclRef->getLocation().isMacroID() || 12232 RHSDeclRef->getLocation().isMacroID()) 12233 return; 12234 const ValueDecl *LHSDecl = 12235 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 12236 const ValueDecl *RHSDecl = 12237 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 12238 if (LHSDecl != RHSDecl) 12239 return; 12240 if (LHSDecl->getType().isVolatileQualified()) 12241 return; 12242 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 12243 if (RefTy->getPointeeType().isVolatileQualified()) 12244 return; 12245 12246 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 12247 : diag::warn_self_assignment_overloaded) 12248 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 12249 << RHSExpr->getSourceRange(); 12250 } 12251 12252 /// Check if a bitwise-& is performed on an Objective-C pointer. This 12253 /// is usually indicative of introspection within the Objective-C pointer. 12254 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 12255 SourceLocation OpLoc) { 12256 if (!S.getLangOpts().ObjC) 12257 return; 12258 12259 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 12260 const Expr *LHS = L.get(); 12261 const Expr *RHS = R.get(); 12262 12263 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 12264 ObjCPointerExpr = LHS; 12265 OtherExpr = RHS; 12266 } 12267 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 12268 ObjCPointerExpr = RHS; 12269 OtherExpr = LHS; 12270 } 12271 12272 // This warning is deliberately made very specific to reduce false 12273 // positives with logic that uses '&' for hashing. This logic mainly 12274 // looks for code trying to introspect into tagged pointers, which 12275 // code should generally never do. 12276 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 12277 unsigned Diag = diag::warn_objc_pointer_masking; 12278 // Determine if we are introspecting the result of performSelectorXXX. 12279 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 12280 // Special case messages to -performSelector and friends, which 12281 // can return non-pointer values boxed in a pointer value. 12282 // Some clients may wish to silence warnings in this subcase. 12283 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 12284 Selector S = ME->getSelector(); 12285 StringRef SelArg0 = S.getNameForSlot(0); 12286 if (SelArg0.startswith("performSelector")) 12287 Diag = diag::warn_objc_pointer_masking_performSelector; 12288 } 12289 12290 S.Diag(OpLoc, Diag) 12291 << ObjCPointerExpr->getSourceRange(); 12292 } 12293 } 12294 12295 static NamedDecl *getDeclFromExpr(Expr *E) { 12296 if (!E) 12297 return nullptr; 12298 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 12299 return DRE->getDecl(); 12300 if (auto *ME = dyn_cast<MemberExpr>(E)) 12301 return ME->getMemberDecl(); 12302 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 12303 return IRE->getDecl(); 12304 return nullptr; 12305 } 12306 12307 // This helper function promotes a binary operator's operands (which are of a 12308 // half vector type) to a vector of floats and then truncates the result to 12309 // a vector of either half or short. 12310 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 12311 BinaryOperatorKind Opc, QualType ResultTy, 12312 ExprValueKind VK, ExprObjectKind OK, 12313 bool IsCompAssign, SourceLocation OpLoc, 12314 FPOptions FPFeatures) { 12315 auto &Context = S.getASTContext(); 12316 assert((isVector(ResultTy, Context.HalfTy) || 12317 isVector(ResultTy, Context.ShortTy)) && 12318 "Result must be a vector of half or short"); 12319 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 12320 isVector(RHS.get()->getType(), Context.HalfTy) && 12321 "both operands expected to be a half vector"); 12322 12323 RHS = convertVector(RHS.get(), Context.FloatTy, S); 12324 QualType BinOpResTy = RHS.get()->getType(); 12325 12326 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 12327 // change BinOpResTy to a vector of ints. 12328 if (isVector(ResultTy, Context.ShortTy)) 12329 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 12330 12331 if (IsCompAssign) 12332 return new (Context) CompoundAssignOperator( 12333 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy, 12334 OpLoc, FPFeatures); 12335 12336 LHS = convertVector(LHS.get(), Context.FloatTy, S); 12337 auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy, 12338 VK, OK, OpLoc, FPFeatures); 12339 return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S); 12340 } 12341 12342 static std::pair<ExprResult, ExprResult> 12343 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 12344 Expr *RHSExpr) { 12345 ExprResult LHS = LHSExpr, RHS = RHSExpr; 12346 if (!S.getLangOpts().CPlusPlus) { 12347 // C cannot handle TypoExpr nodes on either side of a binop because it 12348 // doesn't handle dependent types properly, so make sure any TypoExprs have 12349 // been dealt with before checking the operands. 12350 LHS = S.CorrectDelayedTyposInExpr(LHS); 12351 RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) { 12352 if (Opc != BO_Assign) 12353 return ExprResult(E); 12354 // Avoid correcting the RHS to the same Expr as the LHS. 12355 Decl *D = getDeclFromExpr(E); 12356 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 12357 }); 12358 } 12359 return std::make_pair(LHS, RHS); 12360 } 12361 12362 /// Returns true if conversion between vectors of halfs and vectors of floats 12363 /// is needed. 12364 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 12365 QualType SrcType) { 12366 return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType && 12367 !Ctx.getTargetInfo().useFP16ConversionIntrinsics() && 12368 isVector(SrcType, Ctx.HalfTy); 12369 } 12370 12371 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 12372 /// operator @p Opc at location @c TokLoc. This routine only supports 12373 /// built-in operations; ActOnBinOp handles overloaded operators. 12374 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 12375 BinaryOperatorKind Opc, 12376 Expr *LHSExpr, Expr *RHSExpr) { 12377 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 12378 // The syntax only allows initializer lists on the RHS of assignment, 12379 // so we don't need to worry about accepting invalid code for 12380 // non-assignment operators. 12381 // C++11 5.17p9: 12382 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 12383 // of x = {} is x = T(). 12384 InitializationKind Kind = InitializationKind::CreateDirectList( 12385 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 12386 InitializedEntity Entity = 12387 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 12388 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 12389 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 12390 if (Init.isInvalid()) 12391 return Init; 12392 RHSExpr = Init.get(); 12393 } 12394 12395 ExprResult LHS = LHSExpr, RHS = RHSExpr; 12396 QualType ResultTy; // Result type of the binary operator. 12397 // The following two variables are used for compound assignment operators 12398 QualType CompLHSTy; // Type of LHS after promotions for computation 12399 QualType CompResultTy; // Type of computation result 12400 ExprValueKind VK = VK_RValue; 12401 ExprObjectKind OK = OK_Ordinary; 12402 bool ConvertHalfVec = false; 12403 12404 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 12405 if (!LHS.isUsable() || !RHS.isUsable()) 12406 return ExprError(); 12407 12408 if (getLangOpts().OpenCL) { 12409 QualType LHSTy = LHSExpr->getType(); 12410 QualType RHSTy = RHSExpr->getType(); 12411 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 12412 // the ATOMIC_VAR_INIT macro. 12413 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 12414 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 12415 if (BO_Assign == Opc) 12416 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 12417 else 12418 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 12419 return ExprError(); 12420 } 12421 12422 // OpenCL special types - image, sampler, pipe, and blocks are to be used 12423 // only with a builtin functions and therefore should be disallowed here. 12424 if (LHSTy->isImageType() || RHSTy->isImageType() || 12425 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 12426 LHSTy->isPipeType() || RHSTy->isPipeType() || 12427 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 12428 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 12429 return ExprError(); 12430 } 12431 } 12432 12433 // Diagnose operations on the unsupported types for OpenMP device compilation. 12434 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) { 12435 if (Opc != BO_Assign && Opc != BO_Comma) { 12436 checkOpenMPDeviceExpr(LHSExpr); 12437 checkOpenMPDeviceExpr(RHSExpr); 12438 } 12439 } 12440 12441 switch (Opc) { 12442 case BO_Assign: 12443 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 12444 if (getLangOpts().CPlusPlus && 12445 LHS.get()->getObjectKind() != OK_ObjCProperty) { 12446 VK = LHS.get()->getValueKind(); 12447 OK = LHS.get()->getObjectKind(); 12448 } 12449 if (!ResultTy.isNull()) { 12450 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 12451 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 12452 12453 // Avoid copying a block to the heap if the block is assigned to a local 12454 // auto variable that is declared in the same scope as the block. This 12455 // optimization is unsafe if the local variable is declared in an outer 12456 // scope. For example: 12457 // 12458 // BlockTy b; 12459 // { 12460 // b = ^{...}; 12461 // } 12462 // // It is unsafe to invoke the block here if it wasn't copied to the 12463 // // heap. 12464 // b(); 12465 12466 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 12467 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 12468 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 12469 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 12470 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 12471 } 12472 RecordModifiableNonNullParam(*this, LHS.get()); 12473 break; 12474 case BO_PtrMemD: 12475 case BO_PtrMemI: 12476 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 12477 Opc == BO_PtrMemI); 12478 break; 12479 case BO_Mul: 12480 case BO_Div: 12481 ConvertHalfVec = true; 12482 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 12483 Opc == BO_Div); 12484 break; 12485 case BO_Rem: 12486 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 12487 break; 12488 case BO_Add: 12489 ConvertHalfVec = true; 12490 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 12491 break; 12492 case BO_Sub: 12493 ConvertHalfVec = true; 12494 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 12495 break; 12496 case BO_Shl: 12497 case BO_Shr: 12498 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 12499 break; 12500 case BO_LE: 12501 case BO_LT: 12502 case BO_GE: 12503 case BO_GT: 12504 ConvertHalfVec = true; 12505 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12506 break; 12507 case BO_EQ: 12508 case BO_NE: 12509 ConvertHalfVec = true; 12510 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12511 break; 12512 case BO_Cmp: 12513 ConvertHalfVec = true; 12514 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12515 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 12516 break; 12517 case BO_And: 12518 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 12519 LLVM_FALLTHROUGH; 12520 case BO_Xor: 12521 case BO_Or: 12522 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 12523 break; 12524 case BO_LAnd: 12525 case BO_LOr: 12526 ConvertHalfVec = true; 12527 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 12528 break; 12529 case BO_MulAssign: 12530 case BO_DivAssign: 12531 ConvertHalfVec = true; 12532 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 12533 Opc == BO_DivAssign); 12534 CompLHSTy = CompResultTy; 12535 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12536 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12537 break; 12538 case BO_RemAssign: 12539 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 12540 CompLHSTy = CompResultTy; 12541 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12542 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12543 break; 12544 case BO_AddAssign: 12545 ConvertHalfVec = true; 12546 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 12547 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12548 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12549 break; 12550 case BO_SubAssign: 12551 ConvertHalfVec = true; 12552 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 12553 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12554 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12555 break; 12556 case BO_ShlAssign: 12557 case BO_ShrAssign: 12558 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 12559 CompLHSTy = CompResultTy; 12560 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12561 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12562 break; 12563 case BO_AndAssign: 12564 case BO_OrAssign: // fallthrough 12565 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 12566 LLVM_FALLTHROUGH; 12567 case BO_XorAssign: 12568 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 12569 CompLHSTy = CompResultTy; 12570 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12571 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12572 break; 12573 case BO_Comma: 12574 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 12575 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 12576 VK = RHS.get()->getValueKind(); 12577 OK = RHS.get()->getObjectKind(); 12578 } 12579 break; 12580 } 12581 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 12582 return ExprError(); 12583 12584 // Some of the binary operations require promoting operands of half vector to 12585 // float vectors and truncating the result back to half vector. For now, we do 12586 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 12587 // arm64). 12588 assert(isVector(RHS.get()->getType(), Context.HalfTy) == 12589 isVector(LHS.get()->getType(), Context.HalfTy) && 12590 "both sides are half vectors or neither sides are"); 12591 ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context, 12592 LHS.get()->getType()); 12593 12594 // Check for array bounds violations for both sides of the BinaryOperator 12595 CheckArrayAccess(LHS.get()); 12596 CheckArrayAccess(RHS.get()); 12597 12598 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 12599 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 12600 &Context.Idents.get("object_setClass"), 12601 SourceLocation(), LookupOrdinaryName); 12602 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 12603 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 12604 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 12605 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 12606 "object_setClass(") 12607 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 12608 ",") 12609 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 12610 } 12611 else 12612 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 12613 } 12614 else if (const ObjCIvarRefExpr *OIRE = 12615 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 12616 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 12617 12618 // Opc is not a compound assignment if CompResultTy is null. 12619 if (CompResultTy.isNull()) { 12620 if (ConvertHalfVec) 12621 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 12622 OpLoc, FPFeatures); 12623 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 12624 OK, OpLoc, FPFeatures); 12625 } 12626 12627 // Handle compound assignments. 12628 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 12629 OK_ObjCProperty) { 12630 VK = VK_LValue; 12631 OK = LHS.get()->getObjectKind(); 12632 } 12633 12634 if (ConvertHalfVec) 12635 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 12636 OpLoc, FPFeatures); 12637 12638 return new (Context) CompoundAssignOperator( 12639 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 12640 OpLoc, FPFeatures); 12641 } 12642 12643 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 12644 /// operators are mixed in a way that suggests that the programmer forgot that 12645 /// comparison operators have higher precedence. The most typical example of 12646 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 12647 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 12648 SourceLocation OpLoc, Expr *LHSExpr, 12649 Expr *RHSExpr) { 12650 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 12651 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 12652 12653 // Check that one of the sides is a comparison operator and the other isn't. 12654 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 12655 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 12656 if (isLeftComp == isRightComp) 12657 return; 12658 12659 // Bitwise operations are sometimes used as eager logical ops. 12660 // Don't diagnose this. 12661 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 12662 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 12663 if (isLeftBitwise || isRightBitwise) 12664 return; 12665 12666 SourceRange DiagRange = isLeftComp 12667 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 12668 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 12669 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 12670 SourceRange ParensRange = 12671 isLeftComp 12672 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 12673 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 12674 12675 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 12676 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 12677 SuggestParentheses(Self, OpLoc, 12678 Self.PDiag(diag::note_precedence_silence) << OpStr, 12679 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 12680 SuggestParentheses(Self, OpLoc, 12681 Self.PDiag(diag::note_precedence_bitwise_first) 12682 << BinaryOperator::getOpcodeStr(Opc), 12683 ParensRange); 12684 } 12685 12686 /// It accepts a '&&' expr that is inside a '||' one. 12687 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 12688 /// in parentheses. 12689 static void 12690 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 12691 BinaryOperator *Bop) { 12692 assert(Bop->getOpcode() == BO_LAnd); 12693 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 12694 << Bop->getSourceRange() << OpLoc; 12695 SuggestParentheses(Self, Bop->getOperatorLoc(), 12696 Self.PDiag(diag::note_precedence_silence) 12697 << Bop->getOpcodeStr(), 12698 Bop->getSourceRange()); 12699 } 12700 12701 /// Returns true if the given expression can be evaluated as a constant 12702 /// 'true'. 12703 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 12704 bool Res; 12705 return !E->isValueDependent() && 12706 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 12707 } 12708 12709 /// Returns true if the given expression can be evaluated as a constant 12710 /// 'false'. 12711 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 12712 bool Res; 12713 return !E->isValueDependent() && 12714 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 12715 } 12716 12717 /// Look for '&&' in the left hand of a '||' expr. 12718 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 12719 Expr *LHSExpr, Expr *RHSExpr) { 12720 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 12721 if (Bop->getOpcode() == BO_LAnd) { 12722 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 12723 if (EvaluatesAsFalse(S, RHSExpr)) 12724 return; 12725 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 12726 if (!EvaluatesAsTrue(S, Bop->getLHS())) 12727 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 12728 } else if (Bop->getOpcode() == BO_LOr) { 12729 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 12730 // If it's "a || b && 1 || c" we didn't warn earlier for 12731 // "a || b && 1", but warn now. 12732 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 12733 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 12734 } 12735 } 12736 } 12737 } 12738 12739 /// Look for '&&' in the right hand of a '||' expr. 12740 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 12741 Expr *LHSExpr, Expr *RHSExpr) { 12742 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 12743 if (Bop->getOpcode() == BO_LAnd) { 12744 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 12745 if (EvaluatesAsFalse(S, LHSExpr)) 12746 return; 12747 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 12748 if (!EvaluatesAsTrue(S, Bop->getRHS())) 12749 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 12750 } 12751 } 12752 } 12753 12754 /// Look for bitwise op in the left or right hand of a bitwise op with 12755 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 12756 /// the '&' expression in parentheses. 12757 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 12758 SourceLocation OpLoc, Expr *SubExpr) { 12759 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 12760 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 12761 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 12762 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 12763 << Bop->getSourceRange() << OpLoc; 12764 SuggestParentheses(S, Bop->getOperatorLoc(), 12765 S.PDiag(diag::note_precedence_silence) 12766 << Bop->getOpcodeStr(), 12767 Bop->getSourceRange()); 12768 } 12769 } 12770 } 12771 12772 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 12773 Expr *SubExpr, StringRef Shift) { 12774 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 12775 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 12776 StringRef Op = Bop->getOpcodeStr(); 12777 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 12778 << Bop->getSourceRange() << OpLoc << Shift << Op; 12779 SuggestParentheses(S, Bop->getOperatorLoc(), 12780 S.PDiag(diag::note_precedence_silence) << Op, 12781 Bop->getSourceRange()); 12782 } 12783 } 12784 } 12785 12786 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 12787 Expr *LHSExpr, Expr *RHSExpr) { 12788 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 12789 if (!OCE) 12790 return; 12791 12792 FunctionDecl *FD = OCE->getDirectCallee(); 12793 if (!FD || !FD->isOverloadedOperator()) 12794 return; 12795 12796 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 12797 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 12798 return; 12799 12800 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 12801 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 12802 << (Kind == OO_LessLess); 12803 SuggestParentheses(S, OCE->getOperatorLoc(), 12804 S.PDiag(diag::note_precedence_silence) 12805 << (Kind == OO_LessLess ? "<<" : ">>"), 12806 OCE->getSourceRange()); 12807 SuggestParentheses( 12808 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 12809 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 12810 } 12811 12812 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 12813 /// precedence. 12814 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 12815 SourceLocation OpLoc, Expr *LHSExpr, 12816 Expr *RHSExpr){ 12817 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 12818 if (BinaryOperator::isBitwiseOp(Opc)) 12819 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 12820 12821 // Diagnose "arg1 & arg2 | arg3" 12822 if ((Opc == BO_Or || Opc == BO_Xor) && 12823 !OpLoc.isMacroID()/* Don't warn in macros. */) { 12824 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 12825 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 12826 } 12827 12828 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 12829 // We don't warn for 'assert(a || b && "bad")' since this is safe. 12830 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 12831 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 12832 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 12833 } 12834 12835 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 12836 || Opc == BO_Shr) { 12837 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 12838 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 12839 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 12840 } 12841 12842 // Warn on overloaded shift operators and comparisons, such as: 12843 // cout << 5 == 4; 12844 if (BinaryOperator::isComparisonOp(Opc)) 12845 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 12846 } 12847 12848 // Binary Operators. 'Tok' is the token for the operator. 12849 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 12850 tok::TokenKind Kind, 12851 Expr *LHSExpr, Expr *RHSExpr) { 12852 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 12853 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 12854 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 12855 12856 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 12857 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 12858 12859 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 12860 } 12861 12862 /// Build an overloaded binary operator expression in the given scope. 12863 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 12864 BinaryOperatorKind Opc, 12865 Expr *LHS, Expr *RHS) { 12866 switch (Opc) { 12867 case BO_Assign: 12868 case BO_DivAssign: 12869 case BO_RemAssign: 12870 case BO_SubAssign: 12871 case BO_AndAssign: 12872 case BO_OrAssign: 12873 case BO_XorAssign: 12874 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 12875 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 12876 break; 12877 default: 12878 break; 12879 } 12880 12881 // Find all of the overloaded operators visible from this 12882 // point. We perform both an operator-name lookup from the local 12883 // scope and an argument-dependent lookup based on the types of 12884 // the arguments. 12885 UnresolvedSet<16> Functions; 12886 OverloadedOperatorKind OverOp 12887 = BinaryOperator::getOverloadedOperator(Opc); 12888 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 12889 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 12890 RHS->getType(), Functions); 12891 12892 // Build the (potentially-overloaded, potentially-dependent) 12893 // binary operation. 12894 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 12895 } 12896 12897 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 12898 BinaryOperatorKind Opc, 12899 Expr *LHSExpr, Expr *RHSExpr) { 12900 ExprResult LHS, RHS; 12901 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 12902 if (!LHS.isUsable() || !RHS.isUsable()) 12903 return ExprError(); 12904 LHSExpr = LHS.get(); 12905 RHSExpr = RHS.get(); 12906 12907 // We want to end up calling one of checkPseudoObjectAssignment 12908 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 12909 // both expressions are overloadable or either is type-dependent), 12910 // or CreateBuiltinBinOp (in any other case). We also want to get 12911 // any placeholder types out of the way. 12912 12913 // Handle pseudo-objects in the LHS. 12914 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 12915 // Assignments with a pseudo-object l-value need special analysis. 12916 if (pty->getKind() == BuiltinType::PseudoObject && 12917 BinaryOperator::isAssignmentOp(Opc)) 12918 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 12919 12920 // Don't resolve overloads if the other type is overloadable. 12921 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 12922 // We can't actually test that if we still have a placeholder, 12923 // though. Fortunately, none of the exceptions we see in that 12924 // code below are valid when the LHS is an overload set. Note 12925 // that an overload set can be dependently-typed, but it never 12926 // instantiates to having an overloadable type. 12927 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 12928 if (resolvedRHS.isInvalid()) return ExprError(); 12929 RHSExpr = resolvedRHS.get(); 12930 12931 if (RHSExpr->isTypeDependent() || 12932 RHSExpr->getType()->isOverloadableType()) 12933 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12934 } 12935 12936 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 12937 // template, diagnose the missing 'template' keyword instead of diagnosing 12938 // an invalid use of a bound member function. 12939 // 12940 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 12941 // to C++1z [over.over]/1.4, but we already checked for that case above. 12942 if (Opc == BO_LT && inTemplateInstantiation() && 12943 (pty->getKind() == BuiltinType::BoundMember || 12944 pty->getKind() == BuiltinType::Overload)) { 12945 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 12946 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 12947 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 12948 return isa<FunctionTemplateDecl>(ND); 12949 })) { 12950 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 12951 : OE->getNameLoc(), 12952 diag::err_template_kw_missing) 12953 << OE->getName().getAsString() << ""; 12954 return ExprError(); 12955 } 12956 } 12957 12958 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 12959 if (LHS.isInvalid()) return ExprError(); 12960 LHSExpr = LHS.get(); 12961 } 12962 12963 // Handle pseudo-objects in the RHS. 12964 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 12965 // An overload in the RHS can potentially be resolved by the type 12966 // being assigned to. 12967 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 12968 if (getLangOpts().CPlusPlus && 12969 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 12970 LHSExpr->getType()->isOverloadableType())) 12971 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12972 12973 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 12974 } 12975 12976 // Don't resolve overloads if the other type is overloadable. 12977 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 12978 LHSExpr->getType()->isOverloadableType()) 12979 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12980 12981 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 12982 if (!resolvedRHS.isUsable()) return ExprError(); 12983 RHSExpr = resolvedRHS.get(); 12984 } 12985 12986 if (getLangOpts().CPlusPlus) { 12987 // If either expression is type-dependent, always build an 12988 // overloaded op. 12989 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 12990 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12991 12992 // Otherwise, build an overloaded op if either expression has an 12993 // overloadable type. 12994 if (LHSExpr->getType()->isOverloadableType() || 12995 RHSExpr->getType()->isOverloadableType()) 12996 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12997 } 12998 12999 // Build a built-in binary operation. 13000 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 13001 } 13002 13003 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 13004 if (T.isNull() || T->isDependentType()) 13005 return false; 13006 13007 if (!T->isPromotableIntegerType()) 13008 return true; 13009 13010 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 13011 } 13012 13013 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 13014 UnaryOperatorKind Opc, 13015 Expr *InputExpr) { 13016 ExprResult Input = InputExpr; 13017 ExprValueKind VK = VK_RValue; 13018 ExprObjectKind OK = OK_Ordinary; 13019 QualType resultType; 13020 bool CanOverflow = false; 13021 13022 bool ConvertHalfVec = false; 13023 if (getLangOpts().OpenCL) { 13024 QualType Ty = InputExpr->getType(); 13025 // The only legal unary operation for atomics is '&'. 13026 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 13027 // OpenCL special types - image, sampler, pipe, and blocks are to be used 13028 // only with a builtin functions and therefore should be disallowed here. 13029 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 13030 || Ty->isBlockPointerType())) { 13031 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13032 << InputExpr->getType() 13033 << Input.get()->getSourceRange()); 13034 } 13035 } 13036 // Diagnose operations on the unsupported types for OpenMP device compilation. 13037 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) { 13038 if (UnaryOperator::isIncrementDecrementOp(Opc) || 13039 UnaryOperator::isArithmeticOp(Opc)) 13040 checkOpenMPDeviceExpr(InputExpr); 13041 } 13042 13043 switch (Opc) { 13044 case UO_PreInc: 13045 case UO_PreDec: 13046 case UO_PostInc: 13047 case UO_PostDec: 13048 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 13049 OpLoc, 13050 Opc == UO_PreInc || 13051 Opc == UO_PostInc, 13052 Opc == UO_PreInc || 13053 Opc == UO_PreDec); 13054 CanOverflow = isOverflowingIntegerType(Context, resultType); 13055 break; 13056 case UO_AddrOf: 13057 resultType = CheckAddressOfOperand(Input, OpLoc); 13058 CheckAddressOfNoDeref(InputExpr); 13059 RecordModifiableNonNullParam(*this, InputExpr); 13060 break; 13061 case UO_Deref: { 13062 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 13063 if (Input.isInvalid()) return ExprError(); 13064 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 13065 break; 13066 } 13067 case UO_Plus: 13068 case UO_Minus: 13069 CanOverflow = Opc == UO_Minus && 13070 isOverflowingIntegerType(Context, Input.get()->getType()); 13071 Input = UsualUnaryConversions(Input.get()); 13072 if (Input.isInvalid()) return ExprError(); 13073 // Unary plus and minus require promoting an operand of half vector to a 13074 // float vector and truncating the result back to a half vector. For now, we 13075 // do this only when HalfArgsAndReturns is set (that is, when the target is 13076 // arm or arm64). 13077 ConvertHalfVec = 13078 needsConversionOfHalfVec(true, Context, Input.get()->getType()); 13079 13080 // If the operand is a half vector, promote it to a float vector. 13081 if (ConvertHalfVec) 13082 Input = convertVector(Input.get(), Context.FloatTy, *this); 13083 resultType = Input.get()->getType(); 13084 if (resultType->isDependentType()) 13085 break; 13086 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 13087 break; 13088 else if (resultType->isVectorType() && 13089 // The z vector extensions don't allow + or - with bool vectors. 13090 (!Context.getLangOpts().ZVector || 13091 resultType->getAs<VectorType>()->getVectorKind() != 13092 VectorType::AltiVecBool)) 13093 break; 13094 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 13095 Opc == UO_Plus && 13096 resultType->isPointerType()) 13097 break; 13098 13099 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13100 << resultType << Input.get()->getSourceRange()); 13101 13102 case UO_Not: // bitwise complement 13103 Input = UsualUnaryConversions(Input.get()); 13104 if (Input.isInvalid()) 13105 return ExprError(); 13106 resultType = Input.get()->getType(); 13107 13108 if (resultType->isDependentType()) 13109 break; 13110 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 13111 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 13112 // C99 does not support '~' for complex conjugation. 13113 Diag(OpLoc, diag::ext_integer_complement_complex) 13114 << resultType << Input.get()->getSourceRange(); 13115 else if (resultType->hasIntegerRepresentation()) 13116 break; 13117 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 13118 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 13119 // on vector float types. 13120 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 13121 if (!T->isIntegerType()) 13122 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13123 << resultType << Input.get()->getSourceRange()); 13124 } else { 13125 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13126 << resultType << Input.get()->getSourceRange()); 13127 } 13128 break; 13129 13130 case UO_LNot: // logical negation 13131 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 13132 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 13133 if (Input.isInvalid()) return ExprError(); 13134 resultType = Input.get()->getType(); 13135 13136 // Though we still have to promote half FP to float... 13137 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 13138 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 13139 resultType = Context.FloatTy; 13140 } 13141 13142 if (resultType->isDependentType()) 13143 break; 13144 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 13145 // C99 6.5.3.3p1: ok, fallthrough; 13146 if (Context.getLangOpts().CPlusPlus) { 13147 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 13148 // operand contextually converted to bool. 13149 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 13150 ScalarTypeToBooleanCastKind(resultType)); 13151 } else if (Context.getLangOpts().OpenCL && 13152 Context.getLangOpts().OpenCLVersion < 120) { 13153 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 13154 // operate on scalar float types. 13155 if (!resultType->isIntegerType() && !resultType->isPointerType()) 13156 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13157 << resultType << Input.get()->getSourceRange()); 13158 } 13159 } else if (resultType->isExtVectorType()) { 13160 if (Context.getLangOpts().OpenCL && 13161 Context.getLangOpts().OpenCLVersion < 120) { 13162 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 13163 // operate on vector float types. 13164 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 13165 if (!T->isIntegerType()) 13166 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13167 << resultType << Input.get()->getSourceRange()); 13168 } 13169 // Vector logical not returns the signed variant of the operand type. 13170 resultType = GetSignedVectorType(resultType); 13171 break; 13172 } else { 13173 // FIXME: GCC's vector extension permits the usage of '!' with a vector 13174 // type in C++. We should allow that here too. 13175 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13176 << resultType << Input.get()->getSourceRange()); 13177 } 13178 13179 // LNot always has type int. C99 6.5.3.3p5. 13180 // In C++, it's bool. C++ 5.3.1p8 13181 resultType = Context.getLogicalOperationType(); 13182 break; 13183 case UO_Real: 13184 case UO_Imag: 13185 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 13186 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 13187 // complex l-values to ordinary l-values and all other values to r-values. 13188 if (Input.isInvalid()) return ExprError(); 13189 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 13190 if (Input.get()->getValueKind() != VK_RValue && 13191 Input.get()->getObjectKind() == OK_Ordinary) 13192 VK = Input.get()->getValueKind(); 13193 } else if (!getLangOpts().CPlusPlus) { 13194 // In C, a volatile scalar is read by __imag. In C++, it is not. 13195 Input = DefaultLvalueConversion(Input.get()); 13196 } 13197 break; 13198 case UO_Extension: 13199 resultType = Input.get()->getType(); 13200 VK = Input.get()->getValueKind(); 13201 OK = Input.get()->getObjectKind(); 13202 break; 13203 case UO_Coawait: 13204 // It's unnecessary to represent the pass-through operator co_await in the 13205 // AST; just return the input expression instead. 13206 assert(!Input.get()->getType()->isDependentType() && 13207 "the co_await expression must be non-dependant before " 13208 "building operator co_await"); 13209 return Input; 13210 } 13211 if (resultType.isNull() || Input.isInvalid()) 13212 return ExprError(); 13213 13214 // Check for array bounds violations in the operand of the UnaryOperator, 13215 // except for the '*' and '&' operators that have to be handled specially 13216 // by CheckArrayAccess (as there are special cases like &array[arraysize] 13217 // that are explicitly defined as valid by the standard). 13218 if (Opc != UO_AddrOf && Opc != UO_Deref) 13219 CheckArrayAccess(Input.get()); 13220 13221 auto *UO = new (Context) 13222 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow); 13223 13224 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 13225 !isa<ArrayType>(UO->getType().getDesugaredType(Context))) 13226 ExprEvalContexts.back().PossibleDerefs.insert(UO); 13227 13228 // Convert the result back to a half vector. 13229 if (ConvertHalfVec) 13230 return convertVector(UO, Context.HalfTy, *this); 13231 return UO; 13232 } 13233 13234 /// Determine whether the given expression is a qualified member 13235 /// access expression, of a form that could be turned into a pointer to member 13236 /// with the address-of operator. 13237 bool Sema::isQualifiedMemberAccess(Expr *E) { 13238 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13239 if (!DRE->getQualifier()) 13240 return false; 13241 13242 ValueDecl *VD = DRE->getDecl(); 13243 if (!VD->isCXXClassMember()) 13244 return false; 13245 13246 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 13247 return true; 13248 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 13249 return Method->isInstance(); 13250 13251 return false; 13252 } 13253 13254 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 13255 if (!ULE->getQualifier()) 13256 return false; 13257 13258 for (NamedDecl *D : ULE->decls()) { 13259 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 13260 if (Method->isInstance()) 13261 return true; 13262 } else { 13263 // Overload set does not contain methods. 13264 break; 13265 } 13266 } 13267 13268 return false; 13269 } 13270 13271 return false; 13272 } 13273 13274 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 13275 UnaryOperatorKind Opc, Expr *Input) { 13276 // First things first: handle placeholders so that the 13277 // overloaded-operator check considers the right type. 13278 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 13279 // Increment and decrement of pseudo-object references. 13280 if (pty->getKind() == BuiltinType::PseudoObject && 13281 UnaryOperator::isIncrementDecrementOp(Opc)) 13282 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 13283 13284 // extension is always a builtin operator. 13285 if (Opc == UO_Extension) 13286 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13287 13288 // & gets special logic for several kinds of placeholder. 13289 // The builtin code knows what to do. 13290 if (Opc == UO_AddrOf && 13291 (pty->getKind() == BuiltinType::Overload || 13292 pty->getKind() == BuiltinType::UnknownAny || 13293 pty->getKind() == BuiltinType::BoundMember)) 13294 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13295 13296 // Anything else needs to be handled now. 13297 ExprResult Result = CheckPlaceholderExpr(Input); 13298 if (Result.isInvalid()) return ExprError(); 13299 Input = Result.get(); 13300 } 13301 13302 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 13303 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 13304 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 13305 // Find all of the overloaded operators visible from this 13306 // point. We perform both an operator-name lookup from the local 13307 // scope and an argument-dependent lookup based on the types of 13308 // the arguments. 13309 UnresolvedSet<16> Functions; 13310 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 13311 if (S && OverOp != OO_None) 13312 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 13313 Functions); 13314 13315 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 13316 } 13317 13318 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13319 } 13320 13321 // Unary Operators. 'Tok' is the token for the operator. 13322 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 13323 tok::TokenKind Op, Expr *Input) { 13324 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 13325 } 13326 13327 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 13328 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 13329 LabelDecl *TheDecl) { 13330 TheDecl->markUsed(Context); 13331 // Create the AST node. The address of a label always has type 'void*'. 13332 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 13333 Context.getPointerType(Context.VoidTy)); 13334 } 13335 13336 void Sema::ActOnStartStmtExpr() { 13337 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 13338 } 13339 13340 void Sema::ActOnStmtExprError() { 13341 // Note that function is also called by TreeTransform when leaving a 13342 // StmtExpr scope without rebuilding anything. 13343 13344 DiscardCleanupsInEvaluationContext(); 13345 PopExpressionEvaluationContext(); 13346 } 13347 13348 ExprResult 13349 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 13350 SourceLocation RPLoc) { // "({..})" 13351 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 13352 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 13353 13354 if (hasAnyUnrecoverableErrorsInThisFunction()) 13355 DiscardCleanupsInEvaluationContext(); 13356 assert(!Cleanup.exprNeedsCleanups() && 13357 "cleanups within StmtExpr not correctly bound!"); 13358 PopExpressionEvaluationContext(); 13359 13360 // FIXME: there are a variety of strange constraints to enforce here, for 13361 // example, it is not possible to goto into a stmt expression apparently. 13362 // More semantic analysis is needed. 13363 13364 // If there are sub-stmts in the compound stmt, take the type of the last one 13365 // as the type of the stmtexpr. 13366 QualType Ty = Context.VoidTy; 13367 bool StmtExprMayBindToTemp = false; 13368 if (!Compound->body_empty()) { 13369 if (const auto *LastStmt = dyn_cast<ValueStmt>(Compound->body_back())) { 13370 if (const Expr *Value = LastStmt->getExprStmt()) { 13371 StmtExprMayBindToTemp = true; 13372 Ty = Value->getType(); 13373 } 13374 } 13375 } 13376 13377 // FIXME: Check that expression type is complete/non-abstract; statement 13378 // expressions are not lvalues. 13379 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 13380 if (StmtExprMayBindToTemp) 13381 return MaybeBindToTemporary(ResStmtExpr); 13382 return ResStmtExpr; 13383 } 13384 13385 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 13386 if (ER.isInvalid()) 13387 return ExprError(); 13388 13389 // Do function/array conversion on the last expression, but not 13390 // lvalue-to-rvalue. However, initialize an unqualified type. 13391 ER = DefaultFunctionArrayConversion(ER.get()); 13392 if (ER.isInvalid()) 13393 return ExprError(); 13394 Expr *E = ER.get(); 13395 13396 if (E->isTypeDependent()) 13397 return E; 13398 13399 // In ARC, if the final expression ends in a consume, splice 13400 // the consume out and bind it later. In the alternate case 13401 // (when dealing with a retainable type), the result 13402 // initialization will create a produce. In both cases the 13403 // result will be +1, and we'll need to balance that out with 13404 // a bind. 13405 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 13406 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 13407 return Cast->getSubExpr(); 13408 13409 // FIXME: Provide a better location for the initialization. 13410 return PerformCopyInitialization( 13411 InitializedEntity::InitializeStmtExprResult( 13412 E->getBeginLoc(), E->getType().getUnqualifiedType()), 13413 SourceLocation(), E); 13414 } 13415 13416 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 13417 TypeSourceInfo *TInfo, 13418 ArrayRef<OffsetOfComponent> Components, 13419 SourceLocation RParenLoc) { 13420 QualType ArgTy = TInfo->getType(); 13421 bool Dependent = ArgTy->isDependentType(); 13422 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 13423 13424 // We must have at least one component that refers to the type, and the first 13425 // one is known to be a field designator. Verify that the ArgTy represents 13426 // a struct/union/class. 13427 if (!Dependent && !ArgTy->isRecordType()) 13428 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 13429 << ArgTy << TypeRange); 13430 13431 // Type must be complete per C99 7.17p3 because a declaring a variable 13432 // with an incomplete type would be ill-formed. 13433 if (!Dependent 13434 && RequireCompleteType(BuiltinLoc, ArgTy, 13435 diag::err_offsetof_incomplete_type, TypeRange)) 13436 return ExprError(); 13437 13438 bool DidWarnAboutNonPOD = false; 13439 QualType CurrentType = ArgTy; 13440 SmallVector<OffsetOfNode, 4> Comps; 13441 SmallVector<Expr*, 4> Exprs; 13442 for (const OffsetOfComponent &OC : Components) { 13443 if (OC.isBrackets) { 13444 // Offset of an array sub-field. TODO: Should we allow vector elements? 13445 if (!CurrentType->isDependentType()) { 13446 const ArrayType *AT = Context.getAsArrayType(CurrentType); 13447 if(!AT) 13448 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 13449 << CurrentType); 13450 CurrentType = AT->getElementType(); 13451 } else 13452 CurrentType = Context.DependentTy; 13453 13454 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 13455 if (IdxRval.isInvalid()) 13456 return ExprError(); 13457 Expr *Idx = IdxRval.get(); 13458 13459 // The expression must be an integral expression. 13460 // FIXME: An integral constant expression? 13461 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 13462 !Idx->getType()->isIntegerType()) 13463 return ExprError( 13464 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 13465 << Idx->getSourceRange()); 13466 13467 // Record this array index. 13468 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 13469 Exprs.push_back(Idx); 13470 continue; 13471 } 13472 13473 // Offset of a field. 13474 if (CurrentType->isDependentType()) { 13475 // We have the offset of a field, but we can't look into the dependent 13476 // type. Just record the identifier of the field. 13477 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 13478 CurrentType = Context.DependentTy; 13479 continue; 13480 } 13481 13482 // We need to have a complete type to look into. 13483 if (RequireCompleteType(OC.LocStart, CurrentType, 13484 diag::err_offsetof_incomplete_type)) 13485 return ExprError(); 13486 13487 // Look for the designated field. 13488 const RecordType *RC = CurrentType->getAs<RecordType>(); 13489 if (!RC) 13490 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 13491 << CurrentType); 13492 RecordDecl *RD = RC->getDecl(); 13493 13494 // C++ [lib.support.types]p5: 13495 // The macro offsetof accepts a restricted set of type arguments in this 13496 // International Standard. type shall be a POD structure or a POD union 13497 // (clause 9). 13498 // C++11 [support.types]p4: 13499 // If type is not a standard-layout class (Clause 9), the results are 13500 // undefined. 13501 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 13502 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 13503 unsigned DiagID = 13504 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 13505 : diag::ext_offsetof_non_pod_type; 13506 13507 if (!IsSafe && !DidWarnAboutNonPOD && 13508 DiagRuntimeBehavior(BuiltinLoc, nullptr, 13509 PDiag(DiagID) 13510 << SourceRange(Components[0].LocStart, OC.LocEnd) 13511 << CurrentType)) 13512 DidWarnAboutNonPOD = true; 13513 } 13514 13515 // Look for the field. 13516 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 13517 LookupQualifiedName(R, RD); 13518 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 13519 IndirectFieldDecl *IndirectMemberDecl = nullptr; 13520 if (!MemberDecl) { 13521 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 13522 MemberDecl = IndirectMemberDecl->getAnonField(); 13523 } 13524 13525 if (!MemberDecl) 13526 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 13527 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 13528 OC.LocEnd)); 13529 13530 // C99 7.17p3: 13531 // (If the specified member is a bit-field, the behavior is undefined.) 13532 // 13533 // We diagnose this as an error. 13534 if (MemberDecl->isBitField()) { 13535 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 13536 << MemberDecl->getDeclName() 13537 << SourceRange(BuiltinLoc, RParenLoc); 13538 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 13539 return ExprError(); 13540 } 13541 13542 RecordDecl *Parent = MemberDecl->getParent(); 13543 if (IndirectMemberDecl) 13544 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 13545 13546 // If the member was found in a base class, introduce OffsetOfNodes for 13547 // the base class indirections. 13548 CXXBasePaths Paths; 13549 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 13550 Paths)) { 13551 if (Paths.getDetectedVirtual()) { 13552 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 13553 << MemberDecl->getDeclName() 13554 << SourceRange(BuiltinLoc, RParenLoc); 13555 return ExprError(); 13556 } 13557 13558 CXXBasePath &Path = Paths.front(); 13559 for (const CXXBasePathElement &B : Path) 13560 Comps.push_back(OffsetOfNode(B.Base)); 13561 } 13562 13563 if (IndirectMemberDecl) { 13564 for (auto *FI : IndirectMemberDecl->chain()) { 13565 assert(isa<FieldDecl>(FI)); 13566 Comps.push_back(OffsetOfNode(OC.LocStart, 13567 cast<FieldDecl>(FI), OC.LocEnd)); 13568 } 13569 } else 13570 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 13571 13572 CurrentType = MemberDecl->getType().getNonReferenceType(); 13573 } 13574 13575 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 13576 Comps, Exprs, RParenLoc); 13577 } 13578 13579 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 13580 SourceLocation BuiltinLoc, 13581 SourceLocation TypeLoc, 13582 ParsedType ParsedArgTy, 13583 ArrayRef<OffsetOfComponent> Components, 13584 SourceLocation RParenLoc) { 13585 13586 TypeSourceInfo *ArgTInfo; 13587 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 13588 if (ArgTy.isNull()) 13589 return ExprError(); 13590 13591 if (!ArgTInfo) 13592 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 13593 13594 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 13595 } 13596 13597 13598 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 13599 Expr *CondExpr, 13600 Expr *LHSExpr, Expr *RHSExpr, 13601 SourceLocation RPLoc) { 13602 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 13603 13604 ExprValueKind VK = VK_RValue; 13605 ExprObjectKind OK = OK_Ordinary; 13606 QualType resType; 13607 bool ValueDependent = false; 13608 bool CondIsTrue = false; 13609 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 13610 resType = Context.DependentTy; 13611 ValueDependent = true; 13612 } else { 13613 // The conditional expression is required to be a constant expression. 13614 llvm::APSInt condEval(32); 13615 ExprResult CondICE 13616 = VerifyIntegerConstantExpression(CondExpr, &condEval, 13617 diag::err_typecheck_choose_expr_requires_constant, false); 13618 if (CondICE.isInvalid()) 13619 return ExprError(); 13620 CondExpr = CondICE.get(); 13621 CondIsTrue = condEval.getZExtValue(); 13622 13623 // If the condition is > zero, then the AST type is the same as the LHSExpr. 13624 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 13625 13626 resType = ActiveExpr->getType(); 13627 ValueDependent = ActiveExpr->isValueDependent(); 13628 VK = ActiveExpr->getValueKind(); 13629 OK = ActiveExpr->getObjectKind(); 13630 } 13631 13632 return new (Context) 13633 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 13634 CondIsTrue, resType->isDependentType(), ValueDependent); 13635 } 13636 13637 //===----------------------------------------------------------------------===// 13638 // Clang Extensions. 13639 //===----------------------------------------------------------------------===// 13640 13641 /// ActOnBlockStart - This callback is invoked when a block literal is started. 13642 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 13643 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 13644 13645 if (LangOpts.CPlusPlus) { 13646 Decl *ManglingContextDecl; 13647 if (MangleNumberingContext *MCtx = 13648 getCurrentMangleNumberContext(Block->getDeclContext(), 13649 ManglingContextDecl)) { 13650 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 13651 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 13652 } 13653 } 13654 13655 PushBlockScope(CurScope, Block); 13656 CurContext->addDecl(Block); 13657 if (CurScope) 13658 PushDeclContext(CurScope, Block); 13659 else 13660 CurContext = Block; 13661 13662 getCurBlock()->HasImplicitReturnType = true; 13663 13664 // Enter a new evaluation context to insulate the block from any 13665 // cleanups from the enclosing full-expression. 13666 PushExpressionEvaluationContext( 13667 ExpressionEvaluationContext::PotentiallyEvaluated); 13668 } 13669 13670 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 13671 Scope *CurScope) { 13672 assert(ParamInfo.getIdentifier() == nullptr && 13673 "block-id should have no identifier!"); 13674 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext); 13675 BlockScopeInfo *CurBlock = getCurBlock(); 13676 13677 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 13678 QualType T = Sig->getType(); 13679 13680 // FIXME: We should allow unexpanded parameter packs here, but that would, 13681 // in turn, make the block expression contain unexpanded parameter packs. 13682 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 13683 // Drop the parameters. 13684 FunctionProtoType::ExtProtoInfo EPI; 13685 EPI.HasTrailingReturn = false; 13686 EPI.TypeQuals.addConst(); 13687 T = Context.getFunctionType(Context.DependentTy, None, EPI); 13688 Sig = Context.getTrivialTypeSourceInfo(T); 13689 } 13690 13691 // GetTypeForDeclarator always produces a function type for a block 13692 // literal signature. Furthermore, it is always a FunctionProtoType 13693 // unless the function was written with a typedef. 13694 assert(T->isFunctionType() && 13695 "GetTypeForDeclarator made a non-function block signature"); 13696 13697 // Look for an explicit signature in that function type. 13698 FunctionProtoTypeLoc ExplicitSignature; 13699 13700 if ((ExplicitSignature = 13701 Sig->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>())) { 13702 13703 // Check whether that explicit signature was synthesized by 13704 // GetTypeForDeclarator. If so, don't save that as part of the 13705 // written signature. 13706 if (ExplicitSignature.getLocalRangeBegin() == 13707 ExplicitSignature.getLocalRangeEnd()) { 13708 // This would be much cheaper if we stored TypeLocs instead of 13709 // TypeSourceInfos. 13710 TypeLoc Result = ExplicitSignature.getReturnLoc(); 13711 unsigned Size = Result.getFullDataSize(); 13712 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 13713 Sig->getTypeLoc().initializeFullCopy(Result, Size); 13714 13715 ExplicitSignature = FunctionProtoTypeLoc(); 13716 } 13717 } 13718 13719 CurBlock->TheDecl->setSignatureAsWritten(Sig); 13720 CurBlock->FunctionType = T; 13721 13722 const FunctionType *Fn = T->getAs<FunctionType>(); 13723 QualType RetTy = Fn->getReturnType(); 13724 bool isVariadic = 13725 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 13726 13727 CurBlock->TheDecl->setIsVariadic(isVariadic); 13728 13729 // Context.DependentTy is used as a placeholder for a missing block 13730 // return type. TODO: what should we do with declarators like: 13731 // ^ * { ... } 13732 // If the answer is "apply template argument deduction".... 13733 if (RetTy != Context.DependentTy) { 13734 CurBlock->ReturnType = RetTy; 13735 CurBlock->TheDecl->setBlockMissingReturnType(false); 13736 CurBlock->HasImplicitReturnType = false; 13737 } 13738 13739 // Push block parameters from the declarator if we had them. 13740 SmallVector<ParmVarDecl*, 8> Params; 13741 if (ExplicitSignature) { 13742 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 13743 ParmVarDecl *Param = ExplicitSignature.getParam(I); 13744 if (Param->getIdentifier() == nullptr && 13745 !Param->isImplicit() && 13746 !Param->isInvalidDecl() && 13747 !getLangOpts().CPlusPlus) 13748 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 13749 Params.push_back(Param); 13750 } 13751 13752 // Fake up parameter variables if we have a typedef, like 13753 // ^ fntype { ... } 13754 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 13755 for (const auto &I : Fn->param_types()) { 13756 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 13757 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 13758 Params.push_back(Param); 13759 } 13760 } 13761 13762 // Set the parameters on the block decl. 13763 if (!Params.empty()) { 13764 CurBlock->TheDecl->setParams(Params); 13765 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 13766 /*CheckParameterNames=*/false); 13767 } 13768 13769 // Finally we can process decl attributes. 13770 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 13771 13772 // Put the parameter variables in scope. 13773 for (auto AI : CurBlock->TheDecl->parameters()) { 13774 AI->setOwningFunction(CurBlock->TheDecl); 13775 13776 // If this has an identifier, add it to the scope stack. 13777 if (AI->getIdentifier()) { 13778 CheckShadow(CurBlock->TheScope, AI); 13779 13780 PushOnScopeChains(AI, CurBlock->TheScope); 13781 } 13782 } 13783 } 13784 13785 /// ActOnBlockError - If there is an error parsing a block, this callback 13786 /// is invoked to pop the information about the block from the action impl. 13787 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 13788 // Leave the expression-evaluation context. 13789 DiscardCleanupsInEvaluationContext(); 13790 PopExpressionEvaluationContext(); 13791 13792 // Pop off CurBlock, handle nested blocks. 13793 PopDeclContext(); 13794 PopFunctionScopeInfo(); 13795 } 13796 13797 /// ActOnBlockStmtExpr - This is called when the body of a block statement 13798 /// literal was successfully completed. ^(int x){...} 13799 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 13800 Stmt *Body, Scope *CurScope) { 13801 // If blocks are disabled, emit an error. 13802 if (!LangOpts.Blocks) 13803 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 13804 13805 // Leave the expression-evaluation context. 13806 if (hasAnyUnrecoverableErrorsInThisFunction()) 13807 DiscardCleanupsInEvaluationContext(); 13808 assert(!Cleanup.exprNeedsCleanups() && 13809 "cleanups within block not correctly bound!"); 13810 PopExpressionEvaluationContext(); 13811 13812 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 13813 BlockDecl *BD = BSI->TheDecl; 13814 13815 if (BSI->HasImplicitReturnType) 13816 deduceClosureReturnType(*BSI); 13817 13818 PopDeclContext(); 13819 13820 QualType RetTy = Context.VoidTy; 13821 if (!BSI->ReturnType.isNull()) 13822 RetTy = BSI->ReturnType; 13823 13824 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 13825 QualType BlockTy; 13826 13827 // Set the captured variables on the block. 13828 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 13829 SmallVector<BlockDecl::Capture, 4> Captures; 13830 for (Capture &Cap : BSI->Captures) { 13831 if (Cap.isThisCapture()) 13832 continue; 13833 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 13834 Cap.isNested(), Cap.getInitExpr()); 13835 Captures.push_back(NewCap); 13836 } 13837 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 13838 13839 // If the user wrote a function type in some form, try to use that. 13840 if (!BSI->FunctionType.isNull()) { 13841 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 13842 13843 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 13844 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 13845 13846 // Turn protoless block types into nullary block types. 13847 if (isa<FunctionNoProtoType>(FTy)) { 13848 FunctionProtoType::ExtProtoInfo EPI; 13849 EPI.ExtInfo = Ext; 13850 BlockTy = Context.getFunctionType(RetTy, None, EPI); 13851 13852 // Otherwise, if we don't need to change anything about the function type, 13853 // preserve its sugar structure. 13854 } else if (FTy->getReturnType() == RetTy && 13855 (!NoReturn || FTy->getNoReturnAttr())) { 13856 BlockTy = BSI->FunctionType; 13857 13858 // Otherwise, make the minimal modifications to the function type. 13859 } else { 13860 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 13861 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 13862 EPI.TypeQuals = Qualifiers(); 13863 EPI.ExtInfo = Ext; 13864 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 13865 } 13866 13867 // If we don't have a function type, just build one from nothing. 13868 } else { 13869 FunctionProtoType::ExtProtoInfo EPI; 13870 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 13871 BlockTy = Context.getFunctionType(RetTy, None, EPI); 13872 } 13873 13874 DiagnoseUnusedParameters(BD->parameters()); 13875 BlockTy = Context.getBlockPointerType(BlockTy); 13876 13877 // If needed, diagnose invalid gotos and switches in the block. 13878 if (getCurFunction()->NeedsScopeChecking() && 13879 !PP.isCodeCompletionEnabled()) 13880 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 13881 13882 BD->setBody(cast<CompoundStmt>(Body)); 13883 13884 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 13885 DiagnoseUnguardedAvailabilityViolations(BD); 13886 13887 // Try to apply the named return value optimization. We have to check again 13888 // if we can do this, though, because blocks keep return statements around 13889 // to deduce an implicit return type. 13890 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 13891 !BD->isDependentContext()) 13892 computeNRVO(Body, BSI); 13893 13894 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 13895 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 13896 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 13897 13898 // If the block isn't obviously global, i.e. it captures anything at 13899 // all, then we need to do a few things in the surrounding context: 13900 if (Result->getBlockDecl()->hasCaptures()) { 13901 // First, this expression has a new cleanup object. 13902 ExprCleanupObjects.push_back(Result->getBlockDecl()); 13903 Cleanup.setExprNeedsCleanups(true); 13904 13905 // It also gets a branch-protected scope if any of the captured 13906 // variables needs destruction. 13907 for (const auto &CI : Result->getBlockDecl()->captures()) { 13908 const VarDecl *var = CI.getVariable(); 13909 if (var->getType().isDestructedType() != QualType::DK_none) { 13910 setFunctionHasBranchProtectedScope(); 13911 break; 13912 } 13913 } 13914 } 13915 13916 if (getCurFunction()) 13917 getCurFunction()->addBlock(BD); 13918 13919 return Result; 13920 } 13921 13922 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 13923 SourceLocation RPLoc) { 13924 TypeSourceInfo *TInfo; 13925 GetTypeFromParser(Ty, &TInfo); 13926 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 13927 } 13928 13929 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 13930 Expr *E, TypeSourceInfo *TInfo, 13931 SourceLocation RPLoc) { 13932 Expr *OrigExpr = E; 13933 bool IsMS = false; 13934 13935 // CUDA device code does not support varargs. 13936 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 13937 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 13938 CUDAFunctionTarget T = IdentifyCUDATarget(F); 13939 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 13940 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 13941 } 13942 } 13943 13944 // NVPTX does not support va_arg expression. 13945 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 13946 Context.getTargetInfo().getTriple().isNVPTX()) 13947 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 13948 13949 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 13950 // as Microsoft ABI on an actual Microsoft platform, where 13951 // __builtin_ms_va_list and __builtin_va_list are the same.) 13952 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 13953 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 13954 QualType MSVaListType = Context.getBuiltinMSVaListType(); 13955 if (Context.hasSameType(MSVaListType, E->getType())) { 13956 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 13957 return ExprError(); 13958 IsMS = true; 13959 } 13960 } 13961 13962 // Get the va_list type 13963 QualType VaListType = Context.getBuiltinVaListType(); 13964 if (!IsMS) { 13965 if (VaListType->isArrayType()) { 13966 // Deal with implicit array decay; for example, on x86-64, 13967 // va_list is an array, but it's supposed to decay to 13968 // a pointer for va_arg. 13969 VaListType = Context.getArrayDecayedType(VaListType); 13970 // Make sure the input expression also decays appropriately. 13971 ExprResult Result = UsualUnaryConversions(E); 13972 if (Result.isInvalid()) 13973 return ExprError(); 13974 E = Result.get(); 13975 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 13976 // If va_list is a record type and we are compiling in C++ mode, 13977 // check the argument using reference binding. 13978 InitializedEntity Entity = InitializedEntity::InitializeParameter( 13979 Context, Context.getLValueReferenceType(VaListType), false); 13980 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 13981 if (Init.isInvalid()) 13982 return ExprError(); 13983 E = Init.getAs<Expr>(); 13984 } else { 13985 // Otherwise, the va_list argument must be an l-value because 13986 // it is modified by va_arg. 13987 if (!E->isTypeDependent() && 13988 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 13989 return ExprError(); 13990 } 13991 } 13992 13993 if (!IsMS && !E->isTypeDependent() && 13994 !Context.hasSameType(VaListType, E->getType())) 13995 return ExprError( 13996 Diag(E->getBeginLoc(), 13997 diag::err_first_argument_to_va_arg_not_of_type_va_list) 13998 << OrigExpr->getType() << E->getSourceRange()); 13999 14000 if (!TInfo->getType()->isDependentType()) { 14001 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 14002 diag::err_second_parameter_to_va_arg_incomplete, 14003 TInfo->getTypeLoc())) 14004 return ExprError(); 14005 14006 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 14007 TInfo->getType(), 14008 diag::err_second_parameter_to_va_arg_abstract, 14009 TInfo->getTypeLoc())) 14010 return ExprError(); 14011 14012 if (!TInfo->getType().isPODType(Context)) { 14013 Diag(TInfo->getTypeLoc().getBeginLoc(), 14014 TInfo->getType()->isObjCLifetimeType() 14015 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 14016 : diag::warn_second_parameter_to_va_arg_not_pod) 14017 << TInfo->getType() 14018 << TInfo->getTypeLoc().getSourceRange(); 14019 } 14020 14021 // Check for va_arg where arguments of the given type will be promoted 14022 // (i.e. this va_arg is guaranteed to have undefined behavior). 14023 QualType PromoteType; 14024 if (TInfo->getType()->isPromotableIntegerType()) { 14025 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 14026 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 14027 PromoteType = QualType(); 14028 } 14029 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 14030 PromoteType = Context.DoubleTy; 14031 if (!PromoteType.isNull()) 14032 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 14033 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 14034 << TInfo->getType() 14035 << PromoteType 14036 << TInfo->getTypeLoc().getSourceRange()); 14037 } 14038 14039 QualType T = TInfo->getType().getNonLValueExprType(Context); 14040 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 14041 } 14042 14043 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 14044 // The type of __null will be int or long, depending on the size of 14045 // pointers on the target. 14046 QualType Ty; 14047 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 14048 if (pw == Context.getTargetInfo().getIntWidth()) 14049 Ty = Context.IntTy; 14050 else if (pw == Context.getTargetInfo().getLongWidth()) 14051 Ty = Context.LongTy; 14052 else if (pw == Context.getTargetInfo().getLongLongWidth()) 14053 Ty = Context.LongLongTy; 14054 else { 14055 llvm_unreachable("I don't know size of pointer!"); 14056 } 14057 14058 return new (Context) GNUNullExpr(Ty, TokenLoc); 14059 } 14060 14061 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 14062 bool Diagnose) { 14063 if (!getLangOpts().ObjC) 14064 return false; 14065 14066 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 14067 if (!PT) 14068 return false; 14069 14070 if (!PT->isObjCIdType()) { 14071 // Check if the destination is the 'NSString' interface. 14072 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 14073 if (!ID || !ID->getIdentifier()->isStr("NSString")) 14074 return false; 14075 } 14076 14077 // Ignore any parens, implicit casts (should only be 14078 // array-to-pointer decays), and not-so-opaque values. The last is 14079 // important for making this trigger for property assignments. 14080 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 14081 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 14082 if (OV->getSourceExpr()) 14083 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 14084 14085 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 14086 if (!SL || !SL->isAscii()) 14087 return false; 14088 if (Diagnose) { 14089 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 14090 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 14091 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 14092 } 14093 return true; 14094 } 14095 14096 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 14097 const Expr *SrcExpr) { 14098 if (!DstType->isFunctionPointerType() || 14099 !SrcExpr->getType()->isFunctionType()) 14100 return false; 14101 14102 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 14103 if (!DRE) 14104 return false; 14105 14106 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 14107 if (!FD) 14108 return false; 14109 14110 return !S.checkAddressOfFunctionIsAvailable(FD, 14111 /*Complain=*/true, 14112 SrcExpr->getBeginLoc()); 14113 } 14114 14115 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 14116 SourceLocation Loc, 14117 QualType DstType, QualType SrcType, 14118 Expr *SrcExpr, AssignmentAction Action, 14119 bool *Complained) { 14120 if (Complained) 14121 *Complained = false; 14122 14123 // Decode the result (notice that AST's are still created for extensions). 14124 bool CheckInferredResultType = false; 14125 bool isInvalid = false; 14126 unsigned DiagKind = 0; 14127 FixItHint Hint; 14128 ConversionFixItGenerator ConvHints; 14129 bool MayHaveConvFixit = false; 14130 bool MayHaveFunctionDiff = false; 14131 const ObjCInterfaceDecl *IFace = nullptr; 14132 const ObjCProtocolDecl *PDecl = nullptr; 14133 14134 switch (ConvTy) { 14135 case Compatible: 14136 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 14137 return false; 14138 14139 case PointerToInt: 14140 DiagKind = diag::ext_typecheck_convert_pointer_int; 14141 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14142 MayHaveConvFixit = true; 14143 break; 14144 case IntToPointer: 14145 DiagKind = diag::ext_typecheck_convert_int_pointer; 14146 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14147 MayHaveConvFixit = true; 14148 break; 14149 case IncompatiblePointer: 14150 if (Action == AA_Passing_CFAudited) 14151 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 14152 else if (SrcType->isFunctionPointerType() && 14153 DstType->isFunctionPointerType()) 14154 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 14155 else 14156 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 14157 14158 CheckInferredResultType = DstType->isObjCObjectPointerType() && 14159 SrcType->isObjCObjectPointerType(); 14160 if (Hint.isNull() && !CheckInferredResultType) { 14161 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14162 } 14163 else if (CheckInferredResultType) { 14164 SrcType = SrcType.getUnqualifiedType(); 14165 DstType = DstType.getUnqualifiedType(); 14166 } 14167 MayHaveConvFixit = true; 14168 break; 14169 case IncompatiblePointerSign: 14170 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 14171 break; 14172 case FunctionVoidPointer: 14173 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 14174 break; 14175 case IncompatiblePointerDiscardsQualifiers: { 14176 // Perform array-to-pointer decay if necessary. 14177 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 14178 14179 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 14180 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 14181 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 14182 DiagKind = diag::err_typecheck_incompatible_address_space; 14183 break; 14184 14185 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 14186 DiagKind = diag::err_typecheck_incompatible_ownership; 14187 break; 14188 } 14189 14190 llvm_unreachable("unknown error case for discarding qualifiers!"); 14191 // fallthrough 14192 } 14193 case CompatiblePointerDiscardsQualifiers: 14194 // If the qualifiers lost were because we were applying the 14195 // (deprecated) C++ conversion from a string literal to a char* 14196 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 14197 // Ideally, this check would be performed in 14198 // checkPointerTypesForAssignment. However, that would require a 14199 // bit of refactoring (so that the second argument is an 14200 // expression, rather than a type), which should be done as part 14201 // of a larger effort to fix checkPointerTypesForAssignment for 14202 // C++ semantics. 14203 if (getLangOpts().CPlusPlus && 14204 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 14205 return false; 14206 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 14207 break; 14208 case IncompatibleNestedPointerQualifiers: 14209 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 14210 break; 14211 case IntToBlockPointer: 14212 DiagKind = diag::err_int_to_block_pointer; 14213 break; 14214 case IncompatibleBlockPointer: 14215 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 14216 break; 14217 case IncompatibleObjCQualifiedId: { 14218 if (SrcType->isObjCQualifiedIdType()) { 14219 const ObjCObjectPointerType *srcOPT = 14220 SrcType->getAs<ObjCObjectPointerType>(); 14221 for (auto *srcProto : srcOPT->quals()) { 14222 PDecl = srcProto; 14223 break; 14224 } 14225 if (const ObjCInterfaceType *IFaceT = 14226 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 14227 IFace = IFaceT->getDecl(); 14228 } 14229 else if (DstType->isObjCQualifiedIdType()) { 14230 const ObjCObjectPointerType *dstOPT = 14231 DstType->getAs<ObjCObjectPointerType>(); 14232 for (auto *dstProto : dstOPT->quals()) { 14233 PDecl = dstProto; 14234 break; 14235 } 14236 if (const ObjCInterfaceType *IFaceT = 14237 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 14238 IFace = IFaceT->getDecl(); 14239 } 14240 DiagKind = diag::warn_incompatible_qualified_id; 14241 break; 14242 } 14243 case IncompatibleVectors: 14244 DiagKind = diag::warn_incompatible_vectors; 14245 break; 14246 case IncompatibleObjCWeakRef: 14247 DiagKind = diag::err_arc_weak_unavailable_assign; 14248 break; 14249 case Incompatible: 14250 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 14251 if (Complained) 14252 *Complained = true; 14253 return true; 14254 } 14255 14256 DiagKind = diag::err_typecheck_convert_incompatible; 14257 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14258 MayHaveConvFixit = true; 14259 isInvalid = true; 14260 MayHaveFunctionDiff = true; 14261 break; 14262 } 14263 14264 QualType FirstType, SecondType; 14265 switch (Action) { 14266 case AA_Assigning: 14267 case AA_Initializing: 14268 // The destination type comes first. 14269 FirstType = DstType; 14270 SecondType = SrcType; 14271 break; 14272 14273 case AA_Returning: 14274 case AA_Passing: 14275 case AA_Passing_CFAudited: 14276 case AA_Converting: 14277 case AA_Sending: 14278 case AA_Casting: 14279 // The source type comes first. 14280 FirstType = SrcType; 14281 SecondType = DstType; 14282 break; 14283 } 14284 14285 PartialDiagnostic FDiag = PDiag(DiagKind); 14286 if (Action == AA_Passing_CFAudited) 14287 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 14288 else 14289 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 14290 14291 // If we can fix the conversion, suggest the FixIts. 14292 assert(ConvHints.isNull() || Hint.isNull()); 14293 if (!ConvHints.isNull()) { 14294 for (FixItHint &H : ConvHints.Hints) 14295 FDiag << H; 14296 } else { 14297 FDiag << Hint; 14298 } 14299 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 14300 14301 if (MayHaveFunctionDiff) 14302 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 14303 14304 Diag(Loc, FDiag); 14305 if (DiagKind == diag::warn_incompatible_qualified_id && 14306 PDecl && IFace && !IFace->hasDefinition()) 14307 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 14308 << IFace << PDecl; 14309 14310 if (SecondType == Context.OverloadTy) 14311 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 14312 FirstType, /*TakingAddress=*/true); 14313 14314 if (CheckInferredResultType) 14315 EmitRelatedResultTypeNote(SrcExpr); 14316 14317 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 14318 EmitRelatedResultTypeNoteForReturn(DstType); 14319 14320 if (Complained) 14321 *Complained = true; 14322 return isInvalid; 14323 } 14324 14325 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 14326 llvm::APSInt *Result) { 14327 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 14328 public: 14329 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 14330 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 14331 } 14332 } Diagnoser; 14333 14334 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 14335 } 14336 14337 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 14338 llvm::APSInt *Result, 14339 unsigned DiagID, 14340 bool AllowFold) { 14341 class IDDiagnoser : public VerifyICEDiagnoser { 14342 unsigned DiagID; 14343 14344 public: 14345 IDDiagnoser(unsigned DiagID) 14346 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 14347 14348 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 14349 S.Diag(Loc, DiagID) << SR; 14350 } 14351 } Diagnoser(DiagID); 14352 14353 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 14354 } 14355 14356 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 14357 SourceRange SR) { 14358 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 14359 } 14360 14361 ExprResult 14362 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 14363 VerifyICEDiagnoser &Diagnoser, 14364 bool AllowFold) { 14365 SourceLocation DiagLoc = E->getBeginLoc(); 14366 14367 if (getLangOpts().CPlusPlus11) { 14368 // C++11 [expr.const]p5: 14369 // If an expression of literal class type is used in a context where an 14370 // integral constant expression is required, then that class type shall 14371 // have a single non-explicit conversion function to an integral or 14372 // unscoped enumeration type 14373 ExprResult Converted; 14374 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 14375 public: 14376 CXX11ConvertDiagnoser(bool Silent) 14377 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 14378 Silent, true) {} 14379 14380 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 14381 QualType T) override { 14382 return S.Diag(Loc, diag::err_ice_not_integral) << T; 14383 } 14384 14385 SemaDiagnosticBuilder diagnoseIncomplete( 14386 Sema &S, SourceLocation Loc, QualType T) override { 14387 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 14388 } 14389 14390 SemaDiagnosticBuilder diagnoseExplicitConv( 14391 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 14392 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 14393 } 14394 14395 SemaDiagnosticBuilder noteExplicitConv( 14396 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 14397 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 14398 << ConvTy->isEnumeralType() << ConvTy; 14399 } 14400 14401 SemaDiagnosticBuilder diagnoseAmbiguous( 14402 Sema &S, SourceLocation Loc, QualType T) override { 14403 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 14404 } 14405 14406 SemaDiagnosticBuilder noteAmbiguous( 14407 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 14408 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 14409 << ConvTy->isEnumeralType() << ConvTy; 14410 } 14411 14412 SemaDiagnosticBuilder diagnoseConversion( 14413 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 14414 llvm_unreachable("conversion functions are permitted"); 14415 } 14416 } ConvertDiagnoser(Diagnoser.Suppress); 14417 14418 Converted = PerformContextualImplicitConversion(DiagLoc, E, 14419 ConvertDiagnoser); 14420 if (Converted.isInvalid()) 14421 return Converted; 14422 E = Converted.get(); 14423 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 14424 return ExprError(); 14425 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 14426 // An ICE must be of integral or unscoped enumeration type. 14427 if (!Diagnoser.Suppress) 14428 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 14429 return ExprError(); 14430 } 14431 14432 if (!isa<ConstantExpr>(E)) 14433 E = ConstantExpr::Create(Context, E); 14434 14435 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 14436 // in the non-ICE case. 14437 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 14438 if (Result) 14439 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 14440 return E; 14441 } 14442 14443 Expr::EvalResult EvalResult; 14444 SmallVector<PartialDiagnosticAt, 8> Notes; 14445 EvalResult.Diag = &Notes; 14446 14447 // Try to evaluate the expression, and produce diagnostics explaining why it's 14448 // not a constant expression as a side-effect. 14449 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 14450 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 14451 14452 // In C++11, we can rely on diagnostics being produced for any expression 14453 // which is not a constant expression. If no diagnostics were produced, then 14454 // this is a constant expression. 14455 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 14456 if (Result) 14457 *Result = EvalResult.Val.getInt(); 14458 return E; 14459 } 14460 14461 // If our only note is the usual "invalid subexpression" note, just point 14462 // the caret at its location rather than producing an essentially 14463 // redundant note. 14464 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 14465 diag::note_invalid_subexpr_in_const_expr) { 14466 DiagLoc = Notes[0].first; 14467 Notes.clear(); 14468 } 14469 14470 if (!Folded || !AllowFold) { 14471 if (!Diagnoser.Suppress) { 14472 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 14473 for (const PartialDiagnosticAt &Note : Notes) 14474 Diag(Note.first, Note.second); 14475 } 14476 14477 return ExprError(); 14478 } 14479 14480 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 14481 for (const PartialDiagnosticAt &Note : Notes) 14482 Diag(Note.first, Note.second); 14483 14484 if (Result) 14485 *Result = EvalResult.Val.getInt(); 14486 return E; 14487 } 14488 14489 namespace { 14490 // Handle the case where we conclude a expression which we speculatively 14491 // considered to be unevaluated is actually evaluated. 14492 class TransformToPE : public TreeTransform<TransformToPE> { 14493 typedef TreeTransform<TransformToPE> BaseTransform; 14494 14495 public: 14496 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 14497 14498 // Make sure we redo semantic analysis 14499 bool AlwaysRebuild() { return true; } 14500 14501 // We need to special-case DeclRefExprs referring to FieldDecls which 14502 // are not part of a member pointer formation; normal TreeTransforming 14503 // doesn't catch this case because of the way we represent them in the AST. 14504 // FIXME: This is a bit ugly; is it really the best way to handle this 14505 // case? 14506 // 14507 // Error on DeclRefExprs referring to FieldDecls. 14508 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 14509 if (isa<FieldDecl>(E->getDecl()) && 14510 !SemaRef.isUnevaluatedContext()) 14511 return SemaRef.Diag(E->getLocation(), 14512 diag::err_invalid_non_static_member_use) 14513 << E->getDecl() << E->getSourceRange(); 14514 14515 return BaseTransform::TransformDeclRefExpr(E); 14516 } 14517 14518 // Exception: filter out member pointer formation 14519 ExprResult TransformUnaryOperator(UnaryOperator *E) { 14520 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 14521 return E; 14522 14523 return BaseTransform::TransformUnaryOperator(E); 14524 } 14525 14526 ExprResult TransformLambdaExpr(LambdaExpr *E) { 14527 // Lambdas never need to be transformed. 14528 return E; 14529 } 14530 }; 14531 } 14532 14533 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 14534 assert(isUnevaluatedContext() && 14535 "Should only transform unevaluated expressions"); 14536 ExprEvalContexts.back().Context = 14537 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 14538 if (isUnevaluatedContext()) 14539 return E; 14540 return TransformToPE(*this).TransformExpr(E); 14541 } 14542 14543 void 14544 Sema::PushExpressionEvaluationContext( 14545 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 14546 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 14547 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 14548 LambdaContextDecl, ExprContext); 14549 Cleanup.reset(); 14550 if (!MaybeODRUseExprs.empty()) 14551 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 14552 } 14553 14554 void 14555 Sema::PushExpressionEvaluationContext( 14556 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 14557 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 14558 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 14559 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 14560 } 14561 14562 namespace { 14563 14564 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 14565 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 14566 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 14567 if (E->getOpcode() == UO_Deref) 14568 return CheckPossibleDeref(S, E->getSubExpr()); 14569 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 14570 return CheckPossibleDeref(S, E->getBase()); 14571 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 14572 return CheckPossibleDeref(S, E->getBase()); 14573 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 14574 QualType Inner; 14575 QualType Ty = E->getType(); 14576 if (const auto *Ptr = Ty->getAs<PointerType>()) 14577 Inner = Ptr->getPointeeType(); 14578 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 14579 Inner = Arr->getElementType(); 14580 else 14581 return nullptr; 14582 14583 if (Inner->hasAttr(attr::NoDeref)) 14584 return E; 14585 } 14586 return nullptr; 14587 } 14588 14589 } // namespace 14590 14591 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 14592 for (const Expr *E : Rec.PossibleDerefs) { 14593 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 14594 if (DeclRef) { 14595 const ValueDecl *Decl = DeclRef->getDecl(); 14596 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 14597 << Decl->getName() << E->getSourceRange(); 14598 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 14599 } else { 14600 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 14601 << E->getSourceRange(); 14602 } 14603 } 14604 Rec.PossibleDerefs.clear(); 14605 } 14606 14607 void Sema::PopExpressionEvaluationContext() { 14608 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 14609 unsigned NumTypos = Rec.NumTypos; 14610 14611 if (!Rec.Lambdas.empty()) { 14612 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 14613 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() || 14614 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) { 14615 unsigned D; 14616 if (Rec.isUnevaluated()) { 14617 // C++11 [expr.prim.lambda]p2: 14618 // A lambda-expression shall not appear in an unevaluated operand 14619 // (Clause 5). 14620 D = diag::err_lambda_unevaluated_operand; 14621 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 14622 // C++1y [expr.const]p2: 14623 // A conditional-expression e is a core constant expression unless the 14624 // evaluation of e, following the rules of the abstract machine, would 14625 // evaluate [...] a lambda-expression. 14626 D = diag::err_lambda_in_constant_expression; 14627 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 14628 // C++17 [expr.prim.lamda]p2: 14629 // A lambda-expression shall not appear [...] in a template-argument. 14630 D = diag::err_lambda_in_invalid_context; 14631 } else 14632 llvm_unreachable("Couldn't infer lambda error message."); 14633 14634 for (const auto *L : Rec.Lambdas) 14635 Diag(L->getBeginLoc(), D); 14636 } else { 14637 // Mark the capture expressions odr-used. This was deferred 14638 // during lambda expression creation. 14639 for (auto *Lambda : Rec.Lambdas) { 14640 for (auto *C : Lambda->capture_inits()) 14641 MarkDeclarationsReferencedInExpr(C); 14642 } 14643 } 14644 } 14645 14646 WarnOnPendingNoDerefs(Rec); 14647 14648 // When are coming out of an unevaluated context, clear out any 14649 // temporaries that we may have created as part of the evaluation of 14650 // the expression in that context: they aren't relevant because they 14651 // will never be constructed. 14652 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 14653 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 14654 ExprCleanupObjects.end()); 14655 Cleanup = Rec.ParentCleanup; 14656 CleanupVarDeclMarking(); 14657 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 14658 // Otherwise, merge the contexts together. 14659 } else { 14660 Cleanup.mergeFrom(Rec.ParentCleanup); 14661 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 14662 Rec.SavedMaybeODRUseExprs.end()); 14663 } 14664 14665 // Pop the current expression evaluation context off the stack. 14666 ExprEvalContexts.pop_back(); 14667 14668 // The global expression evaluation context record is never popped. 14669 ExprEvalContexts.back().NumTypos += NumTypos; 14670 } 14671 14672 void Sema::DiscardCleanupsInEvaluationContext() { 14673 ExprCleanupObjects.erase( 14674 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 14675 ExprCleanupObjects.end()); 14676 Cleanup.reset(); 14677 MaybeODRUseExprs.clear(); 14678 } 14679 14680 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 14681 ExprResult Result = CheckPlaceholderExpr(E); 14682 if (Result.isInvalid()) 14683 return ExprError(); 14684 E = Result.get(); 14685 if (!E->getType()->isVariablyModifiedType()) 14686 return E; 14687 return TransformToPotentiallyEvaluated(E); 14688 } 14689 14690 /// Are we within a context in which some evaluation could be performed (be it 14691 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite 14692 /// captured by C++'s idea of an "unevaluated context". 14693 static bool isEvaluatableContext(Sema &SemaRef) { 14694 switch (SemaRef.ExprEvalContexts.back().Context) { 14695 case Sema::ExpressionEvaluationContext::Unevaluated: 14696 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 14697 // Expressions in this context are never evaluated. 14698 return false; 14699 14700 case Sema::ExpressionEvaluationContext::UnevaluatedList: 14701 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 14702 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 14703 case Sema::ExpressionEvaluationContext::DiscardedStatement: 14704 // Expressions in this context could be evaluated. 14705 return true; 14706 14707 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 14708 // Referenced declarations will only be used if the construct in the 14709 // containing expression is used, at which point we'll be given another 14710 // turn to mark them. 14711 return false; 14712 } 14713 llvm_unreachable("Invalid context"); 14714 } 14715 14716 /// Are we within a context in which references to resolved functions or to 14717 /// variables result in odr-use? 14718 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) { 14719 // An expression in a template is not really an expression until it's been 14720 // instantiated, so it doesn't trigger odr-use. 14721 if (SkipDependentUses && SemaRef.CurContext->isDependentContext()) 14722 return false; 14723 14724 switch (SemaRef.ExprEvalContexts.back().Context) { 14725 case Sema::ExpressionEvaluationContext::Unevaluated: 14726 case Sema::ExpressionEvaluationContext::UnevaluatedList: 14727 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 14728 case Sema::ExpressionEvaluationContext::DiscardedStatement: 14729 return false; 14730 14731 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 14732 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 14733 return true; 14734 14735 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 14736 return false; 14737 } 14738 llvm_unreachable("Invalid context"); 14739 } 14740 14741 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 14742 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 14743 return Func->isConstexpr() && 14744 (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided())); 14745 } 14746 14747 /// Mark a function referenced, and check whether it is odr-used 14748 /// (C++ [basic.def.odr]p2, C99 6.9p3) 14749 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 14750 bool MightBeOdrUse) { 14751 assert(Func && "No function?"); 14752 14753 Func->setReferenced(); 14754 14755 // C++11 [basic.def.odr]p3: 14756 // A function whose name appears as a potentially-evaluated expression is 14757 // odr-used if it is the unique lookup result or the selected member of a 14758 // set of overloaded functions [...]. 14759 // 14760 // We (incorrectly) mark overload resolution as an unevaluated context, so we 14761 // can just check that here. 14762 bool OdrUse = MightBeOdrUse && isOdrUseContext(*this); 14763 14764 // Determine whether we require a function definition to exist, per 14765 // C++11 [temp.inst]p3: 14766 // Unless a function template specialization has been explicitly 14767 // instantiated or explicitly specialized, the function template 14768 // specialization is implicitly instantiated when the specialization is 14769 // referenced in a context that requires a function definition to exist. 14770 // 14771 // That is either when this is an odr-use, or when a usage of a constexpr 14772 // function occurs within an evaluatable context. 14773 bool NeedDefinition = 14774 OdrUse || (isEvaluatableContext(*this) && 14775 isImplicitlyDefinableConstexprFunction(Func)); 14776 14777 // C++14 [temp.expl.spec]p6: 14778 // If a template [...] is explicitly specialized then that specialization 14779 // shall be declared before the first use of that specialization that would 14780 // cause an implicit instantiation to take place, in every translation unit 14781 // in which such a use occurs 14782 if (NeedDefinition && 14783 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 14784 Func->getMemberSpecializationInfo())) 14785 checkSpecializationVisibility(Loc, Func); 14786 14787 // C++14 [except.spec]p17: 14788 // An exception-specification is considered to be needed when: 14789 // - the function is odr-used or, if it appears in an unevaluated operand, 14790 // would be odr-used if the expression were potentially-evaluated; 14791 // 14792 // Note, we do this even if MightBeOdrUse is false. That indicates that the 14793 // function is a pure virtual function we're calling, and in that case the 14794 // function was selected by overload resolution and we need to resolve its 14795 // exception specification for a different reason. 14796 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 14797 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 14798 ResolveExceptionSpec(Loc, FPT); 14799 14800 if (getLangOpts().CUDA) 14801 CheckCUDACall(Loc, Func); 14802 14803 // If we don't need to mark the function as used, and we don't need to 14804 // try to provide a definition, there's nothing more to do. 14805 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) && 14806 (!NeedDefinition || Func->getBody())) 14807 return; 14808 14809 // Note that this declaration has been used. 14810 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 14811 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 14812 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 14813 if (Constructor->isDefaultConstructor()) { 14814 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 14815 return; 14816 DefineImplicitDefaultConstructor(Loc, Constructor); 14817 } else if (Constructor->isCopyConstructor()) { 14818 DefineImplicitCopyConstructor(Loc, Constructor); 14819 } else if (Constructor->isMoveConstructor()) { 14820 DefineImplicitMoveConstructor(Loc, Constructor); 14821 } 14822 } else if (Constructor->getInheritedConstructor()) { 14823 DefineInheritingConstructor(Loc, Constructor); 14824 } 14825 } else if (CXXDestructorDecl *Destructor = 14826 dyn_cast<CXXDestructorDecl>(Func)) { 14827 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 14828 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 14829 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 14830 return; 14831 DefineImplicitDestructor(Loc, Destructor); 14832 } 14833 if (Destructor->isVirtual() && getLangOpts().AppleKext) 14834 MarkVTableUsed(Loc, Destructor->getParent()); 14835 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 14836 if (MethodDecl->isOverloadedOperator() && 14837 MethodDecl->getOverloadedOperator() == OO_Equal) { 14838 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 14839 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 14840 if (MethodDecl->isCopyAssignmentOperator()) 14841 DefineImplicitCopyAssignment(Loc, MethodDecl); 14842 else if (MethodDecl->isMoveAssignmentOperator()) 14843 DefineImplicitMoveAssignment(Loc, MethodDecl); 14844 } 14845 } else if (isa<CXXConversionDecl>(MethodDecl) && 14846 MethodDecl->getParent()->isLambda()) { 14847 CXXConversionDecl *Conversion = 14848 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 14849 if (Conversion->isLambdaToBlockPointerConversion()) 14850 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 14851 else 14852 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 14853 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 14854 MarkVTableUsed(Loc, MethodDecl->getParent()); 14855 } 14856 14857 // Recursive functions should be marked when used from another function. 14858 // FIXME: Is this really right? 14859 if (CurContext == Func) return; 14860 14861 // Implicit instantiation of function templates and member functions of 14862 // class templates. 14863 if (Func->isImplicitlyInstantiable()) { 14864 TemplateSpecializationKind TSK = Func->getTemplateSpecializationKind(); 14865 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 14866 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 14867 if (FirstInstantiation) { 14868 PointOfInstantiation = Loc; 14869 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 14870 } else if (TSK != TSK_ImplicitInstantiation) { 14871 // Use the point of use as the point of instantiation, instead of the 14872 // point of explicit instantiation (which we track as the actual point of 14873 // instantiation). This gives better backtraces in diagnostics. 14874 PointOfInstantiation = Loc; 14875 } 14876 14877 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 14878 Func->isConstexpr()) { 14879 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 14880 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 14881 CodeSynthesisContexts.size()) 14882 PendingLocalImplicitInstantiations.push_back( 14883 std::make_pair(Func, PointOfInstantiation)); 14884 else if (Func->isConstexpr()) 14885 // Do not defer instantiations of constexpr functions, to avoid the 14886 // expression evaluator needing to call back into Sema if it sees a 14887 // call to such a function. 14888 InstantiateFunctionDefinition(PointOfInstantiation, Func); 14889 else { 14890 Func->setInstantiationIsPending(true); 14891 PendingInstantiations.push_back(std::make_pair(Func, 14892 PointOfInstantiation)); 14893 // Notify the consumer that a function was implicitly instantiated. 14894 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 14895 } 14896 } 14897 } else { 14898 // Walk redefinitions, as some of them may be instantiable. 14899 for (auto i : Func->redecls()) { 14900 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 14901 MarkFunctionReferenced(Loc, i, OdrUse); 14902 } 14903 } 14904 14905 if (!OdrUse) return; 14906 14907 // Keep track of used but undefined functions. 14908 if (!Func->isDefined()) { 14909 if (mightHaveNonExternalLinkage(Func)) 14910 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14911 else if (Func->getMostRecentDecl()->isInlined() && 14912 !LangOpts.GNUInline && 14913 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 14914 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14915 else if (isExternalWithNoLinkageType(Func)) 14916 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14917 } 14918 14919 Func->markUsed(Context); 14920 14921 if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice) 14922 checkOpenMPDeviceFunction(Loc, Func); 14923 } 14924 14925 static void 14926 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 14927 ValueDecl *var, DeclContext *DC) { 14928 DeclContext *VarDC = var->getDeclContext(); 14929 14930 // If the parameter still belongs to the translation unit, then 14931 // we're actually just using one parameter in the declaration of 14932 // the next. 14933 if (isa<ParmVarDecl>(var) && 14934 isa<TranslationUnitDecl>(VarDC)) 14935 return; 14936 14937 // For C code, don't diagnose about capture if we're not actually in code 14938 // right now; it's impossible to write a non-constant expression outside of 14939 // function context, so we'll get other (more useful) diagnostics later. 14940 // 14941 // For C++, things get a bit more nasty... it would be nice to suppress this 14942 // diagnostic for certain cases like using a local variable in an array bound 14943 // for a member of a local class, but the correct predicate is not obvious. 14944 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 14945 return; 14946 14947 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 14948 unsigned ContextKind = 3; // unknown 14949 if (isa<CXXMethodDecl>(VarDC) && 14950 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 14951 ContextKind = 2; 14952 } else if (isa<FunctionDecl>(VarDC)) { 14953 ContextKind = 0; 14954 } else if (isa<BlockDecl>(VarDC)) { 14955 ContextKind = 1; 14956 } 14957 14958 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 14959 << var << ValueKind << ContextKind << VarDC; 14960 S.Diag(var->getLocation(), diag::note_entity_declared_at) 14961 << var; 14962 14963 // FIXME: Add additional diagnostic info about class etc. which prevents 14964 // capture. 14965 } 14966 14967 14968 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 14969 bool &SubCapturesAreNested, 14970 QualType &CaptureType, 14971 QualType &DeclRefType) { 14972 // Check whether we've already captured it. 14973 if (CSI->CaptureMap.count(Var)) { 14974 // If we found a capture, any subcaptures are nested. 14975 SubCapturesAreNested = true; 14976 14977 // Retrieve the capture type for this variable. 14978 CaptureType = CSI->getCapture(Var).getCaptureType(); 14979 14980 // Compute the type of an expression that refers to this variable. 14981 DeclRefType = CaptureType.getNonReferenceType(); 14982 14983 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 14984 // are mutable in the sense that user can change their value - they are 14985 // private instances of the captured declarations. 14986 const Capture &Cap = CSI->getCapture(Var); 14987 if (Cap.isCopyCapture() && 14988 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 14989 !(isa<CapturedRegionScopeInfo>(CSI) && 14990 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 14991 DeclRefType.addConst(); 14992 return true; 14993 } 14994 return false; 14995 } 14996 14997 // Only block literals, captured statements, and lambda expressions can 14998 // capture; other scopes don't work. 14999 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 15000 SourceLocation Loc, 15001 const bool Diagnose, Sema &S) { 15002 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 15003 return getLambdaAwareParentOfDeclContext(DC); 15004 else if (Var->hasLocalStorage()) { 15005 if (Diagnose) 15006 diagnoseUncapturableValueReference(S, Loc, Var, DC); 15007 } 15008 return nullptr; 15009 } 15010 15011 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 15012 // certain types of variables (unnamed, variably modified types etc.) 15013 // so check for eligibility. 15014 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 15015 SourceLocation Loc, 15016 const bool Diagnose, Sema &S) { 15017 15018 bool IsBlock = isa<BlockScopeInfo>(CSI); 15019 bool IsLambda = isa<LambdaScopeInfo>(CSI); 15020 15021 // Lambdas are not allowed to capture unnamed variables 15022 // (e.g. anonymous unions). 15023 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 15024 // assuming that's the intent. 15025 if (IsLambda && !Var->getDeclName()) { 15026 if (Diagnose) { 15027 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 15028 S.Diag(Var->getLocation(), diag::note_declared_at); 15029 } 15030 return false; 15031 } 15032 15033 // Prohibit variably-modified types in blocks; they're difficult to deal with. 15034 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 15035 if (Diagnose) { 15036 S.Diag(Loc, diag::err_ref_vm_type); 15037 S.Diag(Var->getLocation(), diag::note_previous_decl) 15038 << Var->getDeclName(); 15039 } 15040 return false; 15041 } 15042 // Prohibit structs with flexible array members too. 15043 // We cannot capture what is in the tail end of the struct. 15044 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 15045 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 15046 if (Diagnose) { 15047 if (IsBlock) 15048 S.Diag(Loc, diag::err_ref_flexarray_type); 15049 else 15050 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 15051 << Var->getDeclName(); 15052 S.Diag(Var->getLocation(), diag::note_previous_decl) 15053 << Var->getDeclName(); 15054 } 15055 return false; 15056 } 15057 } 15058 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 15059 // Lambdas and captured statements are not allowed to capture __block 15060 // variables; they don't support the expected semantics. 15061 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 15062 if (Diagnose) { 15063 S.Diag(Loc, diag::err_capture_block_variable) 15064 << Var->getDeclName() << !IsLambda; 15065 S.Diag(Var->getLocation(), diag::note_previous_decl) 15066 << Var->getDeclName(); 15067 } 15068 return false; 15069 } 15070 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 15071 if (S.getLangOpts().OpenCL && IsBlock && 15072 Var->getType()->isBlockPointerType()) { 15073 if (Diagnose) 15074 S.Diag(Loc, diag::err_opencl_block_ref_block); 15075 return false; 15076 } 15077 15078 return true; 15079 } 15080 15081 // Returns true if the capture by block was successful. 15082 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 15083 SourceLocation Loc, 15084 const bool BuildAndDiagnose, 15085 QualType &CaptureType, 15086 QualType &DeclRefType, 15087 const bool Nested, 15088 Sema &S) { 15089 Expr *CopyExpr = nullptr; 15090 bool ByRef = false; 15091 15092 // Blocks are not allowed to capture arrays, excepting OpenCL. 15093 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 15094 // (decayed to pointers). 15095 if (!S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 15096 if (BuildAndDiagnose) { 15097 S.Diag(Loc, diag::err_ref_array_type); 15098 S.Diag(Var->getLocation(), diag::note_previous_decl) 15099 << Var->getDeclName(); 15100 } 15101 return false; 15102 } 15103 15104 // Forbid the block-capture of autoreleasing variables. 15105 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 15106 if (BuildAndDiagnose) { 15107 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 15108 << /*block*/ 0; 15109 S.Diag(Var->getLocation(), diag::note_previous_decl) 15110 << Var->getDeclName(); 15111 } 15112 return false; 15113 } 15114 15115 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 15116 if (const auto *PT = CaptureType->getAs<PointerType>()) { 15117 // This function finds out whether there is an AttributedType of kind 15118 // attr::ObjCOwnership in Ty. The existence of AttributedType of kind 15119 // attr::ObjCOwnership implies __autoreleasing was explicitly specified 15120 // rather than being added implicitly by the compiler. 15121 auto IsObjCOwnershipAttributedType = [](QualType Ty) { 15122 while (const auto *AttrTy = Ty->getAs<AttributedType>()) { 15123 if (AttrTy->getAttrKind() == attr::ObjCOwnership) 15124 return true; 15125 15126 // Peel off AttributedTypes that are not of kind ObjCOwnership. 15127 Ty = AttrTy->getModifiedType(); 15128 } 15129 15130 return false; 15131 }; 15132 15133 QualType PointeeTy = PT->getPointeeType(); 15134 15135 if (PointeeTy->getAs<ObjCObjectPointerType>() && 15136 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 15137 !IsObjCOwnershipAttributedType(PointeeTy)) { 15138 if (BuildAndDiagnose) { 15139 SourceLocation VarLoc = Var->getLocation(); 15140 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 15141 S.Diag(VarLoc, diag::note_declare_parameter_strong); 15142 } 15143 } 15144 } 15145 15146 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 15147 if (HasBlocksAttr || CaptureType->isReferenceType() || 15148 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 15149 // Block capture by reference does not change the capture or 15150 // declaration reference types. 15151 ByRef = true; 15152 } else { 15153 // Block capture by copy introduces 'const'. 15154 CaptureType = CaptureType.getNonReferenceType().withConst(); 15155 DeclRefType = CaptureType; 15156 15157 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 15158 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 15159 // The capture logic needs the destructor, so make sure we mark it. 15160 // Usually this is unnecessary because most local variables have 15161 // their destructors marked at declaration time, but parameters are 15162 // an exception because it's technically only the call site that 15163 // actually requires the destructor. 15164 if (isa<ParmVarDecl>(Var)) 15165 S.FinalizeVarWithDestructor(Var, Record); 15166 15167 // Enter a new evaluation context to insulate the copy 15168 // full-expression. 15169 EnterExpressionEvaluationContext scope( 15170 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 15171 15172 // According to the blocks spec, the capture of a variable from 15173 // the stack requires a const copy constructor. This is not true 15174 // of the copy/move done to move a __block variable to the heap. 15175 Expr *DeclRef = new (S.Context) DeclRefExpr( 15176 S.Context, Var, Nested, DeclRefType.withConst(), VK_LValue, Loc); 15177 15178 ExprResult Result 15179 = S.PerformCopyInitialization( 15180 InitializedEntity::InitializeBlock(Var->getLocation(), 15181 CaptureType, false), 15182 Loc, DeclRef); 15183 15184 // Build a full-expression copy expression if initialization 15185 // succeeded and used a non-trivial constructor. Recover from 15186 // errors by pretending that the copy isn't necessary. 15187 if (!Result.isInvalid() && 15188 !cast<CXXConstructExpr>(Result.get())->getConstructor() 15189 ->isTrivial()) { 15190 Result = S.MaybeCreateExprWithCleanups(Result); 15191 CopyExpr = Result.get(); 15192 } 15193 } 15194 } 15195 } 15196 15197 // Actually capture the variable. 15198 if (BuildAndDiagnose) 15199 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 15200 SourceLocation(), CaptureType, CopyExpr); 15201 15202 return true; 15203 15204 } 15205 15206 15207 /// Capture the given variable in the captured region. 15208 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 15209 VarDecl *Var, 15210 SourceLocation Loc, 15211 const bool BuildAndDiagnose, 15212 QualType &CaptureType, 15213 QualType &DeclRefType, 15214 const bool RefersToCapturedVariable, 15215 Sema &S) { 15216 // By default, capture variables by reference. 15217 bool ByRef = true; 15218 // Using an LValue reference type is consistent with Lambdas (see below). 15219 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 15220 if (S.isOpenMPCapturedDecl(Var)) { 15221 bool HasConst = DeclRefType.isConstQualified(); 15222 DeclRefType = DeclRefType.getUnqualifiedType(); 15223 // Don't lose diagnostics about assignments to const. 15224 if (HasConst) 15225 DeclRefType.addConst(); 15226 } 15227 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel); 15228 } 15229 15230 if (ByRef) 15231 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 15232 else 15233 CaptureType = DeclRefType; 15234 15235 Expr *CopyExpr = nullptr; 15236 if (BuildAndDiagnose) { 15237 // The current implementation assumes that all variables are captured 15238 // by references. Since there is no capture by copy, no expression 15239 // evaluation will be needed. 15240 RecordDecl *RD = RSI->TheRecordDecl; 15241 15242 FieldDecl *Field 15243 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 15244 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 15245 nullptr, false, ICIS_NoInit); 15246 Field->setImplicit(true); 15247 Field->setAccess(AS_private); 15248 RD->addDecl(Field); 15249 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) 15250 S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel); 15251 15252 CopyExpr = new (S.Context) DeclRefExpr( 15253 S.Context, Var, RefersToCapturedVariable, DeclRefType, VK_LValue, Loc); 15254 Var->setReferenced(true); 15255 Var->markUsed(S.Context); 15256 } 15257 15258 // Actually capture the variable. 15259 if (BuildAndDiagnose) 15260 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 15261 SourceLocation(), CaptureType, CopyExpr); 15262 15263 15264 return true; 15265 } 15266 15267 /// Create a field within the lambda class for the variable 15268 /// being captured. 15269 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, 15270 QualType FieldType, QualType DeclRefType, 15271 SourceLocation Loc, 15272 bool RefersToCapturedVariable) { 15273 CXXRecordDecl *Lambda = LSI->Lambda; 15274 15275 // Build the non-static data member. 15276 FieldDecl *Field 15277 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 15278 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 15279 nullptr, false, ICIS_NoInit); 15280 // If the variable being captured has an invalid type, mark the lambda class 15281 // as invalid as well. 15282 if (!FieldType->isDependentType()) { 15283 if (S.RequireCompleteType(Loc, FieldType, diag::err_field_incomplete)) { 15284 Lambda->setInvalidDecl(); 15285 Field->setInvalidDecl(); 15286 } else { 15287 NamedDecl *Def; 15288 FieldType->isIncompleteType(&Def); 15289 if (Def && Def->isInvalidDecl()) { 15290 Lambda->setInvalidDecl(); 15291 Field->setInvalidDecl(); 15292 } 15293 } 15294 } 15295 Field->setImplicit(true); 15296 Field->setAccess(AS_private); 15297 Lambda->addDecl(Field); 15298 } 15299 15300 /// Capture the given variable in the lambda. 15301 static bool captureInLambda(LambdaScopeInfo *LSI, 15302 VarDecl *Var, 15303 SourceLocation Loc, 15304 const bool BuildAndDiagnose, 15305 QualType &CaptureType, 15306 QualType &DeclRefType, 15307 const bool RefersToCapturedVariable, 15308 const Sema::TryCaptureKind Kind, 15309 SourceLocation EllipsisLoc, 15310 const bool IsTopScope, 15311 Sema &S) { 15312 15313 // Determine whether we are capturing by reference or by value. 15314 bool ByRef = false; 15315 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 15316 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 15317 } else { 15318 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 15319 } 15320 15321 // Compute the type of the field that will capture this variable. 15322 if (ByRef) { 15323 // C++11 [expr.prim.lambda]p15: 15324 // An entity is captured by reference if it is implicitly or 15325 // explicitly captured but not captured by copy. It is 15326 // unspecified whether additional unnamed non-static data 15327 // members are declared in the closure type for entities 15328 // captured by reference. 15329 // 15330 // FIXME: It is not clear whether we want to build an lvalue reference 15331 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 15332 // to do the former, while EDG does the latter. Core issue 1249 will 15333 // clarify, but for now we follow GCC because it's a more permissive and 15334 // easily defensible position. 15335 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 15336 } else { 15337 // C++11 [expr.prim.lambda]p14: 15338 // For each entity captured by copy, an unnamed non-static 15339 // data member is declared in the closure type. The 15340 // declaration order of these members is unspecified. The type 15341 // of such a data member is the type of the corresponding 15342 // captured entity if the entity is not a reference to an 15343 // object, or the referenced type otherwise. [Note: If the 15344 // captured entity is a reference to a function, the 15345 // corresponding data member is also a reference to a 15346 // function. - end note ] 15347 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 15348 if (!RefType->getPointeeType()->isFunctionType()) 15349 CaptureType = RefType->getPointeeType(); 15350 } 15351 15352 // Forbid the lambda copy-capture of autoreleasing variables. 15353 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 15354 if (BuildAndDiagnose) { 15355 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 15356 S.Diag(Var->getLocation(), diag::note_previous_decl) 15357 << Var->getDeclName(); 15358 } 15359 return false; 15360 } 15361 15362 // Make sure that by-copy captures are of a complete and non-abstract type. 15363 if (BuildAndDiagnose) { 15364 if (!CaptureType->isDependentType() && 15365 S.RequireCompleteType(Loc, CaptureType, 15366 diag::err_capture_of_incomplete_type, 15367 Var->getDeclName())) 15368 return false; 15369 15370 if (S.RequireNonAbstractType(Loc, CaptureType, 15371 diag::err_capture_of_abstract_type)) 15372 return false; 15373 } 15374 } 15375 15376 // Capture this variable in the lambda. 15377 if (BuildAndDiagnose) 15378 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc, 15379 RefersToCapturedVariable); 15380 15381 // Compute the type of a reference to this captured variable. 15382 if (ByRef) 15383 DeclRefType = CaptureType.getNonReferenceType(); 15384 else { 15385 // C++ [expr.prim.lambda]p5: 15386 // The closure type for a lambda-expression has a public inline 15387 // function call operator [...]. This function call operator is 15388 // declared const (9.3.1) if and only if the lambda-expression's 15389 // parameter-declaration-clause is not followed by mutable. 15390 DeclRefType = CaptureType.getNonReferenceType(); 15391 if (!LSI->Mutable && !CaptureType->isReferenceType()) 15392 DeclRefType.addConst(); 15393 } 15394 15395 // Add the capture. 15396 if (BuildAndDiagnose) 15397 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 15398 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 15399 15400 return true; 15401 } 15402 15403 bool Sema::tryCaptureVariable( 15404 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 15405 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 15406 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 15407 // An init-capture is notionally from the context surrounding its 15408 // declaration, but its parent DC is the lambda class. 15409 DeclContext *VarDC = Var->getDeclContext(); 15410 if (Var->isInitCapture()) 15411 VarDC = VarDC->getParent(); 15412 15413 DeclContext *DC = CurContext; 15414 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 15415 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 15416 // We need to sync up the Declaration Context with the 15417 // FunctionScopeIndexToStopAt 15418 if (FunctionScopeIndexToStopAt) { 15419 unsigned FSIndex = FunctionScopes.size() - 1; 15420 while (FSIndex != MaxFunctionScopesIndex) { 15421 DC = getLambdaAwareParentOfDeclContext(DC); 15422 --FSIndex; 15423 } 15424 } 15425 15426 15427 // If the variable is declared in the current context, there is no need to 15428 // capture it. 15429 if (VarDC == DC) return true; 15430 15431 // Capture global variables if it is required to use private copy of this 15432 // variable. 15433 bool IsGlobal = !Var->hasLocalStorage(); 15434 if (IsGlobal && !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var))) 15435 return true; 15436 Var = Var->getCanonicalDecl(); 15437 15438 // Walk up the stack to determine whether we can capture the variable, 15439 // performing the "simple" checks that don't depend on type. We stop when 15440 // we've either hit the declared scope of the variable or find an existing 15441 // capture of that variable. We start from the innermost capturing-entity 15442 // (the DC) and ensure that all intervening capturing-entities 15443 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 15444 // declcontext can either capture the variable or have already captured 15445 // the variable. 15446 CaptureType = Var->getType(); 15447 DeclRefType = CaptureType.getNonReferenceType(); 15448 bool Nested = false; 15449 bool Explicit = (Kind != TryCapture_Implicit); 15450 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 15451 do { 15452 // Only block literals, captured statements, and lambda expressions can 15453 // capture; other scopes don't work. 15454 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 15455 ExprLoc, 15456 BuildAndDiagnose, 15457 *this); 15458 // We need to check for the parent *first* because, if we *have* 15459 // private-captured a global variable, we need to recursively capture it in 15460 // intermediate blocks, lambdas, etc. 15461 if (!ParentDC) { 15462 if (IsGlobal) { 15463 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 15464 break; 15465 } 15466 return true; 15467 } 15468 15469 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 15470 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 15471 15472 15473 // Check whether we've already captured it. 15474 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 15475 DeclRefType)) { 15476 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 15477 break; 15478 } 15479 // If we are instantiating a generic lambda call operator body, 15480 // we do not want to capture new variables. What was captured 15481 // during either a lambdas transformation or initial parsing 15482 // should be used. 15483 if (isGenericLambdaCallOperatorSpecialization(DC)) { 15484 if (BuildAndDiagnose) { 15485 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 15486 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 15487 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 15488 Diag(Var->getLocation(), diag::note_previous_decl) 15489 << Var->getDeclName(); 15490 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 15491 } else 15492 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 15493 } 15494 return true; 15495 } 15496 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 15497 // certain types of variables (unnamed, variably modified types etc.) 15498 // so check for eligibility. 15499 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 15500 return true; 15501 15502 // Try to capture variable-length arrays types. 15503 if (Var->getType()->isVariablyModifiedType()) { 15504 // We're going to walk down into the type and look for VLA 15505 // expressions. 15506 QualType QTy = Var->getType(); 15507 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 15508 QTy = PVD->getOriginalType(); 15509 captureVariablyModifiedType(Context, QTy, CSI); 15510 } 15511 15512 if (getLangOpts().OpenMP) { 15513 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 15514 // OpenMP private variables should not be captured in outer scope, so 15515 // just break here. Similarly, global variables that are captured in a 15516 // target region should not be captured outside the scope of the region. 15517 if (RSI->CapRegionKind == CR_OpenMP) { 15518 bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel); 15519 auto IsTargetCap = !IsOpenMPPrivateDecl && 15520 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 15521 // When we detect target captures we are looking from inside the 15522 // target region, therefore we need to propagate the capture from the 15523 // enclosing region. Therefore, the capture is not initially nested. 15524 if (IsTargetCap) 15525 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 15526 15527 if (IsTargetCap || IsOpenMPPrivateDecl) { 15528 Nested = !IsTargetCap; 15529 DeclRefType = DeclRefType.getUnqualifiedType(); 15530 CaptureType = Context.getLValueReferenceType(DeclRefType); 15531 break; 15532 } 15533 } 15534 } 15535 } 15536 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 15537 // No capture-default, and this is not an explicit capture 15538 // so cannot capture this variable. 15539 if (BuildAndDiagnose) { 15540 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 15541 Diag(Var->getLocation(), diag::note_previous_decl) 15542 << Var->getDeclName(); 15543 if (cast<LambdaScopeInfo>(CSI)->Lambda) 15544 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(), 15545 diag::note_lambda_decl); 15546 // FIXME: If we error out because an outer lambda can not implicitly 15547 // capture a variable that an inner lambda explicitly captures, we 15548 // should have the inner lambda do the explicit capture - because 15549 // it makes for cleaner diagnostics later. This would purely be done 15550 // so that the diagnostic does not misleadingly claim that a variable 15551 // can not be captured by a lambda implicitly even though it is captured 15552 // explicitly. Suggestion: 15553 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 15554 // at the function head 15555 // - cache the StartingDeclContext - this must be a lambda 15556 // - captureInLambda in the innermost lambda the variable. 15557 } 15558 return true; 15559 } 15560 15561 FunctionScopesIndex--; 15562 DC = ParentDC; 15563 Explicit = false; 15564 } while (!VarDC->Equals(DC)); 15565 15566 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 15567 // computing the type of the capture at each step, checking type-specific 15568 // requirements, and adding captures if requested. 15569 // If the variable had already been captured previously, we start capturing 15570 // at the lambda nested within that one. 15571 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 15572 ++I) { 15573 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 15574 15575 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 15576 if (!captureInBlock(BSI, Var, ExprLoc, 15577 BuildAndDiagnose, CaptureType, 15578 DeclRefType, Nested, *this)) 15579 return true; 15580 Nested = true; 15581 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 15582 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 15583 BuildAndDiagnose, CaptureType, 15584 DeclRefType, Nested, *this)) 15585 return true; 15586 Nested = true; 15587 } else { 15588 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 15589 if (!captureInLambda(LSI, Var, ExprLoc, 15590 BuildAndDiagnose, CaptureType, 15591 DeclRefType, Nested, Kind, EllipsisLoc, 15592 /*IsTopScope*/I == N - 1, *this)) 15593 return true; 15594 Nested = true; 15595 } 15596 } 15597 return false; 15598 } 15599 15600 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 15601 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 15602 QualType CaptureType; 15603 QualType DeclRefType; 15604 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 15605 /*BuildAndDiagnose=*/true, CaptureType, 15606 DeclRefType, nullptr); 15607 } 15608 15609 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 15610 QualType CaptureType; 15611 QualType DeclRefType; 15612 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 15613 /*BuildAndDiagnose=*/false, CaptureType, 15614 DeclRefType, nullptr); 15615 } 15616 15617 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 15618 QualType CaptureType; 15619 QualType DeclRefType; 15620 15621 // Determine whether we can capture this variable. 15622 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 15623 /*BuildAndDiagnose=*/false, CaptureType, 15624 DeclRefType, nullptr)) 15625 return QualType(); 15626 15627 return DeclRefType; 15628 } 15629 15630 15631 15632 // If either the type of the variable or the initializer is dependent, 15633 // return false. Otherwise, determine whether the variable is a constant 15634 // expression. Use this if you need to know if a variable that might or 15635 // might not be dependent is truly a constant expression. 15636 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 15637 ASTContext &Context) { 15638 15639 if (Var->getType()->isDependentType()) 15640 return false; 15641 const VarDecl *DefVD = nullptr; 15642 Var->getAnyInitializer(DefVD); 15643 if (!DefVD) 15644 return false; 15645 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 15646 Expr *Init = cast<Expr>(Eval->Value); 15647 if (Init->isValueDependent()) 15648 return false; 15649 return IsVariableAConstantExpression(Var, Context); 15650 } 15651 15652 15653 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 15654 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 15655 // an object that satisfies the requirements for appearing in a 15656 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 15657 // is immediately applied." This function handles the lvalue-to-rvalue 15658 // conversion part. 15659 MaybeODRUseExprs.erase(E->IgnoreParens()); 15660 15661 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 15662 // to a variable that is a constant expression, and if so, identify it as 15663 // a reference to a variable that does not involve an odr-use of that 15664 // variable. 15665 if (LambdaScopeInfo *LSI = getCurLambda()) { 15666 Expr *SansParensExpr = E->IgnoreParens(); 15667 VarDecl *Var = nullptr; 15668 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 15669 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 15670 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 15671 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 15672 15673 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 15674 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 15675 } 15676 } 15677 15678 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 15679 Res = CorrectDelayedTyposInExpr(Res); 15680 15681 if (!Res.isUsable()) 15682 return Res; 15683 15684 // If a constant-expression is a reference to a variable where we delay 15685 // deciding whether it is an odr-use, just assume we will apply the 15686 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 15687 // (a non-type template argument), we have special handling anyway. 15688 UpdateMarkingForLValueToRValue(Res.get()); 15689 return Res; 15690 } 15691 15692 void Sema::CleanupVarDeclMarking() { 15693 for (Expr *E : MaybeODRUseExprs) { 15694 VarDecl *Var; 15695 SourceLocation Loc; 15696 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 15697 Var = cast<VarDecl>(DRE->getDecl()); 15698 Loc = DRE->getLocation(); 15699 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 15700 Var = cast<VarDecl>(ME->getMemberDecl()); 15701 Loc = ME->getMemberLoc(); 15702 } else { 15703 llvm_unreachable("Unexpected expression"); 15704 } 15705 15706 MarkVarDeclODRUsed(Var, Loc, *this, 15707 /*MaxFunctionScopeIndex Pointer*/ nullptr); 15708 } 15709 15710 MaybeODRUseExprs.clear(); 15711 } 15712 15713 15714 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 15715 VarDecl *Var, Expr *E) { 15716 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 15717 "Invalid Expr argument to DoMarkVarDeclReferenced"); 15718 Var->setReferenced(); 15719 15720 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 15721 15722 bool OdrUseContext = isOdrUseContext(SemaRef); 15723 bool UsableInConstantExpr = 15724 Var->isUsableInConstantExpressions(SemaRef.Context); 15725 bool NeedDefinition = 15726 OdrUseContext || (isEvaluatableContext(SemaRef) && UsableInConstantExpr); 15727 15728 VarTemplateSpecializationDecl *VarSpec = 15729 dyn_cast<VarTemplateSpecializationDecl>(Var); 15730 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 15731 "Can't instantiate a partial template specialization."); 15732 15733 // If this might be a member specialization of a static data member, check 15734 // the specialization is visible. We already did the checks for variable 15735 // template specializations when we created them. 15736 if (NeedDefinition && TSK != TSK_Undeclared && 15737 !isa<VarTemplateSpecializationDecl>(Var)) 15738 SemaRef.checkSpecializationVisibility(Loc, Var); 15739 15740 // Perform implicit instantiation of static data members, static data member 15741 // templates of class templates, and variable template specializations. Delay 15742 // instantiations of variable templates, except for those that could be used 15743 // in a constant expression. 15744 if (NeedDefinition && isTemplateInstantiation(TSK)) { 15745 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 15746 // instantiation declaration if a variable is usable in a constant 15747 // expression (among other cases). 15748 bool TryInstantiating = 15749 TSK == TSK_ImplicitInstantiation || 15750 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 15751 15752 if (TryInstantiating) { 15753 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 15754 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 15755 if (FirstInstantiation) { 15756 PointOfInstantiation = Loc; 15757 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 15758 } 15759 15760 bool InstantiationDependent = false; 15761 bool IsNonDependent = 15762 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 15763 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 15764 : true; 15765 15766 // Do not instantiate specializations that are still type-dependent. 15767 if (IsNonDependent) { 15768 if (UsableInConstantExpr) { 15769 // Do not defer instantiations of variables that could be used in a 15770 // constant expression. 15771 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 15772 } else if (FirstInstantiation || 15773 isa<VarTemplateSpecializationDecl>(Var)) { 15774 // FIXME: For a specialization of a variable template, we don't 15775 // distinguish between "declaration and type implicitly instantiated" 15776 // and "implicit instantiation of definition requested", so we have 15777 // no direct way to avoid enqueueing the pending instantiation 15778 // multiple times. 15779 SemaRef.PendingInstantiations 15780 .push_back(std::make_pair(Var, PointOfInstantiation)); 15781 } 15782 } 15783 } 15784 } 15785 15786 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 15787 // the requirements for appearing in a constant expression (5.19) and, if 15788 // it is an object, the lvalue-to-rvalue conversion (4.1) 15789 // is immediately applied." We check the first part here, and 15790 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 15791 // Note that we use the C++11 definition everywhere because nothing in 15792 // C++03 depends on whether we get the C++03 version correct. The second 15793 // part does not apply to references, since they are not objects. 15794 if (OdrUseContext && E && 15795 IsVariableAConstantExpression(Var, SemaRef.Context)) { 15796 // A reference initialized by a constant expression can never be 15797 // odr-used, so simply ignore it. 15798 if (!Var->getType()->isReferenceType() || 15799 (SemaRef.LangOpts.OpenMP && SemaRef.isOpenMPCapturedDecl(Var))) 15800 SemaRef.MaybeODRUseExprs.insert(E); 15801 } else if (OdrUseContext) { 15802 MarkVarDeclODRUsed(Var, Loc, SemaRef, 15803 /*MaxFunctionScopeIndex ptr*/ nullptr); 15804 } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) { 15805 // If this is a dependent context, we don't need to mark variables as 15806 // odr-used, but we may still need to track them for lambda capture. 15807 // FIXME: Do we also need to do this inside dependent typeid expressions 15808 // (which are modeled as unevaluated at this point)? 15809 const bool RefersToEnclosingScope = 15810 (SemaRef.CurContext != Var->getDeclContext() && 15811 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 15812 if (RefersToEnclosingScope) { 15813 LambdaScopeInfo *const LSI = 15814 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 15815 if (LSI && (!LSI->CallOperator || 15816 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 15817 // If a variable could potentially be odr-used, defer marking it so 15818 // until we finish analyzing the full expression for any 15819 // lvalue-to-rvalue 15820 // or discarded value conversions that would obviate odr-use. 15821 // Add it to the list of potential captures that will be analyzed 15822 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 15823 // unless the variable is a reference that was initialized by a constant 15824 // expression (this will never need to be captured or odr-used). 15825 assert(E && "Capture variable should be used in an expression."); 15826 if (!Var->getType()->isReferenceType() || 15827 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 15828 LSI->addPotentialCapture(E->IgnoreParens()); 15829 } 15830 } 15831 } 15832 } 15833 15834 /// Mark a variable referenced, and check whether it is odr-used 15835 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 15836 /// used directly for normal expressions referring to VarDecl. 15837 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 15838 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 15839 } 15840 15841 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 15842 Decl *D, Expr *E, bool MightBeOdrUse) { 15843 if (SemaRef.isInOpenMPDeclareTargetContext()) 15844 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 15845 15846 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 15847 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 15848 return; 15849 } 15850 15851 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 15852 15853 // If this is a call to a method via a cast, also mark the method in the 15854 // derived class used in case codegen can devirtualize the call. 15855 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 15856 if (!ME) 15857 return; 15858 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 15859 if (!MD) 15860 return; 15861 // Only attempt to devirtualize if this is truly a virtual call. 15862 bool IsVirtualCall = MD->isVirtual() && 15863 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 15864 if (!IsVirtualCall) 15865 return; 15866 15867 // If it's possible to devirtualize the call, mark the called function 15868 // referenced. 15869 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 15870 ME->getBase(), SemaRef.getLangOpts().AppleKext); 15871 if (DM) 15872 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 15873 } 15874 15875 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 15876 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 15877 // TODO: update this with DR# once a defect report is filed. 15878 // C++11 defect. The address of a pure member should not be an ODR use, even 15879 // if it's a qualified reference. 15880 bool OdrUse = true; 15881 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 15882 if (Method->isVirtual() && 15883 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 15884 OdrUse = false; 15885 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 15886 } 15887 15888 /// Perform reference-marking and odr-use handling for a MemberExpr. 15889 void Sema::MarkMemberReferenced(MemberExpr *E) { 15890 // C++11 [basic.def.odr]p2: 15891 // A non-overloaded function whose name appears as a potentially-evaluated 15892 // expression or a member of a set of candidate functions, if selected by 15893 // overload resolution when referred to from a potentially-evaluated 15894 // expression, is odr-used, unless it is a pure virtual function and its 15895 // name is not explicitly qualified. 15896 bool MightBeOdrUse = true; 15897 if (E->performsVirtualDispatch(getLangOpts())) { 15898 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 15899 if (Method->isPure()) 15900 MightBeOdrUse = false; 15901 } 15902 SourceLocation Loc = 15903 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 15904 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 15905 } 15906 15907 /// Perform marking for a reference to an arbitrary declaration. It 15908 /// marks the declaration referenced, and performs odr-use checking for 15909 /// functions and variables. This method should not be used when building a 15910 /// normal expression which refers to a variable. 15911 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 15912 bool MightBeOdrUse) { 15913 if (MightBeOdrUse) { 15914 if (auto *VD = dyn_cast<VarDecl>(D)) { 15915 MarkVariableReferenced(Loc, VD); 15916 return; 15917 } 15918 } 15919 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 15920 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 15921 return; 15922 } 15923 D->setReferenced(); 15924 } 15925 15926 namespace { 15927 // Mark all of the declarations used by a type as referenced. 15928 // FIXME: Not fully implemented yet! We need to have a better understanding 15929 // of when we're entering a context we should not recurse into. 15930 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 15931 // TreeTransforms rebuilding the type in a new context. Rather than 15932 // duplicating the TreeTransform logic, we should consider reusing it here. 15933 // Currently that causes problems when rebuilding LambdaExprs. 15934 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 15935 Sema &S; 15936 SourceLocation Loc; 15937 15938 public: 15939 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 15940 15941 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 15942 15943 bool TraverseTemplateArgument(const TemplateArgument &Arg); 15944 }; 15945 } 15946 15947 bool MarkReferencedDecls::TraverseTemplateArgument( 15948 const TemplateArgument &Arg) { 15949 { 15950 // A non-type template argument is a constant-evaluated context. 15951 EnterExpressionEvaluationContext Evaluated( 15952 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 15953 if (Arg.getKind() == TemplateArgument::Declaration) { 15954 if (Decl *D = Arg.getAsDecl()) 15955 S.MarkAnyDeclReferenced(Loc, D, true); 15956 } else if (Arg.getKind() == TemplateArgument::Expression) { 15957 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 15958 } 15959 } 15960 15961 return Inherited::TraverseTemplateArgument(Arg); 15962 } 15963 15964 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 15965 MarkReferencedDecls Marker(*this, Loc); 15966 Marker.TraverseType(T); 15967 } 15968 15969 namespace { 15970 /// Helper class that marks all of the declarations referenced by 15971 /// potentially-evaluated subexpressions as "referenced". 15972 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 15973 Sema &S; 15974 bool SkipLocalVariables; 15975 15976 public: 15977 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 15978 15979 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 15980 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 15981 15982 void VisitDeclRefExpr(DeclRefExpr *E) { 15983 // If we were asked not to visit local variables, don't. 15984 if (SkipLocalVariables) { 15985 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 15986 if (VD->hasLocalStorage()) 15987 return; 15988 } 15989 15990 S.MarkDeclRefReferenced(E); 15991 } 15992 15993 void VisitMemberExpr(MemberExpr *E) { 15994 S.MarkMemberReferenced(E); 15995 Inherited::VisitMemberExpr(E); 15996 } 15997 15998 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 15999 S.MarkFunctionReferenced( 16000 E->getBeginLoc(), 16001 const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor())); 16002 Visit(E->getSubExpr()); 16003 } 16004 16005 void VisitCXXNewExpr(CXXNewExpr *E) { 16006 if (E->getOperatorNew()) 16007 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew()); 16008 if (E->getOperatorDelete()) 16009 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete()); 16010 Inherited::VisitCXXNewExpr(E); 16011 } 16012 16013 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 16014 if (E->getOperatorDelete()) 16015 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete()); 16016 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 16017 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 16018 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 16019 S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record)); 16020 } 16021 16022 Inherited::VisitCXXDeleteExpr(E); 16023 } 16024 16025 void VisitCXXConstructExpr(CXXConstructExpr *E) { 16026 S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor()); 16027 Inherited::VisitCXXConstructExpr(E); 16028 } 16029 16030 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 16031 Visit(E->getExpr()); 16032 } 16033 16034 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 16035 Inherited::VisitImplicitCastExpr(E); 16036 16037 if (E->getCastKind() == CK_LValueToRValue) 16038 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 16039 } 16040 }; 16041 } 16042 16043 /// Mark any declarations that appear within this expression or any 16044 /// potentially-evaluated subexpressions as "referenced". 16045 /// 16046 /// \param SkipLocalVariables If true, don't mark local variables as 16047 /// 'referenced'. 16048 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 16049 bool SkipLocalVariables) { 16050 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 16051 } 16052 16053 /// Emit a diagnostic that describes an effect on the run-time behavior 16054 /// of the program being compiled. 16055 /// 16056 /// This routine emits the given diagnostic when the code currently being 16057 /// type-checked is "potentially evaluated", meaning that there is a 16058 /// possibility that the code will actually be executable. Code in sizeof() 16059 /// expressions, code used only during overload resolution, etc., are not 16060 /// potentially evaluated. This routine will suppress such diagnostics or, 16061 /// in the absolutely nutty case of potentially potentially evaluated 16062 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 16063 /// later. 16064 /// 16065 /// This routine should be used for all diagnostics that describe the run-time 16066 /// behavior of a program, such as passing a non-POD value through an ellipsis. 16067 /// Failure to do so will likely result in spurious diagnostics or failures 16068 /// during overload resolution or within sizeof/alignof/typeof/typeid. 16069 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 16070 const PartialDiagnostic &PD) { 16071 switch (ExprEvalContexts.back().Context) { 16072 case ExpressionEvaluationContext::Unevaluated: 16073 case ExpressionEvaluationContext::UnevaluatedList: 16074 case ExpressionEvaluationContext::UnevaluatedAbstract: 16075 case ExpressionEvaluationContext::DiscardedStatement: 16076 // The argument will never be evaluated, so don't complain. 16077 break; 16078 16079 case ExpressionEvaluationContext::ConstantEvaluated: 16080 // Relevant diagnostics should be produced by constant evaluation. 16081 break; 16082 16083 case ExpressionEvaluationContext::PotentiallyEvaluated: 16084 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16085 if (Statement && getCurFunctionOrMethodDecl()) { 16086 FunctionScopes.back()->PossiblyUnreachableDiags. 16087 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 16088 return true; 16089 } 16090 16091 // The initializer of a constexpr variable or of the first declaration of a 16092 // static data member is not syntactically a constant evaluated constant, 16093 // but nonetheless is always required to be a constant expression, so we 16094 // can skip diagnosing. 16095 // FIXME: Using the mangling context here is a hack. 16096 if (auto *VD = dyn_cast_or_null<VarDecl>( 16097 ExprEvalContexts.back().ManglingContextDecl)) { 16098 if (VD->isConstexpr() || 16099 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 16100 break; 16101 // FIXME: For any other kind of variable, we should build a CFG for its 16102 // initializer and check whether the context in question is reachable. 16103 } 16104 16105 Diag(Loc, PD); 16106 return true; 16107 } 16108 16109 return false; 16110 } 16111 16112 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 16113 CallExpr *CE, FunctionDecl *FD) { 16114 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 16115 return false; 16116 16117 // If we're inside a decltype's expression, don't check for a valid return 16118 // type or construct temporaries until we know whether this is the last call. 16119 if (ExprEvalContexts.back().ExprContext == 16120 ExpressionEvaluationContextRecord::EK_Decltype) { 16121 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 16122 return false; 16123 } 16124 16125 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 16126 FunctionDecl *FD; 16127 CallExpr *CE; 16128 16129 public: 16130 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 16131 : FD(FD), CE(CE) { } 16132 16133 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 16134 if (!FD) { 16135 S.Diag(Loc, diag::err_call_incomplete_return) 16136 << T << CE->getSourceRange(); 16137 return; 16138 } 16139 16140 S.Diag(Loc, diag::err_call_function_incomplete_return) 16141 << CE->getSourceRange() << FD->getDeclName() << T; 16142 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 16143 << FD->getDeclName(); 16144 } 16145 } Diagnoser(FD, CE); 16146 16147 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 16148 return true; 16149 16150 return false; 16151 } 16152 16153 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 16154 // will prevent this condition from triggering, which is what we want. 16155 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 16156 SourceLocation Loc; 16157 16158 unsigned diagnostic = diag::warn_condition_is_assignment; 16159 bool IsOrAssign = false; 16160 16161 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 16162 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 16163 return; 16164 16165 IsOrAssign = Op->getOpcode() == BO_OrAssign; 16166 16167 // Greylist some idioms by putting them into a warning subcategory. 16168 if (ObjCMessageExpr *ME 16169 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 16170 Selector Sel = ME->getSelector(); 16171 16172 // self = [<foo> init...] 16173 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 16174 diagnostic = diag::warn_condition_is_idiomatic_assignment; 16175 16176 // <foo> = [<bar> nextObject] 16177 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 16178 diagnostic = diag::warn_condition_is_idiomatic_assignment; 16179 } 16180 16181 Loc = Op->getOperatorLoc(); 16182 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 16183 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 16184 return; 16185 16186 IsOrAssign = Op->getOperator() == OO_PipeEqual; 16187 Loc = Op->getOperatorLoc(); 16188 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 16189 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 16190 else { 16191 // Not an assignment. 16192 return; 16193 } 16194 16195 Diag(Loc, diagnostic) << E->getSourceRange(); 16196 16197 SourceLocation Open = E->getBeginLoc(); 16198 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 16199 Diag(Loc, diag::note_condition_assign_silence) 16200 << FixItHint::CreateInsertion(Open, "(") 16201 << FixItHint::CreateInsertion(Close, ")"); 16202 16203 if (IsOrAssign) 16204 Diag(Loc, diag::note_condition_or_assign_to_comparison) 16205 << FixItHint::CreateReplacement(Loc, "!="); 16206 else 16207 Diag(Loc, diag::note_condition_assign_to_comparison) 16208 << FixItHint::CreateReplacement(Loc, "=="); 16209 } 16210 16211 /// Redundant parentheses over an equality comparison can indicate 16212 /// that the user intended an assignment used as condition. 16213 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 16214 // Don't warn if the parens came from a macro. 16215 SourceLocation parenLoc = ParenE->getBeginLoc(); 16216 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 16217 return; 16218 // Don't warn for dependent expressions. 16219 if (ParenE->isTypeDependent()) 16220 return; 16221 16222 Expr *E = ParenE->IgnoreParens(); 16223 16224 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 16225 if (opE->getOpcode() == BO_EQ && 16226 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 16227 == Expr::MLV_Valid) { 16228 SourceLocation Loc = opE->getOperatorLoc(); 16229 16230 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 16231 SourceRange ParenERange = ParenE->getSourceRange(); 16232 Diag(Loc, diag::note_equality_comparison_silence) 16233 << FixItHint::CreateRemoval(ParenERange.getBegin()) 16234 << FixItHint::CreateRemoval(ParenERange.getEnd()); 16235 Diag(Loc, diag::note_equality_comparison_to_assign) 16236 << FixItHint::CreateReplacement(Loc, "="); 16237 } 16238 } 16239 16240 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 16241 bool IsConstexpr) { 16242 DiagnoseAssignmentAsCondition(E); 16243 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 16244 DiagnoseEqualityWithExtraParens(parenE); 16245 16246 ExprResult result = CheckPlaceholderExpr(E); 16247 if (result.isInvalid()) return ExprError(); 16248 E = result.get(); 16249 16250 if (!E->isTypeDependent()) { 16251 if (getLangOpts().CPlusPlus) 16252 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 16253 16254 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 16255 if (ERes.isInvalid()) 16256 return ExprError(); 16257 E = ERes.get(); 16258 16259 QualType T = E->getType(); 16260 if (!T->isScalarType()) { // C99 6.8.4.1p1 16261 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 16262 << T << E->getSourceRange(); 16263 return ExprError(); 16264 } 16265 CheckBoolLikeConversion(E, Loc); 16266 } 16267 16268 return E; 16269 } 16270 16271 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 16272 Expr *SubExpr, ConditionKind CK) { 16273 // Empty conditions are valid in for-statements. 16274 if (!SubExpr) 16275 return ConditionResult(); 16276 16277 ExprResult Cond; 16278 switch (CK) { 16279 case ConditionKind::Boolean: 16280 Cond = CheckBooleanCondition(Loc, SubExpr); 16281 break; 16282 16283 case ConditionKind::ConstexprIf: 16284 Cond = CheckBooleanCondition(Loc, SubExpr, true); 16285 break; 16286 16287 case ConditionKind::Switch: 16288 Cond = CheckSwitchCondition(Loc, SubExpr); 16289 break; 16290 } 16291 if (Cond.isInvalid()) 16292 return ConditionError(); 16293 16294 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 16295 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 16296 if (!FullExpr.get()) 16297 return ConditionError(); 16298 16299 return ConditionResult(*this, nullptr, FullExpr, 16300 CK == ConditionKind::ConstexprIf); 16301 } 16302 16303 namespace { 16304 /// A visitor for rebuilding a call to an __unknown_any expression 16305 /// to have an appropriate type. 16306 struct RebuildUnknownAnyFunction 16307 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 16308 16309 Sema &S; 16310 16311 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 16312 16313 ExprResult VisitStmt(Stmt *S) { 16314 llvm_unreachable("unexpected statement!"); 16315 } 16316 16317 ExprResult VisitExpr(Expr *E) { 16318 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 16319 << E->getSourceRange(); 16320 return ExprError(); 16321 } 16322 16323 /// Rebuild an expression which simply semantically wraps another 16324 /// expression which it shares the type and value kind of. 16325 template <class T> ExprResult rebuildSugarExpr(T *E) { 16326 ExprResult SubResult = Visit(E->getSubExpr()); 16327 if (SubResult.isInvalid()) return ExprError(); 16328 16329 Expr *SubExpr = SubResult.get(); 16330 E->setSubExpr(SubExpr); 16331 E->setType(SubExpr->getType()); 16332 E->setValueKind(SubExpr->getValueKind()); 16333 assert(E->getObjectKind() == OK_Ordinary); 16334 return E; 16335 } 16336 16337 ExprResult VisitParenExpr(ParenExpr *E) { 16338 return rebuildSugarExpr(E); 16339 } 16340 16341 ExprResult VisitUnaryExtension(UnaryOperator *E) { 16342 return rebuildSugarExpr(E); 16343 } 16344 16345 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 16346 ExprResult SubResult = Visit(E->getSubExpr()); 16347 if (SubResult.isInvalid()) return ExprError(); 16348 16349 Expr *SubExpr = SubResult.get(); 16350 E->setSubExpr(SubExpr); 16351 E->setType(S.Context.getPointerType(SubExpr->getType())); 16352 assert(E->getValueKind() == VK_RValue); 16353 assert(E->getObjectKind() == OK_Ordinary); 16354 return E; 16355 } 16356 16357 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 16358 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 16359 16360 E->setType(VD->getType()); 16361 16362 assert(E->getValueKind() == VK_RValue); 16363 if (S.getLangOpts().CPlusPlus && 16364 !(isa<CXXMethodDecl>(VD) && 16365 cast<CXXMethodDecl>(VD)->isInstance())) 16366 E->setValueKind(VK_LValue); 16367 16368 return E; 16369 } 16370 16371 ExprResult VisitMemberExpr(MemberExpr *E) { 16372 return resolveDecl(E, E->getMemberDecl()); 16373 } 16374 16375 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 16376 return resolveDecl(E, E->getDecl()); 16377 } 16378 }; 16379 } 16380 16381 /// Given a function expression of unknown-any type, try to rebuild it 16382 /// to have a function type. 16383 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 16384 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 16385 if (Result.isInvalid()) return ExprError(); 16386 return S.DefaultFunctionArrayConversion(Result.get()); 16387 } 16388 16389 namespace { 16390 /// A visitor for rebuilding an expression of type __unknown_anytype 16391 /// into one which resolves the type directly on the referring 16392 /// expression. Strict preservation of the original source 16393 /// structure is not a goal. 16394 struct RebuildUnknownAnyExpr 16395 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 16396 16397 Sema &S; 16398 16399 /// The current destination type. 16400 QualType DestType; 16401 16402 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 16403 : S(S), DestType(CastType) {} 16404 16405 ExprResult VisitStmt(Stmt *S) { 16406 llvm_unreachable("unexpected statement!"); 16407 } 16408 16409 ExprResult VisitExpr(Expr *E) { 16410 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 16411 << E->getSourceRange(); 16412 return ExprError(); 16413 } 16414 16415 ExprResult VisitCallExpr(CallExpr *E); 16416 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 16417 16418 /// Rebuild an expression which simply semantically wraps another 16419 /// expression which it shares the type and value kind of. 16420 template <class T> ExprResult rebuildSugarExpr(T *E) { 16421 ExprResult SubResult = Visit(E->getSubExpr()); 16422 if (SubResult.isInvalid()) return ExprError(); 16423 Expr *SubExpr = SubResult.get(); 16424 E->setSubExpr(SubExpr); 16425 E->setType(SubExpr->getType()); 16426 E->setValueKind(SubExpr->getValueKind()); 16427 assert(E->getObjectKind() == OK_Ordinary); 16428 return E; 16429 } 16430 16431 ExprResult VisitParenExpr(ParenExpr *E) { 16432 return rebuildSugarExpr(E); 16433 } 16434 16435 ExprResult VisitUnaryExtension(UnaryOperator *E) { 16436 return rebuildSugarExpr(E); 16437 } 16438 16439 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 16440 const PointerType *Ptr = DestType->getAs<PointerType>(); 16441 if (!Ptr) { 16442 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 16443 << E->getSourceRange(); 16444 return ExprError(); 16445 } 16446 16447 if (isa<CallExpr>(E->getSubExpr())) { 16448 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 16449 << E->getSourceRange(); 16450 return ExprError(); 16451 } 16452 16453 assert(E->getValueKind() == VK_RValue); 16454 assert(E->getObjectKind() == OK_Ordinary); 16455 E->setType(DestType); 16456 16457 // Build the sub-expression as if it were an object of the pointee type. 16458 DestType = Ptr->getPointeeType(); 16459 ExprResult SubResult = Visit(E->getSubExpr()); 16460 if (SubResult.isInvalid()) return ExprError(); 16461 E->setSubExpr(SubResult.get()); 16462 return E; 16463 } 16464 16465 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 16466 16467 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 16468 16469 ExprResult VisitMemberExpr(MemberExpr *E) { 16470 return resolveDecl(E, E->getMemberDecl()); 16471 } 16472 16473 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 16474 return resolveDecl(E, E->getDecl()); 16475 } 16476 }; 16477 } 16478 16479 /// Rebuilds a call expression which yielded __unknown_anytype. 16480 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 16481 Expr *CalleeExpr = E->getCallee(); 16482 16483 enum FnKind { 16484 FK_MemberFunction, 16485 FK_FunctionPointer, 16486 FK_BlockPointer 16487 }; 16488 16489 FnKind Kind; 16490 QualType CalleeType = CalleeExpr->getType(); 16491 if (CalleeType == S.Context.BoundMemberTy) { 16492 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 16493 Kind = FK_MemberFunction; 16494 CalleeType = Expr::findBoundMemberType(CalleeExpr); 16495 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 16496 CalleeType = Ptr->getPointeeType(); 16497 Kind = FK_FunctionPointer; 16498 } else { 16499 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 16500 Kind = FK_BlockPointer; 16501 } 16502 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 16503 16504 // Verify that this is a legal result type of a function. 16505 if (DestType->isArrayType() || DestType->isFunctionType()) { 16506 unsigned diagID = diag::err_func_returning_array_function; 16507 if (Kind == FK_BlockPointer) 16508 diagID = diag::err_block_returning_array_function; 16509 16510 S.Diag(E->getExprLoc(), diagID) 16511 << DestType->isFunctionType() << DestType; 16512 return ExprError(); 16513 } 16514 16515 // Otherwise, go ahead and set DestType as the call's result. 16516 E->setType(DestType.getNonLValueExprType(S.Context)); 16517 E->setValueKind(Expr::getValueKindForType(DestType)); 16518 assert(E->getObjectKind() == OK_Ordinary); 16519 16520 // Rebuild the function type, replacing the result type with DestType. 16521 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 16522 if (Proto) { 16523 // __unknown_anytype(...) is a special case used by the debugger when 16524 // it has no idea what a function's signature is. 16525 // 16526 // We want to build this call essentially under the K&R 16527 // unprototyped rules, but making a FunctionNoProtoType in C++ 16528 // would foul up all sorts of assumptions. However, we cannot 16529 // simply pass all arguments as variadic arguments, nor can we 16530 // portably just call the function under a non-variadic type; see 16531 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 16532 // However, it turns out that in practice it is generally safe to 16533 // call a function declared as "A foo(B,C,D);" under the prototype 16534 // "A foo(B,C,D,...);". The only known exception is with the 16535 // Windows ABI, where any variadic function is implicitly cdecl 16536 // regardless of its normal CC. Therefore we change the parameter 16537 // types to match the types of the arguments. 16538 // 16539 // This is a hack, but it is far superior to moving the 16540 // corresponding target-specific code from IR-gen to Sema/AST. 16541 16542 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 16543 SmallVector<QualType, 8> ArgTypes; 16544 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 16545 ArgTypes.reserve(E->getNumArgs()); 16546 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 16547 Expr *Arg = E->getArg(i); 16548 QualType ArgType = Arg->getType(); 16549 if (E->isLValue()) { 16550 ArgType = S.Context.getLValueReferenceType(ArgType); 16551 } else if (E->isXValue()) { 16552 ArgType = S.Context.getRValueReferenceType(ArgType); 16553 } 16554 ArgTypes.push_back(ArgType); 16555 } 16556 ParamTypes = ArgTypes; 16557 } 16558 DestType = S.Context.getFunctionType(DestType, ParamTypes, 16559 Proto->getExtProtoInfo()); 16560 } else { 16561 DestType = S.Context.getFunctionNoProtoType(DestType, 16562 FnType->getExtInfo()); 16563 } 16564 16565 // Rebuild the appropriate pointer-to-function type. 16566 switch (Kind) { 16567 case FK_MemberFunction: 16568 // Nothing to do. 16569 break; 16570 16571 case FK_FunctionPointer: 16572 DestType = S.Context.getPointerType(DestType); 16573 break; 16574 16575 case FK_BlockPointer: 16576 DestType = S.Context.getBlockPointerType(DestType); 16577 break; 16578 } 16579 16580 // Finally, we can recurse. 16581 ExprResult CalleeResult = Visit(CalleeExpr); 16582 if (!CalleeResult.isUsable()) return ExprError(); 16583 E->setCallee(CalleeResult.get()); 16584 16585 // Bind a temporary if necessary. 16586 return S.MaybeBindToTemporary(E); 16587 } 16588 16589 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 16590 // Verify that this is a legal result type of a call. 16591 if (DestType->isArrayType() || DestType->isFunctionType()) { 16592 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 16593 << DestType->isFunctionType() << DestType; 16594 return ExprError(); 16595 } 16596 16597 // Rewrite the method result type if available. 16598 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 16599 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 16600 Method->setReturnType(DestType); 16601 } 16602 16603 // Change the type of the message. 16604 E->setType(DestType.getNonReferenceType()); 16605 E->setValueKind(Expr::getValueKindForType(DestType)); 16606 16607 return S.MaybeBindToTemporary(E); 16608 } 16609 16610 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 16611 // The only case we should ever see here is a function-to-pointer decay. 16612 if (E->getCastKind() == CK_FunctionToPointerDecay) { 16613 assert(E->getValueKind() == VK_RValue); 16614 assert(E->getObjectKind() == OK_Ordinary); 16615 16616 E->setType(DestType); 16617 16618 // Rebuild the sub-expression as the pointee (function) type. 16619 DestType = DestType->castAs<PointerType>()->getPointeeType(); 16620 16621 ExprResult Result = Visit(E->getSubExpr()); 16622 if (!Result.isUsable()) return ExprError(); 16623 16624 E->setSubExpr(Result.get()); 16625 return E; 16626 } else if (E->getCastKind() == CK_LValueToRValue) { 16627 assert(E->getValueKind() == VK_RValue); 16628 assert(E->getObjectKind() == OK_Ordinary); 16629 16630 assert(isa<BlockPointerType>(E->getType())); 16631 16632 E->setType(DestType); 16633 16634 // The sub-expression has to be a lvalue reference, so rebuild it as such. 16635 DestType = S.Context.getLValueReferenceType(DestType); 16636 16637 ExprResult Result = Visit(E->getSubExpr()); 16638 if (!Result.isUsable()) return ExprError(); 16639 16640 E->setSubExpr(Result.get()); 16641 return E; 16642 } else { 16643 llvm_unreachable("Unhandled cast type!"); 16644 } 16645 } 16646 16647 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 16648 ExprValueKind ValueKind = VK_LValue; 16649 QualType Type = DestType; 16650 16651 // We know how to make this work for certain kinds of decls: 16652 16653 // - functions 16654 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 16655 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 16656 DestType = Ptr->getPointeeType(); 16657 ExprResult Result = resolveDecl(E, VD); 16658 if (Result.isInvalid()) return ExprError(); 16659 return S.ImpCastExprToType(Result.get(), Type, 16660 CK_FunctionToPointerDecay, VK_RValue); 16661 } 16662 16663 if (!Type->isFunctionType()) { 16664 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 16665 << VD << E->getSourceRange(); 16666 return ExprError(); 16667 } 16668 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 16669 // We must match the FunctionDecl's type to the hack introduced in 16670 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 16671 // type. See the lengthy commentary in that routine. 16672 QualType FDT = FD->getType(); 16673 const FunctionType *FnType = FDT->castAs<FunctionType>(); 16674 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 16675 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 16676 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 16677 SourceLocation Loc = FD->getLocation(); 16678 FunctionDecl *NewFD = FunctionDecl::Create(S.Context, 16679 FD->getDeclContext(), 16680 Loc, Loc, FD->getNameInfo().getName(), 16681 DestType, FD->getTypeSourceInfo(), 16682 SC_None, false/*isInlineSpecified*/, 16683 FD->hasPrototype(), 16684 false/*isConstexprSpecified*/); 16685 16686 if (FD->getQualifier()) 16687 NewFD->setQualifierInfo(FD->getQualifierLoc()); 16688 16689 SmallVector<ParmVarDecl*, 16> Params; 16690 for (const auto &AI : FT->param_types()) { 16691 ParmVarDecl *Param = 16692 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 16693 Param->setScopeInfo(0, Params.size()); 16694 Params.push_back(Param); 16695 } 16696 NewFD->setParams(Params); 16697 DRE->setDecl(NewFD); 16698 VD = DRE->getDecl(); 16699 } 16700 } 16701 16702 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 16703 if (MD->isInstance()) { 16704 ValueKind = VK_RValue; 16705 Type = S.Context.BoundMemberTy; 16706 } 16707 16708 // Function references aren't l-values in C. 16709 if (!S.getLangOpts().CPlusPlus) 16710 ValueKind = VK_RValue; 16711 16712 // - variables 16713 } else if (isa<VarDecl>(VD)) { 16714 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 16715 Type = RefTy->getPointeeType(); 16716 } else if (Type->isFunctionType()) { 16717 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 16718 << VD << E->getSourceRange(); 16719 return ExprError(); 16720 } 16721 16722 // - nothing else 16723 } else { 16724 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 16725 << VD << E->getSourceRange(); 16726 return ExprError(); 16727 } 16728 16729 // Modifying the declaration like this is friendly to IR-gen but 16730 // also really dangerous. 16731 VD->setType(DestType); 16732 E->setType(Type); 16733 E->setValueKind(ValueKind); 16734 return E; 16735 } 16736 16737 /// Check a cast of an unknown-any type. We intentionally only 16738 /// trigger this for C-style casts. 16739 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 16740 Expr *CastExpr, CastKind &CastKind, 16741 ExprValueKind &VK, CXXCastPath &Path) { 16742 // The type we're casting to must be either void or complete. 16743 if (!CastType->isVoidType() && 16744 RequireCompleteType(TypeRange.getBegin(), CastType, 16745 diag::err_typecheck_cast_to_incomplete)) 16746 return ExprError(); 16747 16748 // Rewrite the casted expression from scratch. 16749 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 16750 if (!result.isUsable()) return ExprError(); 16751 16752 CastExpr = result.get(); 16753 VK = CastExpr->getValueKind(); 16754 CastKind = CK_NoOp; 16755 16756 return CastExpr; 16757 } 16758 16759 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 16760 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 16761 } 16762 16763 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 16764 Expr *arg, QualType ¶mType) { 16765 // If the syntactic form of the argument is not an explicit cast of 16766 // any sort, just do default argument promotion. 16767 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 16768 if (!castArg) { 16769 ExprResult result = DefaultArgumentPromotion(arg); 16770 if (result.isInvalid()) return ExprError(); 16771 paramType = result.get()->getType(); 16772 return result; 16773 } 16774 16775 // Otherwise, use the type that was written in the explicit cast. 16776 assert(!arg->hasPlaceholderType()); 16777 paramType = castArg->getTypeAsWritten(); 16778 16779 // Copy-initialize a parameter of that type. 16780 InitializedEntity entity = 16781 InitializedEntity::InitializeParameter(Context, paramType, 16782 /*consumed*/ false); 16783 return PerformCopyInitialization(entity, callLoc, arg); 16784 } 16785 16786 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 16787 Expr *orig = E; 16788 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 16789 while (true) { 16790 E = E->IgnoreParenImpCasts(); 16791 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 16792 E = call->getCallee(); 16793 diagID = diag::err_uncasted_call_of_unknown_any; 16794 } else { 16795 break; 16796 } 16797 } 16798 16799 SourceLocation loc; 16800 NamedDecl *d; 16801 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 16802 loc = ref->getLocation(); 16803 d = ref->getDecl(); 16804 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 16805 loc = mem->getMemberLoc(); 16806 d = mem->getMemberDecl(); 16807 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 16808 diagID = diag::err_uncasted_call_of_unknown_any; 16809 loc = msg->getSelectorStartLoc(); 16810 d = msg->getMethodDecl(); 16811 if (!d) { 16812 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 16813 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 16814 << orig->getSourceRange(); 16815 return ExprError(); 16816 } 16817 } else { 16818 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 16819 << E->getSourceRange(); 16820 return ExprError(); 16821 } 16822 16823 S.Diag(loc, diagID) << d << orig->getSourceRange(); 16824 16825 // Never recoverable. 16826 return ExprError(); 16827 } 16828 16829 /// Check for operands with placeholder types and complain if found. 16830 /// Returns ExprError() if there was an error and no recovery was possible. 16831 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 16832 if (!getLangOpts().CPlusPlus) { 16833 // C cannot handle TypoExpr nodes on either side of a binop because it 16834 // doesn't handle dependent types properly, so make sure any TypoExprs have 16835 // been dealt with before checking the operands. 16836 ExprResult Result = CorrectDelayedTyposInExpr(E); 16837 if (!Result.isUsable()) return ExprError(); 16838 E = Result.get(); 16839 } 16840 16841 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 16842 if (!placeholderType) return E; 16843 16844 switch (placeholderType->getKind()) { 16845 16846 // Overloaded expressions. 16847 case BuiltinType::Overload: { 16848 // Try to resolve a single function template specialization. 16849 // This is obligatory. 16850 ExprResult Result = E; 16851 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 16852 return Result; 16853 16854 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 16855 // leaves Result unchanged on failure. 16856 Result = E; 16857 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) 16858 return Result; 16859 16860 // If that failed, try to recover with a call. 16861 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 16862 /*complain*/ true); 16863 return Result; 16864 } 16865 16866 // Bound member functions. 16867 case BuiltinType::BoundMember: { 16868 ExprResult result = E; 16869 const Expr *BME = E->IgnoreParens(); 16870 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 16871 // Try to give a nicer diagnostic if it is a bound member that we recognize. 16872 if (isa<CXXPseudoDestructorExpr>(BME)) { 16873 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 16874 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 16875 if (ME->getMemberNameInfo().getName().getNameKind() == 16876 DeclarationName::CXXDestructorName) 16877 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 16878 } 16879 tryToRecoverWithCall(result, PD, 16880 /*complain*/ true); 16881 return result; 16882 } 16883 16884 // ARC unbridged casts. 16885 case BuiltinType::ARCUnbridgedCast: { 16886 Expr *realCast = stripARCUnbridgedCast(E); 16887 diagnoseARCUnbridgedCast(realCast); 16888 return realCast; 16889 } 16890 16891 // Expressions of unknown type. 16892 case BuiltinType::UnknownAny: 16893 return diagnoseUnknownAnyExpr(*this, E); 16894 16895 // Pseudo-objects. 16896 case BuiltinType::PseudoObject: 16897 return checkPseudoObjectRValue(E); 16898 16899 case BuiltinType::BuiltinFn: { 16900 // Accept __noop without parens by implicitly converting it to a call expr. 16901 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 16902 if (DRE) { 16903 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 16904 if (FD->getBuiltinID() == Builtin::BI__noop) { 16905 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 16906 CK_BuiltinFnToFnPtr) 16907 .get(); 16908 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 16909 VK_RValue, SourceLocation()); 16910 } 16911 } 16912 16913 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 16914 return ExprError(); 16915 } 16916 16917 // Expressions of unknown type. 16918 case BuiltinType::OMPArraySection: 16919 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 16920 return ExprError(); 16921 16922 // Everything else should be impossible. 16923 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 16924 case BuiltinType::Id: 16925 #include "clang/Basic/OpenCLImageTypes.def" 16926 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 16927 case BuiltinType::Id: 16928 #include "clang/Basic/OpenCLExtensionTypes.def" 16929 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 16930 #define PLACEHOLDER_TYPE(Id, SingletonId) 16931 #include "clang/AST/BuiltinTypes.def" 16932 break; 16933 } 16934 16935 llvm_unreachable("invalid placeholder type!"); 16936 } 16937 16938 bool Sema::CheckCaseExpression(Expr *E) { 16939 if (E->isTypeDependent()) 16940 return true; 16941 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 16942 return E->getType()->isIntegralOrEnumerationType(); 16943 return false; 16944 } 16945 16946 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 16947 ExprResult 16948 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 16949 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 16950 "Unknown Objective-C Boolean value!"); 16951 QualType BoolT = Context.ObjCBuiltinBoolTy; 16952 if (!Context.getBOOLDecl()) { 16953 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 16954 Sema::LookupOrdinaryName); 16955 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 16956 NamedDecl *ND = Result.getFoundDecl(); 16957 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 16958 Context.setBOOLDecl(TD); 16959 } 16960 } 16961 if (Context.getBOOLDecl()) 16962 BoolT = Context.getBOOLType(); 16963 return new (Context) 16964 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 16965 } 16966 16967 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 16968 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 16969 SourceLocation RParen) { 16970 16971 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 16972 16973 auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(), 16974 [&](const AvailabilitySpec &Spec) { 16975 return Spec.getPlatform() == Platform; 16976 }); 16977 16978 VersionTuple Version; 16979 if (Spec != AvailSpecs.end()) 16980 Version = Spec->getVersion(); 16981 16982 // The use of `@available` in the enclosing function should be analyzed to 16983 // warn when it's used inappropriately (i.e. not if(@available)). 16984 if (getCurFunctionOrMethodDecl()) 16985 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 16986 else if (getCurBlock() || getCurLambda()) 16987 getCurFunction()->HasPotentialAvailabilityViolations = true; 16988 16989 return new (Context) 16990 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 16991 } 16992