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 /// DiagnoseSentinelCalls - This routine checks whether a call or 337 /// message-send is to a declaration with the sentinel attribute, and 338 /// if so, it checks that the requirements of the sentinel are 339 /// satisfied. 340 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 341 ArrayRef<Expr *> Args) { 342 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 343 if (!attr) 344 return; 345 346 // The number of formal parameters of the declaration. 347 unsigned numFormalParams; 348 349 // The kind of declaration. This is also an index into a %select in 350 // the diagnostic. 351 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 352 353 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 354 numFormalParams = MD->param_size(); 355 calleeType = CT_Method; 356 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 357 numFormalParams = FD->param_size(); 358 calleeType = CT_Function; 359 } else if (isa<VarDecl>(D)) { 360 QualType type = cast<ValueDecl>(D)->getType(); 361 const FunctionType *fn = nullptr; 362 if (const PointerType *ptr = type->getAs<PointerType>()) { 363 fn = ptr->getPointeeType()->getAs<FunctionType>(); 364 if (!fn) return; 365 calleeType = CT_Function; 366 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 367 fn = ptr->getPointeeType()->castAs<FunctionType>(); 368 calleeType = CT_Block; 369 } else { 370 return; 371 } 372 373 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 374 numFormalParams = proto->getNumParams(); 375 } else { 376 numFormalParams = 0; 377 } 378 } else { 379 return; 380 } 381 382 // "nullPos" is the number of formal parameters at the end which 383 // effectively count as part of the variadic arguments. This is 384 // useful if you would prefer to not have *any* formal parameters, 385 // but the language forces you to have at least one. 386 unsigned nullPos = attr->getNullPos(); 387 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 388 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 389 390 // The number of arguments which should follow the sentinel. 391 unsigned numArgsAfterSentinel = attr->getSentinel(); 392 393 // If there aren't enough arguments for all the formal parameters, 394 // the sentinel, and the args after the sentinel, complain. 395 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 396 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 397 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 398 return; 399 } 400 401 // Otherwise, find the sentinel expression. 402 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 403 if (!sentinelExpr) return; 404 if (sentinelExpr->isValueDependent()) return; 405 if (Context.isSentinelNullExpr(sentinelExpr)) return; 406 407 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 408 // or 'NULL' if those are actually defined in the context. Only use 409 // 'nil' for ObjC methods, where it's much more likely that the 410 // variadic arguments form a list of object pointers. 411 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 412 std::string NullValue; 413 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 414 NullValue = "nil"; 415 else if (getLangOpts().CPlusPlus11) 416 NullValue = "nullptr"; 417 else if (PP.isMacroDefined("NULL")) 418 NullValue = "NULL"; 419 else 420 NullValue = "(void*) 0"; 421 422 if (MissingNilLoc.isInvalid()) 423 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 424 else 425 Diag(MissingNilLoc, diag::warn_missing_sentinel) 426 << int(calleeType) 427 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 428 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 429 } 430 431 SourceRange Sema::getExprRange(Expr *E) const { 432 return E ? E->getSourceRange() : SourceRange(); 433 } 434 435 //===----------------------------------------------------------------------===// 436 // Standard Promotions and Conversions 437 //===----------------------------------------------------------------------===// 438 439 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 440 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 441 // Handle any placeholder expressions which made it here. 442 if (E->getType()->isPlaceholderType()) { 443 ExprResult result = CheckPlaceholderExpr(E); 444 if (result.isInvalid()) return ExprError(); 445 E = result.get(); 446 } 447 448 QualType Ty = E->getType(); 449 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 450 451 if (Ty->isFunctionType()) { 452 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 453 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 454 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 455 return ExprError(); 456 457 E = ImpCastExprToType(E, Context.getPointerType(Ty), 458 CK_FunctionToPointerDecay).get(); 459 } else if (Ty->isArrayType()) { 460 // In C90 mode, arrays only promote to pointers if the array expression is 461 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 462 // type 'array of type' is converted to an expression that has type 'pointer 463 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 464 // that has type 'array of type' ...". The relevant change is "an lvalue" 465 // (C90) to "an expression" (C99). 466 // 467 // C++ 4.2p1: 468 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 469 // T" can be converted to an rvalue of type "pointer to T". 470 // 471 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 472 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 473 CK_ArrayToPointerDecay).get(); 474 } 475 return E; 476 } 477 478 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 479 // Check to see if we are dereferencing a null pointer. If so, 480 // and if not volatile-qualified, this is undefined behavior that the 481 // optimizer will delete, so warn about it. People sometimes try to use this 482 // to get a deterministic trap and are surprised by clang's behavior. This 483 // only handles the pattern "*null", which is a very syntactic check. 484 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 485 if (UO->getOpcode() == UO_Deref && 486 UO->getSubExpr()->IgnoreParenCasts()-> 487 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 488 !UO->getType().isVolatileQualified()) { 489 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 490 S.PDiag(diag::warn_indirection_through_null) 491 << UO->getSubExpr()->getSourceRange()); 492 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 493 S.PDiag(diag::note_indirection_through_null)); 494 } 495 } 496 497 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 498 SourceLocation AssignLoc, 499 const Expr* RHS) { 500 const ObjCIvarDecl *IV = OIRE->getDecl(); 501 if (!IV) 502 return; 503 504 DeclarationName MemberName = IV->getDeclName(); 505 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 506 if (!Member || !Member->isStr("isa")) 507 return; 508 509 const Expr *Base = OIRE->getBase(); 510 QualType BaseType = Base->getType(); 511 if (OIRE->isArrow()) 512 BaseType = BaseType->getPointeeType(); 513 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 514 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 515 ObjCInterfaceDecl *ClassDeclared = nullptr; 516 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 517 if (!ClassDeclared->getSuperClass() 518 && (*ClassDeclared->ivar_begin()) == IV) { 519 if (RHS) { 520 NamedDecl *ObjectSetClass = 521 S.LookupSingleName(S.TUScope, 522 &S.Context.Idents.get("object_setClass"), 523 SourceLocation(), S.LookupOrdinaryName); 524 if (ObjectSetClass) { 525 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 526 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 527 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 528 "object_setClass(") 529 << FixItHint::CreateReplacement( 530 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 531 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 532 } 533 else 534 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 535 } else { 536 NamedDecl *ObjectGetClass = 537 S.LookupSingleName(S.TUScope, 538 &S.Context.Idents.get("object_getClass"), 539 SourceLocation(), S.LookupOrdinaryName); 540 if (ObjectGetClass) 541 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 542 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 543 "object_getClass(") 544 << FixItHint::CreateReplacement( 545 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 546 else 547 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 548 } 549 S.Diag(IV->getLocation(), diag::note_ivar_decl); 550 } 551 } 552 } 553 554 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 555 // Handle any placeholder expressions which made it here. 556 if (E->getType()->isPlaceholderType()) { 557 ExprResult result = CheckPlaceholderExpr(E); 558 if (result.isInvalid()) return ExprError(); 559 E = result.get(); 560 } 561 562 // C++ [conv.lval]p1: 563 // A glvalue of a non-function, non-array type T can be 564 // converted to a prvalue. 565 if (!E->isGLValue()) return E; 566 567 QualType T = E->getType(); 568 assert(!T.isNull() && "r-value conversion on typeless expression?"); 569 570 // We don't want to throw lvalue-to-rvalue casts on top of 571 // expressions of certain types in C++. 572 if (getLangOpts().CPlusPlus && 573 (E->getType() == Context.OverloadTy || 574 T->isDependentType() || 575 T->isRecordType())) 576 return E; 577 578 // The C standard is actually really unclear on this point, and 579 // DR106 tells us what the result should be but not why. It's 580 // generally best to say that void types just doesn't undergo 581 // lvalue-to-rvalue at all. Note that expressions of unqualified 582 // 'void' type are never l-values, but qualified void can be. 583 if (T->isVoidType()) 584 return E; 585 586 // OpenCL usually rejects direct accesses to values of 'half' type. 587 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 588 T->isHalfType()) { 589 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 590 << 0 << T; 591 return ExprError(); 592 } 593 594 CheckForNullPointerDereference(*this, E); 595 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 596 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 597 &Context.Idents.get("object_getClass"), 598 SourceLocation(), LookupOrdinaryName); 599 if (ObjectGetClass) 600 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 601 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 602 << FixItHint::CreateReplacement( 603 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 604 else 605 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 606 } 607 else if (const ObjCIvarRefExpr *OIRE = 608 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 609 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 610 611 // C++ [conv.lval]p1: 612 // [...] If T is a non-class type, the type of the prvalue is the 613 // cv-unqualified version of T. Otherwise, the type of the 614 // rvalue is T. 615 // 616 // C99 6.3.2.1p2: 617 // If the lvalue has qualified type, the value has the unqualified 618 // version of the type of the lvalue; otherwise, the value has the 619 // type of the lvalue. 620 if (T.hasQualifiers()) 621 T = T.getUnqualifiedType(); 622 623 // Under the MS ABI, lock down the inheritance model now. 624 if (T->isMemberPointerType() && 625 Context.getTargetInfo().getCXXABI().isMicrosoft()) 626 (void)isCompleteType(E->getExprLoc(), T); 627 628 UpdateMarkingForLValueToRValue(E); 629 630 // Loading a __weak object implicitly retains the value, so we need a cleanup to 631 // balance that. 632 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 633 Cleanup.setExprNeedsCleanups(true); 634 635 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 636 nullptr, VK_RValue); 637 638 // C11 6.3.2.1p2: 639 // ... if the lvalue has atomic type, the value has the non-atomic version 640 // of the type of the lvalue ... 641 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 642 T = Atomic->getValueType().getUnqualifiedType(); 643 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 644 nullptr, VK_RValue); 645 } 646 647 return Res; 648 } 649 650 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 651 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 652 if (Res.isInvalid()) 653 return ExprError(); 654 Res = DefaultLvalueConversion(Res.get()); 655 if (Res.isInvalid()) 656 return ExprError(); 657 return Res; 658 } 659 660 /// CallExprUnaryConversions - a special case of an unary conversion 661 /// performed on a function designator of a call expression. 662 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 663 QualType Ty = E->getType(); 664 ExprResult Res = E; 665 // Only do implicit cast for a function type, but not for a pointer 666 // to function type. 667 if (Ty->isFunctionType()) { 668 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 669 CK_FunctionToPointerDecay).get(); 670 if (Res.isInvalid()) 671 return ExprError(); 672 } 673 Res = DefaultLvalueConversion(Res.get()); 674 if (Res.isInvalid()) 675 return ExprError(); 676 return Res.get(); 677 } 678 679 /// UsualUnaryConversions - Performs various conversions that are common to most 680 /// operators (C99 6.3). The conversions of array and function types are 681 /// sometimes suppressed. For example, the array->pointer conversion doesn't 682 /// apply if the array is an argument to the sizeof or address (&) operators. 683 /// In these instances, this routine should *not* be called. 684 ExprResult Sema::UsualUnaryConversions(Expr *E) { 685 // First, convert to an r-value. 686 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 687 if (Res.isInvalid()) 688 return ExprError(); 689 E = Res.get(); 690 691 QualType Ty = E->getType(); 692 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 693 694 // Half FP have to be promoted to float unless it is natively supported 695 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 696 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 697 698 // Try to perform integral promotions if the object has a theoretically 699 // promotable type. 700 if (Ty->isIntegralOrUnscopedEnumerationType()) { 701 // C99 6.3.1.1p2: 702 // 703 // The following may be used in an expression wherever an int or 704 // unsigned int may be used: 705 // - an object or expression with an integer type whose integer 706 // conversion rank is less than or equal to the rank of int 707 // and unsigned int. 708 // - A bit-field of type _Bool, int, signed int, or unsigned int. 709 // 710 // If an int can represent all values of the original type, the 711 // value is converted to an int; otherwise, it is converted to an 712 // unsigned int. These are called the integer promotions. All 713 // other types are unchanged by the integer promotions. 714 715 QualType PTy = Context.isPromotableBitField(E); 716 if (!PTy.isNull()) { 717 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 718 return E; 719 } 720 if (Ty->isPromotableIntegerType()) { 721 QualType PT = Context.getPromotedIntegerType(Ty); 722 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 723 return E; 724 } 725 } 726 return E; 727 } 728 729 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 730 /// do not have a prototype. Arguments that have type float or __fp16 731 /// are promoted to double. All other argument types are converted by 732 /// UsualUnaryConversions(). 733 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 734 QualType Ty = E->getType(); 735 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 736 737 ExprResult Res = UsualUnaryConversions(E); 738 if (Res.isInvalid()) 739 return ExprError(); 740 E = Res.get(); 741 742 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 743 // promote to double. 744 // Note that default argument promotion applies only to float (and 745 // half/fp16); it does not apply to _Float16. 746 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 747 if (BTy && (BTy->getKind() == BuiltinType::Half || 748 BTy->getKind() == BuiltinType::Float)) { 749 if (getLangOpts().OpenCL && 750 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 751 if (BTy->getKind() == BuiltinType::Half) { 752 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 753 } 754 } else { 755 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 756 } 757 } 758 759 // C++ performs lvalue-to-rvalue conversion as a default argument 760 // promotion, even on class types, but note: 761 // C++11 [conv.lval]p2: 762 // When an lvalue-to-rvalue conversion occurs in an unevaluated 763 // operand or a subexpression thereof the value contained in the 764 // referenced object is not accessed. Otherwise, if the glvalue 765 // has a class type, the conversion copy-initializes a temporary 766 // of type T from the glvalue and the result of the conversion 767 // is a prvalue for the temporary. 768 // FIXME: add some way to gate this entire thing for correctness in 769 // potentially potentially evaluated contexts. 770 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 771 ExprResult Temp = PerformCopyInitialization( 772 InitializedEntity::InitializeTemporary(E->getType()), 773 E->getExprLoc(), E); 774 if (Temp.isInvalid()) 775 return ExprError(); 776 E = Temp.get(); 777 } 778 779 return E; 780 } 781 782 /// Determine the degree of POD-ness for an expression. 783 /// Incomplete types are considered POD, since this check can be performed 784 /// when we're in an unevaluated context. 785 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 786 if (Ty->isIncompleteType()) { 787 // C++11 [expr.call]p7: 788 // After these conversions, if the argument does not have arithmetic, 789 // enumeration, pointer, pointer to member, or class type, the program 790 // is ill-formed. 791 // 792 // Since we've already performed array-to-pointer and function-to-pointer 793 // decay, the only such type in C++ is cv void. This also handles 794 // initializer lists as variadic arguments. 795 if (Ty->isVoidType()) 796 return VAK_Invalid; 797 798 if (Ty->isObjCObjectType()) 799 return VAK_Invalid; 800 return VAK_Valid; 801 } 802 803 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 804 return VAK_Invalid; 805 806 if (Ty.isCXX98PODType(Context)) 807 return VAK_Valid; 808 809 // C++11 [expr.call]p7: 810 // Passing a potentially-evaluated argument of class type (Clause 9) 811 // having a non-trivial copy constructor, a non-trivial move constructor, 812 // or a non-trivial destructor, with no corresponding parameter, 813 // is conditionally-supported with implementation-defined semantics. 814 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 815 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 816 if (!Record->hasNonTrivialCopyConstructor() && 817 !Record->hasNonTrivialMoveConstructor() && 818 !Record->hasNonTrivialDestructor()) 819 return VAK_ValidInCXX11; 820 821 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 822 return VAK_Valid; 823 824 if (Ty->isObjCObjectType()) 825 return VAK_Invalid; 826 827 if (getLangOpts().MSVCCompat) 828 return VAK_MSVCUndefined; 829 830 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 831 // permitted to reject them. We should consider doing so. 832 return VAK_Undefined; 833 } 834 835 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 836 // Don't allow one to pass an Objective-C interface to a vararg. 837 const QualType &Ty = E->getType(); 838 VarArgKind VAK = isValidVarArgType(Ty); 839 840 // Complain about passing non-POD types through varargs. 841 switch (VAK) { 842 case VAK_ValidInCXX11: 843 DiagRuntimeBehavior( 844 E->getBeginLoc(), nullptr, 845 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 846 LLVM_FALLTHROUGH; 847 case VAK_Valid: 848 if (Ty->isRecordType()) { 849 // This is unlikely to be what the user intended. If the class has a 850 // 'c_str' member function, the user probably meant to call that. 851 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 852 PDiag(diag::warn_pass_class_arg_to_vararg) 853 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 854 } 855 break; 856 857 case VAK_Undefined: 858 case VAK_MSVCUndefined: 859 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 860 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 861 << getLangOpts().CPlusPlus11 << Ty << CT); 862 break; 863 864 case VAK_Invalid: 865 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 866 Diag(E->getBeginLoc(), 867 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 868 << Ty << CT; 869 else if (Ty->isObjCObjectType()) 870 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 871 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 872 << Ty << CT); 873 else 874 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 875 << isa<InitListExpr>(E) << Ty << CT; 876 break; 877 } 878 } 879 880 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 881 /// will create a trap if the resulting type is not a POD type. 882 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 883 FunctionDecl *FDecl) { 884 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 885 // Strip the unbridged-cast placeholder expression off, if applicable. 886 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 887 (CT == VariadicMethod || 888 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 889 E = stripARCUnbridgedCast(E); 890 891 // Otherwise, do normal placeholder checking. 892 } else { 893 ExprResult ExprRes = CheckPlaceholderExpr(E); 894 if (ExprRes.isInvalid()) 895 return ExprError(); 896 E = ExprRes.get(); 897 } 898 } 899 900 ExprResult ExprRes = DefaultArgumentPromotion(E); 901 if (ExprRes.isInvalid()) 902 return ExprError(); 903 E = ExprRes.get(); 904 905 // Diagnostics regarding non-POD argument types are 906 // emitted along with format string checking in Sema::CheckFunctionCall(). 907 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 908 // Turn this into a trap. 909 CXXScopeSpec SS; 910 SourceLocation TemplateKWLoc; 911 UnqualifiedId Name; 912 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 913 E->getBeginLoc()); 914 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 915 /*HasTrailingLParen=*/true, 916 /*IsAddressOfOperand=*/false); 917 if (TrapFn.isInvalid()) 918 return ExprError(); 919 920 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 921 None, E->getEndLoc()); 922 if (Call.isInvalid()) 923 return ExprError(); 924 925 ExprResult Comma = 926 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 927 if (Comma.isInvalid()) 928 return ExprError(); 929 return Comma.get(); 930 } 931 932 if (!getLangOpts().CPlusPlus && 933 RequireCompleteType(E->getExprLoc(), E->getType(), 934 diag::err_call_incomplete_argument)) 935 return ExprError(); 936 937 return E; 938 } 939 940 /// Converts an integer to complex float type. Helper function of 941 /// UsualArithmeticConversions() 942 /// 943 /// \return false if the integer expression is an integer type and is 944 /// successfully converted to the complex type. 945 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 946 ExprResult &ComplexExpr, 947 QualType IntTy, 948 QualType ComplexTy, 949 bool SkipCast) { 950 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 951 if (SkipCast) return false; 952 if (IntTy->isIntegerType()) { 953 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 954 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 955 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 956 CK_FloatingRealToComplex); 957 } else { 958 assert(IntTy->isComplexIntegerType()); 959 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 960 CK_IntegralComplexToFloatingComplex); 961 } 962 return false; 963 } 964 965 /// Handle arithmetic conversion with complex types. Helper function of 966 /// UsualArithmeticConversions() 967 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 968 ExprResult &RHS, QualType LHSType, 969 QualType RHSType, 970 bool IsCompAssign) { 971 // if we have an integer operand, the result is the complex type. 972 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 973 /*skipCast*/false)) 974 return LHSType; 975 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 976 /*skipCast*/IsCompAssign)) 977 return RHSType; 978 979 // This handles complex/complex, complex/float, or float/complex. 980 // When both operands are complex, the shorter operand is converted to the 981 // type of the longer, and that is the type of the result. This corresponds 982 // to what is done when combining two real floating-point operands. 983 // The fun begins when size promotion occur across type domains. 984 // From H&S 6.3.4: When one operand is complex and the other is a real 985 // floating-point type, the less precise type is converted, within it's 986 // real or complex domain, to the precision of the other type. For example, 987 // when combining a "long double" with a "double _Complex", the 988 // "double _Complex" is promoted to "long double _Complex". 989 990 // Compute the rank of the two types, regardless of whether they are complex. 991 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 992 993 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 994 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 995 QualType LHSElementType = 996 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 997 QualType RHSElementType = 998 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 999 1000 QualType ResultType = S.Context.getComplexType(LHSElementType); 1001 if (Order < 0) { 1002 // Promote the precision of the LHS if not an assignment. 1003 ResultType = S.Context.getComplexType(RHSElementType); 1004 if (!IsCompAssign) { 1005 if (LHSComplexType) 1006 LHS = 1007 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1008 else 1009 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1010 } 1011 } else if (Order > 0) { 1012 // Promote the precision of the RHS. 1013 if (RHSComplexType) 1014 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1015 else 1016 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1017 } 1018 return ResultType; 1019 } 1020 1021 /// Handle arithmetic conversion from integer to float. Helper function 1022 /// of UsualArithmeticConversions() 1023 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1024 ExprResult &IntExpr, 1025 QualType FloatTy, QualType IntTy, 1026 bool ConvertFloat, bool ConvertInt) { 1027 if (IntTy->isIntegerType()) { 1028 if (ConvertInt) 1029 // Convert intExpr to the lhs floating point type. 1030 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1031 CK_IntegralToFloating); 1032 return FloatTy; 1033 } 1034 1035 // Convert both sides to the appropriate complex float. 1036 assert(IntTy->isComplexIntegerType()); 1037 QualType result = S.Context.getComplexType(FloatTy); 1038 1039 // _Complex int -> _Complex float 1040 if (ConvertInt) 1041 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1042 CK_IntegralComplexToFloatingComplex); 1043 1044 // float -> _Complex float 1045 if (ConvertFloat) 1046 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1047 CK_FloatingRealToComplex); 1048 1049 return result; 1050 } 1051 1052 /// Handle arithmethic conversion with floating point types. Helper 1053 /// function of UsualArithmeticConversions() 1054 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1055 ExprResult &RHS, QualType LHSType, 1056 QualType RHSType, bool IsCompAssign) { 1057 bool LHSFloat = LHSType->isRealFloatingType(); 1058 bool RHSFloat = RHSType->isRealFloatingType(); 1059 1060 // If we have two real floating types, convert the smaller operand 1061 // to the bigger result. 1062 if (LHSFloat && RHSFloat) { 1063 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1064 if (order > 0) { 1065 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1066 return LHSType; 1067 } 1068 1069 assert(order < 0 && "illegal float comparison"); 1070 if (!IsCompAssign) 1071 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1072 return RHSType; 1073 } 1074 1075 if (LHSFloat) { 1076 // Half FP has to be promoted to float unless it is natively supported 1077 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1078 LHSType = S.Context.FloatTy; 1079 1080 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1081 /*convertFloat=*/!IsCompAssign, 1082 /*convertInt=*/ true); 1083 } 1084 assert(RHSFloat); 1085 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1086 /*convertInt=*/ true, 1087 /*convertFloat=*/!IsCompAssign); 1088 } 1089 1090 /// Diagnose attempts to convert between __float128 and long double if 1091 /// there is no support for such conversion. Helper function of 1092 /// UsualArithmeticConversions(). 1093 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1094 QualType RHSType) { 1095 /* No issue converting if at least one of the types is not a floating point 1096 type or the two types have the same rank. 1097 */ 1098 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1099 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1100 return false; 1101 1102 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1103 "The remaining types must be floating point types."); 1104 1105 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1106 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1107 1108 QualType LHSElemType = LHSComplex ? 1109 LHSComplex->getElementType() : LHSType; 1110 QualType RHSElemType = RHSComplex ? 1111 RHSComplex->getElementType() : RHSType; 1112 1113 // No issue if the two types have the same representation 1114 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1115 &S.Context.getFloatTypeSemantics(RHSElemType)) 1116 return false; 1117 1118 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1119 RHSElemType == S.Context.LongDoubleTy); 1120 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1121 RHSElemType == S.Context.Float128Ty); 1122 1123 // We've handled the situation where __float128 and long double have the same 1124 // representation. We allow all conversions for all possible long double types 1125 // except PPC's double double. 1126 return Float128AndLongDouble && 1127 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1128 &llvm::APFloat::PPCDoubleDouble()); 1129 } 1130 1131 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1132 1133 namespace { 1134 /// These helper callbacks are placed in an anonymous namespace to 1135 /// permit their use as function template parameters. 1136 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1137 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1138 } 1139 1140 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1141 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1142 CK_IntegralComplexCast); 1143 } 1144 } 1145 1146 /// Handle integer arithmetic conversions. Helper function of 1147 /// UsualArithmeticConversions() 1148 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1149 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1150 ExprResult &RHS, QualType LHSType, 1151 QualType RHSType, bool IsCompAssign) { 1152 // The rules for this case are in C99 6.3.1.8 1153 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1154 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1155 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1156 if (LHSSigned == RHSSigned) { 1157 // Same signedness; use the higher-ranked type 1158 if (order >= 0) { 1159 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1160 return LHSType; 1161 } else if (!IsCompAssign) 1162 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1163 return RHSType; 1164 } else if (order != (LHSSigned ? 1 : -1)) { 1165 // The unsigned type has greater than or equal rank to the 1166 // signed type, so use the unsigned type 1167 if (RHSSigned) { 1168 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1169 return LHSType; 1170 } else if (!IsCompAssign) 1171 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1172 return RHSType; 1173 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1174 // The two types are different widths; if we are here, that 1175 // means the signed type is larger than the unsigned type, so 1176 // use the signed type. 1177 if (LHSSigned) { 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 { 1184 // The signed type is higher-ranked than the unsigned type, 1185 // but isn't actually any bigger (like unsigned int and long 1186 // on most 32-bit systems). Use the unsigned type corresponding 1187 // to the signed type. 1188 QualType result = 1189 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1190 RHS = (*doRHSCast)(S, RHS.get(), result); 1191 if (!IsCompAssign) 1192 LHS = (*doLHSCast)(S, LHS.get(), result); 1193 return result; 1194 } 1195 } 1196 1197 /// Handle conversions with GCC complex int extension. Helper function 1198 /// of UsualArithmeticConversions() 1199 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1200 ExprResult &RHS, QualType LHSType, 1201 QualType RHSType, 1202 bool IsCompAssign) { 1203 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1204 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1205 1206 if (LHSComplexInt && RHSComplexInt) { 1207 QualType LHSEltType = LHSComplexInt->getElementType(); 1208 QualType RHSEltType = RHSComplexInt->getElementType(); 1209 QualType ScalarType = 1210 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1211 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1212 1213 return S.Context.getComplexType(ScalarType); 1214 } 1215 1216 if (LHSComplexInt) { 1217 QualType LHSEltType = LHSComplexInt->getElementType(); 1218 QualType ScalarType = 1219 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1220 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1221 QualType ComplexType = S.Context.getComplexType(ScalarType); 1222 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1223 CK_IntegralRealToComplex); 1224 1225 return ComplexType; 1226 } 1227 1228 assert(RHSComplexInt); 1229 1230 QualType RHSEltType = RHSComplexInt->getElementType(); 1231 QualType ScalarType = 1232 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1233 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1234 QualType ComplexType = S.Context.getComplexType(ScalarType); 1235 1236 if (!IsCompAssign) 1237 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1238 CK_IntegralRealToComplex); 1239 return ComplexType; 1240 } 1241 1242 /// Return the rank of a given fixed point or integer type. The value itself 1243 /// doesn't matter, but the values must be increasing with proper increasing 1244 /// rank as described in N1169 4.1.1. 1245 static unsigned GetFixedPointRank(QualType Ty) { 1246 const auto *BTy = Ty->getAs<BuiltinType>(); 1247 assert(BTy && "Expected a builtin type."); 1248 1249 switch (BTy->getKind()) { 1250 case BuiltinType::ShortFract: 1251 case BuiltinType::UShortFract: 1252 case BuiltinType::SatShortFract: 1253 case BuiltinType::SatUShortFract: 1254 return 1; 1255 case BuiltinType::Fract: 1256 case BuiltinType::UFract: 1257 case BuiltinType::SatFract: 1258 case BuiltinType::SatUFract: 1259 return 2; 1260 case BuiltinType::LongFract: 1261 case BuiltinType::ULongFract: 1262 case BuiltinType::SatLongFract: 1263 case BuiltinType::SatULongFract: 1264 return 3; 1265 case BuiltinType::ShortAccum: 1266 case BuiltinType::UShortAccum: 1267 case BuiltinType::SatShortAccum: 1268 case BuiltinType::SatUShortAccum: 1269 return 4; 1270 case BuiltinType::Accum: 1271 case BuiltinType::UAccum: 1272 case BuiltinType::SatAccum: 1273 case BuiltinType::SatUAccum: 1274 return 5; 1275 case BuiltinType::LongAccum: 1276 case BuiltinType::ULongAccum: 1277 case BuiltinType::SatLongAccum: 1278 case BuiltinType::SatULongAccum: 1279 return 6; 1280 default: 1281 if (BTy->isInteger()) 1282 return 0; 1283 llvm_unreachable("Unexpected fixed point or integer type"); 1284 } 1285 } 1286 1287 /// handleFixedPointConversion - Fixed point operations between fixed 1288 /// point types and integers or other fixed point types do not fall under 1289 /// usual arithmetic conversion since these conversions could result in loss 1290 /// of precsision (N1169 4.1.4). These operations should be calculated with 1291 /// the full precision of their result type (N1169 4.1.6.2.1). 1292 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1293 QualType RHSTy) { 1294 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1295 "Expected at least one of the operands to be a fixed point type"); 1296 assert((LHSTy->isFixedPointOrIntegerType() || 1297 RHSTy->isFixedPointOrIntegerType()) && 1298 "Special fixed point arithmetic operation conversions are only " 1299 "applied to ints or other fixed point types"); 1300 1301 // If one operand has signed fixed-point type and the other operand has 1302 // unsigned fixed-point type, then the unsigned fixed-point operand is 1303 // converted to its corresponding signed fixed-point type and the resulting 1304 // type is the type of the converted operand. 1305 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1306 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1307 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1308 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1309 1310 // The result type is the type with the highest rank, whereby a fixed-point 1311 // conversion rank is always greater than an integer conversion rank; if the 1312 // type of either of the operands is a saturating fixedpoint type, the result 1313 // type shall be the saturating fixed-point type corresponding to the type 1314 // with the highest rank; the resulting value is converted (taking into 1315 // account rounding and overflow) to the precision of the resulting type. 1316 // Same ranks between signed and unsigned types are resolved earlier, so both 1317 // types are either signed or both unsigned at this point. 1318 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1319 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1320 1321 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1322 1323 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1324 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1325 1326 return ResultTy; 1327 } 1328 1329 /// UsualArithmeticConversions - Performs various conversions that are common to 1330 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1331 /// routine returns the first non-arithmetic type found. The client is 1332 /// responsible for emitting appropriate error diagnostics. 1333 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1334 bool IsCompAssign) { 1335 if (!IsCompAssign) { 1336 LHS = UsualUnaryConversions(LHS.get()); 1337 if (LHS.isInvalid()) 1338 return QualType(); 1339 } 1340 1341 RHS = UsualUnaryConversions(RHS.get()); 1342 if (RHS.isInvalid()) 1343 return QualType(); 1344 1345 // For conversion purposes, we ignore any qualifiers. 1346 // For example, "const float" and "float" are equivalent. 1347 QualType LHSType = 1348 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1349 QualType RHSType = 1350 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1351 1352 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1353 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1354 LHSType = AtomicLHS->getValueType(); 1355 1356 // If both types are identical, no conversion is needed. 1357 if (LHSType == RHSType) 1358 return LHSType; 1359 1360 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1361 // The caller can deal with this (e.g. pointer + int). 1362 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1363 return QualType(); 1364 1365 // Apply unary and bitfield promotions to the LHS's type. 1366 QualType LHSUnpromotedType = LHSType; 1367 if (LHSType->isPromotableIntegerType()) 1368 LHSType = Context.getPromotedIntegerType(LHSType); 1369 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1370 if (!LHSBitfieldPromoteTy.isNull()) 1371 LHSType = LHSBitfieldPromoteTy; 1372 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1373 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1374 1375 // If both types are identical, no conversion is needed. 1376 if (LHSType == RHSType) 1377 return LHSType; 1378 1379 // At this point, we have two different arithmetic types. 1380 1381 // Diagnose attempts to convert between __float128 and long double where 1382 // such conversions currently can't be handled. 1383 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1384 return QualType(); 1385 1386 // Handle complex types first (C99 6.3.1.8p1). 1387 if (LHSType->isComplexType() || RHSType->isComplexType()) 1388 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1389 IsCompAssign); 1390 1391 // Now handle "real" floating types (i.e. float, double, long double). 1392 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1393 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1394 IsCompAssign); 1395 1396 // Handle GCC complex int extension. 1397 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1398 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1399 IsCompAssign); 1400 1401 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1402 return handleFixedPointConversion(*this, LHSType, RHSType); 1403 1404 // Finally, we have two differing integer types. 1405 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1406 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1407 } 1408 1409 //===----------------------------------------------------------------------===// 1410 // Semantic Analysis for various Expression Types 1411 //===----------------------------------------------------------------------===// 1412 1413 1414 ExprResult 1415 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1416 SourceLocation DefaultLoc, 1417 SourceLocation RParenLoc, 1418 Expr *ControllingExpr, 1419 ArrayRef<ParsedType> ArgTypes, 1420 ArrayRef<Expr *> ArgExprs) { 1421 unsigned NumAssocs = ArgTypes.size(); 1422 assert(NumAssocs == ArgExprs.size()); 1423 1424 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1425 for (unsigned i = 0; i < NumAssocs; ++i) { 1426 if (ArgTypes[i]) 1427 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1428 else 1429 Types[i] = nullptr; 1430 } 1431 1432 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1433 ControllingExpr, 1434 llvm::makeArrayRef(Types, NumAssocs), 1435 ArgExprs); 1436 delete [] Types; 1437 return ER; 1438 } 1439 1440 ExprResult 1441 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1442 SourceLocation DefaultLoc, 1443 SourceLocation RParenLoc, 1444 Expr *ControllingExpr, 1445 ArrayRef<TypeSourceInfo *> Types, 1446 ArrayRef<Expr *> Exprs) { 1447 unsigned NumAssocs = Types.size(); 1448 assert(NumAssocs == Exprs.size()); 1449 1450 // Decay and strip qualifiers for the controlling expression type, and handle 1451 // placeholder type replacement. See committee discussion from WG14 DR423. 1452 { 1453 EnterExpressionEvaluationContext Unevaluated( 1454 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1455 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1456 if (R.isInvalid()) 1457 return ExprError(); 1458 ControllingExpr = R.get(); 1459 } 1460 1461 // The controlling expression is an unevaluated operand, so side effects are 1462 // likely unintended. 1463 if (!inTemplateInstantiation() && 1464 ControllingExpr->HasSideEffects(Context, false)) 1465 Diag(ControllingExpr->getExprLoc(), 1466 diag::warn_side_effects_unevaluated_context); 1467 1468 bool TypeErrorFound = false, 1469 IsResultDependent = ControllingExpr->isTypeDependent(), 1470 ContainsUnexpandedParameterPack 1471 = ControllingExpr->containsUnexpandedParameterPack(); 1472 1473 for (unsigned i = 0; i < NumAssocs; ++i) { 1474 if (Exprs[i]->containsUnexpandedParameterPack()) 1475 ContainsUnexpandedParameterPack = true; 1476 1477 if (Types[i]) { 1478 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1479 ContainsUnexpandedParameterPack = true; 1480 1481 if (Types[i]->getType()->isDependentType()) { 1482 IsResultDependent = true; 1483 } else { 1484 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1485 // complete object type other than a variably modified type." 1486 unsigned D = 0; 1487 if (Types[i]->getType()->isIncompleteType()) 1488 D = diag::err_assoc_type_incomplete; 1489 else if (!Types[i]->getType()->isObjectType()) 1490 D = diag::err_assoc_type_nonobject; 1491 else if (Types[i]->getType()->isVariablyModifiedType()) 1492 D = diag::err_assoc_type_variably_modified; 1493 1494 if (D != 0) { 1495 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1496 << Types[i]->getTypeLoc().getSourceRange() 1497 << Types[i]->getType(); 1498 TypeErrorFound = true; 1499 } 1500 1501 // C11 6.5.1.1p2 "No two generic associations in the same generic 1502 // selection shall specify compatible types." 1503 for (unsigned j = i+1; j < NumAssocs; ++j) 1504 if (Types[j] && !Types[j]->getType()->isDependentType() && 1505 Context.typesAreCompatible(Types[i]->getType(), 1506 Types[j]->getType())) { 1507 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1508 diag::err_assoc_compatible_types) 1509 << Types[j]->getTypeLoc().getSourceRange() 1510 << Types[j]->getType() 1511 << Types[i]->getType(); 1512 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1513 diag::note_compat_assoc) 1514 << Types[i]->getTypeLoc().getSourceRange() 1515 << Types[i]->getType(); 1516 TypeErrorFound = true; 1517 } 1518 } 1519 } 1520 } 1521 if (TypeErrorFound) 1522 return ExprError(); 1523 1524 // If we determined that the generic selection is result-dependent, don't 1525 // try to compute the result expression. 1526 if (IsResultDependent) 1527 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1528 Exprs, DefaultLoc, RParenLoc, 1529 ContainsUnexpandedParameterPack); 1530 1531 SmallVector<unsigned, 1> CompatIndices; 1532 unsigned DefaultIndex = -1U; 1533 for (unsigned i = 0; i < NumAssocs; ++i) { 1534 if (!Types[i]) 1535 DefaultIndex = i; 1536 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1537 Types[i]->getType())) 1538 CompatIndices.push_back(i); 1539 } 1540 1541 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1542 // type compatible with at most one of the types named in its generic 1543 // association list." 1544 if (CompatIndices.size() > 1) { 1545 // We strip parens here because the controlling expression is typically 1546 // parenthesized in macro definitions. 1547 ControllingExpr = ControllingExpr->IgnoreParens(); 1548 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1549 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1550 << (unsigned)CompatIndices.size(); 1551 for (unsigned I : CompatIndices) { 1552 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1553 diag::note_compat_assoc) 1554 << Types[I]->getTypeLoc().getSourceRange() 1555 << Types[I]->getType(); 1556 } 1557 return ExprError(); 1558 } 1559 1560 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1561 // its controlling expression shall have type compatible with exactly one of 1562 // the types named in its generic association list." 1563 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1564 // We strip parens here because the controlling expression is typically 1565 // parenthesized in macro definitions. 1566 ControllingExpr = ControllingExpr->IgnoreParens(); 1567 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1568 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1569 return ExprError(); 1570 } 1571 1572 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1573 // type name that is compatible with the type of the controlling expression, 1574 // then the result expression of the generic selection is the expression 1575 // in that generic association. Otherwise, the result expression of the 1576 // generic selection is the expression in the default generic association." 1577 unsigned ResultIndex = 1578 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1579 1580 return GenericSelectionExpr::Create( 1581 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1582 ContainsUnexpandedParameterPack, ResultIndex); 1583 } 1584 1585 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1586 /// location of the token and the offset of the ud-suffix within it. 1587 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1588 unsigned Offset) { 1589 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1590 S.getLangOpts()); 1591 } 1592 1593 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1594 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1595 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1596 IdentifierInfo *UDSuffix, 1597 SourceLocation UDSuffixLoc, 1598 ArrayRef<Expr*> Args, 1599 SourceLocation LitEndLoc) { 1600 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1601 1602 QualType ArgTy[2]; 1603 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1604 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1605 if (ArgTy[ArgIdx]->isArrayType()) 1606 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1607 } 1608 1609 DeclarationName OpName = 1610 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1611 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1612 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1613 1614 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1615 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1616 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1617 /*AllowStringTemplate*/ false, 1618 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1619 return ExprError(); 1620 1621 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1622 } 1623 1624 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1625 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1626 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1627 /// multiple tokens. However, the common case is that StringToks points to one 1628 /// string. 1629 /// 1630 ExprResult 1631 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1632 assert(!StringToks.empty() && "Must have at least one string!"); 1633 1634 StringLiteralParser Literal(StringToks, PP); 1635 if (Literal.hadError) 1636 return ExprError(); 1637 1638 SmallVector<SourceLocation, 4> StringTokLocs; 1639 for (const Token &Tok : StringToks) 1640 StringTokLocs.push_back(Tok.getLocation()); 1641 1642 QualType CharTy = Context.CharTy; 1643 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1644 if (Literal.isWide()) { 1645 CharTy = Context.getWideCharType(); 1646 Kind = StringLiteral::Wide; 1647 } else if (Literal.isUTF8()) { 1648 if (getLangOpts().Char8) 1649 CharTy = Context.Char8Ty; 1650 Kind = StringLiteral::UTF8; 1651 } else if (Literal.isUTF16()) { 1652 CharTy = Context.Char16Ty; 1653 Kind = StringLiteral::UTF16; 1654 } else if (Literal.isUTF32()) { 1655 CharTy = Context.Char32Ty; 1656 Kind = StringLiteral::UTF32; 1657 } else if (Literal.isPascal()) { 1658 CharTy = Context.UnsignedCharTy; 1659 } 1660 1661 // Warn on initializing an array of char from a u8 string literal; this 1662 // becomes ill-formed in C++2a. 1663 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus2a && 1664 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1665 Diag(StringTokLocs.front(), diag::warn_cxx2a_compat_utf8_string); 1666 1667 // Create removals for all 'u8' prefixes in the string literal(s). This 1668 // ensures C++2a compatibility (but may change the program behavior when 1669 // built by non-Clang compilers for which the execution character set is 1670 // not always UTF-8). 1671 auto RemovalDiag = PDiag(diag::note_cxx2a_compat_utf8_string_remove_u8); 1672 SourceLocation RemovalDiagLoc; 1673 for (const Token &Tok : StringToks) { 1674 if (Tok.getKind() == tok::utf8_string_literal) { 1675 if (RemovalDiagLoc.isInvalid()) 1676 RemovalDiagLoc = Tok.getLocation(); 1677 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1678 Tok.getLocation(), 1679 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1680 getSourceManager(), getLangOpts()))); 1681 } 1682 } 1683 Diag(RemovalDiagLoc, RemovalDiag); 1684 } 1685 1686 1687 QualType CharTyConst = CharTy; 1688 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1689 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1690 CharTyConst.addConst(); 1691 1692 CharTyConst = Context.adjustStringLiteralBaseType(CharTyConst); 1693 1694 // Get an array type for the string, according to C99 6.4.5. This includes 1695 // the nul terminator character as well as the string length for pascal 1696 // strings. 1697 QualType StrTy = Context.getConstantArrayType( 1698 CharTyConst, llvm::APInt(32, Literal.GetNumStringChars() + 1), 1699 ArrayType::Normal, 0); 1700 1701 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1702 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1703 Kind, Literal.Pascal, StrTy, 1704 &StringTokLocs[0], 1705 StringTokLocs.size()); 1706 if (Literal.getUDSuffix().empty()) 1707 return Lit; 1708 1709 // We're building a user-defined literal. 1710 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1711 SourceLocation UDSuffixLoc = 1712 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1713 Literal.getUDSuffixOffset()); 1714 1715 // Make sure we're allowed user-defined literals here. 1716 if (!UDLScope) 1717 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1718 1719 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1720 // operator "" X (str, len) 1721 QualType SizeType = Context.getSizeType(); 1722 1723 DeclarationName OpName = 1724 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1725 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1726 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1727 1728 QualType ArgTy[] = { 1729 Context.getArrayDecayedType(StrTy), SizeType 1730 }; 1731 1732 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1733 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1734 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1735 /*AllowStringTemplate*/ true, 1736 /*DiagnoseMissing*/ true)) { 1737 1738 case LOLR_Cooked: { 1739 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1740 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1741 StringTokLocs[0]); 1742 Expr *Args[] = { Lit, LenArg }; 1743 1744 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1745 } 1746 1747 case LOLR_StringTemplate: { 1748 TemplateArgumentListInfo ExplicitArgs; 1749 1750 unsigned CharBits = Context.getIntWidth(CharTy); 1751 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1752 llvm::APSInt Value(CharBits, CharIsUnsigned); 1753 1754 TemplateArgument TypeArg(CharTy); 1755 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1756 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1757 1758 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1759 Value = Lit->getCodeUnit(I); 1760 TemplateArgument Arg(Context, Value, CharTy); 1761 TemplateArgumentLocInfo ArgInfo; 1762 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1763 } 1764 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1765 &ExplicitArgs); 1766 } 1767 case LOLR_Raw: 1768 case LOLR_Template: 1769 case LOLR_ErrorNoDiagnostic: 1770 llvm_unreachable("unexpected literal operator lookup result"); 1771 case LOLR_Error: 1772 return ExprError(); 1773 } 1774 llvm_unreachable("unexpected literal operator lookup result"); 1775 } 1776 1777 ExprResult 1778 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1779 SourceLocation Loc, 1780 const CXXScopeSpec *SS) { 1781 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1782 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1783 } 1784 1785 /// BuildDeclRefExpr - Build an expression that references a 1786 /// declaration that does not require a closure capture. 1787 ExprResult 1788 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1789 const DeclarationNameInfo &NameInfo, 1790 const CXXScopeSpec *SS, NamedDecl *FoundD, 1791 const TemplateArgumentListInfo *TemplateArgs) { 1792 bool RefersToCapturedVariable = 1793 isa<VarDecl>(D) && 1794 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1795 1796 DeclRefExpr *E; 1797 if (isa<VarTemplateSpecializationDecl>(D)) { 1798 VarTemplateSpecializationDecl *VarSpec = 1799 cast<VarTemplateSpecializationDecl>(D); 1800 1801 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1802 : NestedNameSpecifierLoc(), 1803 VarSpec->getTemplateKeywordLoc(), D, 1804 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK, 1805 FoundD, TemplateArgs); 1806 } else { 1807 assert(!TemplateArgs && "No template arguments for non-variable" 1808 " template specialization references"); 1809 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1810 : NestedNameSpecifierLoc(), 1811 SourceLocation(), D, RefersToCapturedVariable, 1812 NameInfo, Ty, VK, FoundD); 1813 } 1814 1815 MarkDeclRefReferenced(E); 1816 1817 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1818 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 1819 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 1820 getCurFunction()->recordUseOfWeak(E); 1821 1822 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1823 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 1824 FD = IFD->getAnonField(); 1825 if (FD) { 1826 UnusedPrivateFields.remove(FD); 1827 // Just in case we're building an illegal pointer-to-member. 1828 if (FD->isBitField()) 1829 E->setObjectKind(OK_BitField); 1830 } 1831 1832 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1833 // designates a bit-field. 1834 if (auto *BD = dyn_cast<BindingDecl>(D)) 1835 if (auto *BE = BD->getBinding()) 1836 E->setObjectKind(BE->getObjectKind()); 1837 1838 return E; 1839 } 1840 1841 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1842 /// possibly a list of template arguments. 1843 /// 1844 /// If this produces template arguments, it is permitted to call 1845 /// DecomposeTemplateName. 1846 /// 1847 /// This actually loses a lot of source location information for 1848 /// non-standard name kinds; we should consider preserving that in 1849 /// some way. 1850 void 1851 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1852 TemplateArgumentListInfo &Buffer, 1853 DeclarationNameInfo &NameInfo, 1854 const TemplateArgumentListInfo *&TemplateArgs) { 1855 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 1856 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1857 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1858 1859 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1860 Id.TemplateId->NumArgs); 1861 translateTemplateArguments(TemplateArgsPtr, Buffer); 1862 1863 TemplateName TName = Id.TemplateId->Template.get(); 1864 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1865 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1866 TemplateArgs = &Buffer; 1867 } else { 1868 NameInfo = GetNameFromUnqualifiedId(Id); 1869 TemplateArgs = nullptr; 1870 } 1871 } 1872 1873 static void emitEmptyLookupTypoDiagnostic( 1874 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1875 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1876 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1877 DeclContext *Ctx = 1878 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1879 if (!TC) { 1880 // Emit a special diagnostic for failed member lookups. 1881 // FIXME: computing the declaration context might fail here (?) 1882 if (Ctx) 1883 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1884 << SS.getRange(); 1885 else 1886 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1887 return; 1888 } 1889 1890 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1891 bool DroppedSpecifier = 1892 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1893 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1894 ? diag::note_implicit_param_decl 1895 : diag::note_previous_decl; 1896 if (!Ctx) 1897 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1898 SemaRef.PDiag(NoteID)); 1899 else 1900 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1901 << Typo << Ctx << DroppedSpecifier 1902 << SS.getRange(), 1903 SemaRef.PDiag(NoteID)); 1904 } 1905 1906 /// Diagnose an empty lookup. 1907 /// 1908 /// \return false if new lookup candidates were found 1909 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1910 CorrectionCandidateCallback &CCC, 1911 TemplateArgumentListInfo *ExplicitTemplateArgs, 1912 ArrayRef<Expr *> Args, TypoExpr **Out) { 1913 DeclarationName Name = R.getLookupName(); 1914 1915 unsigned diagnostic = diag::err_undeclared_var_use; 1916 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1917 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1918 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1919 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1920 diagnostic = diag::err_undeclared_use; 1921 diagnostic_suggest = diag::err_undeclared_use_suggest; 1922 } 1923 1924 // If the original lookup was an unqualified lookup, fake an 1925 // unqualified lookup. This is useful when (for example) the 1926 // original lookup would not have found something because it was a 1927 // dependent name. 1928 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1929 while (DC) { 1930 if (isa<CXXRecordDecl>(DC)) { 1931 LookupQualifiedName(R, DC); 1932 1933 if (!R.empty()) { 1934 // Don't give errors about ambiguities in this lookup. 1935 R.suppressDiagnostics(); 1936 1937 // During a default argument instantiation the CurContext points 1938 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1939 // function parameter list, hence add an explicit check. 1940 bool isDefaultArgument = 1941 !CodeSynthesisContexts.empty() && 1942 CodeSynthesisContexts.back().Kind == 1943 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 1944 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1945 bool isInstance = CurMethod && 1946 CurMethod->isInstance() && 1947 DC == CurMethod->getParent() && !isDefaultArgument; 1948 1949 // Give a code modification hint to insert 'this->'. 1950 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1951 // Actually quite difficult! 1952 if (getLangOpts().MSVCCompat) 1953 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1954 if (isInstance) { 1955 Diag(R.getNameLoc(), diagnostic) << Name 1956 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1957 CheckCXXThisCapture(R.getNameLoc()); 1958 } else { 1959 Diag(R.getNameLoc(), diagnostic) << Name; 1960 } 1961 1962 // Do we really want to note all of these? 1963 for (NamedDecl *D : R) 1964 Diag(D->getLocation(), diag::note_dependent_var_use); 1965 1966 // Return true if we are inside a default argument instantiation 1967 // and the found name refers to an instance member function, otherwise 1968 // the function calling DiagnoseEmptyLookup will try to create an 1969 // implicit member call and this is wrong for default argument. 1970 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1971 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1972 return true; 1973 } 1974 1975 // Tell the callee to try to recover. 1976 return false; 1977 } 1978 1979 R.clear(); 1980 } 1981 1982 // In Microsoft mode, if we are performing lookup from within a friend 1983 // function definition declared at class scope then we must set 1984 // DC to the lexical parent to be able to search into the parent 1985 // class. 1986 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1987 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1988 DC->getLexicalParent()->isRecord()) 1989 DC = DC->getLexicalParent(); 1990 else 1991 DC = DC->getParent(); 1992 } 1993 1994 // We didn't find anything, so try to correct for a typo. 1995 TypoCorrection Corrected; 1996 if (S && Out) { 1997 SourceLocation TypoLoc = R.getNameLoc(); 1998 assert(!ExplicitTemplateArgs && 1999 "Diagnosing an empty lookup with explicit template args!"); 2000 *Out = CorrectTypoDelayed( 2001 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 2002 [=](const TypoCorrection &TC) { 2003 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2004 diagnostic, diagnostic_suggest); 2005 }, 2006 nullptr, CTK_ErrorRecovery); 2007 if (*Out) 2008 return true; 2009 } else if (S && 2010 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 2011 S, &SS, CCC, CTK_ErrorRecovery))) { 2012 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2013 bool DroppedSpecifier = 2014 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2015 R.setLookupName(Corrected.getCorrection()); 2016 2017 bool AcceptableWithRecovery = false; 2018 bool AcceptableWithoutRecovery = false; 2019 NamedDecl *ND = Corrected.getFoundDecl(); 2020 if (ND) { 2021 if (Corrected.isOverloaded()) { 2022 OverloadCandidateSet OCS(R.getNameLoc(), 2023 OverloadCandidateSet::CSK_Normal); 2024 OverloadCandidateSet::iterator Best; 2025 for (NamedDecl *CD : Corrected) { 2026 if (FunctionTemplateDecl *FTD = 2027 dyn_cast<FunctionTemplateDecl>(CD)) 2028 AddTemplateOverloadCandidate( 2029 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2030 Args, OCS); 2031 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2032 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2033 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2034 Args, OCS); 2035 } 2036 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2037 case OR_Success: 2038 ND = Best->FoundDecl; 2039 Corrected.setCorrectionDecl(ND); 2040 break; 2041 default: 2042 // FIXME: Arbitrarily pick the first declaration for the note. 2043 Corrected.setCorrectionDecl(ND); 2044 break; 2045 } 2046 } 2047 R.addDecl(ND); 2048 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2049 CXXRecordDecl *Record = nullptr; 2050 if (Corrected.getCorrectionSpecifier()) { 2051 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2052 Record = Ty->getAsCXXRecordDecl(); 2053 } 2054 if (!Record) 2055 Record = cast<CXXRecordDecl>( 2056 ND->getDeclContext()->getRedeclContext()); 2057 R.setNamingClass(Record); 2058 } 2059 2060 auto *UnderlyingND = ND->getUnderlyingDecl(); 2061 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2062 isa<FunctionTemplateDecl>(UnderlyingND); 2063 // FIXME: If we ended up with a typo for a type name or 2064 // Objective-C class name, we're in trouble because the parser 2065 // is in the wrong place to recover. Suggest the typo 2066 // correction, but don't make it a fix-it since we're not going 2067 // to recover well anyway. 2068 AcceptableWithoutRecovery = 2069 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND); 2070 } else { 2071 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2072 // because we aren't able to recover. 2073 AcceptableWithoutRecovery = true; 2074 } 2075 2076 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2077 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2078 ? diag::note_implicit_param_decl 2079 : diag::note_previous_decl; 2080 if (SS.isEmpty()) 2081 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2082 PDiag(NoteID), AcceptableWithRecovery); 2083 else 2084 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2085 << Name << computeDeclContext(SS, false) 2086 << DroppedSpecifier << SS.getRange(), 2087 PDiag(NoteID), AcceptableWithRecovery); 2088 2089 // Tell the callee whether to try to recover. 2090 return !AcceptableWithRecovery; 2091 } 2092 } 2093 R.clear(); 2094 2095 // Emit a special diagnostic for failed member lookups. 2096 // FIXME: computing the declaration context might fail here (?) 2097 if (!SS.isEmpty()) { 2098 Diag(R.getNameLoc(), diag::err_no_member) 2099 << Name << computeDeclContext(SS, false) 2100 << SS.getRange(); 2101 return true; 2102 } 2103 2104 // Give up, we can't recover. 2105 Diag(R.getNameLoc(), diagnostic) << Name; 2106 return true; 2107 } 2108 2109 /// In Microsoft mode, if we are inside a template class whose parent class has 2110 /// dependent base classes, and we can't resolve an unqualified identifier, then 2111 /// assume the identifier is a member of a dependent base class. We can only 2112 /// recover successfully in static methods, instance methods, and other contexts 2113 /// where 'this' is available. This doesn't precisely match MSVC's 2114 /// instantiation model, but it's close enough. 2115 static Expr * 2116 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2117 DeclarationNameInfo &NameInfo, 2118 SourceLocation TemplateKWLoc, 2119 const TemplateArgumentListInfo *TemplateArgs) { 2120 // Only try to recover from lookup into dependent bases in static methods or 2121 // contexts where 'this' is available. 2122 QualType ThisType = S.getCurrentThisType(); 2123 const CXXRecordDecl *RD = nullptr; 2124 if (!ThisType.isNull()) 2125 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2126 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2127 RD = MD->getParent(); 2128 if (!RD || !RD->hasAnyDependentBases()) 2129 return nullptr; 2130 2131 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2132 // is available, suggest inserting 'this->' as a fixit. 2133 SourceLocation Loc = NameInfo.getLoc(); 2134 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2135 DB << NameInfo.getName() << RD; 2136 2137 if (!ThisType.isNull()) { 2138 DB << FixItHint::CreateInsertion(Loc, "this->"); 2139 return CXXDependentScopeMemberExpr::Create( 2140 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2141 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2142 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 2143 } 2144 2145 // Synthesize a fake NNS that points to the derived class. This will 2146 // perform name lookup during template instantiation. 2147 CXXScopeSpec SS; 2148 auto *NNS = 2149 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2150 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2151 return DependentScopeDeclRefExpr::Create( 2152 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2153 TemplateArgs); 2154 } 2155 2156 ExprResult 2157 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2158 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2159 bool HasTrailingLParen, bool IsAddressOfOperand, 2160 CorrectionCandidateCallback *CCC, 2161 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2162 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2163 "cannot be direct & operand and have a trailing lparen"); 2164 if (SS.isInvalid()) 2165 return ExprError(); 2166 2167 TemplateArgumentListInfo TemplateArgsBuffer; 2168 2169 // Decompose the UnqualifiedId into the following data. 2170 DeclarationNameInfo NameInfo; 2171 const TemplateArgumentListInfo *TemplateArgs; 2172 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2173 2174 DeclarationName Name = NameInfo.getName(); 2175 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2176 SourceLocation NameLoc = NameInfo.getLoc(); 2177 2178 if (II && II->isEditorPlaceholder()) { 2179 // FIXME: When typed placeholders are supported we can create a typed 2180 // placeholder expression node. 2181 return ExprError(); 2182 } 2183 2184 // C++ [temp.dep.expr]p3: 2185 // An id-expression is type-dependent if it contains: 2186 // -- an identifier that was declared with a dependent type, 2187 // (note: handled after lookup) 2188 // -- a template-id that is dependent, 2189 // (note: handled in BuildTemplateIdExpr) 2190 // -- a conversion-function-id that specifies a dependent type, 2191 // -- a nested-name-specifier that contains a class-name that 2192 // names a dependent type. 2193 // Determine whether this is a member of an unknown specialization; 2194 // we need to handle these differently. 2195 bool DependentID = false; 2196 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2197 Name.getCXXNameType()->isDependentType()) { 2198 DependentID = true; 2199 } else if (SS.isSet()) { 2200 if (DeclContext *DC = computeDeclContext(SS, false)) { 2201 if (RequireCompleteDeclContext(SS, DC)) 2202 return ExprError(); 2203 } else { 2204 DependentID = true; 2205 } 2206 } 2207 2208 if (DependentID) 2209 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2210 IsAddressOfOperand, TemplateArgs); 2211 2212 // Perform the required lookup. 2213 LookupResult R(*this, NameInfo, 2214 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2215 ? LookupObjCImplicitSelfParam 2216 : LookupOrdinaryName); 2217 if (TemplateKWLoc.isValid() || TemplateArgs) { 2218 // Lookup the template name again to correctly establish the context in 2219 // which it was found. This is really unfortunate as we already did the 2220 // lookup to determine that it was a template name in the first place. If 2221 // this becomes a performance hit, we can work harder to preserve those 2222 // results until we get here but it's likely not worth it. 2223 bool MemberOfUnknownSpecialization; 2224 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2225 MemberOfUnknownSpecialization, TemplateKWLoc)) 2226 return ExprError(); 2227 2228 if (MemberOfUnknownSpecialization || 2229 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2230 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2231 IsAddressOfOperand, TemplateArgs); 2232 } else { 2233 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2234 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2235 2236 // If the result might be in a dependent base class, this is a dependent 2237 // id-expression. 2238 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2239 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2240 IsAddressOfOperand, TemplateArgs); 2241 2242 // If this reference is in an Objective-C method, then we need to do 2243 // some special Objective-C lookup, too. 2244 if (IvarLookupFollowUp) { 2245 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2246 if (E.isInvalid()) 2247 return ExprError(); 2248 2249 if (Expr *Ex = E.getAs<Expr>()) 2250 return Ex; 2251 } 2252 } 2253 2254 if (R.isAmbiguous()) 2255 return ExprError(); 2256 2257 // This could be an implicitly declared function reference (legal in C90, 2258 // extension in C99, forbidden in C++). 2259 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2260 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2261 if (D) R.addDecl(D); 2262 } 2263 2264 // Determine whether this name might be a candidate for 2265 // argument-dependent lookup. 2266 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2267 2268 if (R.empty() && !ADL) { 2269 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2270 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2271 TemplateKWLoc, TemplateArgs)) 2272 return E; 2273 } 2274 2275 // Don't diagnose an empty lookup for inline assembly. 2276 if (IsInlineAsmIdentifier) 2277 return ExprError(); 2278 2279 // If this name wasn't predeclared and if this is not a function 2280 // call, diagnose the problem. 2281 TypoExpr *TE = nullptr; 2282 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2283 : nullptr); 2284 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2285 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2286 "Typo correction callback misconfigured"); 2287 if (CCC) { 2288 // Make sure the callback knows what the typo being diagnosed is. 2289 CCC->setTypoName(II); 2290 if (SS.isValid()) 2291 CCC->setTypoNNS(SS.getScopeRep()); 2292 } 2293 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2294 // a template name, but we happen to have always already looked up the name 2295 // before we get here if it must be a template name. 2296 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2297 None, &TE)) { 2298 if (TE && KeywordReplacement) { 2299 auto &State = getTypoExprState(TE); 2300 auto BestTC = State.Consumer->getNextCorrection(); 2301 if (BestTC.isKeyword()) { 2302 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2303 if (State.DiagHandler) 2304 State.DiagHandler(BestTC); 2305 KeywordReplacement->startToken(); 2306 KeywordReplacement->setKind(II->getTokenID()); 2307 KeywordReplacement->setIdentifierInfo(II); 2308 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2309 // Clean up the state associated with the TypoExpr, since it has 2310 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2311 clearDelayedTypo(TE); 2312 // Signal that a correction to a keyword was performed by returning a 2313 // valid-but-null ExprResult. 2314 return (Expr*)nullptr; 2315 } 2316 State.Consumer->resetCorrectionStream(); 2317 } 2318 return TE ? TE : ExprError(); 2319 } 2320 2321 assert(!R.empty() && 2322 "DiagnoseEmptyLookup returned false but added no results"); 2323 2324 // If we found an Objective-C instance variable, let 2325 // LookupInObjCMethod build the appropriate expression to 2326 // reference the ivar. 2327 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2328 R.clear(); 2329 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2330 // In a hopelessly buggy code, Objective-C instance variable 2331 // lookup fails and no expression will be built to reference it. 2332 if (!E.isInvalid() && !E.get()) 2333 return ExprError(); 2334 return E; 2335 } 2336 } 2337 2338 // This is guaranteed from this point on. 2339 assert(!R.empty() || ADL); 2340 2341 // Check whether this might be a C++ implicit instance member access. 2342 // C++ [class.mfct.non-static]p3: 2343 // When an id-expression that is not part of a class member access 2344 // syntax and not used to form a pointer to member is used in the 2345 // body of a non-static member function of class X, if name lookup 2346 // resolves the name in the id-expression to a non-static non-type 2347 // member of some class C, the id-expression is transformed into a 2348 // class member access expression using (*this) as the 2349 // postfix-expression to the left of the . operator. 2350 // 2351 // But we don't actually need to do this for '&' operands if R 2352 // resolved to a function or overloaded function set, because the 2353 // expression is ill-formed if it actually works out to be a 2354 // non-static member function: 2355 // 2356 // C++ [expr.ref]p4: 2357 // Otherwise, if E1.E2 refers to a non-static member function. . . 2358 // [t]he expression can be used only as the left-hand operand of a 2359 // member function call. 2360 // 2361 // There are other safeguards against such uses, but it's important 2362 // to get this right here so that we don't end up making a 2363 // spuriously dependent expression if we're inside a dependent 2364 // instance method. 2365 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2366 bool MightBeImplicitMember; 2367 if (!IsAddressOfOperand) 2368 MightBeImplicitMember = true; 2369 else if (!SS.isEmpty()) 2370 MightBeImplicitMember = false; 2371 else if (R.isOverloadedResult()) 2372 MightBeImplicitMember = false; 2373 else if (R.isUnresolvableResult()) 2374 MightBeImplicitMember = true; 2375 else 2376 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2377 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2378 isa<MSPropertyDecl>(R.getFoundDecl()); 2379 2380 if (MightBeImplicitMember) 2381 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2382 R, TemplateArgs, S); 2383 } 2384 2385 if (TemplateArgs || TemplateKWLoc.isValid()) { 2386 2387 // In C++1y, if this is a variable template id, then check it 2388 // in BuildTemplateIdExpr(). 2389 // The single lookup result must be a variable template declaration. 2390 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2391 Id.TemplateId->Kind == TNK_Var_template) { 2392 assert(R.getAsSingle<VarTemplateDecl>() && 2393 "There should only be one declaration found."); 2394 } 2395 2396 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2397 } 2398 2399 return BuildDeclarationNameExpr(SS, R, ADL); 2400 } 2401 2402 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2403 /// declaration name, generally during template instantiation. 2404 /// There's a large number of things which don't need to be done along 2405 /// this path. 2406 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2407 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2408 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2409 DeclContext *DC = computeDeclContext(SS, false); 2410 if (!DC) 2411 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2412 NameInfo, /*TemplateArgs=*/nullptr); 2413 2414 if (RequireCompleteDeclContext(SS, DC)) 2415 return ExprError(); 2416 2417 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2418 LookupQualifiedName(R, DC); 2419 2420 if (R.isAmbiguous()) 2421 return ExprError(); 2422 2423 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2424 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2425 NameInfo, /*TemplateArgs=*/nullptr); 2426 2427 if (R.empty()) { 2428 Diag(NameInfo.getLoc(), diag::err_no_member) 2429 << NameInfo.getName() << DC << SS.getRange(); 2430 return ExprError(); 2431 } 2432 2433 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2434 // Diagnose a missing typename if this resolved unambiguously to a type in 2435 // a dependent context. If we can recover with a type, downgrade this to 2436 // a warning in Microsoft compatibility mode. 2437 unsigned DiagID = diag::err_typename_missing; 2438 if (RecoveryTSI && getLangOpts().MSVCCompat) 2439 DiagID = diag::ext_typename_missing; 2440 SourceLocation Loc = SS.getBeginLoc(); 2441 auto D = Diag(Loc, DiagID); 2442 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2443 << SourceRange(Loc, NameInfo.getEndLoc()); 2444 2445 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2446 // context. 2447 if (!RecoveryTSI) 2448 return ExprError(); 2449 2450 // Only issue the fixit if we're prepared to recover. 2451 D << FixItHint::CreateInsertion(Loc, "typename "); 2452 2453 // Recover by pretending this was an elaborated type. 2454 QualType Ty = Context.getTypeDeclType(TD); 2455 TypeLocBuilder TLB; 2456 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2457 2458 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2459 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2460 QTL.setElaboratedKeywordLoc(SourceLocation()); 2461 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2462 2463 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2464 2465 return ExprEmpty(); 2466 } 2467 2468 // Defend against this resolving to an implicit member access. We usually 2469 // won't get here if this might be a legitimate a class member (we end up in 2470 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2471 // a pointer-to-member or in an unevaluated context in C++11. 2472 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2473 return BuildPossibleImplicitMemberExpr(SS, 2474 /*TemplateKWLoc=*/SourceLocation(), 2475 R, /*TemplateArgs=*/nullptr, S); 2476 2477 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2478 } 2479 2480 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2481 /// detected that we're currently inside an ObjC method. Perform some 2482 /// additional lookup. 2483 /// 2484 /// Ideally, most of this would be done by lookup, but there's 2485 /// actually quite a lot of extra work involved. 2486 /// 2487 /// Returns a null sentinel to indicate trivial success. 2488 ExprResult 2489 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2490 IdentifierInfo *II, bool AllowBuiltinCreation) { 2491 SourceLocation Loc = Lookup.getNameLoc(); 2492 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2493 2494 // Check for error condition which is already reported. 2495 if (!CurMethod) 2496 return ExprError(); 2497 2498 // There are two cases to handle here. 1) scoped lookup could have failed, 2499 // in which case we should look for an ivar. 2) scoped lookup could have 2500 // found a decl, but that decl is outside the current instance method (i.e. 2501 // a global variable). In these two cases, we do a lookup for an ivar with 2502 // this name, if the lookup sucedes, we replace it our current decl. 2503 2504 // If we're in a class method, we don't normally want to look for 2505 // ivars. But if we don't find anything else, and there's an 2506 // ivar, that's an error. 2507 bool IsClassMethod = CurMethod->isClassMethod(); 2508 2509 bool LookForIvars; 2510 if (Lookup.empty()) 2511 LookForIvars = true; 2512 else if (IsClassMethod) 2513 LookForIvars = false; 2514 else 2515 LookForIvars = (Lookup.isSingleResult() && 2516 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2517 ObjCInterfaceDecl *IFace = nullptr; 2518 if (LookForIvars) { 2519 IFace = CurMethod->getClassInterface(); 2520 ObjCInterfaceDecl *ClassDeclared; 2521 ObjCIvarDecl *IV = nullptr; 2522 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2523 // Diagnose using an ivar in a class method. 2524 if (IsClassMethod) 2525 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2526 << IV->getDeclName()); 2527 2528 // If we're referencing an invalid decl, just return this as a silent 2529 // error node. The error diagnostic was already emitted on the decl. 2530 if (IV->isInvalidDecl()) 2531 return ExprError(); 2532 2533 // Check if referencing a field with __attribute__((deprecated)). 2534 if (DiagnoseUseOfDecl(IV, Loc)) 2535 return ExprError(); 2536 2537 // Diagnose the use of an ivar outside of the declaring class. 2538 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2539 !declaresSameEntity(ClassDeclared, IFace) && 2540 !getLangOpts().DebuggerSupport) 2541 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2542 2543 // FIXME: This should use a new expr for a direct reference, don't 2544 // turn this into Self->ivar, just return a BareIVarExpr or something. 2545 IdentifierInfo &II = Context.Idents.get("self"); 2546 UnqualifiedId SelfName; 2547 SelfName.setIdentifier(&II, SourceLocation()); 2548 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam); 2549 CXXScopeSpec SelfScopeSpec; 2550 SourceLocation TemplateKWLoc; 2551 ExprResult SelfExpr = 2552 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2553 /*HasTrailingLParen=*/false, 2554 /*IsAddressOfOperand=*/false); 2555 if (SelfExpr.isInvalid()) 2556 return ExprError(); 2557 2558 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2559 if (SelfExpr.isInvalid()) 2560 return ExprError(); 2561 2562 MarkAnyDeclReferenced(Loc, IV, true); 2563 2564 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2565 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2566 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2567 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2568 2569 ObjCIvarRefExpr *Result = new (Context) 2570 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2571 IV->getLocation(), SelfExpr.get(), true, true); 2572 2573 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2574 if (!isUnevaluatedContext() && 2575 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2576 getCurFunction()->recordUseOfWeak(Result); 2577 } 2578 if (getLangOpts().ObjCAutoRefCount) 2579 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2580 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2581 2582 return Result; 2583 } 2584 } else if (CurMethod->isInstanceMethod()) { 2585 // We should warn if a local variable hides an ivar. 2586 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2587 ObjCInterfaceDecl *ClassDeclared; 2588 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2589 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2590 declaresSameEntity(IFace, ClassDeclared)) 2591 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2592 } 2593 } 2594 } else if (Lookup.isSingleResult() && 2595 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2596 // If accessing a stand-alone ivar in a class method, this is an error. 2597 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2598 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2599 << IV->getDeclName()); 2600 } 2601 2602 if (Lookup.empty() && II && AllowBuiltinCreation) { 2603 // FIXME. Consolidate this with similar code in LookupName. 2604 if (unsigned BuiltinID = II->getBuiltinID()) { 2605 if (!(getLangOpts().CPlusPlus && 2606 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2607 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2608 S, Lookup.isForRedeclaration(), 2609 Lookup.getNameLoc()); 2610 if (D) Lookup.addDecl(D); 2611 } 2612 } 2613 } 2614 // Sentinel value saying that we didn't do anything special. 2615 return ExprResult((Expr *)nullptr); 2616 } 2617 2618 /// Cast a base object to a member's actual type. 2619 /// 2620 /// Logically this happens in three phases: 2621 /// 2622 /// * First we cast from the base type to the naming class. 2623 /// The naming class is the class into which we were looking 2624 /// when we found the member; it's the qualifier type if a 2625 /// qualifier was provided, and otherwise it's the base type. 2626 /// 2627 /// * Next we cast from the naming class to the declaring class. 2628 /// If the member we found was brought into a class's scope by 2629 /// a using declaration, this is that class; otherwise it's 2630 /// the class declaring the member. 2631 /// 2632 /// * Finally we cast from the declaring class to the "true" 2633 /// declaring class of the member. This conversion does not 2634 /// obey access control. 2635 ExprResult 2636 Sema::PerformObjectMemberConversion(Expr *From, 2637 NestedNameSpecifier *Qualifier, 2638 NamedDecl *FoundDecl, 2639 NamedDecl *Member) { 2640 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2641 if (!RD) 2642 return From; 2643 2644 QualType DestRecordType; 2645 QualType DestType; 2646 QualType FromRecordType; 2647 QualType FromType = From->getType(); 2648 bool PointerConversions = false; 2649 if (isa<FieldDecl>(Member)) { 2650 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2651 auto FromPtrType = FromType->getAs<PointerType>(); 2652 DestRecordType = Context.getAddrSpaceQualType( 2653 DestRecordType, FromPtrType 2654 ? FromType->getPointeeType().getAddressSpace() 2655 : FromType.getAddressSpace()); 2656 2657 if (FromPtrType) { 2658 DestType = Context.getPointerType(DestRecordType); 2659 FromRecordType = FromPtrType->getPointeeType(); 2660 PointerConversions = true; 2661 } else { 2662 DestType = DestRecordType; 2663 FromRecordType = FromType; 2664 } 2665 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2666 if (Method->isStatic()) 2667 return From; 2668 2669 DestType = Method->getThisType(); 2670 DestRecordType = DestType->getPointeeType(); 2671 2672 if (FromType->getAs<PointerType>()) { 2673 FromRecordType = FromType->getPointeeType(); 2674 PointerConversions = true; 2675 } else { 2676 FromRecordType = FromType; 2677 DestType = DestRecordType; 2678 } 2679 } else { 2680 // No conversion necessary. 2681 return From; 2682 } 2683 2684 if (DestType->isDependentType() || FromType->isDependentType()) 2685 return From; 2686 2687 // If the unqualified types are the same, no conversion is necessary. 2688 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2689 return From; 2690 2691 SourceRange FromRange = From->getSourceRange(); 2692 SourceLocation FromLoc = FromRange.getBegin(); 2693 2694 ExprValueKind VK = From->getValueKind(); 2695 2696 // C++ [class.member.lookup]p8: 2697 // [...] Ambiguities can often be resolved by qualifying a name with its 2698 // class name. 2699 // 2700 // If the member was a qualified name and the qualified referred to a 2701 // specific base subobject type, we'll cast to that intermediate type 2702 // first and then to the object in which the member is declared. That allows 2703 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2704 // 2705 // class Base { public: int x; }; 2706 // class Derived1 : public Base { }; 2707 // class Derived2 : public Base { }; 2708 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2709 // 2710 // void VeryDerived::f() { 2711 // x = 17; // error: ambiguous base subobjects 2712 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2713 // } 2714 if (Qualifier && Qualifier->getAsType()) { 2715 QualType QType = QualType(Qualifier->getAsType(), 0); 2716 assert(QType->isRecordType() && "lookup done with non-record type"); 2717 2718 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2719 2720 // In C++98, the qualifier type doesn't actually have to be a base 2721 // type of the object type, in which case we just ignore it. 2722 // Otherwise build the appropriate casts. 2723 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2724 CXXCastPath BasePath; 2725 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2726 FromLoc, FromRange, &BasePath)) 2727 return ExprError(); 2728 2729 if (PointerConversions) 2730 QType = Context.getPointerType(QType); 2731 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2732 VK, &BasePath).get(); 2733 2734 FromType = QType; 2735 FromRecordType = QRecordType; 2736 2737 // If the qualifier type was the same as the destination type, 2738 // we're done. 2739 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2740 return From; 2741 } 2742 } 2743 2744 bool IgnoreAccess = false; 2745 2746 // If we actually found the member through a using declaration, cast 2747 // down to the using declaration's type. 2748 // 2749 // Pointer equality is fine here because only one declaration of a 2750 // class ever has member declarations. 2751 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2752 assert(isa<UsingShadowDecl>(FoundDecl)); 2753 QualType URecordType = Context.getTypeDeclType( 2754 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2755 2756 // We only need to do this if the naming-class to declaring-class 2757 // conversion is non-trivial. 2758 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2759 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2760 CXXCastPath BasePath; 2761 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2762 FromLoc, FromRange, &BasePath)) 2763 return ExprError(); 2764 2765 QualType UType = URecordType; 2766 if (PointerConversions) 2767 UType = Context.getPointerType(UType); 2768 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2769 VK, &BasePath).get(); 2770 FromType = UType; 2771 FromRecordType = URecordType; 2772 } 2773 2774 // We don't do access control for the conversion from the 2775 // declaring class to the true declaring class. 2776 IgnoreAccess = true; 2777 } 2778 2779 CXXCastPath BasePath; 2780 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2781 FromLoc, FromRange, &BasePath, 2782 IgnoreAccess)) 2783 return ExprError(); 2784 2785 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2786 VK, &BasePath); 2787 } 2788 2789 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2790 const LookupResult &R, 2791 bool HasTrailingLParen) { 2792 // Only when used directly as the postfix-expression of a call. 2793 if (!HasTrailingLParen) 2794 return false; 2795 2796 // Never if a scope specifier was provided. 2797 if (SS.isSet()) 2798 return false; 2799 2800 // Only in C++ or ObjC++. 2801 if (!getLangOpts().CPlusPlus) 2802 return false; 2803 2804 // Turn off ADL when we find certain kinds of declarations during 2805 // normal lookup: 2806 for (NamedDecl *D : R) { 2807 // C++0x [basic.lookup.argdep]p3: 2808 // -- a declaration of a class member 2809 // Since using decls preserve this property, we check this on the 2810 // original decl. 2811 if (D->isCXXClassMember()) 2812 return false; 2813 2814 // C++0x [basic.lookup.argdep]p3: 2815 // -- a block-scope function declaration that is not a 2816 // using-declaration 2817 // NOTE: we also trigger this for function templates (in fact, we 2818 // don't check the decl type at all, since all other decl types 2819 // turn off ADL anyway). 2820 if (isa<UsingShadowDecl>(D)) 2821 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2822 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2823 return false; 2824 2825 // C++0x [basic.lookup.argdep]p3: 2826 // -- a declaration that is neither a function or a function 2827 // template 2828 // And also for builtin functions. 2829 if (isa<FunctionDecl>(D)) { 2830 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2831 2832 // But also builtin functions. 2833 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2834 return false; 2835 } else if (!isa<FunctionTemplateDecl>(D)) 2836 return false; 2837 } 2838 2839 return true; 2840 } 2841 2842 2843 /// Diagnoses obvious problems with the use of the given declaration 2844 /// as an expression. This is only actually called for lookups that 2845 /// were not overloaded, and it doesn't promise that the declaration 2846 /// will in fact be used. 2847 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2848 if (D->isInvalidDecl()) 2849 return true; 2850 2851 if (isa<TypedefNameDecl>(D)) { 2852 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2853 return true; 2854 } 2855 2856 if (isa<ObjCInterfaceDecl>(D)) { 2857 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2858 return true; 2859 } 2860 2861 if (isa<NamespaceDecl>(D)) { 2862 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2863 return true; 2864 } 2865 2866 return false; 2867 } 2868 2869 // Certain multiversion types should be treated as overloaded even when there is 2870 // only one result. 2871 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 2872 assert(R.isSingleResult() && "Expected only a single result"); 2873 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 2874 return FD && 2875 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 2876 } 2877 2878 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2879 LookupResult &R, bool NeedsADL, 2880 bool AcceptInvalidDecl) { 2881 // If this is a single, fully-resolved result and we don't need ADL, 2882 // just build an ordinary singleton decl ref. 2883 if (!NeedsADL && R.isSingleResult() && 2884 !R.getAsSingle<FunctionTemplateDecl>() && 2885 !ShouldLookupResultBeMultiVersionOverload(R)) 2886 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2887 R.getRepresentativeDecl(), nullptr, 2888 AcceptInvalidDecl); 2889 2890 // We only need to check the declaration if there's exactly one 2891 // result, because in the overloaded case the results can only be 2892 // functions and function templates. 2893 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 2894 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2895 return ExprError(); 2896 2897 // Otherwise, just build an unresolved lookup expression. Suppress 2898 // any lookup-related diagnostics; we'll hash these out later, when 2899 // we've picked a target. 2900 R.suppressDiagnostics(); 2901 2902 UnresolvedLookupExpr *ULE 2903 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2904 SS.getWithLocInContext(Context), 2905 R.getLookupNameInfo(), 2906 NeedsADL, R.isOverloadedResult(), 2907 R.begin(), R.end()); 2908 2909 return ULE; 2910 } 2911 2912 static void 2913 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 2914 ValueDecl *var, DeclContext *DC); 2915 2916 /// Complete semantic analysis for a reference to the given declaration. 2917 ExprResult Sema::BuildDeclarationNameExpr( 2918 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2919 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2920 bool AcceptInvalidDecl) { 2921 assert(D && "Cannot refer to a NULL declaration"); 2922 assert(!isa<FunctionTemplateDecl>(D) && 2923 "Cannot refer unambiguously to a function template"); 2924 2925 SourceLocation Loc = NameInfo.getLoc(); 2926 if (CheckDeclInExpr(*this, Loc, D)) 2927 return ExprError(); 2928 2929 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2930 // Specifically diagnose references to class templates that are missing 2931 // a template argument list. 2932 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 2933 return ExprError(); 2934 } 2935 2936 // Make sure that we're referring to a value. 2937 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2938 if (!VD) { 2939 Diag(Loc, diag::err_ref_non_value) 2940 << D << SS.getRange(); 2941 Diag(D->getLocation(), diag::note_declared_at); 2942 return ExprError(); 2943 } 2944 2945 // Check whether this declaration can be used. Note that we suppress 2946 // this check when we're going to perform argument-dependent lookup 2947 // on this function name, because this might not be the function 2948 // that overload resolution actually selects. 2949 if (DiagnoseUseOfDecl(VD, Loc)) 2950 return ExprError(); 2951 2952 // Only create DeclRefExpr's for valid Decl's. 2953 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2954 return ExprError(); 2955 2956 // Handle members of anonymous structs and unions. If we got here, 2957 // and the reference is to a class member indirect field, then this 2958 // must be the subject of a pointer-to-member expression. 2959 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2960 if (!indirectField->isCXXClassMember()) 2961 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2962 indirectField); 2963 2964 { 2965 QualType type = VD->getType(); 2966 if (type.isNull()) 2967 return ExprError(); 2968 if (auto *FPT = type->getAs<FunctionProtoType>()) { 2969 // C++ [except.spec]p17: 2970 // An exception-specification is considered to be needed when: 2971 // - in an expression, the function is the unique lookup result or 2972 // the selected member of a set of overloaded functions. 2973 ResolveExceptionSpec(Loc, FPT); 2974 type = VD->getType(); 2975 } 2976 ExprValueKind valueKind = VK_RValue; 2977 2978 switch (D->getKind()) { 2979 // Ignore all the non-ValueDecl kinds. 2980 #define ABSTRACT_DECL(kind) 2981 #define VALUE(type, base) 2982 #define DECL(type, base) \ 2983 case Decl::type: 2984 #include "clang/AST/DeclNodes.inc" 2985 llvm_unreachable("invalid value decl kind"); 2986 2987 // These shouldn't make it here. 2988 case Decl::ObjCAtDefsField: 2989 llvm_unreachable("forming non-member reference to ivar?"); 2990 2991 // Enum constants are always r-values and never references. 2992 // Unresolved using declarations are dependent. 2993 case Decl::EnumConstant: 2994 case Decl::UnresolvedUsingValue: 2995 case Decl::OMPDeclareReduction: 2996 case Decl::OMPDeclareMapper: 2997 valueKind = VK_RValue; 2998 break; 2999 3000 // Fields and indirect fields that got here must be for 3001 // pointer-to-member expressions; we just call them l-values for 3002 // internal consistency, because this subexpression doesn't really 3003 // exist in the high-level semantics. 3004 case Decl::Field: 3005 case Decl::IndirectField: 3006 case Decl::ObjCIvar: 3007 assert(getLangOpts().CPlusPlus && 3008 "building reference to field in C?"); 3009 3010 // These can't have reference type in well-formed programs, but 3011 // for internal consistency we do this anyway. 3012 type = type.getNonReferenceType(); 3013 valueKind = VK_LValue; 3014 break; 3015 3016 // Non-type template parameters are either l-values or r-values 3017 // depending on the type. 3018 case Decl::NonTypeTemplateParm: { 3019 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3020 type = reftype->getPointeeType(); 3021 valueKind = VK_LValue; // even if the parameter is an r-value reference 3022 break; 3023 } 3024 3025 // For non-references, we need to strip qualifiers just in case 3026 // the template parameter was declared as 'const int' or whatever. 3027 valueKind = VK_RValue; 3028 type = type.getUnqualifiedType(); 3029 break; 3030 } 3031 3032 case Decl::Var: 3033 case Decl::VarTemplateSpecialization: 3034 case Decl::VarTemplatePartialSpecialization: 3035 case Decl::Decomposition: 3036 case Decl::OMPCapturedExpr: 3037 // In C, "extern void blah;" is valid and is an r-value. 3038 if (!getLangOpts().CPlusPlus && 3039 !type.hasQualifiers() && 3040 type->isVoidType()) { 3041 valueKind = VK_RValue; 3042 break; 3043 } 3044 LLVM_FALLTHROUGH; 3045 3046 case Decl::ImplicitParam: 3047 case Decl::ParmVar: { 3048 // These are always l-values. 3049 valueKind = VK_LValue; 3050 type = type.getNonReferenceType(); 3051 3052 // FIXME: Does the addition of const really only apply in 3053 // potentially-evaluated contexts? Since the variable isn't actually 3054 // captured in an unevaluated context, it seems that the answer is no. 3055 if (!isUnevaluatedContext()) { 3056 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3057 if (!CapturedType.isNull()) 3058 type = CapturedType; 3059 } 3060 3061 break; 3062 } 3063 3064 case Decl::Binding: { 3065 // These are always lvalues. 3066 valueKind = VK_LValue; 3067 type = type.getNonReferenceType(); 3068 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3069 // decides how that's supposed to work. 3070 auto *BD = cast<BindingDecl>(VD); 3071 if (BD->getDeclContext()->isFunctionOrMethod() && 3072 BD->getDeclContext() != CurContext) 3073 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 3074 break; 3075 } 3076 3077 case Decl::Function: { 3078 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3079 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3080 type = Context.BuiltinFnTy; 3081 valueKind = VK_RValue; 3082 break; 3083 } 3084 } 3085 3086 const FunctionType *fty = type->castAs<FunctionType>(); 3087 3088 // If we're referring to a function with an __unknown_anytype 3089 // result type, make the entire expression __unknown_anytype. 3090 if (fty->getReturnType() == Context.UnknownAnyTy) { 3091 type = Context.UnknownAnyTy; 3092 valueKind = VK_RValue; 3093 break; 3094 } 3095 3096 // Functions are l-values in C++. 3097 if (getLangOpts().CPlusPlus) { 3098 valueKind = VK_LValue; 3099 break; 3100 } 3101 3102 // C99 DR 316 says that, if a function type comes from a 3103 // function definition (without a prototype), that type is only 3104 // used for checking compatibility. Therefore, when referencing 3105 // the function, we pretend that we don't have the full function 3106 // type. 3107 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3108 isa<FunctionProtoType>(fty)) 3109 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3110 fty->getExtInfo()); 3111 3112 // Functions are r-values in C. 3113 valueKind = VK_RValue; 3114 break; 3115 } 3116 3117 case Decl::CXXDeductionGuide: 3118 llvm_unreachable("building reference to deduction guide"); 3119 3120 case Decl::MSProperty: 3121 valueKind = VK_LValue; 3122 break; 3123 3124 case Decl::CXXMethod: 3125 // If we're referring to a method with an __unknown_anytype 3126 // result type, make the entire expression __unknown_anytype. 3127 // This should only be possible with a type written directly. 3128 if (const FunctionProtoType *proto 3129 = dyn_cast<FunctionProtoType>(VD->getType())) 3130 if (proto->getReturnType() == Context.UnknownAnyTy) { 3131 type = Context.UnknownAnyTy; 3132 valueKind = VK_RValue; 3133 break; 3134 } 3135 3136 // C++ methods are l-values if static, r-values if non-static. 3137 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3138 valueKind = VK_LValue; 3139 break; 3140 } 3141 LLVM_FALLTHROUGH; 3142 3143 case Decl::CXXConversion: 3144 case Decl::CXXDestructor: 3145 case Decl::CXXConstructor: 3146 valueKind = VK_RValue; 3147 break; 3148 } 3149 3150 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3151 TemplateArgs); 3152 } 3153 } 3154 3155 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3156 SmallString<32> &Target) { 3157 Target.resize(CharByteWidth * (Source.size() + 1)); 3158 char *ResultPtr = &Target[0]; 3159 const llvm::UTF8 *ErrorPtr; 3160 bool success = 3161 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3162 (void)success; 3163 assert(success); 3164 Target.resize(ResultPtr - &Target[0]); 3165 } 3166 3167 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3168 PredefinedExpr::IdentKind IK) { 3169 // Pick the current block, lambda, captured statement or function. 3170 Decl *currentDecl = nullptr; 3171 if (const BlockScopeInfo *BSI = getCurBlock()) 3172 currentDecl = BSI->TheDecl; 3173 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3174 currentDecl = LSI->CallOperator; 3175 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3176 currentDecl = CSI->TheCapturedDecl; 3177 else 3178 currentDecl = getCurFunctionOrMethodDecl(); 3179 3180 if (!currentDecl) { 3181 Diag(Loc, diag::ext_predef_outside_function); 3182 currentDecl = Context.getTranslationUnitDecl(); 3183 } 3184 3185 QualType ResTy; 3186 StringLiteral *SL = nullptr; 3187 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3188 ResTy = Context.DependentTy; 3189 else { 3190 // Pre-defined identifiers are of type char[x], where x is the length of 3191 // the string. 3192 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3193 unsigned Length = Str.length(); 3194 3195 llvm::APInt LengthI(32, Length + 1); 3196 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3197 ResTy = 3198 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3199 SmallString<32> RawChars; 3200 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3201 Str, RawChars); 3202 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3203 /*IndexTypeQuals*/ 0); 3204 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3205 /*Pascal*/ false, ResTy, Loc); 3206 } else { 3207 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3208 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3209 /*IndexTypeQuals*/ 0); 3210 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3211 /*Pascal*/ false, ResTy, Loc); 3212 } 3213 } 3214 3215 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3216 } 3217 3218 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3219 PredefinedExpr::IdentKind IK; 3220 3221 switch (Kind) { 3222 default: llvm_unreachable("Unknown simple primary expr!"); 3223 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3224 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3225 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3226 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3227 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3228 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3229 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3230 } 3231 3232 return BuildPredefinedExpr(Loc, IK); 3233 } 3234 3235 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3236 SmallString<16> CharBuffer; 3237 bool Invalid = false; 3238 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3239 if (Invalid) 3240 return ExprError(); 3241 3242 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3243 PP, Tok.getKind()); 3244 if (Literal.hadError()) 3245 return ExprError(); 3246 3247 QualType Ty; 3248 if (Literal.isWide()) 3249 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3250 else if (Literal.isUTF8() && getLangOpts().Char8) 3251 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3252 else if (Literal.isUTF16()) 3253 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3254 else if (Literal.isUTF32()) 3255 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3256 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3257 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3258 else 3259 Ty = Context.CharTy; // 'x' -> char in C++ 3260 3261 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3262 if (Literal.isWide()) 3263 Kind = CharacterLiteral::Wide; 3264 else if (Literal.isUTF16()) 3265 Kind = CharacterLiteral::UTF16; 3266 else if (Literal.isUTF32()) 3267 Kind = CharacterLiteral::UTF32; 3268 else if (Literal.isUTF8()) 3269 Kind = CharacterLiteral::UTF8; 3270 3271 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3272 Tok.getLocation()); 3273 3274 if (Literal.getUDSuffix().empty()) 3275 return Lit; 3276 3277 // We're building a user-defined literal. 3278 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3279 SourceLocation UDSuffixLoc = 3280 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3281 3282 // Make sure we're allowed user-defined literals here. 3283 if (!UDLScope) 3284 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3285 3286 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3287 // operator "" X (ch) 3288 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3289 Lit, Tok.getLocation()); 3290 } 3291 3292 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3293 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3294 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3295 Context.IntTy, Loc); 3296 } 3297 3298 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3299 QualType Ty, SourceLocation Loc) { 3300 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3301 3302 using llvm::APFloat; 3303 APFloat Val(Format); 3304 3305 APFloat::opStatus result = Literal.GetFloatValue(Val); 3306 3307 // Overflow is always an error, but underflow is only an error if 3308 // we underflowed to zero (APFloat reports denormals as underflow). 3309 if ((result & APFloat::opOverflow) || 3310 ((result & APFloat::opUnderflow) && Val.isZero())) { 3311 unsigned diagnostic; 3312 SmallString<20> buffer; 3313 if (result & APFloat::opOverflow) { 3314 diagnostic = diag::warn_float_overflow; 3315 APFloat::getLargest(Format).toString(buffer); 3316 } else { 3317 diagnostic = diag::warn_float_underflow; 3318 APFloat::getSmallest(Format).toString(buffer); 3319 } 3320 3321 S.Diag(Loc, diagnostic) 3322 << Ty 3323 << StringRef(buffer.data(), buffer.size()); 3324 } 3325 3326 bool isExact = (result == APFloat::opOK); 3327 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3328 } 3329 3330 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3331 assert(E && "Invalid expression"); 3332 3333 if (E->isValueDependent()) 3334 return false; 3335 3336 QualType QT = E->getType(); 3337 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3338 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3339 return true; 3340 } 3341 3342 llvm::APSInt ValueAPS; 3343 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3344 3345 if (R.isInvalid()) 3346 return true; 3347 3348 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3349 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3350 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3351 << ValueAPS.toString(10) << ValueIsPositive; 3352 return true; 3353 } 3354 3355 return false; 3356 } 3357 3358 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3359 // Fast path for a single digit (which is quite common). A single digit 3360 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3361 if (Tok.getLength() == 1) { 3362 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3363 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3364 } 3365 3366 SmallString<128> SpellingBuffer; 3367 // NumericLiteralParser wants to overread by one character. Add padding to 3368 // the buffer in case the token is copied to the buffer. If getSpelling() 3369 // returns a StringRef to the memory buffer, it should have a null char at 3370 // the EOF, so it is also safe. 3371 SpellingBuffer.resize(Tok.getLength() + 1); 3372 3373 // Get the spelling of the token, which eliminates trigraphs, etc. 3374 bool Invalid = false; 3375 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3376 if (Invalid) 3377 return ExprError(); 3378 3379 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3380 if (Literal.hadError) 3381 return ExprError(); 3382 3383 if (Literal.hasUDSuffix()) { 3384 // We're building a user-defined literal. 3385 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3386 SourceLocation UDSuffixLoc = 3387 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3388 3389 // Make sure we're allowed user-defined literals here. 3390 if (!UDLScope) 3391 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3392 3393 QualType CookedTy; 3394 if (Literal.isFloatingLiteral()) { 3395 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3396 // long double, the literal is treated as a call of the form 3397 // operator "" X (f L) 3398 CookedTy = Context.LongDoubleTy; 3399 } else { 3400 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3401 // unsigned long long, the literal is treated as a call of the form 3402 // operator "" X (n ULL) 3403 CookedTy = Context.UnsignedLongLongTy; 3404 } 3405 3406 DeclarationName OpName = 3407 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3408 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3409 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3410 3411 SourceLocation TokLoc = Tok.getLocation(); 3412 3413 // Perform literal operator lookup to determine if we're building a raw 3414 // literal or a cooked one. 3415 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3416 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3417 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3418 /*AllowStringTemplate*/ false, 3419 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3420 case LOLR_ErrorNoDiagnostic: 3421 // Lookup failure for imaginary constants isn't fatal, there's still the 3422 // GNU extension producing _Complex types. 3423 break; 3424 case LOLR_Error: 3425 return ExprError(); 3426 case LOLR_Cooked: { 3427 Expr *Lit; 3428 if (Literal.isFloatingLiteral()) { 3429 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3430 } else { 3431 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3432 if (Literal.GetIntegerValue(ResultVal)) 3433 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3434 << /* Unsigned */ 1; 3435 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3436 Tok.getLocation()); 3437 } 3438 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3439 } 3440 3441 case LOLR_Raw: { 3442 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3443 // literal is treated as a call of the form 3444 // operator "" X ("n") 3445 unsigned Length = Literal.getUDSuffixOffset(); 3446 QualType StrTy = Context.getConstantArrayType( 3447 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3448 llvm::APInt(32, Length + 1), ArrayType::Normal, 0); 3449 Expr *Lit = StringLiteral::Create( 3450 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3451 /*Pascal*/false, StrTy, &TokLoc, 1); 3452 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3453 } 3454 3455 case LOLR_Template: { 3456 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3457 // template), L is treated as a call fo the form 3458 // operator "" X <'c1', 'c2', ... 'ck'>() 3459 // where n is the source character sequence c1 c2 ... ck. 3460 TemplateArgumentListInfo ExplicitArgs; 3461 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3462 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3463 llvm::APSInt Value(CharBits, CharIsUnsigned); 3464 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3465 Value = TokSpelling[I]; 3466 TemplateArgument Arg(Context, Value, Context.CharTy); 3467 TemplateArgumentLocInfo ArgInfo; 3468 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3469 } 3470 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3471 &ExplicitArgs); 3472 } 3473 case LOLR_StringTemplate: 3474 llvm_unreachable("unexpected literal operator lookup result"); 3475 } 3476 } 3477 3478 Expr *Res; 3479 3480 if (Literal.isFixedPointLiteral()) { 3481 QualType Ty; 3482 3483 if (Literal.isAccum) { 3484 if (Literal.isHalf) { 3485 Ty = Context.ShortAccumTy; 3486 } else if (Literal.isLong) { 3487 Ty = Context.LongAccumTy; 3488 } else { 3489 Ty = Context.AccumTy; 3490 } 3491 } else if (Literal.isFract) { 3492 if (Literal.isHalf) { 3493 Ty = Context.ShortFractTy; 3494 } else if (Literal.isLong) { 3495 Ty = Context.LongFractTy; 3496 } else { 3497 Ty = Context.FractTy; 3498 } 3499 } 3500 3501 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3502 3503 bool isSigned = !Literal.isUnsigned; 3504 unsigned scale = Context.getFixedPointScale(Ty); 3505 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3506 3507 llvm::APInt Val(bit_width, 0, isSigned); 3508 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3509 bool ValIsZero = Val.isNullValue() && !Overflowed; 3510 3511 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3512 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3513 // Clause 6.4.4 - The value of a constant shall be in the range of 3514 // representable values for its type, with exception for constants of a 3515 // fract type with a value of exactly 1; such a constant shall denote 3516 // the maximal value for the type. 3517 --Val; 3518 else if (Val.ugt(MaxVal) || Overflowed) 3519 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3520 3521 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3522 Tok.getLocation(), scale); 3523 } else if (Literal.isFloatingLiteral()) { 3524 QualType Ty; 3525 if (Literal.isHalf){ 3526 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3527 Ty = Context.HalfTy; 3528 else { 3529 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3530 return ExprError(); 3531 } 3532 } else if (Literal.isFloat) 3533 Ty = Context.FloatTy; 3534 else if (Literal.isLong) 3535 Ty = Context.LongDoubleTy; 3536 else if (Literal.isFloat16) 3537 Ty = Context.Float16Ty; 3538 else if (Literal.isFloat128) 3539 Ty = Context.Float128Ty; 3540 else 3541 Ty = Context.DoubleTy; 3542 3543 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3544 3545 if (Ty == Context.DoubleTy) { 3546 if (getLangOpts().SinglePrecisionConstants) { 3547 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3548 if (BTy->getKind() != BuiltinType::Float) { 3549 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3550 } 3551 } else if (getLangOpts().OpenCL && 3552 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3553 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3554 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3555 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3556 } 3557 } 3558 } else if (!Literal.isIntegerLiteral()) { 3559 return ExprError(); 3560 } else { 3561 QualType Ty; 3562 3563 // 'long long' is a C99 or C++11 feature. 3564 if (!getLangOpts().C99 && Literal.isLongLong) { 3565 if (getLangOpts().CPlusPlus) 3566 Diag(Tok.getLocation(), 3567 getLangOpts().CPlusPlus11 ? 3568 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3569 else 3570 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3571 } 3572 3573 // Get the value in the widest-possible width. 3574 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3575 llvm::APInt ResultVal(MaxWidth, 0); 3576 3577 if (Literal.GetIntegerValue(ResultVal)) { 3578 // If this value didn't fit into uintmax_t, error and force to ull. 3579 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3580 << /* Unsigned */ 1; 3581 Ty = Context.UnsignedLongLongTy; 3582 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3583 "long long is not intmax_t?"); 3584 } else { 3585 // If this value fits into a ULL, try to figure out what else it fits into 3586 // according to the rules of C99 6.4.4.1p5. 3587 3588 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3589 // be an unsigned int. 3590 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3591 3592 // Check from smallest to largest, picking the smallest type we can. 3593 unsigned Width = 0; 3594 3595 // Microsoft specific integer suffixes are explicitly sized. 3596 if (Literal.MicrosoftInteger) { 3597 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3598 Width = 8; 3599 Ty = Context.CharTy; 3600 } else { 3601 Width = Literal.MicrosoftInteger; 3602 Ty = Context.getIntTypeForBitwidth(Width, 3603 /*Signed=*/!Literal.isUnsigned); 3604 } 3605 } 3606 3607 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3608 // Are int/unsigned possibilities? 3609 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3610 3611 // Does it fit in a unsigned int? 3612 if (ResultVal.isIntN(IntSize)) { 3613 // Does it fit in a signed int? 3614 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3615 Ty = Context.IntTy; 3616 else if (AllowUnsigned) 3617 Ty = Context.UnsignedIntTy; 3618 Width = IntSize; 3619 } 3620 } 3621 3622 // Are long/unsigned long possibilities? 3623 if (Ty.isNull() && !Literal.isLongLong) { 3624 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3625 3626 // Does it fit in a unsigned long? 3627 if (ResultVal.isIntN(LongSize)) { 3628 // Does it fit in a signed long? 3629 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3630 Ty = Context.LongTy; 3631 else if (AllowUnsigned) 3632 Ty = Context.UnsignedLongTy; 3633 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3634 // is compatible. 3635 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3636 const unsigned LongLongSize = 3637 Context.getTargetInfo().getLongLongWidth(); 3638 Diag(Tok.getLocation(), 3639 getLangOpts().CPlusPlus 3640 ? Literal.isLong 3641 ? diag::warn_old_implicitly_unsigned_long_cxx 3642 : /*C++98 UB*/ diag:: 3643 ext_old_implicitly_unsigned_long_cxx 3644 : diag::warn_old_implicitly_unsigned_long) 3645 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3646 : /*will be ill-formed*/ 1); 3647 Ty = Context.UnsignedLongTy; 3648 } 3649 Width = LongSize; 3650 } 3651 } 3652 3653 // Check long long if needed. 3654 if (Ty.isNull()) { 3655 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3656 3657 // Does it fit in a unsigned long long? 3658 if (ResultVal.isIntN(LongLongSize)) { 3659 // Does it fit in a signed long long? 3660 // To be compatible with MSVC, hex integer literals ending with the 3661 // LL or i64 suffix are always signed in Microsoft mode. 3662 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3663 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3664 Ty = Context.LongLongTy; 3665 else if (AllowUnsigned) 3666 Ty = Context.UnsignedLongLongTy; 3667 Width = LongLongSize; 3668 } 3669 } 3670 3671 // If we still couldn't decide a type, we probably have something that 3672 // does not fit in a signed long long, but has no U suffix. 3673 if (Ty.isNull()) { 3674 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3675 Ty = Context.UnsignedLongLongTy; 3676 Width = Context.getTargetInfo().getLongLongWidth(); 3677 } 3678 3679 if (ResultVal.getBitWidth() != Width) 3680 ResultVal = ResultVal.trunc(Width); 3681 } 3682 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3683 } 3684 3685 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3686 if (Literal.isImaginary) { 3687 Res = new (Context) ImaginaryLiteral(Res, 3688 Context.getComplexType(Res->getType())); 3689 3690 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3691 } 3692 return Res; 3693 } 3694 3695 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3696 assert(E && "ActOnParenExpr() missing expr"); 3697 return new (Context) ParenExpr(L, R, E); 3698 } 3699 3700 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3701 SourceLocation Loc, 3702 SourceRange ArgRange) { 3703 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3704 // scalar or vector data type argument..." 3705 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3706 // type (C99 6.2.5p18) or void. 3707 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3708 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3709 << T << ArgRange; 3710 return true; 3711 } 3712 3713 assert((T->isVoidType() || !T->isIncompleteType()) && 3714 "Scalar types should always be complete"); 3715 return false; 3716 } 3717 3718 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3719 SourceLocation Loc, 3720 SourceRange ArgRange, 3721 UnaryExprOrTypeTrait TraitKind) { 3722 // Invalid types must be hard errors for SFINAE in C++. 3723 if (S.LangOpts.CPlusPlus) 3724 return true; 3725 3726 // C99 6.5.3.4p1: 3727 if (T->isFunctionType() && 3728 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 3729 TraitKind == UETT_PreferredAlignOf)) { 3730 // sizeof(function)/alignof(function) is allowed as an extension. 3731 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3732 << TraitKind << ArgRange; 3733 return false; 3734 } 3735 3736 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3737 // this is an error (OpenCL v1.1 s6.3.k) 3738 if (T->isVoidType()) { 3739 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3740 : diag::ext_sizeof_alignof_void_type; 3741 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3742 return false; 3743 } 3744 3745 return true; 3746 } 3747 3748 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3749 SourceLocation Loc, 3750 SourceRange ArgRange, 3751 UnaryExprOrTypeTrait TraitKind) { 3752 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3753 // runtime doesn't allow it. 3754 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3755 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3756 << T << (TraitKind == UETT_SizeOf) 3757 << ArgRange; 3758 return true; 3759 } 3760 3761 return false; 3762 } 3763 3764 /// Check whether E is a pointer from a decayed array type (the decayed 3765 /// pointer type is equal to T) and emit a warning if it is. 3766 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3767 Expr *E) { 3768 // Don't warn if the operation changed the type. 3769 if (T != E->getType()) 3770 return; 3771 3772 // Now look for array decays. 3773 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3774 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3775 return; 3776 3777 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3778 << ICE->getType() 3779 << ICE->getSubExpr()->getType(); 3780 } 3781 3782 /// Check the constraints on expression operands to unary type expression 3783 /// and type traits. 3784 /// 3785 /// Completes any types necessary and validates the constraints on the operand 3786 /// expression. The logic mostly mirrors the type-based overload, but may modify 3787 /// the expression as it completes the type for that expression through template 3788 /// instantiation, etc. 3789 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3790 UnaryExprOrTypeTrait ExprKind) { 3791 QualType ExprTy = E->getType(); 3792 assert(!ExprTy->isReferenceType()); 3793 3794 if (ExprKind == UETT_VecStep) 3795 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3796 E->getSourceRange()); 3797 3798 // Whitelist some types as extensions 3799 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3800 E->getSourceRange(), ExprKind)) 3801 return false; 3802 3803 // 'alignof' applied to an expression only requires the base element type of 3804 // the expression to be complete. 'sizeof' requires the expression's type to 3805 // be complete (and will attempt to complete it if it's an array of unknown 3806 // bound). 3807 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 3808 if (RequireCompleteType(E->getExprLoc(), 3809 Context.getBaseElementType(E->getType()), 3810 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3811 E->getSourceRange())) 3812 return true; 3813 } else { 3814 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3815 ExprKind, E->getSourceRange())) 3816 return true; 3817 } 3818 3819 // Completing the expression's type may have changed it. 3820 ExprTy = E->getType(); 3821 assert(!ExprTy->isReferenceType()); 3822 3823 if (ExprTy->isFunctionType()) { 3824 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3825 << ExprKind << E->getSourceRange(); 3826 return true; 3827 } 3828 3829 // The operand for sizeof and alignof is in an unevaluated expression context, 3830 // so side effects could result in unintended consequences. 3831 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 3832 ExprKind == UETT_PreferredAlignOf) && 3833 !inTemplateInstantiation() && E->HasSideEffects(Context, false)) 3834 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3835 3836 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3837 E->getSourceRange(), ExprKind)) 3838 return true; 3839 3840 if (ExprKind == UETT_SizeOf) { 3841 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3842 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3843 QualType OType = PVD->getOriginalType(); 3844 QualType Type = PVD->getType(); 3845 if (Type->isPointerType() && OType->isArrayType()) { 3846 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3847 << Type << OType; 3848 Diag(PVD->getLocation(), diag::note_declared_at); 3849 } 3850 } 3851 } 3852 3853 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3854 // decays into a pointer and returns an unintended result. This is most 3855 // likely a typo for "sizeof(array) op x". 3856 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3857 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3858 BO->getLHS()); 3859 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3860 BO->getRHS()); 3861 } 3862 } 3863 3864 return false; 3865 } 3866 3867 /// Check the constraints on operands to unary expression and type 3868 /// traits. 3869 /// 3870 /// This will complete any types necessary, and validate the various constraints 3871 /// on those operands. 3872 /// 3873 /// The UsualUnaryConversions() function is *not* called by this routine. 3874 /// C99 6.3.2.1p[2-4] all state: 3875 /// Except when it is the operand of the sizeof operator ... 3876 /// 3877 /// C++ [expr.sizeof]p4 3878 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3879 /// standard conversions are not applied to the operand of sizeof. 3880 /// 3881 /// This policy is followed for all of the unary trait expressions. 3882 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3883 SourceLocation OpLoc, 3884 SourceRange ExprRange, 3885 UnaryExprOrTypeTrait ExprKind) { 3886 if (ExprType->isDependentType()) 3887 return false; 3888 3889 // C++ [expr.sizeof]p2: 3890 // When applied to a reference or a reference type, the result 3891 // is the size of the referenced type. 3892 // C++11 [expr.alignof]p3: 3893 // When alignof is applied to a reference type, the result 3894 // shall be the alignment of the referenced type. 3895 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3896 ExprType = Ref->getPointeeType(); 3897 3898 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3899 // When alignof or _Alignof is applied to an array type, the result 3900 // is the alignment of the element type. 3901 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 3902 ExprKind == UETT_OpenMPRequiredSimdAlign) 3903 ExprType = Context.getBaseElementType(ExprType); 3904 3905 if (ExprKind == UETT_VecStep) 3906 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3907 3908 // Whitelist some types as extensions 3909 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3910 ExprKind)) 3911 return false; 3912 3913 if (RequireCompleteType(OpLoc, ExprType, 3914 diag::err_sizeof_alignof_incomplete_type, 3915 ExprKind, ExprRange)) 3916 return true; 3917 3918 if (ExprType->isFunctionType()) { 3919 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3920 << ExprKind << ExprRange; 3921 return true; 3922 } 3923 3924 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3925 ExprKind)) 3926 return true; 3927 3928 return false; 3929 } 3930 3931 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 3932 E = E->IgnoreParens(); 3933 3934 // Cannot know anything else if the expression is dependent. 3935 if (E->isTypeDependent()) 3936 return false; 3937 3938 if (E->getObjectKind() == OK_BitField) { 3939 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3940 << 1 << E->getSourceRange(); 3941 return true; 3942 } 3943 3944 ValueDecl *D = nullptr; 3945 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3946 D = DRE->getDecl(); 3947 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3948 D = ME->getMemberDecl(); 3949 } 3950 3951 // If it's a field, require the containing struct to have a 3952 // complete definition so that we can compute the layout. 3953 // 3954 // This can happen in C++11 onwards, either by naming the member 3955 // in a way that is not transformed into a member access expression 3956 // (in an unevaluated operand, for instance), or by naming the member 3957 // in a trailing-return-type. 3958 // 3959 // For the record, since __alignof__ on expressions is a GCC 3960 // extension, GCC seems to permit this but always gives the 3961 // nonsensical answer 0. 3962 // 3963 // We don't really need the layout here --- we could instead just 3964 // directly check for all the appropriate alignment-lowing 3965 // attributes --- but that would require duplicating a lot of 3966 // logic that just isn't worth duplicating for such a marginal 3967 // use-case. 3968 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3969 // Fast path this check, since we at least know the record has a 3970 // definition if we can find a member of it. 3971 if (!FD->getParent()->isCompleteDefinition()) { 3972 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3973 << E->getSourceRange(); 3974 return true; 3975 } 3976 3977 // Otherwise, if it's a field, and the field doesn't have 3978 // reference type, then it must have a complete type (or be a 3979 // flexible array member, which we explicitly want to 3980 // white-list anyway), which makes the following checks trivial. 3981 if (!FD->getType()->isReferenceType()) 3982 return false; 3983 } 3984 3985 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 3986 } 3987 3988 bool Sema::CheckVecStepExpr(Expr *E) { 3989 E = E->IgnoreParens(); 3990 3991 // Cannot know anything else if the expression is dependent. 3992 if (E->isTypeDependent()) 3993 return false; 3994 3995 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3996 } 3997 3998 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 3999 CapturingScopeInfo *CSI) { 4000 assert(T->isVariablyModifiedType()); 4001 assert(CSI != nullptr); 4002 4003 // We're going to walk down into the type and look for VLA expressions. 4004 do { 4005 const Type *Ty = T.getTypePtr(); 4006 switch (Ty->getTypeClass()) { 4007 #define TYPE(Class, Base) 4008 #define ABSTRACT_TYPE(Class, Base) 4009 #define NON_CANONICAL_TYPE(Class, Base) 4010 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4011 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4012 #include "clang/AST/TypeNodes.def" 4013 T = QualType(); 4014 break; 4015 // These types are never variably-modified. 4016 case Type::Builtin: 4017 case Type::Complex: 4018 case Type::Vector: 4019 case Type::ExtVector: 4020 case Type::Record: 4021 case Type::Enum: 4022 case Type::Elaborated: 4023 case Type::TemplateSpecialization: 4024 case Type::ObjCObject: 4025 case Type::ObjCInterface: 4026 case Type::ObjCObjectPointer: 4027 case Type::ObjCTypeParam: 4028 case Type::Pipe: 4029 llvm_unreachable("type class is never variably-modified!"); 4030 case Type::Adjusted: 4031 T = cast<AdjustedType>(Ty)->getOriginalType(); 4032 break; 4033 case Type::Decayed: 4034 T = cast<DecayedType>(Ty)->getPointeeType(); 4035 break; 4036 case Type::Pointer: 4037 T = cast<PointerType>(Ty)->getPointeeType(); 4038 break; 4039 case Type::BlockPointer: 4040 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4041 break; 4042 case Type::LValueReference: 4043 case Type::RValueReference: 4044 T = cast<ReferenceType>(Ty)->getPointeeType(); 4045 break; 4046 case Type::MemberPointer: 4047 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4048 break; 4049 case Type::ConstantArray: 4050 case Type::IncompleteArray: 4051 // Losing element qualification here is fine. 4052 T = cast<ArrayType>(Ty)->getElementType(); 4053 break; 4054 case Type::VariableArray: { 4055 // Losing element qualification here is fine. 4056 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4057 4058 // Unknown size indication requires no size computation. 4059 // Otherwise, evaluate and record it. 4060 if (auto Size = VAT->getSizeExpr()) { 4061 if (!CSI->isVLATypeCaptured(VAT)) { 4062 RecordDecl *CapRecord = nullptr; 4063 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 4064 CapRecord = LSI->Lambda; 4065 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 4066 CapRecord = CRSI->TheRecordDecl; 4067 } 4068 if (CapRecord) { 4069 auto ExprLoc = Size->getExprLoc(); 4070 auto SizeType = Context.getSizeType(); 4071 // Build the non-static data member. 4072 auto Field = 4073 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc, 4074 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 4075 /*BW*/ nullptr, /*Mutable*/ false, 4076 /*InitStyle*/ ICIS_NoInit); 4077 Field->setImplicit(true); 4078 Field->setAccess(AS_private); 4079 Field->setCapturedVLAType(VAT); 4080 CapRecord->addDecl(Field); 4081 4082 CSI->addVLATypeCapture(ExprLoc, SizeType); 4083 } 4084 } 4085 } 4086 T = VAT->getElementType(); 4087 break; 4088 } 4089 case Type::FunctionProto: 4090 case Type::FunctionNoProto: 4091 T = cast<FunctionType>(Ty)->getReturnType(); 4092 break; 4093 case Type::Paren: 4094 case Type::TypeOf: 4095 case Type::UnaryTransform: 4096 case Type::Attributed: 4097 case Type::SubstTemplateTypeParm: 4098 case Type::PackExpansion: 4099 // Keep walking after single level desugaring. 4100 T = T.getSingleStepDesugaredType(Context); 4101 break; 4102 case Type::Typedef: 4103 T = cast<TypedefType>(Ty)->desugar(); 4104 break; 4105 case Type::Decltype: 4106 T = cast<DecltypeType>(Ty)->desugar(); 4107 break; 4108 case Type::Auto: 4109 case Type::DeducedTemplateSpecialization: 4110 T = cast<DeducedType>(Ty)->getDeducedType(); 4111 break; 4112 case Type::TypeOfExpr: 4113 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4114 break; 4115 case Type::Atomic: 4116 T = cast<AtomicType>(Ty)->getValueType(); 4117 break; 4118 } 4119 } while (!T.isNull() && T->isVariablyModifiedType()); 4120 } 4121 4122 /// Build a sizeof or alignof expression given a type operand. 4123 ExprResult 4124 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4125 SourceLocation OpLoc, 4126 UnaryExprOrTypeTrait ExprKind, 4127 SourceRange R) { 4128 if (!TInfo) 4129 return ExprError(); 4130 4131 QualType T = TInfo->getType(); 4132 4133 if (!T->isDependentType() && 4134 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4135 return ExprError(); 4136 4137 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4138 if (auto *TT = T->getAs<TypedefType>()) { 4139 for (auto I = FunctionScopes.rbegin(), 4140 E = std::prev(FunctionScopes.rend()); 4141 I != E; ++I) { 4142 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4143 if (CSI == nullptr) 4144 break; 4145 DeclContext *DC = nullptr; 4146 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4147 DC = LSI->CallOperator; 4148 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4149 DC = CRSI->TheCapturedDecl; 4150 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4151 DC = BSI->TheDecl; 4152 if (DC) { 4153 if (DC->containsDecl(TT->getDecl())) 4154 break; 4155 captureVariablyModifiedType(Context, T, CSI); 4156 } 4157 } 4158 } 4159 } 4160 4161 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4162 return new (Context) UnaryExprOrTypeTraitExpr( 4163 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4164 } 4165 4166 /// Build a sizeof or alignof expression given an expression 4167 /// operand. 4168 ExprResult 4169 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4170 UnaryExprOrTypeTrait ExprKind) { 4171 ExprResult PE = CheckPlaceholderExpr(E); 4172 if (PE.isInvalid()) 4173 return ExprError(); 4174 4175 E = PE.get(); 4176 4177 // Verify that the operand is valid. 4178 bool isInvalid = false; 4179 if (E->isTypeDependent()) { 4180 // Delay type-checking for type-dependent expressions. 4181 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4182 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4183 } else if (ExprKind == UETT_VecStep) { 4184 isInvalid = CheckVecStepExpr(E); 4185 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4186 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4187 isInvalid = true; 4188 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4189 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4190 isInvalid = true; 4191 } else { 4192 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4193 } 4194 4195 if (isInvalid) 4196 return ExprError(); 4197 4198 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4199 PE = TransformToPotentiallyEvaluated(E); 4200 if (PE.isInvalid()) return ExprError(); 4201 E = PE.get(); 4202 } 4203 4204 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4205 return new (Context) UnaryExprOrTypeTraitExpr( 4206 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4207 } 4208 4209 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4210 /// expr and the same for @c alignof and @c __alignof 4211 /// Note that the ArgRange is invalid if isType is false. 4212 ExprResult 4213 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4214 UnaryExprOrTypeTrait ExprKind, bool IsType, 4215 void *TyOrEx, SourceRange ArgRange) { 4216 // If error parsing type, ignore. 4217 if (!TyOrEx) return ExprError(); 4218 4219 if (IsType) { 4220 TypeSourceInfo *TInfo; 4221 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4222 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4223 } 4224 4225 Expr *ArgEx = (Expr *)TyOrEx; 4226 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4227 return Result; 4228 } 4229 4230 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4231 bool IsReal) { 4232 if (V.get()->isTypeDependent()) 4233 return S.Context.DependentTy; 4234 4235 // _Real and _Imag are only l-values for normal l-values. 4236 if (V.get()->getObjectKind() != OK_Ordinary) { 4237 V = S.DefaultLvalueConversion(V.get()); 4238 if (V.isInvalid()) 4239 return QualType(); 4240 } 4241 4242 // These operators return the element type of a complex type. 4243 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4244 return CT->getElementType(); 4245 4246 // Otherwise they pass through real integer and floating point types here. 4247 if (V.get()->getType()->isArithmeticType()) 4248 return V.get()->getType(); 4249 4250 // Test for placeholders. 4251 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4252 if (PR.isInvalid()) return QualType(); 4253 if (PR.get() != V.get()) { 4254 V = PR; 4255 return CheckRealImagOperand(S, V, Loc, IsReal); 4256 } 4257 4258 // Reject anything else. 4259 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4260 << (IsReal ? "__real" : "__imag"); 4261 return QualType(); 4262 } 4263 4264 4265 4266 ExprResult 4267 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4268 tok::TokenKind Kind, Expr *Input) { 4269 UnaryOperatorKind Opc; 4270 switch (Kind) { 4271 default: llvm_unreachable("Unknown unary op!"); 4272 case tok::plusplus: Opc = UO_PostInc; break; 4273 case tok::minusminus: Opc = UO_PostDec; break; 4274 } 4275 4276 // Since this might is a postfix expression, get rid of ParenListExprs. 4277 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4278 if (Result.isInvalid()) return ExprError(); 4279 Input = Result.get(); 4280 4281 return BuildUnaryOp(S, OpLoc, Opc, Input); 4282 } 4283 4284 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4285 /// 4286 /// \return true on error 4287 static bool checkArithmeticOnObjCPointer(Sema &S, 4288 SourceLocation opLoc, 4289 Expr *op) { 4290 assert(op->getType()->isObjCObjectPointerType()); 4291 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4292 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4293 return false; 4294 4295 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4296 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4297 << op->getSourceRange(); 4298 return true; 4299 } 4300 4301 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4302 auto *BaseNoParens = Base->IgnoreParens(); 4303 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4304 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4305 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4306 } 4307 4308 ExprResult 4309 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4310 Expr *idx, SourceLocation rbLoc) { 4311 if (base && !base->getType().isNull() && 4312 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4313 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4314 /*Length=*/nullptr, rbLoc); 4315 4316 // Since this might be a postfix expression, get rid of ParenListExprs. 4317 if (isa<ParenListExpr>(base)) { 4318 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4319 if (result.isInvalid()) return ExprError(); 4320 base = result.get(); 4321 } 4322 4323 // Handle any non-overload placeholder types in the base and index 4324 // expressions. We can't handle overloads here because the other 4325 // operand might be an overloadable type, in which case the overload 4326 // resolution for the operator overload should get the first crack 4327 // at the overload. 4328 bool IsMSPropertySubscript = false; 4329 if (base->getType()->isNonOverloadPlaceholderType()) { 4330 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4331 if (!IsMSPropertySubscript) { 4332 ExprResult result = CheckPlaceholderExpr(base); 4333 if (result.isInvalid()) 4334 return ExprError(); 4335 base = result.get(); 4336 } 4337 } 4338 if (idx->getType()->isNonOverloadPlaceholderType()) { 4339 ExprResult result = CheckPlaceholderExpr(idx); 4340 if (result.isInvalid()) return ExprError(); 4341 idx = result.get(); 4342 } 4343 4344 // Build an unanalyzed expression if either operand is type-dependent. 4345 if (getLangOpts().CPlusPlus && 4346 (base->isTypeDependent() || idx->isTypeDependent())) { 4347 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4348 VK_LValue, OK_Ordinary, rbLoc); 4349 } 4350 4351 // MSDN, property (C++) 4352 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4353 // This attribute can also be used in the declaration of an empty array in a 4354 // class or structure definition. For example: 4355 // __declspec(property(get=GetX, put=PutX)) int x[]; 4356 // The above statement indicates that x[] can be used with one or more array 4357 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4358 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4359 if (IsMSPropertySubscript) { 4360 // Build MS property subscript expression if base is MS property reference 4361 // or MS property subscript. 4362 return new (Context) MSPropertySubscriptExpr( 4363 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4364 } 4365 4366 // Use C++ overloaded-operator rules if either operand has record 4367 // type. The spec says to do this if either type is *overloadable*, 4368 // but enum types can't declare subscript operators or conversion 4369 // operators, so there's nothing interesting for overload resolution 4370 // to do if there aren't any record types involved. 4371 // 4372 // ObjC pointers have their own subscripting logic that is not tied 4373 // to overload resolution and so should not take this path. 4374 if (getLangOpts().CPlusPlus && 4375 (base->getType()->isRecordType() || 4376 (!base->getType()->isObjCObjectPointerType() && 4377 idx->getType()->isRecordType()))) { 4378 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4379 } 4380 4381 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4382 4383 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4384 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4385 4386 return Res; 4387 } 4388 4389 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4390 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4391 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4392 4393 // For expressions like `&(*s).b`, the base is recorded and what should be 4394 // checked. 4395 const MemberExpr *Member = nullptr; 4396 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4397 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4398 4399 LastRecord.PossibleDerefs.erase(StrippedExpr); 4400 } 4401 4402 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4403 QualType ResultTy = E->getType(); 4404 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4405 4406 // Bail if the element is an array since it is not memory access. 4407 if (isa<ArrayType>(ResultTy)) 4408 return; 4409 4410 if (ResultTy->hasAttr(attr::NoDeref)) { 4411 LastRecord.PossibleDerefs.insert(E); 4412 return; 4413 } 4414 4415 // Check if the base type is a pointer to a member access of a struct 4416 // marked with noderef. 4417 const Expr *Base = E->getBase(); 4418 QualType BaseTy = Base->getType(); 4419 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4420 // Not a pointer access 4421 return; 4422 4423 const MemberExpr *Member = nullptr; 4424 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4425 Member->isArrow()) 4426 Base = Member->getBase(); 4427 4428 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4429 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4430 LastRecord.PossibleDerefs.insert(E); 4431 } 4432 } 4433 4434 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4435 Expr *LowerBound, 4436 SourceLocation ColonLoc, Expr *Length, 4437 SourceLocation RBLoc) { 4438 if (Base->getType()->isPlaceholderType() && 4439 !Base->getType()->isSpecificPlaceholderType( 4440 BuiltinType::OMPArraySection)) { 4441 ExprResult Result = CheckPlaceholderExpr(Base); 4442 if (Result.isInvalid()) 4443 return ExprError(); 4444 Base = Result.get(); 4445 } 4446 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4447 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4448 if (Result.isInvalid()) 4449 return ExprError(); 4450 Result = DefaultLvalueConversion(Result.get()); 4451 if (Result.isInvalid()) 4452 return ExprError(); 4453 LowerBound = Result.get(); 4454 } 4455 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4456 ExprResult Result = CheckPlaceholderExpr(Length); 4457 if (Result.isInvalid()) 4458 return ExprError(); 4459 Result = DefaultLvalueConversion(Result.get()); 4460 if (Result.isInvalid()) 4461 return ExprError(); 4462 Length = Result.get(); 4463 } 4464 4465 // Build an unanalyzed expression if either operand is type-dependent. 4466 if (Base->isTypeDependent() || 4467 (LowerBound && 4468 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4469 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4470 return new (Context) 4471 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4472 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4473 } 4474 4475 // Perform default conversions. 4476 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4477 QualType ResultTy; 4478 if (OriginalTy->isAnyPointerType()) { 4479 ResultTy = OriginalTy->getPointeeType(); 4480 } else if (OriginalTy->isArrayType()) { 4481 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4482 } else { 4483 return ExprError( 4484 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4485 << Base->getSourceRange()); 4486 } 4487 // C99 6.5.2.1p1 4488 if (LowerBound) { 4489 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4490 LowerBound); 4491 if (Res.isInvalid()) 4492 return ExprError(Diag(LowerBound->getExprLoc(), 4493 diag::err_omp_typecheck_section_not_integer) 4494 << 0 << LowerBound->getSourceRange()); 4495 LowerBound = Res.get(); 4496 4497 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4498 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4499 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4500 << 0 << LowerBound->getSourceRange(); 4501 } 4502 if (Length) { 4503 auto Res = 4504 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4505 if (Res.isInvalid()) 4506 return ExprError(Diag(Length->getExprLoc(), 4507 diag::err_omp_typecheck_section_not_integer) 4508 << 1 << Length->getSourceRange()); 4509 Length = Res.get(); 4510 4511 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4512 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4513 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4514 << 1 << Length->getSourceRange(); 4515 } 4516 4517 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4518 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4519 // type. Note that functions are not objects, and that (in C99 parlance) 4520 // incomplete types are not object types. 4521 if (ResultTy->isFunctionType()) { 4522 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4523 << ResultTy << Base->getSourceRange(); 4524 return ExprError(); 4525 } 4526 4527 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4528 diag::err_omp_section_incomplete_type, Base)) 4529 return ExprError(); 4530 4531 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4532 Expr::EvalResult Result; 4533 if (LowerBound->EvaluateAsInt(Result, Context)) { 4534 // OpenMP 4.5, [2.4 Array Sections] 4535 // The array section must be a subset of the original array. 4536 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 4537 if (LowerBoundValue.isNegative()) { 4538 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4539 << LowerBound->getSourceRange(); 4540 return ExprError(); 4541 } 4542 } 4543 } 4544 4545 if (Length) { 4546 Expr::EvalResult Result; 4547 if (Length->EvaluateAsInt(Result, Context)) { 4548 // OpenMP 4.5, [2.4 Array Sections] 4549 // The length must evaluate to non-negative integers. 4550 llvm::APSInt LengthValue = Result.Val.getInt(); 4551 if (LengthValue.isNegative()) { 4552 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4553 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4554 << Length->getSourceRange(); 4555 return ExprError(); 4556 } 4557 } 4558 } else if (ColonLoc.isValid() && 4559 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4560 !OriginalTy->isVariableArrayType()))) { 4561 // OpenMP 4.5, [2.4 Array Sections] 4562 // When the size of the array dimension is not known, the length must be 4563 // specified explicitly. 4564 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4565 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4566 return ExprError(); 4567 } 4568 4569 if (!Base->getType()->isSpecificPlaceholderType( 4570 BuiltinType::OMPArraySection)) { 4571 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4572 if (Result.isInvalid()) 4573 return ExprError(); 4574 Base = Result.get(); 4575 } 4576 return new (Context) 4577 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4578 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4579 } 4580 4581 ExprResult 4582 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4583 Expr *Idx, SourceLocation RLoc) { 4584 Expr *LHSExp = Base; 4585 Expr *RHSExp = Idx; 4586 4587 ExprValueKind VK = VK_LValue; 4588 ExprObjectKind OK = OK_Ordinary; 4589 4590 // Per C++ core issue 1213, the result is an xvalue if either operand is 4591 // a non-lvalue array, and an lvalue otherwise. 4592 if (getLangOpts().CPlusPlus11) { 4593 for (auto *Op : {LHSExp, RHSExp}) { 4594 Op = Op->IgnoreImplicit(); 4595 if (Op->getType()->isArrayType() && !Op->isLValue()) 4596 VK = VK_XValue; 4597 } 4598 } 4599 4600 // Perform default conversions. 4601 if (!LHSExp->getType()->getAs<VectorType>()) { 4602 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4603 if (Result.isInvalid()) 4604 return ExprError(); 4605 LHSExp = Result.get(); 4606 } 4607 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4608 if (Result.isInvalid()) 4609 return ExprError(); 4610 RHSExp = Result.get(); 4611 4612 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4613 4614 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4615 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4616 // in the subscript position. As a result, we need to derive the array base 4617 // and index from the expression types. 4618 Expr *BaseExpr, *IndexExpr; 4619 QualType ResultType; 4620 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4621 BaseExpr = LHSExp; 4622 IndexExpr = RHSExp; 4623 ResultType = Context.DependentTy; 4624 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4625 BaseExpr = LHSExp; 4626 IndexExpr = RHSExp; 4627 ResultType = PTy->getPointeeType(); 4628 } else if (const ObjCObjectPointerType *PTy = 4629 LHSTy->getAs<ObjCObjectPointerType>()) { 4630 BaseExpr = LHSExp; 4631 IndexExpr = RHSExp; 4632 4633 // Use custom logic if this should be the pseudo-object subscript 4634 // expression. 4635 if (!LangOpts.isSubscriptPointerArithmetic()) 4636 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4637 nullptr); 4638 4639 ResultType = PTy->getPointeeType(); 4640 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4641 // Handle the uncommon case of "123[Ptr]". 4642 BaseExpr = RHSExp; 4643 IndexExpr = LHSExp; 4644 ResultType = PTy->getPointeeType(); 4645 } else if (const ObjCObjectPointerType *PTy = 4646 RHSTy->getAs<ObjCObjectPointerType>()) { 4647 // Handle the uncommon case of "123[Ptr]". 4648 BaseExpr = RHSExp; 4649 IndexExpr = LHSExp; 4650 ResultType = PTy->getPointeeType(); 4651 if (!LangOpts.isSubscriptPointerArithmetic()) { 4652 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4653 << ResultType << BaseExpr->getSourceRange(); 4654 return ExprError(); 4655 } 4656 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4657 BaseExpr = LHSExp; // vectors: V[123] 4658 IndexExpr = RHSExp; 4659 // We apply C++ DR1213 to vector subscripting too. 4660 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { 4661 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 4662 if (Materialized.isInvalid()) 4663 return ExprError(); 4664 LHSExp = Materialized.get(); 4665 } 4666 VK = LHSExp->getValueKind(); 4667 if (VK != VK_RValue) 4668 OK = OK_VectorComponent; 4669 4670 ResultType = VTy->getElementType(); 4671 QualType BaseType = BaseExpr->getType(); 4672 Qualifiers BaseQuals = BaseType.getQualifiers(); 4673 Qualifiers MemberQuals = ResultType.getQualifiers(); 4674 Qualifiers Combined = BaseQuals + MemberQuals; 4675 if (Combined != MemberQuals) 4676 ResultType = Context.getQualifiedType(ResultType, Combined); 4677 } else if (LHSTy->isArrayType()) { 4678 // If we see an array that wasn't promoted by 4679 // DefaultFunctionArrayLvalueConversion, it must be an array that 4680 // wasn't promoted because of the C90 rule that doesn't 4681 // allow promoting non-lvalue arrays. Warn, then 4682 // force the promotion here. 4683 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 4684 << LHSExp->getSourceRange(); 4685 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4686 CK_ArrayToPointerDecay).get(); 4687 LHSTy = LHSExp->getType(); 4688 4689 BaseExpr = LHSExp; 4690 IndexExpr = RHSExp; 4691 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4692 } else if (RHSTy->isArrayType()) { 4693 // Same as previous, except for 123[f().a] case 4694 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 4695 << RHSExp->getSourceRange(); 4696 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4697 CK_ArrayToPointerDecay).get(); 4698 RHSTy = RHSExp->getType(); 4699 4700 BaseExpr = RHSExp; 4701 IndexExpr = LHSExp; 4702 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4703 } else { 4704 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4705 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4706 } 4707 // C99 6.5.2.1p1 4708 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4709 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4710 << IndexExpr->getSourceRange()); 4711 4712 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4713 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4714 && !IndexExpr->isTypeDependent()) 4715 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4716 4717 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4718 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4719 // type. Note that Functions are not objects, and that (in C99 parlance) 4720 // incomplete types are not object types. 4721 if (ResultType->isFunctionType()) { 4722 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 4723 << ResultType << BaseExpr->getSourceRange(); 4724 return ExprError(); 4725 } 4726 4727 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4728 // GNU extension: subscripting on pointer to void 4729 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4730 << BaseExpr->getSourceRange(); 4731 4732 // C forbids expressions of unqualified void type from being l-values. 4733 // See IsCForbiddenLValueType. 4734 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4735 } else if (!ResultType->isDependentType() && 4736 RequireCompleteType(LLoc, ResultType, 4737 diag::err_subscript_incomplete_type, BaseExpr)) 4738 return ExprError(); 4739 4740 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4741 !ResultType.isCForbiddenLValueType()); 4742 4743 return new (Context) 4744 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4745 } 4746 4747 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 4748 ParmVarDecl *Param) { 4749 if (Param->hasUnparsedDefaultArg()) { 4750 Diag(CallLoc, 4751 diag::err_use_of_default_argument_to_function_declared_later) << 4752 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4753 Diag(UnparsedDefaultArgLocs[Param], 4754 diag::note_default_argument_declared_here); 4755 return true; 4756 } 4757 4758 if (Param->hasUninstantiatedDefaultArg()) { 4759 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4760 4761 EnterExpressionEvaluationContext EvalContext( 4762 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 4763 4764 // Instantiate the expression. 4765 // 4766 // FIXME: Pass in a correct Pattern argument, otherwise 4767 // getTemplateInstantiationArgs uses the lexical context of FD, e.g. 4768 // 4769 // template<typename T> 4770 // struct A { 4771 // static int FooImpl(); 4772 // 4773 // template<typename Tp> 4774 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level 4775 // // template argument list [[T], [Tp]], should be [[Tp]]. 4776 // friend A<Tp> Foo(int a); 4777 // }; 4778 // 4779 // template<typename T> 4780 // A<T> Foo(int a = A<T>::FooImpl()); 4781 MultiLevelTemplateArgumentList MutiLevelArgList 4782 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4783 4784 InstantiatingTemplate Inst(*this, CallLoc, Param, 4785 MutiLevelArgList.getInnermost()); 4786 if (Inst.isInvalid()) 4787 return true; 4788 if (Inst.isAlreadyInstantiating()) { 4789 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 4790 Param->setInvalidDecl(); 4791 return true; 4792 } 4793 4794 ExprResult Result; 4795 { 4796 // C++ [dcl.fct.default]p5: 4797 // The names in the [default argument] expression are bound, and 4798 // the semantic constraints are checked, at the point where the 4799 // default argument expression appears. 4800 ContextRAII SavedContext(*this, FD); 4801 LocalInstantiationScope Local(*this); 4802 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 4803 /*DirectInit*/false); 4804 } 4805 if (Result.isInvalid()) 4806 return true; 4807 4808 // Check the expression as an initializer for the parameter. 4809 InitializedEntity Entity 4810 = InitializedEntity::InitializeParameter(Context, Param); 4811 InitializationKind Kind = InitializationKind::CreateCopy( 4812 Param->getLocation(), 4813 /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc()); 4814 Expr *ResultE = Result.getAs<Expr>(); 4815 4816 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4817 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4818 if (Result.isInvalid()) 4819 return true; 4820 4821 Result = 4822 ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(), 4823 /*DiscardedValue*/ false); 4824 if (Result.isInvalid()) 4825 return true; 4826 4827 // Remember the instantiated default argument. 4828 Param->setDefaultArg(Result.getAs<Expr>()); 4829 if (ASTMutationListener *L = getASTMutationListener()) { 4830 L->DefaultArgumentInstantiated(Param); 4831 } 4832 } 4833 4834 // If the default argument expression is not set yet, we are building it now. 4835 if (!Param->hasInit()) { 4836 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 4837 Param->setInvalidDecl(); 4838 return true; 4839 } 4840 4841 // If the default expression creates temporaries, we need to 4842 // push them to the current stack of expression temporaries so they'll 4843 // be properly destroyed. 4844 // FIXME: We should really be rebuilding the default argument with new 4845 // bound temporaries; see the comment in PR5810. 4846 // We don't need to do that with block decls, though, because 4847 // blocks in default argument expression can never capture anything. 4848 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 4849 // Set the "needs cleanups" bit regardless of whether there are 4850 // any explicit objects. 4851 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 4852 4853 // Append all the objects to the cleanup list. Right now, this 4854 // should always be a no-op, because blocks in default argument 4855 // expressions should never be able to capture anything. 4856 assert(!Init->getNumObjects() && 4857 "default argument expression has capturing blocks?"); 4858 } 4859 4860 // We already type-checked the argument, so we know it works. 4861 // Just mark all of the declarations in this potentially-evaluated expression 4862 // as being "referenced". 4863 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4864 /*SkipLocalVariables=*/true); 4865 return false; 4866 } 4867 4868 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4869 FunctionDecl *FD, ParmVarDecl *Param) { 4870 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 4871 return ExprError(); 4872 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4873 } 4874 4875 Sema::VariadicCallType 4876 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4877 Expr *Fn) { 4878 if (Proto && Proto->isVariadic()) { 4879 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4880 return VariadicConstructor; 4881 else if (Fn && Fn->getType()->isBlockPointerType()) 4882 return VariadicBlock; 4883 else if (FDecl) { 4884 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4885 if (Method->isInstance()) 4886 return VariadicMethod; 4887 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4888 return VariadicMethod; 4889 return VariadicFunction; 4890 } 4891 return VariadicDoesNotApply; 4892 } 4893 4894 namespace { 4895 class FunctionCallCCC final : public FunctionCallFilterCCC { 4896 public: 4897 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4898 unsigned NumArgs, MemberExpr *ME) 4899 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4900 FunctionName(FuncName) {} 4901 4902 bool ValidateCandidate(const TypoCorrection &candidate) override { 4903 if (!candidate.getCorrectionSpecifier() || 4904 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4905 return false; 4906 } 4907 4908 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4909 } 4910 4911 std::unique_ptr<CorrectionCandidateCallback> clone() override { 4912 return llvm::make_unique<FunctionCallCCC>(*this); 4913 } 4914 4915 private: 4916 const IdentifierInfo *const FunctionName; 4917 }; 4918 } 4919 4920 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4921 FunctionDecl *FDecl, 4922 ArrayRef<Expr *> Args) { 4923 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4924 DeclarationName FuncName = FDecl->getDeclName(); 4925 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 4926 4927 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 4928 if (TypoCorrection Corrected = S.CorrectTypo( 4929 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4930 S.getScopeForContext(S.CurContext), nullptr, CCC, 4931 Sema::CTK_ErrorRecovery)) { 4932 if (NamedDecl *ND = Corrected.getFoundDecl()) { 4933 if (Corrected.isOverloaded()) { 4934 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4935 OverloadCandidateSet::iterator Best; 4936 for (NamedDecl *CD : Corrected) { 4937 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 4938 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4939 OCS); 4940 } 4941 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4942 case OR_Success: 4943 ND = Best->FoundDecl; 4944 Corrected.setCorrectionDecl(ND); 4945 break; 4946 default: 4947 break; 4948 } 4949 } 4950 ND = ND->getUnderlyingDecl(); 4951 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 4952 return Corrected; 4953 } 4954 } 4955 return TypoCorrection(); 4956 } 4957 4958 /// ConvertArgumentsForCall - Converts the arguments specified in 4959 /// Args/NumArgs to the parameter types of the function FDecl with 4960 /// function prototype Proto. Call is the call expression itself, and 4961 /// Fn is the function expression. For a C++ member function, this 4962 /// routine does not attempt to convert the object argument. Returns 4963 /// true if the call is ill-formed. 4964 bool 4965 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4966 FunctionDecl *FDecl, 4967 const FunctionProtoType *Proto, 4968 ArrayRef<Expr *> Args, 4969 SourceLocation RParenLoc, 4970 bool IsExecConfig) { 4971 // Bail out early if calling a builtin with custom typechecking. 4972 if (FDecl) 4973 if (unsigned ID = FDecl->getBuiltinID()) 4974 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4975 return false; 4976 4977 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4978 // assignment, to the types of the corresponding parameter, ... 4979 unsigned NumParams = Proto->getNumParams(); 4980 bool Invalid = false; 4981 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4982 unsigned FnKind = Fn->getType()->isBlockPointerType() 4983 ? 1 /* block */ 4984 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4985 : 0 /* function */); 4986 4987 // If too few arguments are available (and we don't have default 4988 // arguments for the remaining parameters), don't make the call. 4989 if (Args.size() < NumParams) { 4990 if (Args.size() < MinArgs) { 4991 TypoCorrection TC; 4992 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4993 unsigned diag_id = 4994 MinArgs == NumParams && !Proto->isVariadic() 4995 ? diag::err_typecheck_call_too_few_args_suggest 4996 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4997 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4998 << static_cast<unsigned>(Args.size()) 4999 << TC.getCorrectionRange()); 5000 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 5001 Diag(RParenLoc, 5002 MinArgs == NumParams && !Proto->isVariadic() 5003 ? diag::err_typecheck_call_too_few_args_one 5004 : diag::err_typecheck_call_too_few_args_at_least_one) 5005 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 5006 else 5007 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 5008 ? diag::err_typecheck_call_too_few_args 5009 : diag::err_typecheck_call_too_few_args_at_least) 5010 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 5011 << Fn->getSourceRange(); 5012 5013 // Emit the location of the prototype. 5014 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5015 Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl; 5016 5017 return true; 5018 } 5019 // We reserve space for the default arguments when we create 5020 // the call expression, before calling ConvertArgumentsForCall. 5021 assert((Call->getNumArgs() == NumParams) && 5022 "We should have reserved space for the default arguments before!"); 5023 } 5024 5025 // If too many are passed and not variadic, error on the extras and drop 5026 // them. 5027 if (Args.size() > NumParams) { 5028 if (!Proto->isVariadic()) { 5029 TypoCorrection TC; 5030 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5031 unsigned diag_id = 5032 MinArgs == NumParams && !Proto->isVariadic() 5033 ? diag::err_typecheck_call_too_many_args_suggest 5034 : diag::err_typecheck_call_too_many_args_at_most_suggest; 5035 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 5036 << static_cast<unsigned>(Args.size()) 5037 << TC.getCorrectionRange()); 5038 } else if (NumParams == 1 && FDecl && 5039 FDecl->getParamDecl(0)->getDeclName()) 5040 Diag(Args[NumParams]->getBeginLoc(), 5041 MinArgs == NumParams 5042 ? diag::err_typecheck_call_too_many_args_one 5043 : diag::err_typecheck_call_too_many_args_at_most_one) 5044 << FnKind << FDecl->getParamDecl(0) 5045 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 5046 << SourceRange(Args[NumParams]->getBeginLoc(), 5047 Args.back()->getEndLoc()); 5048 else 5049 Diag(Args[NumParams]->getBeginLoc(), 5050 MinArgs == NumParams 5051 ? diag::err_typecheck_call_too_many_args 5052 : diag::err_typecheck_call_too_many_args_at_most) 5053 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 5054 << Fn->getSourceRange() 5055 << SourceRange(Args[NumParams]->getBeginLoc(), 5056 Args.back()->getEndLoc()); 5057 5058 // Emit the location of the prototype. 5059 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5060 Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl; 5061 5062 // This deletes the extra arguments. 5063 Call->shrinkNumArgs(NumParams); 5064 return true; 5065 } 5066 } 5067 SmallVector<Expr *, 8> AllArgs; 5068 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 5069 5070 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 5071 AllArgs, CallType); 5072 if (Invalid) 5073 return true; 5074 unsigned TotalNumArgs = AllArgs.size(); 5075 for (unsigned i = 0; i < TotalNumArgs; ++i) 5076 Call->setArg(i, AllArgs[i]); 5077 5078 return false; 5079 } 5080 5081 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 5082 const FunctionProtoType *Proto, 5083 unsigned FirstParam, ArrayRef<Expr *> Args, 5084 SmallVectorImpl<Expr *> &AllArgs, 5085 VariadicCallType CallType, bool AllowExplicit, 5086 bool IsListInitialization) { 5087 unsigned NumParams = Proto->getNumParams(); 5088 bool Invalid = false; 5089 size_t ArgIx = 0; 5090 // Continue to check argument types (even if we have too few/many args). 5091 for (unsigned i = FirstParam; i < NumParams; i++) { 5092 QualType ProtoArgType = Proto->getParamType(i); 5093 5094 Expr *Arg; 5095 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 5096 if (ArgIx < Args.size()) { 5097 Arg = Args[ArgIx++]; 5098 5099 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5100 diag::err_call_incomplete_argument, Arg)) 5101 return true; 5102 5103 // Strip the unbridged-cast placeholder expression off, if applicable. 5104 bool CFAudited = false; 5105 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5106 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5107 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5108 Arg = stripARCUnbridgedCast(Arg); 5109 else if (getLangOpts().ObjCAutoRefCount && 5110 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5111 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5112 CFAudited = true; 5113 5114 if (Proto->getExtParameterInfo(i).isNoEscape()) 5115 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 5116 BE->getBlockDecl()->setDoesNotEscape(); 5117 5118 InitializedEntity Entity = 5119 Param ? InitializedEntity::InitializeParameter(Context, Param, 5120 ProtoArgType) 5121 : InitializedEntity::InitializeParameter( 5122 Context, ProtoArgType, Proto->isParamConsumed(i)); 5123 5124 // Remember that parameter belongs to a CF audited API. 5125 if (CFAudited) 5126 Entity.setParameterCFAudited(); 5127 5128 ExprResult ArgE = PerformCopyInitialization( 5129 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 5130 if (ArgE.isInvalid()) 5131 return true; 5132 5133 Arg = ArgE.getAs<Expr>(); 5134 } else { 5135 assert(Param && "can't use default arguments without a known callee"); 5136 5137 ExprResult ArgExpr = 5138 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 5139 if (ArgExpr.isInvalid()) 5140 return true; 5141 5142 Arg = ArgExpr.getAs<Expr>(); 5143 } 5144 5145 // Check for array bounds violations for each argument to the call. This 5146 // check only triggers warnings when the argument isn't a more complex Expr 5147 // with its own checking, such as a BinaryOperator. 5148 CheckArrayAccess(Arg); 5149 5150 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 5151 CheckStaticArrayArgument(CallLoc, Param, Arg); 5152 5153 AllArgs.push_back(Arg); 5154 } 5155 5156 // If this is a variadic call, handle args passed through "...". 5157 if (CallType != VariadicDoesNotApply) { 5158 // Assume that extern "C" functions with variadic arguments that 5159 // return __unknown_anytype aren't *really* variadic. 5160 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 5161 FDecl->isExternC()) { 5162 for (Expr *A : Args.slice(ArgIx)) { 5163 QualType paramType; // ignored 5164 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 5165 Invalid |= arg.isInvalid(); 5166 AllArgs.push_back(arg.get()); 5167 } 5168 5169 // Otherwise do argument promotion, (C99 6.5.2.2p7). 5170 } else { 5171 for (Expr *A : Args.slice(ArgIx)) { 5172 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 5173 Invalid |= Arg.isInvalid(); 5174 AllArgs.push_back(Arg.get()); 5175 } 5176 } 5177 5178 // Check for array bounds violations. 5179 for (Expr *A : Args.slice(ArgIx)) 5180 CheckArrayAccess(A); 5181 } 5182 return Invalid; 5183 } 5184 5185 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 5186 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 5187 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 5188 TL = DTL.getOriginalLoc(); 5189 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 5190 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 5191 << ATL.getLocalSourceRange(); 5192 } 5193 5194 /// CheckStaticArrayArgument - If the given argument corresponds to a static 5195 /// array parameter, check that it is non-null, and that if it is formed by 5196 /// array-to-pointer decay, the underlying array is sufficiently large. 5197 /// 5198 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 5199 /// array type derivation, then for each call to the function, the value of the 5200 /// corresponding actual argument shall provide access to the first element of 5201 /// an array with at least as many elements as specified by the size expression. 5202 void 5203 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 5204 ParmVarDecl *Param, 5205 const Expr *ArgExpr) { 5206 // Static array parameters are not supported in C++. 5207 if (!Param || getLangOpts().CPlusPlus) 5208 return; 5209 5210 QualType OrigTy = Param->getOriginalType(); 5211 5212 const ArrayType *AT = Context.getAsArrayType(OrigTy); 5213 if (!AT || AT->getSizeModifier() != ArrayType::Static) 5214 return; 5215 5216 if (ArgExpr->isNullPointerConstant(Context, 5217 Expr::NPC_NeverValueDependent)) { 5218 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 5219 DiagnoseCalleeStaticArrayParam(*this, Param); 5220 return; 5221 } 5222 5223 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 5224 if (!CAT) 5225 return; 5226 5227 const ConstantArrayType *ArgCAT = 5228 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 5229 if (!ArgCAT) 5230 return; 5231 5232 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 5233 ArgCAT->getElementType())) { 5234 if (ArgCAT->getSize().ult(CAT->getSize())) { 5235 Diag(CallLoc, diag::warn_static_array_too_small) 5236 << ArgExpr->getSourceRange() 5237 << (unsigned)ArgCAT->getSize().getZExtValue() 5238 << (unsigned)CAT->getSize().getZExtValue() << 0; 5239 DiagnoseCalleeStaticArrayParam(*this, Param); 5240 } 5241 return; 5242 } 5243 5244 Optional<CharUnits> ArgSize = 5245 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 5246 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 5247 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 5248 Diag(CallLoc, diag::warn_static_array_too_small) 5249 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 5250 << (unsigned)ParmSize->getQuantity() << 1; 5251 DiagnoseCalleeStaticArrayParam(*this, Param); 5252 } 5253 } 5254 5255 /// Given a function expression of unknown-any type, try to rebuild it 5256 /// to have a function type. 5257 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 5258 5259 /// Is the given type a placeholder that we need to lower out 5260 /// immediately during argument processing? 5261 static bool isPlaceholderToRemoveAsArg(QualType type) { 5262 // Placeholders are never sugared. 5263 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 5264 if (!placeholder) return false; 5265 5266 switch (placeholder->getKind()) { 5267 // Ignore all the non-placeholder types. 5268 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 5269 case BuiltinType::Id: 5270 #include "clang/Basic/OpenCLImageTypes.def" 5271 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 5272 case BuiltinType::Id: 5273 #include "clang/Basic/OpenCLExtensionTypes.def" 5274 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 5275 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 5276 #include "clang/AST/BuiltinTypes.def" 5277 return false; 5278 5279 // We cannot lower out overload sets; they might validly be resolved 5280 // by the call machinery. 5281 case BuiltinType::Overload: 5282 return false; 5283 5284 // Unbridged casts in ARC can be handled in some call positions and 5285 // should be left in place. 5286 case BuiltinType::ARCUnbridgedCast: 5287 return false; 5288 5289 // Pseudo-objects should be converted as soon as possible. 5290 case BuiltinType::PseudoObject: 5291 return true; 5292 5293 // The debugger mode could theoretically but currently does not try 5294 // to resolve unknown-typed arguments based on known parameter types. 5295 case BuiltinType::UnknownAny: 5296 return true; 5297 5298 // These are always invalid as call arguments and should be reported. 5299 case BuiltinType::BoundMember: 5300 case BuiltinType::BuiltinFn: 5301 case BuiltinType::OMPArraySection: 5302 return true; 5303 5304 } 5305 llvm_unreachable("bad builtin type kind"); 5306 } 5307 5308 /// Check an argument list for placeholders that we won't try to 5309 /// handle later. 5310 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5311 // Apply this processing to all the arguments at once instead of 5312 // dying at the first failure. 5313 bool hasInvalid = false; 5314 for (size_t i = 0, e = args.size(); i != e; i++) { 5315 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5316 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5317 if (result.isInvalid()) hasInvalid = true; 5318 else args[i] = result.get(); 5319 } else if (hasInvalid) { 5320 (void)S.CorrectDelayedTyposInExpr(args[i]); 5321 } 5322 } 5323 return hasInvalid; 5324 } 5325 5326 /// If a builtin function has a pointer argument with no explicit address 5327 /// space, then it should be able to accept a pointer to any address 5328 /// space as input. In order to do this, we need to replace the 5329 /// standard builtin declaration with one that uses the same address space 5330 /// as the call. 5331 /// 5332 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5333 /// it does not contain any pointer arguments without 5334 /// an address space qualifer. Otherwise the rewritten 5335 /// FunctionDecl is returned. 5336 /// TODO: Handle pointer return types. 5337 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5338 const FunctionDecl *FDecl, 5339 MultiExprArg ArgExprs) { 5340 5341 QualType DeclType = FDecl->getType(); 5342 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5343 5344 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 5345 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 5346 return nullptr; 5347 5348 bool NeedsNewDecl = false; 5349 unsigned i = 0; 5350 SmallVector<QualType, 8> OverloadParams; 5351 5352 for (QualType ParamType : FT->param_types()) { 5353 5354 // Convert array arguments to pointer to simplify type lookup. 5355 ExprResult ArgRes = 5356 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5357 if (ArgRes.isInvalid()) 5358 return nullptr; 5359 Expr *Arg = ArgRes.get(); 5360 QualType ArgType = Arg->getType(); 5361 if (!ParamType->isPointerType() || 5362 ParamType.getQualifiers().hasAddressSpace() || 5363 !ArgType->isPointerType() || 5364 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 5365 OverloadParams.push_back(ParamType); 5366 continue; 5367 } 5368 5369 QualType PointeeType = ParamType->getPointeeType(); 5370 if (PointeeType.getQualifiers().hasAddressSpace()) 5371 continue; 5372 5373 NeedsNewDecl = true; 5374 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 5375 5376 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5377 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5378 } 5379 5380 if (!NeedsNewDecl) 5381 return nullptr; 5382 5383 FunctionProtoType::ExtProtoInfo EPI; 5384 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5385 OverloadParams, EPI); 5386 DeclContext *Parent = Context.getTranslationUnitDecl(); 5387 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5388 FDecl->getLocation(), 5389 FDecl->getLocation(), 5390 FDecl->getIdentifier(), 5391 OverloadTy, 5392 /*TInfo=*/nullptr, 5393 SC_Extern, false, 5394 /*hasPrototype=*/true); 5395 SmallVector<ParmVarDecl*, 16> Params; 5396 FT = cast<FunctionProtoType>(OverloadTy); 5397 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5398 QualType ParamType = FT->getParamType(i); 5399 ParmVarDecl *Parm = 5400 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5401 SourceLocation(), nullptr, ParamType, 5402 /*TInfo=*/nullptr, SC_None, nullptr); 5403 Parm->setScopeInfo(0, i); 5404 Params.push_back(Parm); 5405 } 5406 OverloadDecl->setParams(Params); 5407 return OverloadDecl; 5408 } 5409 5410 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 5411 FunctionDecl *Callee, 5412 MultiExprArg ArgExprs) { 5413 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 5414 // similar attributes) really don't like it when functions are called with an 5415 // invalid number of args. 5416 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 5417 /*PartialOverloading=*/false) && 5418 !Callee->isVariadic()) 5419 return; 5420 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 5421 return; 5422 5423 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) { 5424 S.Diag(Fn->getBeginLoc(), 5425 isa<CXXMethodDecl>(Callee) 5426 ? diag::err_ovl_no_viable_member_function_in_call 5427 : diag::err_ovl_no_viable_function_in_call) 5428 << Callee << Callee->getSourceRange(); 5429 S.Diag(Callee->getLocation(), 5430 diag::note_ovl_candidate_disabled_by_function_cond_attr) 5431 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5432 return; 5433 } 5434 } 5435 5436 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 5437 const UnresolvedMemberExpr *const UME, Sema &S) { 5438 5439 const auto GetFunctionLevelDCIfCXXClass = 5440 [](Sema &S) -> const CXXRecordDecl * { 5441 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 5442 if (!DC || !DC->getParent()) 5443 return nullptr; 5444 5445 // If the call to some member function was made from within a member 5446 // function body 'M' return return 'M's parent. 5447 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 5448 return MD->getParent()->getCanonicalDecl(); 5449 // else the call was made from within a default member initializer of a 5450 // class, so return the class. 5451 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 5452 return RD->getCanonicalDecl(); 5453 return nullptr; 5454 }; 5455 // If our DeclContext is neither a member function nor a class (in the 5456 // case of a lambda in a default member initializer), we can't have an 5457 // enclosing 'this'. 5458 5459 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 5460 if (!CurParentClass) 5461 return false; 5462 5463 // The naming class for implicit member functions call is the class in which 5464 // name lookup starts. 5465 const CXXRecordDecl *const NamingClass = 5466 UME->getNamingClass()->getCanonicalDecl(); 5467 assert(NamingClass && "Must have naming class even for implicit access"); 5468 5469 // If the unresolved member functions were found in a 'naming class' that is 5470 // related (either the same or derived from) to the class that contains the 5471 // member function that itself contained the implicit member access. 5472 5473 return CurParentClass == NamingClass || 5474 CurParentClass->isDerivedFrom(NamingClass); 5475 } 5476 5477 static void 5478 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5479 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 5480 5481 if (!UME) 5482 return; 5483 5484 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 5485 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 5486 // already been captured, or if this is an implicit member function call (if 5487 // it isn't, an attempt to capture 'this' should already have been made). 5488 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 5489 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 5490 return; 5491 5492 // Check if the naming class in which the unresolved members were found is 5493 // related (same as or is a base of) to the enclosing class. 5494 5495 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 5496 return; 5497 5498 5499 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 5500 // If the enclosing function is not dependent, then this lambda is 5501 // capture ready, so if we can capture this, do so. 5502 if (!EnclosingFunctionCtx->isDependentContext()) { 5503 // If the current lambda and all enclosing lambdas can capture 'this' - 5504 // then go ahead and capture 'this' (since our unresolved overload set 5505 // contains at least one non-static member function). 5506 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 5507 S.CheckCXXThisCapture(CallLoc); 5508 } else if (S.CurContext->isDependentContext()) { 5509 // ... since this is an implicit member reference, that might potentially 5510 // involve a 'this' capture, mark 'this' for potential capture in 5511 // enclosing lambdas. 5512 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 5513 CurLSI->addPotentialThisCapture(CallLoc); 5514 } 5515 } 5516 5517 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 5518 /// This provides the location of the left/right parens and a list of comma 5519 /// locations. 5520 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5521 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5522 Expr *ExecConfig, bool IsExecConfig) { 5523 // Since this might be a postfix expression, get rid of ParenListExprs. 5524 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 5525 if (Result.isInvalid()) return ExprError(); 5526 Fn = Result.get(); 5527 5528 if (checkArgsForPlaceholders(*this, ArgExprs)) 5529 return ExprError(); 5530 5531 if (getLangOpts().CPlusPlus) { 5532 // If this is a pseudo-destructor expression, build the call immediately. 5533 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5534 if (!ArgExprs.empty()) { 5535 // Pseudo-destructor calls should not have any arguments. 5536 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 5537 << FixItHint::CreateRemoval( 5538 SourceRange(ArgExprs.front()->getBeginLoc(), 5539 ArgExprs.back()->getEndLoc())); 5540 } 5541 5542 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 5543 VK_RValue, RParenLoc); 5544 } 5545 if (Fn->getType() == Context.PseudoObjectTy) { 5546 ExprResult result = CheckPlaceholderExpr(Fn); 5547 if (result.isInvalid()) return ExprError(); 5548 Fn = result.get(); 5549 } 5550 5551 // Determine whether this is a dependent call inside a C++ template, 5552 // in which case we won't do any semantic analysis now. 5553 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 5554 if (ExecConfig) { 5555 return CUDAKernelCallExpr::Create( 5556 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5557 Context.DependentTy, VK_RValue, RParenLoc); 5558 } else { 5559 5560 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5561 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 5562 Fn->getBeginLoc()); 5563 5564 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 5565 VK_RValue, RParenLoc); 5566 } 5567 } 5568 5569 // Determine whether this is a call to an object (C++ [over.call.object]). 5570 if (Fn->getType()->isRecordType()) 5571 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 5572 RParenLoc); 5573 5574 if (Fn->getType() == Context.UnknownAnyTy) { 5575 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5576 if (result.isInvalid()) return ExprError(); 5577 Fn = result.get(); 5578 } 5579 5580 if (Fn->getType() == Context.BoundMemberTy) { 5581 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5582 RParenLoc); 5583 } 5584 } 5585 5586 // Check for overloaded calls. This can happen even in C due to extensions. 5587 if (Fn->getType() == Context.OverloadTy) { 5588 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5589 5590 // We aren't supposed to apply this logic if there's an '&' involved. 5591 if (!find.HasFormOfMemberPointer) { 5592 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5593 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 5594 VK_RValue, RParenLoc); 5595 OverloadExpr *ovl = find.Expression; 5596 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5597 return BuildOverloadedCallExpr( 5598 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 5599 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 5600 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5601 RParenLoc); 5602 } 5603 } 5604 5605 // If we're directly calling a function, get the appropriate declaration. 5606 if (Fn->getType() == Context.UnknownAnyTy) { 5607 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5608 if (result.isInvalid()) return ExprError(); 5609 Fn = result.get(); 5610 } 5611 5612 Expr *NakedFn = Fn->IgnoreParens(); 5613 5614 bool CallingNDeclIndirectly = false; 5615 NamedDecl *NDecl = nullptr; 5616 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5617 if (UnOp->getOpcode() == UO_AddrOf) { 5618 CallingNDeclIndirectly = true; 5619 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5620 } 5621 } 5622 5623 if (isa<DeclRefExpr>(NakedFn)) { 5624 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 5625 5626 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5627 if (FDecl && FDecl->getBuiltinID()) { 5628 // Rewrite the function decl for this builtin by replacing parameters 5629 // with no explicit address space with the address space of the arguments 5630 // in ArgExprs. 5631 if ((FDecl = 5632 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5633 NDecl = FDecl; 5634 Fn = DeclRefExpr::Create( 5635 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 5636 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl); 5637 } 5638 } 5639 } else if (isa<MemberExpr>(NakedFn)) 5640 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5641 5642 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5643 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 5644 FD, /*Complain=*/true, Fn->getBeginLoc())) 5645 return ExprError(); 5646 5647 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 5648 return ExprError(); 5649 5650 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 5651 } 5652 5653 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5654 ExecConfig, IsExecConfig); 5655 } 5656 5657 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5658 /// 5659 /// __builtin_astype( value, dst type ) 5660 /// 5661 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5662 SourceLocation BuiltinLoc, 5663 SourceLocation RParenLoc) { 5664 ExprValueKind VK = VK_RValue; 5665 ExprObjectKind OK = OK_Ordinary; 5666 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5667 QualType SrcTy = E->getType(); 5668 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5669 return ExprError(Diag(BuiltinLoc, 5670 diag::err_invalid_astype_of_different_size) 5671 << DstTy 5672 << SrcTy 5673 << E->getSourceRange()); 5674 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5675 } 5676 5677 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5678 /// provided arguments. 5679 /// 5680 /// __builtin_convertvector( value, dst type ) 5681 /// 5682 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5683 SourceLocation BuiltinLoc, 5684 SourceLocation RParenLoc) { 5685 TypeSourceInfo *TInfo; 5686 GetTypeFromParser(ParsedDestTy, &TInfo); 5687 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5688 } 5689 5690 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5691 /// i.e. an expression not of \p OverloadTy. The expression should 5692 /// unary-convert to an expression of function-pointer or 5693 /// block-pointer type. 5694 /// 5695 /// \param NDecl the declaration being called, if available 5696 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5697 SourceLocation LParenLoc, 5698 ArrayRef<Expr *> Args, 5699 SourceLocation RParenLoc, Expr *Config, 5700 bool IsExecConfig, ADLCallKind UsesADL) { 5701 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5702 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5703 5704 // Functions with 'interrupt' attribute cannot be called directly. 5705 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5706 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5707 return ExprError(); 5708 } 5709 5710 // Interrupt handlers don't save off the VFP regs automatically on ARM, 5711 // so there's some risk when calling out to non-interrupt handler functions 5712 // that the callee might not preserve them. This is easy to diagnose here, 5713 // but can be very challenging to debug. 5714 if (auto *Caller = getCurFunctionDecl()) 5715 if (Caller->hasAttr<ARMInterruptAttr>()) { 5716 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 5717 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) 5718 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 5719 } 5720 5721 // Promote the function operand. 5722 // We special-case function promotion here because we only allow promoting 5723 // builtin functions to function pointers in the callee of a call. 5724 ExprResult Result; 5725 QualType ResultTy; 5726 if (BuiltinID && 5727 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5728 // Extract the return type from the (builtin) function pointer type. 5729 // FIXME Several builtins still have setType in 5730 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 5731 // Builtins.def to ensure they are correct before removing setType calls. 5732 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 5733 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 5734 ResultTy = FDecl->getCallResultType(); 5735 } else { 5736 Result = CallExprUnaryConversions(Fn); 5737 ResultTy = Context.BoolTy; 5738 } 5739 if (Result.isInvalid()) 5740 return ExprError(); 5741 Fn = Result.get(); 5742 5743 // Check for a valid function type, but only if it is not a builtin which 5744 // requires custom type checking. These will be handled by 5745 // CheckBuiltinFunctionCall below just after creation of the call expression. 5746 const FunctionType *FuncT = nullptr; 5747 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 5748 retry: 5749 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5750 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5751 // have type pointer to function". 5752 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5753 if (!FuncT) 5754 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5755 << Fn->getType() << Fn->getSourceRange()); 5756 } else if (const BlockPointerType *BPT = 5757 Fn->getType()->getAs<BlockPointerType>()) { 5758 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5759 } else { 5760 // Handle calls to expressions of unknown-any type. 5761 if (Fn->getType() == Context.UnknownAnyTy) { 5762 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5763 if (rewrite.isInvalid()) return ExprError(); 5764 Fn = rewrite.get(); 5765 goto retry; 5766 } 5767 5768 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5769 << Fn->getType() << Fn->getSourceRange()); 5770 } 5771 } 5772 5773 // Get the number of parameters in the function prototype, if any. 5774 // We will allocate space for max(Args.size(), NumParams) arguments 5775 // in the call expression. 5776 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 5777 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 5778 5779 CallExpr *TheCall; 5780 if (Config) { 5781 assert(UsesADL == ADLCallKind::NotADL && 5782 "CUDAKernelCallExpr should not use ADL"); 5783 TheCall = 5784 CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args, 5785 ResultTy, VK_RValue, RParenLoc, NumParams); 5786 } else { 5787 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, 5788 RParenLoc, NumParams, UsesADL); 5789 } 5790 5791 if (!getLangOpts().CPlusPlus) { 5792 // Forget about the nulled arguments since typo correction 5793 // do not handle them well. 5794 TheCall->shrinkNumArgs(Args.size()); 5795 // C cannot always handle TypoExpr nodes in builtin calls and direct 5796 // function calls as their argument checking don't necessarily handle 5797 // dependent types properly, so make sure any TypoExprs have been 5798 // dealt with. 5799 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5800 if (!Result.isUsable()) return ExprError(); 5801 CallExpr *TheOldCall = TheCall; 5802 TheCall = dyn_cast<CallExpr>(Result.get()); 5803 bool CorrectedTypos = TheCall != TheOldCall; 5804 if (!TheCall) return Result; 5805 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5806 5807 // A new call expression node was created if some typos were corrected. 5808 // However it may not have been constructed with enough storage. In this 5809 // case, rebuild the node with enough storage. The waste of space is 5810 // immaterial since this only happens when some typos were corrected. 5811 if (CorrectedTypos && Args.size() < NumParams) { 5812 if (Config) 5813 TheCall = CUDAKernelCallExpr::Create( 5814 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue, 5815 RParenLoc, NumParams); 5816 else 5817 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, 5818 RParenLoc, NumParams, UsesADL); 5819 } 5820 // We can now handle the nulled arguments for the default arguments. 5821 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 5822 } 5823 5824 // Bail out early if calling a builtin with custom type checking. 5825 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5826 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5827 5828 if (getLangOpts().CUDA) { 5829 if (Config) { 5830 // CUDA: Kernel calls must be to global functions 5831 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5832 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5833 << FDecl << Fn->getSourceRange()); 5834 5835 // CUDA: Kernel function must have 'void' return type 5836 if (!FuncT->getReturnType()->isVoidType()) 5837 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5838 << Fn->getType() << Fn->getSourceRange()); 5839 } else { 5840 // CUDA: Calls to global functions must be configured 5841 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5842 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5843 << FDecl << Fn->getSourceRange()); 5844 } 5845 } 5846 5847 // Check for a valid return type 5848 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 5849 FDecl)) 5850 return ExprError(); 5851 5852 // We know the result type of the call, set it. 5853 TheCall->setType(FuncT->getCallResultType(Context)); 5854 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5855 5856 if (Proto) { 5857 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5858 IsExecConfig)) 5859 return ExprError(); 5860 } else { 5861 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5862 5863 if (FDecl) { 5864 // Check if we have too few/too many template arguments, based 5865 // on our knowledge of the function definition. 5866 const FunctionDecl *Def = nullptr; 5867 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5868 Proto = Def->getType()->getAs<FunctionProtoType>(); 5869 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5870 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5871 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5872 } 5873 5874 // If the function we're calling isn't a function prototype, but we have 5875 // a function prototype from a prior declaratiom, use that prototype. 5876 if (!FDecl->hasPrototype()) 5877 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5878 } 5879 5880 // Promote the arguments (C99 6.5.2.2p6). 5881 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5882 Expr *Arg = Args[i]; 5883 5884 if (Proto && i < Proto->getNumParams()) { 5885 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5886 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5887 ExprResult ArgE = 5888 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5889 if (ArgE.isInvalid()) 5890 return true; 5891 5892 Arg = ArgE.getAs<Expr>(); 5893 5894 } else { 5895 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5896 5897 if (ArgE.isInvalid()) 5898 return true; 5899 5900 Arg = ArgE.getAs<Expr>(); 5901 } 5902 5903 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 5904 diag::err_call_incomplete_argument, Arg)) 5905 return ExprError(); 5906 5907 TheCall->setArg(i, Arg); 5908 } 5909 } 5910 5911 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5912 if (!Method->isStatic()) 5913 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5914 << Fn->getSourceRange()); 5915 5916 // Check for sentinels 5917 if (NDecl) 5918 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5919 5920 // Do special checking on direct calls to functions. 5921 if (FDecl) { 5922 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5923 return ExprError(); 5924 5925 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 5926 5927 if (BuiltinID) 5928 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5929 } else if (NDecl) { 5930 if (CheckPointerCall(NDecl, TheCall, Proto)) 5931 return ExprError(); 5932 } else { 5933 if (CheckOtherCall(TheCall, Proto)) 5934 return ExprError(); 5935 } 5936 5937 return MaybeBindToTemporary(TheCall); 5938 } 5939 5940 ExprResult 5941 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5942 SourceLocation RParenLoc, Expr *InitExpr) { 5943 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5944 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 5945 5946 TypeSourceInfo *TInfo; 5947 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5948 if (!TInfo) 5949 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5950 5951 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5952 } 5953 5954 ExprResult 5955 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5956 SourceLocation RParenLoc, Expr *LiteralExpr) { 5957 QualType literalType = TInfo->getType(); 5958 5959 if (literalType->isArrayType()) { 5960 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5961 diag::err_illegal_decl_array_incomplete_type, 5962 SourceRange(LParenLoc, 5963 LiteralExpr->getSourceRange().getEnd()))) 5964 return ExprError(); 5965 if (literalType->isVariableArrayType()) 5966 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5967 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5968 } else if (!literalType->isDependentType() && 5969 RequireCompleteType(LParenLoc, literalType, 5970 diag::err_typecheck_decl_incomplete_type, 5971 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5972 return ExprError(); 5973 5974 InitializedEntity Entity 5975 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5976 InitializationKind Kind 5977 = InitializationKind::CreateCStyleCast(LParenLoc, 5978 SourceRange(LParenLoc, RParenLoc), 5979 /*InitList=*/true); 5980 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5981 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5982 &literalType); 5983 if (Result.isInvalid()) 5984 return ExprError(); 5985 LiteralExpr = Result.get(); 5986 5987 bool isFileScope = !CurContext->isFunctionOrMethod(); 5988 5989 // In C, compound literals are l-values for some reason. 5990 // For GCC compatibility, in C++, file-scope array compound literals with 5991 // constant initializers are also l-values, and compound literals are 5992 // otherwise prvalues. 5993 // 5994 // (GCC also treats C++ list-initialized file-scope array prvalues with 5995 // constant initializers as l-values, but that's non-conforming, so we don't 5996 // follow it there.) 5997 // 5998 // FIXME: It would be better to handle the lvalue cases as materializing and 5999 // lifetime-extending a temporary object, but our materialized temporaries 6000 // representation only supports lifetime extension from a variable, not "out 6001 // of thin air". 6002 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 6003 // is bound to the result of applying array-to-pointer decay to the compound 6004 // literal. 6005 // FIXME: GCC supports compound literals of reference type, which should 6006 // obviously have a value kind derived from the kind of reference involved. 6007 ExprValueKind VK = 6008 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 6009 ? VK_RValue 6010 : VK_LValue; 6011 6012 if (isFileScope) 6013 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 6014 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 6015 Expr *Init = ILE->getInit(i); 6016 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 6017 } 6018 6019 Expr *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 6020 VK, LiteralExpr, isFileScope); 6021 if (isFileScope) { 6022 if (!LiteralExpr->isTypeDependent() && 6023 !LiteralExpr->isValueDependent() && 6024 !literalType->isDependentType()) // C99 6.5.2.5p3 6025 if (CheckForConstantInitializer(LiteralExpr, literalType)) 6026 return ExprError(); 6027 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 6028 literalType.getAddressSpace() != LangAS::Default) { 6029 // Embedded-C extensions to C99 6.5.2.5: 6030 // "If the compound literal occurs inside the body of a function, the 6031 // type name shall not be qualified by an address-space qualifier." 6032 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 6033 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 6034 return ExprError(); 6035 } 6036 6037 return MaybeBindToTemporary(E); 6038 } 6039 6040 ExprResult 6041 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6042 SourceLocation RBraceLoc) { 6043 // Immediately handle non-overload placeholders. Overloads can be 6044 // resolved contextually, but everything else here can't. 6045 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6046 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 6047 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 6048 6049 // Ignore failures; dropping the entire initializer list because 6050 // of one failure would be terrible for indexing/etc. 6051 if (result.isInvalid()) continue; 6052 6053 InitArgList[I] = result.get(); 6054 } 6055 } 6056 6057 // Semantic analysis for initializers is done by ActOnDeclarator() and 6058 // CheckInitializer() - it requires knowledge of the object being initialized. 6059 6060 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 6061 RBraceLoc); 6062 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 6063 return E; 6064 } 6065 6066 /// Do an explicit extend of the given block pointer if we're in ARC. 6067 void Sema::maybeExtendBlockObject(ExprResult &E) { 6068 assert(E.get()->getType()->isBlockPointerType()); 6069 assert(E.get()->isRValue()); 6070 6071 // Only do this in an r-value context. 6072 if (!getLangOpts().ObjCAutoRefCount) return; 6073 6074 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 6075 CK_ARCExtendBlockObject, E.get(), 6076 /*base path*/ nullptr, VK_RValue); 6077 Cleanup.setExprNeedsCleanups(true); 6078 } 6079 6080 /// Prepare a conversion of the given expression to an ObjC object 6081 /// pointer type. 6082 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 6083 QualType type = E.get()->getType(); 6084 if (type->isObjCObjectPointerType()) { 6085 return CK_BitCast; 6086 } else if (type->isBlockPointerType()) { 6087 maybeExtendBlockObject(E); 6088 return CK_BlockPointerToObjCPointerCast; 6089 } else { 6090 assert(type->isPointerType()); 6091 return CK_CPointerToObjCPointerCast; 6092 } 6093 } 6094 6095 /// Prepares for a scalar cast, performing all the necessary stages 6096 /// except the final cast and returning the kind required. 6097 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 6098 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 6099 // Also, callers should have filtered out the invalid cases with 6100 // pointers. Everything else should be possible. 6101 6102 QualType SrcTy = Src.get()->getType(); 6103 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 6104 return CK_NoOp; 6105 6106 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 6107 case Type::STK_MemberPointer: 6108 llvm_unreachable("member pointer type in C"); 6109 6110 case Type::STK_CPointer: 6111 case Type::STK_BlockPointer: 6112 case Type::STK_ObjCObjectPointer: 6113 switch (DestTy->getScalarTypeKind()) { 6114 case Type::STK_CPointer: { 6115 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 6116 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 6117 if (SrcAS != DestAS) 6118 return CK_AddressSpaceConversion; 6119 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 6120 return CK_NoOp; 6121 return CK_BitCast; 6122 } 6123 case Type::STK_BlockPointer: 6124 return (SrcKind == Type::STK_BlockPointer 6125 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 6126 case Type::STK_ObjCObjectPointer: 6127 if (SrcKind == Type::STK_ObjCObjectPointer) 6128 return CK_BitCast; 6129 if (SrcKind == Type::STK_CPointer) 6130 return CK_CPointerToObjCPointerCast; 6131 maybeExtendBlockObject(Src); 6132 return CK_BlockPointerToObjCPointerCast; 6133 case Type::STK_Bool: 6134 return CK_PointerToBoolean; 6135 case Type::STK_Integral: 6136 return CK_PointerToIntegral; 6137 case Type::STK_Floating: 6138 case Type::STK_FloatingComplex: 6139 case Type::STK_IntegralComplex: 6140 case Type::STK_MemberPointer: 6141 case Type::STK_FixedPoint: 6142 llvm_unreachable("illegal cast from pointer"); 6143 } 6144 llvm_unreachable("Should have returned before this"); 6145 6146 case Type::STK_FixedPoint: 6147 switch (DestTy->getScalarTypeKind()) { 6148 case Type::STK_FixedPoint: 6149 return CK_FixedPointCast; 6150 case Type::STK_Bool: 6151 return CK_FixedPointToBoolean; 6152 case Type::STK_Integral: 6153 return CK_FixedPointToIntegral; 6154 case Type::STK_Floating: 6155 case Type::STK_IntegralComplex: 6156 case Type::STK_FloatingComplex: 6157 Diag(Src.get()->getExprLoc(), 6158 diag::err_unimplemented_conversion_with_fixed_point_type) 6159 << DestTy; 6160 return CK_IntegralCast; 6161 case Type::STK_CPointer: 6162 case Type::STK_ObjCObjectPointer: 6163 case Type::STK_BlockPointer: 6164 case Type::STK_MemberPointer: 6165 llvm_unreachable("illegal cast to pointer type"); 6166 } 6167 llvm_unreachable("Should have returned before this"); 6168 6169 case Type::STK_Bool: // casting from bool is like casting from an integer 6170 case Type::STK_Integral: 6171 switch (DestTy->getScalarTypeKind()) { 6172 case Type::STK_CPointer: 6173 case Type::STK_ObjCObjectPointer: 6174 case Type::STK_BlockPointer: 6175 if (Src.get()->isNullPointerConstant(Context, 6176 Expr::NPC_ValueDependentIsNull)) 6177 return CK_NullToPointer; 6178 return CK_IntegralToPointer; 6179 case Type::STK_Bool: 6180 return CK_IntegralToBoolean; 6181 case Type::STK_Integral: 6182 return CK_IntegralCast; 6183 case Type::STK_Floating: 6184 return CK_IntegralToFloating; 6185 case Type::STK_IntegralComplex: 6186 Src = ImpCastExprToType(Src.get(), 6187 DestTy->castAs<ComplexType>()->getElementType(), 6188 CK_IntegralCast); 6189 return CK_IntegralRealToComplex; 6190 case Type::STK_FloatingComplex: 6191 Src = ImpCastExprToType(Src.get(), 6192 DestTy->castAs<ComplexType>()->getElementType(), 6193 CK_IntegralToFloating); 6194 return CK_FloatingRealToComplex; 6195 case Type::STK_MemberPointer: 6196 llvm_unreachable("member pointer type in C"); 6197 case Type::STK_FixedPoint: 6198 return CK_IntegralToFixedPoint; 6199 } 6200 llvm_unreachable("Should have returned before this"); 6201 6202 case Type::STK_Floating: 6203 switch (DestTy->getScalarTypeKind()) { 6204 case Type::STK_Floating: 6205 return CK_FloatingCast; 6206 case Type::STK_Bool: 6207 return CK_FloatingToBoolean; 6208 case Type::STK_Integral: 6209 return CK_FloatingToIntegral; 6210 case Type::STK_FloatingComplex: 6211 Src = ImpCastExprToType(Src.get(), 6212 DestTy->castAs<ComplexType>()->getElementType(), 6213 CK_FloatingCast); 6214 return CK_FloatingRealToComplex; 6215 case Type::STK_IntegralComplex: 6216 Src = ImpCastExprToType(Src.get(), 6217 DestTy->castAs<ComplexType>()->getElementType(), 6218 CK_FloatingToIntegral); 6219 return CK_IntegralRealToComplex; 6220 case Type::STK_CPointer: 6221 case Type::STK_ObjCObjectPointer: 6222 case Type::STK_BlockPointer: 6223 llvm_unreachable("valid float->pointer cast?"); 6224 case Type::STK_MemberPointer: 6225 llvm_unreachable("member pointer type in C"); 6226 case Type::STK_FixedPoint: 6227 Diag(Src.get()->getExprLoc(), 6228 diag::err_unimplemented_conversion_with_fixed_point_type) 6229 << SrcTy; 6230 return CK_IntegralCast; 6231 } 6232 llvm_unreachable("Should have returned before this"); 6233 6234 case Type::STK_FloatingComplex: 6235 switch (DestTy->getScalarTypeKind()) { 6236 case Type::STK_FloatingComplex: 6237 return CK_FloatingComplexCast; 6238 case Type::STK_IntegralComplex: 6239 return CK_FloatingComplexToIntegralComplex; 6240 case Type::STK_Floating: { 6241 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 6242 if (Context.hasSameType(ET, DestTy)) 6243 return CK_FloatingComplexToReal; 6244 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 6245 return CK_FloatingCast; 6246 } 6247 case Type::STK_Bool: 6248 return CK_FloatingComplexToBoolean; 6249 case Type::STK_Integral: 6250 Src = ImpCastExprToType(Src.get(), 6251 SrcTy->castAs<ComplexType>()->getElementType(), 6252 CK_FloatingComplexToReal); 6253 return CK_FloatingToIntegral; 6254 case Type::STK_CPointer: 6255 case Type::STK_ObjCObjectPointer: 6256 case Type::STK_BlockPointer: 6257 llvm_unreachable("valid complex float->pointer cast?"); 6258 case Type::STK_MemberPointer: 6259 llvm_unreachable("member pointer type in C"); 6260 case Type::STK_FixedPoint: 6261 Diag(Src.get()->getExprLoc(), 6262 diag::err_unimplemented_conversion_with_fixed_point_type) 6263 << SrcTy; 6264 return CK_IntegralCast; 6265 } 6266 llvm_unreachable("Should have returned before this"); 6267 6268 case Type::STK_IntegralComplex: 6269 switch (DestTy->getScalarTypeKind()) { 6270 case Type::STK_FloatingComplex: 6271 return CK_IntegralComplexToFloatingComplex; 6272 case Type::STK_IntegralComplex: 6273 return CK_IntegralComplexCast; 6274 case Type::STK_Integral: { 6275 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 6276 if (Context.hasSameType(ET, DestTy)) 6277 return CK_IntegralComplexToReal; 6278 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 6279 return CK_IntegralCast; 6280 } 6281 case Type::STK_Bool: 6282 return CK_IntegralComplexToBoolean; 6283 case Type::STK_Floating: 6284 Src = ImpCastExprToType(Src.get(), 6285 SrcTy->castAs<ComplexType>()->getElementType(), 6286 CK_IntegralComplexToReal); 6287 return CK_IntegralToFloating; 6288 case Type::STK_CPointer: 6289 case Type::STK_ObjCObjectPointer: 6290 case Type::STK_BlockPointer: 6291 llvm_unreachable("valid complex int->pointer cast?"); 6292 case Type::STK_MemberPointer: 6293 llvm_unreachable("member pointer type in C"); 6294 case Type::STK_FixedPoint: 6295 Diag(Src.get()->getExprLoc(), 6296 diag::err_unimplemented_conversion_with_fixed_point_type) 6297 << SrcTy; 6298 return CK_IntegralCast; 6299 } 6300 llvm_unreachable("Should have returned before this"); 6301 } 6302 6303 llvm_unreachable("Unhandled scalar cast"); 6304 } 6305 6306 static bool breakDownVectorType(QualType type, uint64_t &len, 6307 QualType &eltType) { 6308 // Vectors are simple. 6309 if (const VectorType *vecType = type->getAs<VectorType>()) { 6310 len = vecType->getNumElements(); 6311 eltType = vecType->getElementType(); 6312 assert(eltType->isScalarType()); 6313 return true; 6314 } 6315 6316 // We allow lax conversion to and from non-vector types, but only if 6317 // they're real types (i.e. non-complex, non-pointer scalar types). 6318 if (!type->isRealType()) return false; 6319 6320 len = 1; 6321 eltType = type; 6322 return true; 6323 } 6324 6325 /// Are the two types lax-compatible vector types? That is, given 6326 /// that one of them is a vector, do they have equal storage sizes, 6327 /// where the storage size is the number of elements times the element 6328 /// size? 6329 /// 6330 /// This will also return false if either of the types is neither a 6331 /// vector nor a real type. 6332 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 6333 assert(destTy->isVectorType() || srcTy->isVectorType()); 6334 6335 // Disallow lax conversions between scalars and ExtVectors (these 6336 // conversions are allowed for other vector types because common headers 6337 // depend on them). Most scalar OP ExtVector cases are handled by the 6338 // splat path anyway, which does what we want (convert, not bitcast). 6339 // What this rules out for ExtVectors is crazy things like char4*float. 6340 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 6341 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 6342 6343 uint64_t srcLen, destLen; 6344 QualType srcEltTy, destEltTy; 6345 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 6346 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 6347 6348 // ASTContext::getTypeSize will return the size rounded up to a 6349 // power of 2, so instead of using that, we need to use the raw 6350 // element size multiplied by the element count. 6351 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 6352 uint64_t destEltSize = Context.getTypeSize(destEltTy); 6353 6354 return (srcLen * srcEltSize == destLen * destEltSize); 6355 } 6356 6357 /// Is this a legal conversion between two types, one of which is 6358 /// known to be a vector type? 6359 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 6360 assert(destTy->isVectorType() || srcTy->isVectorType()); 6361 6362 if (!Context.getLangOpts().LaxVectorConversions) 6363 return false; 6364 return areLaxCompatibleVectorTypes(srcTy, destTy); 6365 } 6366 6367 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 6368 CastKind &Kind) { 6369 assert(VectorTy->isVectorType() && "Not a vector type!"); 6370 6371 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 6372 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 6373 return Diag(R.getBegin(), 6374 Ty->isVectorType() ? 6375 diag::err_invalid_conversion_between_vectors : 6376 diag::err_invalid_conversion_between_vector_and_integer) 6377 << VectorTy << Ty << R; 6378 } else 6379 return Diag(R.getBegin(), 6380 diag::err_invalid_conversion_between_vector_and_scalar) 6381 << VectorTy << Ty << R; 6382 6383 Kind = CK_BitCast; 6384 return false; 6385 } 6386 6387 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 6388 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 6389 6390 if (DestElemTy == SplattedExpr->getType()) 6391 return SplattedExpr; 6392 6393 assert(DestElemTy->isFloatingType() || 6394 DestElemTy->isIntegralOrEnumerationType()); 6395 6396 CastKind CK; 6397 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 6398 // OpenCL requires that we convert `true` boolean expressions to -1, but 6399 // only when splatting vectors. 6400 if (DestElemTy->isFloatingType()) { 6401 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 6402 // in two steps: boolean to signed integral, then to floating. 6403 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 6404 CK_BooleanToSignedIntegral); 6405 SplattedExpr = CastExprRes.get(); 6406 CK = CK_IntegralToFloating; 6407 } else { 6408 CK = CK_BooleanToSignedIntegral; 6409 } 6410 } else { 6411 ExprResult CastExprRes = SplattedExpr; 6412 CK = PrepareScalarCast(CastExprRes, DestElemTy); 6413 if (CastExprRes.isInvalid()) 6414 return ExprError(); 6415 SplattedExpr = CastExprRes.get(); 6416 } 6417 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 6418 } 6419 6420 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 6421 Expr *CastExpr, CastKind &Kind) { 6422 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 6423 6424 QualType SrcTy = CastExpr->getType(); 6425 6426 // If SrcTy is a VectorType, the total size must match to explicitly cast to 6427 // an ExtVectorType. 6428 // In OpenCL, casts between vectors of different types are not allowed. 6429 // (See OpenCL 6.2). 6430 if (SrcTy->isVectorType()) { 6431 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 6432 (getLangOpts().OpenCL && 6433 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 6434 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 6435 << DestTy << SrcTy << R; 6436 return ExprError(); 6437 } 6438 Kind = CK_BitCast; 6439 return CastExpr; 6440 } 6441 6442 // All non-pointer scalars can be cast to ExtVector type. The appropriate 6443 // conversion will take place first from scalar to elt type, and then 6444 // splat from elt type to vector. 6445 if (SrcTy->isPointerType()) 6446 return Diag(R.getBegin(), 6447 diag::err_invalid_conversion_between_vector_and_scalar) 6448 << DestTy << SrcTy << R; 6449 6450 Kind = CK_VectorSplat; 6451 return prepareVectorSplat(DestTy, CastExpr); 6452 } 6453 6454 ExprResult 6455 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 6456 Declarator &D, ParsedType &Ty, 6457 SourceLocation RParenLoc, Expr *CastExpr) { 6458 assert(!D.isInvalidType() && (CastExpr != nullptr) && 6459 "ActOnCastExpr(): missing type or expr"); 6460 6461 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 6462 if (D.isInvalidType()) 6463 return ExprError(); 6464 6465 if (getLangOpts().CPlusPlus) { 6466 // Check that there are no default arguments (C++ only). 6467 CheckExtraCXXDefaultArguments(D); 6468 } else { 6469 // Make sure any TypoExprs have been dealt with. 6470 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 6471 if (!Res.isUsable()) 6472 return ExprError(); 6473 CastExpr = Res.get(); 6474 } 6475 6476 checkUnusedDeclAttributes(D); 6477 6478 QualType castType = castTInfo->getType(); 6479 Ty = CreateParsedType(castType, castTInfo); 6480 6481 bool isVectorLiteral = false; 6482 6483 // Check for an altivec or OpenCL literal, 6484 // i.e. all the elements are integer constants. 6485 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 6486 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 6487 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 6488 && castType->isVectorType() && (PE || PLE)) { 6489 if (PLE && PLE->getNumExprs() == 0) { 6490 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 6491 return ExprError(); 6492 } 6493 if (PE || PLE->getNumExprs() == 1) { 6494 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 6495 if (!E->getType()->isVectorType()) 6496 isVectorLiteral = true; 6497 } 6498 else 6499 isVectorLiteral = true; 6500 } 6501 6502 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 6503 // then handle it as such. 6504 if (isVectorLiteral) 6505 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 6506 6507 // If the Expr being casted is a ParenListExpr, handle it specially. 6508 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 6509 // sequence of BinOp comma operators. 6510 if (isa<ParenListExpr>(CastExpr)) { 6511 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 6512 if (Result.isInvalid()) return ExprError(); 6513 CastExpr = Result.get(); 6514 } 6515 6516 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6517 !getSourceManager().isInSystemMacro(LParenLoc)) 6518 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6519 6520 CheckTollFreeBridgeCast(castType, CastExpr); 6521 6522 CheckObjCBridgeRelatedCast(castType, CastExpr); 6523 6524 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 6525 6526 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6527 } 6528 6529 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6530 SourceLocation RParenLoc, Expr *E, 6531 TypeSourceInfo *TInfo) { 6532 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6533 "Expected paren or paren list expression"); 6534 6535 Expr **exprs; 6536 unsigned numExprs; 6537 Expr *subExpr; 6538 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6539 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6540 LiteralLParenLoc = PE->getLParenLoc(); 6541 LiteralRParenLoc = PE->getRParenLoc(); 6542 exprs = PE->getExprs(); 6543 numExprs = PE->getNumExprs(); 6544 } else { // isa<ParenExpr> by assertion at function entrance 6545 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6546 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6547 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6548 exprs = &subExpr; 6549 numExprs = 1; 6550 } 6551 6552 QualType Ty = TInfo->getType(); 6553 assert(Ty->isVectorType() && "Expected vector type"); 6554 6555 SmallVector<Expr *, 8> initExprs; 6556 const VectorType *VTy = Ty->getAs<VectorType>(); 6557 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 6558 6559 // '(...)' form of vector initialization in AltiVec: the number of 6560 // initializers must be one or must match the size of the vector. 6561 // If a single value is specified in the initializer then it will be 6562 // replicated to all the components of the vector 6563 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6564 // The number of initializers must be one or must match the size of the 6565 // vector. If a single value is specified in the initializer then it will 6566 // be replicated to all the components of the vector 6567 if (numExprs == 1) { 6568 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6569 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6570 if (Literal.isInvalid()) 6571 return ExprError(); 6572 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6573 PrepareScalarCast(Literal, ElemTy)); 6574 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6575 } 6576 else if (numExprs < numElems) { 6577 Diag(E->getExprLoc(), 6578 diag::err_incorrect_number_of_vector_initializers); 6579 return ExprError(); 6580 } 6581 else 6582 initExprs.append(exprs, exprs + numExprs); 6583 } 6584 else { 6585 // For OpenCL, when the number of initializers is a single value, 6586 // it will be replicated to all components of the vector. 6587 if (getLangOpts().OpenCL && 6588 VTy->getVectorKind() == VectorType::GenericVector && 6589 numExprs == 1) { 6590 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6591 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6592 if (Literal.isInvalid()) 6593 return ExprError(); 6594 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6595 PrepareScalarCast(Literal, ElemTy)); 6596 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6597 } 6598 6599 initExprs.append(exprs, exprs + numExprs); 6600 } 6601 // FIXME: This means that pretty-printing the final AST will produce curly 6602 // braces instead of the original commas. 6603 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6604 initExprs, LiteralRParenLoc); 6605 initE->setType(Ty); 6606 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6607 } 6608 6609 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6610 /// the ParenListExpr into a sequence of comma binary operators. 6611 ExprResult 6612 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6613 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6614 if (!E) 6615 return OrigExpr; 6616 6617 ExprResult Result(E->getExpr(0)); 6618 6619 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6620 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6621 E->getExpr(i)); 6622 6623 if (Result.isInvalid()) return ExprError(); 6624 6625 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6626 } 6627 6628 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6629 SourceLocation R, 6630 MultiExprArg Val) { 6631 return ParenListExpr::Create(Context, L, Val, R); 6632 } 6633 6634 /// Emit a specialized diagnostic when one expression is a null pointer 6635 /// constant and the other is not a pointer. Returns true if a diagnostic is 6636 /// emitted. 6637 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6638 SourceLocation QuestionLoc) { 6639 Expr *NullExpr = LHSExpr; 6640 Expr *NonPointerExpr = RHSExpr; 6641 Expr::NullPointerConstantKind NullKind = 6642 NullExpr->isNullPointerConstant(Context, 6643 Expr::NPC_ValueDependentIsNotNull); 6644 6645 if (NullKind == Expr::NPCK_NotNull) { 6646 NullExpr = RHSExpr; 6647 NonPointerExpr = LHSExpr; 6648 NullKind = 6649 NullExpr->isNullPointerConstant(Context, 6650 Expr::NPC_ValueDependentIsNotNull); 6651 } 6652 6653 if (NullKind == Expr::NPCK_NotNull) 6654 return false; 6655 6656 if (NullKind == Expr::NPCK_ZeroExpression) 6657 return false; 6658 6659 if (NullKind == Expr::NPCK_ZeroLiteral) { 6660 // In this case, check to make sure that we got here from a "NULL" 6661 // string in the source code. 6662 NullExpr = NullExpr->IgnoreParenImpCasts(); 6663 SourceLocation loc = NullExpr->getExprLoc(); 6664 if (!findMacroSpelling(loc, "NULL")) 6665 return false; 6666 } 6667 6668 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6669 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6670 << NonPointerExpr->getType() << DiagType 6671 << NonPointerExpr->getSourceRange(); 6672 return true; 6673 } 6674 6675 /// Return false if the condition expression is valid, true otherwise. 6676 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6677 QualType CondTy = Cond->getType(); 6678 6679 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6680 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6681 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6682 << CondTy << Cond->getSourceRange(); 6683 return true; 6684 } 6685 6686 // C99 6.5.15p2 6687 if (CondTy->isScalarType()) return false; 6688 6689 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6690 << CondTy << Cond->getSourceRange(); 6691 return true; 6692 } 6693 6694 /// Handle when one or both operands are void type. 6695 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6696 ExprResult &RHS) { 6697 Expr *LHSExpr = LHS.get(); 6698 Expr *RHSExpr = RHS.get(); 6699 6700 if (!LHSExpr->getType()->isVoidType()) 6701 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 6702 << RHSExpr->getSourceRange(); 6703 if (!RHSExpr->getType()->isVoidType()) 6704 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 6705 << LHSExpr->getSourceRange(); 6706 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6707 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6708 return S.Context.VoidTy; 6709 } 6710 6711 /// Return false if the NullExpr can be promoted to PointerTy, 6712 /// true otherwise. 6713 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6714 QualType PointerTy) { 6715 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6716 !NullExpr.get()->isNullPointerConstant(S.Context, 6717 Expr::NPC_ValueDependentIsNull)) 6718 return true; 6719 6720 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6721 return false; 6722 } 6723 6724 /// Checks compatibility between two pointers and return the resulting 6725 /// type. 6726 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6727 ExprResult &RHS, 6728 SourceLocation Loc) { 6729 QualType LHSTy = LHS.get()->getType(); 6730 QualType RHSTy = RHS.get()->getType(); 6731 6732 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6733 // Two identical pointers types are always compatible. 6734 return LHSTy; 6735 } 6736 6737 QualType lhptee, rhptee; 6738 6739 // Get the pointee types. 6740 bool IsBlockPointer = false; 6741 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6742 lhptee = LHSBTy->getPointeeType(); 6743 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6744 IsBlockPointer = true; 6745 } else { 6746 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6747 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6748 } 6749 6750 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6751 // differently qualified versions of compatible types, the result type is 6752 // a pointer to an appropriately qualified version of the composite 6753 // type. 6754 6755 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6756 // clause doesn't make sense for our extensions. E.g. address space 2 should 6757 // be incompatible with address space 3: they may live on different devices or 6758 // anything. 6759 Qualifiers lhQual = lhptee.getQualifiers(); 6760 Qualifiers rhQual = rhptee.getQualifiers(); 6761 6762 LangAS ResultAddrSpace = LangAS::Default; 6763 LangAS LAddrSpace = lhQual.getAddressSpace(); 6764 LangAS RAddrSpace = rhQual.getAddressSpace(); 6765 6766 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 6767 // spaces is disallowed. 6768 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 6769 ResultAddrSpace = LAddrSpace; 6770 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 6771 ResultAddrSpace = RAddrSpace; 6772 else { 6773 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 6774 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 6775 << RHS.get()->getSourceRange(); 6776 return QualType(); 6777 } 6778 6779 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6780 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 6781 lhQual.removeCVRQualifiers(); 6782 rhQual.removeCVRQualifiers(); 6783 6784 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 6785 // (C99 6.7.3) for address spaces. We assume that the check should behave in 6786 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 6787 // qual types are compatible iff 6788 // * corresponded types are compatible 6789 // * CVR qualifiers are equal 6790 // * address spaces are equal 6791 // Thus for conditional operator we merge CVR and address space unqualified 6792 // pointees and if there is a composite type we return a pointer to it with 6793 // merged qualifiers. 6794 LHSCastKind = 6795 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 6796 RHSCastKind = 6797 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 6798 lhQual.removeAddressSpace(); 6799 rhQual.removeAddressSpace(); 6800 6801 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 6802 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 6803 6804 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 6805 6806 if (CompositeTy.isNull()) { 6807 // In this situation, we assume void* type. No especially good 6808 // reason, but this is what gcc does, and we do have to pick 6809 // to get a consistent AST. 6810 QualType incompatTy; 6811 incompatTy = S.Context.getPointerType( 6812 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 6813 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 6814 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 6815 6816 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 6817 // for casts between types with incompatible address space qualifiers. 6818 // For the following code the compiler produces casts between global and 6819 // local address spaces of the corresponded innermost pointees: 6820 // local int *global *a; 6821 // global int *global *b; 6822 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 6823 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 6824 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6825 << RHS.get()->getSourceRange(); 6826 6827 return incompatTy; 6828 } 6829 6830 // The pointer types are compatible. 6831 // In case of OpenCL ResultTy should have the address space qualifier 6832 // which is a superset of address spaces of both the 2nd and the 3rd 6833 // operands of the conditional operator. 6834 QualType ResultTy = [&, ResultAddrSpace]() { 6835 if (S.getLangOpts().OpenCL) { 6836 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 6837 CompositeQuals.setAddressSpace(ResultAddrSpace); 6838 return S.Context 6839 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 6840 .withCVRQualifiers(MergedCVRQual); 6841 } 6842 return CompositeTy.withCVRQualifiers(MergedCVRQual); 6843 }(); 6844 if (IsBlockPointer) 6845 ResultTy = S.Context.getBlockPointerType(ResultTy); 6846 else 6847 ResultTy = S.Context.getPointerType(ResultTy); 6848 6849 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 6850 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 6851 return ResultTy; 6852 } 6853 6854 /// Return the resulting type when the operands are both block pointers. 6855 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 6856 ExprResult &LHS, 6857 ExprResult &RHS, 6858 SourceLocation Loc) { 6859 QualType LHSTy = LHS.get()->getType(); 6860 QualType RHSTy = RHS.get()->getType(); 6861 6862 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 6863 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 6864 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 6865 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6866 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6867 return destType; 6868 } 6869 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 6870 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6871 << RHS.get()->getSourceRange(); 6872 return QualType(); 6873 } 6874 6875 // We have 2 block pointer types. 6876 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6877 } 6878 6879 /// Return the resulting type when the operands are both pointers. 6880 static QualType 6881 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 6882 ExprResult &RHS, 6883 SourceLocation Loc) { 6884 // get the pointer types 6885 QualType LHSTy = LHS.get()->getType(); 6886 QualType RHSTy = RHS.get()->getType(); 6887 6888 // get the "pointed to" types 6889 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6890 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6891 6892 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 6893 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 6894 // Figure out necessary qualifiers (C99 6.5.15p6) 6895 QualType destPointee 6896 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6897 QualType destType = S.Context.getPointerType(destPointee); 6898 // Add qualifiers if necessary. 6899 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6900 // Promote to void*. 6901 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6902 return destType; 6903 } 6904 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 6905 QualType destPointee 6906 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6907 QualType destType = S.Context.getPointerType(destPointee); 6908 // Add qualifiers if necessary. 6909 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6910 // Promote to void*. 6911 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6912 return destType; 6913 } 6914 6915 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6916 } 6917 6918 /// Return false if the first expression is not an integer and the second 6919 /// expression is not a pointer, true otherwise. 6920 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 6921 Expr* PointerExpr, SourceLocation Loc, 6922 bool IsIntFirstExpr) { 6923 if (!PointerExpr->getType()->isPointerType() || 6924 !Int.get()->getType()->isIntegerType()) 6925 return false; 6926 6927 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 6928 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 6929 6930 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 6931 << Expr1->getType() << Expr2->getType() 6932 << Expr1->getSourceRange() << Expr2->getSourceRange(); 6933 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 6934 CK_IntegralToPointer); 6935 return true; 6936 } 6937 6938 /// Simple conversion between integer and floating point types. 6939 /// 6940 /// Used when handling the OpenCL conditional operator where the 6941 /// condition is a vector while the other operands are scalar. 6942 /// 6943 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 6944 /// types are either integer or floating type. Between the two 6945 /// operands, the type with the higher rank is defined as the "result 6946 /// type". The other operand needs to be promoted to the same type. No 6947 /// other type promotion is allowed. We cannot use 6948 /// UsualArithmeticConversions() for this purpose, since it always 6949 /// promotes promotable types. 6950 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 6951 ExprResult &RHS, 6952 SourceLocation QuestionLoc) { 6953 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 6954 if (LHS.isInvalid()) 6955 return QualType(); 6956 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 6957 if (RHS.isInvalid()) 6958 return QualType(); 6959 6960 // For conversion purposes, we ignore any qualifiers. 6961 // For example, "const float" and "float" are equivalent. 6962 QualType LHSType = 6963 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6964 QualType RHSType = 6965 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6966 6967 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 6968 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6969 << LHSType << LHS.get()->getSourceRange(); 6970 return QualType(); 6971 } 6972 6973 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 6974 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6975 << RHSType << RHS.get()->getSourceRange(); 6976 return QualType(); 6977 } 6978 6979 // If both types are identical, no conversion is needed. 6980 if (LHSType == RHSType) 6981 return LHSType; 6982 6983 // Now handle "real" floating types (i.e. float, double, long double). 6984 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 6985 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 6986 /*IsCompAssign = */ false); 6987 6988 // Finally, we have two differing integer types. 6989 return handleIntegerConversion<doIntegralCast, doIntegralCast> 6990 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 6991 } 6992 6993 /// Convert scalar operands to a vector that matches the 6994 /// condition in length. 6995 /// 6996 /// Used when handling the OpenCL conditional operator where the 6997 /// condition is a vector while the other operands are scalar. 6998 /// 6999 /// We first compute the "result type" for the scalar operands 7000 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 7001 /// into a vector of that type where the length matches the condition 7002 /// vector type. s6.11.6 requires that the element types of the result 7003 /// and the condition must have the same number of bits. 7004 static QualType 7005 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 7006 QualType CondTy, SourceLocation QuestionLoc) { 7007 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 7008 if (ResTy.isNull()) return QualType(); 7009 7010 const VectorType *CV = CondTy->getAs<VectorType>(); 7011 assert(CV); 7012 7013 // Determine the vector result type 7014 unsigned NumElements = CV->getNumElements(); 7015 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 7016 7017 // Ensure that all types have the same number of bits 7018 if (S.Context.getTypeSize(CV->getElementType()) 7019 != S.Context.getTypeSize(ResTy)) { 7020 // Since VectorTy is created internally, it does not pretty print 7021 // with an OpenCL name. Instead, we just print a description. 7022 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 7023 SmallString<64> Str; 7024 llvm::raw_svector_ostream OS(Str); 7025 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 7026 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 7027 << CondTy << OS.str(); 7028 return QualType(); 7029 } 7030 7031 // Convert operands to the vector result type 7032 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 7033 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 7034 7035 return VectorTy; 7036 } 7037 7038 /// Return false if this is a valid OpenCL condition vector 7039 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 7040 SourceLocation QuestionLoc) { 7041 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 7042 // integral type. 7043 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 7044 assert(CondTy); 7045 QualType EleTy = CondTy->getElementType(); 7046 if (EleTy->isIntegerType()) return false; 7047 7048 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7049 << Cond->getType() << Cond->getSourceRange(); 7050 return true; 7051 } 7052 7053 /// Return false if the vector condition type and the vector 7054 /// result type are compatible. 7055 /// 7056 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 7057 /// number of elements, and their element types have the same number 7058 /// of bits. 7059 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 7060 SourceLocation QuestionLoc) { 7061 const VectorType *CV = CondTy->getAs<VectorType>(); 7062 const VectorType *RV = VecResTy->getAs<VectorType>(); 7063 assert(CV && RV); 7064 7065 if (CV->getNumElements() != RV->getNumElements()) { 7066 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 7067 << CondTy << VecResTy; 7068 return true; 7069 } 7070 7071 QualType CVE = CV->getElementType(); 7072 QualType RVE = RV->getElementType(); 7073 7074 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 7075 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 7076 << CondTy << VecResTy; 7077 return true; 7078 } 7079 7080 return false; 7081 } 7082 7083 /// Return the resulting type for the conditional operator in 7084 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 7085 /// s6.3.i) when the condition is a vector type. 7086 static QualType 7087 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 7088 ExprResult &LHS, ExprResult &RHS, 7089 SourceLocation QuestionLoc) { 7090 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 7091 if (Cond.isInvalid()) 7092 return QualType(); 7093 QualType CondTy = Cond.get()->getType(); 7094 7095 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 7096 return QualType(); 7097 7098 // If either operand is a vector then find the vector type of the 7099 // result as specified in OpenCL v1.1 s6.3.i. 7100 if (LHS.get()->getType()->isVectorType() || 7101 RHS.get()->getType()->isVectorType()) { 7102 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 7103 /*isCompAssign*/false, 7104 /*AllowBothBool*/true, 7105 /*AllowBoolConversions*/false); 7106 if (VecResTy.isNull()) return QualType(); 7107 // The result type must match the condition type as specified in 7108 // OpenCL v1.1 s6.11.6. 7109 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 7110 return QualType(); 7111 return VecResTy; 7112 } 7113 7114 // Both operands are scalar. 7115 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 7116 } 7117 7118 /// Return true if the Expr is block type 7119 static bool checkBlockType(Sema &S, const Expr *E) { 7120 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 7121 QualType Ty = CE->getCallee()->getType(); 7122 if (Ty->isBlockPointerType()) { 7123 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 7124 return true; 7125 } 7126 } 7127 return false; 7128 } 7129 7130 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 7131 /// In that case, LHS = cond. 7132 /// C99 6.5.15 7133 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 7134 ExprResult &RHS, ExprValueKind &VK, 7135 ExprObjectKind &OK, 7136 SourceLocation QuestionLoc) { 7137 7138 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 7139 if (!LHSResult.isUsable()) return QualType(); 7140 LHS = LHSResult; 7141 7142 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 7143 if (!RHSResult.isUsable()) return QualType(); 7144 RHS = RHSResult; 7145 7146 // C++ is sufficiently different to merit its own checker. 7147 if (getLangOpts().CPlusPlus) 7148 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 7149 7150 VK = VK_RValue; 7151 OK = OK_Ordinary; 7152 7153 // The OpenCL operator with a vector condition is sufficiently 7154 // different to merit its own checker. 7155 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 7156 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 7157 7158 // First, check the condition. 7159 Cond = UsualUnaryConversions(Cond.get()); 7160 if (Cond.isInvalid()) 7161 return QualType(); 7162 if (checkCondition(*this, Cond.get(), QuestionLoc)) 7163 return QualType(); 7164 7165 // Now check the two expressions. 7166 if (LHS.get()->getType()->isVectorType() || 7167 RHS.get()->getType()->isVectorType()) 7168 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 7169 /*AllowBothBool*/true, 7170 /*AllowBoolConversions*/false); 7171 7172 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 7173 if (LHS.isInvalid() || RHS.isInvalid()) 7174 return QualType(); 7175 7176 QualType LHSTy = LHS.get()->getType(); 7177 QualType RHSTy = RHS.get()->getType(); 7178 7179 // Diagnose attempts to convert between __float128 and long double where 7180 // such conversions currently can't be handled. 7181 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 7182 Diag(QuestionLoc, 7183 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 7184 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7185 return QualType(); 7186 } 7187 7188 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 7189 // selection operator (?:). 7190 if (getLangOpts().OpenCL && 7191 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 7192 return QualType(); 7193 } 7194 7195 // If both operands have arithmetic type, do the usual arithmetic conversions 7196 // to find a common type: C99 6.5.15p3,5. 7197 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 7198 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 7199 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 7200 7201 return ResTy; 7202 } 7203 7204 // If both operands are the same structure or union type, the result is that 7205 // type. 7206 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 7207 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 7208 if (LHSRT->getDecl() == RHSRT->getDecl()) 7209 // "If both the operands have structure or union type, the result has 7210 // that type." This implies that CV qualifiers are dropped. 7211 return LHSTy.getUnqualifiedType(); 7212 // FIXME: Type of conditional expression must be complete in C mode. 7213 } 7214 7215 // C99 6.5.15p5: "If both operands have void type, the result has void type." 7216 // The following || allows only one side to be void (a GCC-ism). 7217 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 7218 return checkConditionalVoidType(*this, LHS, RHS); 7219 } 7220 7221 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 7222 // the type of the other operand." 7223 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 7224 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 7225 7226 // All objective-c pointer type analysis is done here. 7227 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 7228 QuestionLoc); 7229 if (LHS.isInvalid() || RHS.isInvalid()) 7230 return QualType(); 7231 if (!compositeType.isNull()) 7232 return compositeType; 7233 7234 7235 // Handle block pointer types. 7236 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 7237 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 7238 QuestionLoc); 7239 7240 // Check constraints for C object pointers types (C99 6.5.15p3,6). 7241 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 7242 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 7243 QuestionLoc); 7244 7245 // GCC compatibility: soften pointer/integer mismatch. Note that 7246 // null pointers have been filtered out by this point. 7247 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 7248 /*isIntFirstExpr=*/true)) 7249 return RHSTy; 7250 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 7251 /*isIntFirstExpr=*/false)) 7252 return LHSTy; 7253 7254 // Emit a better diagnostic if one of the expressions is a null pointer 7255 // constant and the other is not a pointer type. In this case, the user most 7256 // likely forgot to take the address of the other expression. 7257 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 7258 return QualType(); 7259 7260 // Otherwise, the operands are not compatible. 7261 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 7262 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7263 << RHS.get()->getSourceRange(); 7264 return QualType(); 7265 } 7266 7267 /// FindCompositeObjCPointerType - Helper method to find composite type of 7268 /// two objective-c pointer types of the two input expressions. 7269 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 7270 SourceLocation QuestionLoc) { 7271 QualType LHSTy = LHS.get()->getType(); 7272 QualType RHSTy = RHS.get()->getType(); 7273 7274 // Handle things like Class and struct objc_class*. Here we case the result 7275 // to the pseudo-builtin, because that will be implicitly cast back to the 7276 // redefinition type if an attempt is made to access its fields. 7277 if (LHSTy->isObjCClassType() && 7278 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 7279 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 7280 return LHSTy; 7281 } 7282 if (RHSTy->isObjCClassType() && 7283 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 7284 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 7285 return RHSTy; 7286 } 7287 // And the same for struct objc_object* / id 7288 if (LHSTy->isObjCIdType() && 7289 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 7290 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 7291 return LHSTy; 7292 } 7293 if (RHSTy->isObjCIdType() && 7294 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 7295 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 7296 return RHSTy; 7297 } 7298 // And the same for struct objc_selector* / SEL 7299 if (Context.isObjCSelType(LHSTy) && 7300 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 7301 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 7302 return LHSTy; 7303 } 7304 if (Context.isObjCSelType(RHSTy) && 7305 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 7306 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 7307 return RHSTy; 7308 } 7309 // Check constraints for Objective-C object pointers types. 7310 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 7311 7312 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 7313 // Two identical object pointer types are always compatible. 7314 return LHSTy; 7315 } 7316 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 7317 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 7318 QualType compositeType = LHSTy; 7319 7320 // If both operands are interfaces and either operand can be 7321 // assigned to the other, use that type as the composite 7322 // type. This allows 7323 // xxx ? (A*) a : (B*) b 7324 // where B is a subclass of A. 7325 // 7326 // Additionally, as for assignment, if either type is 'id' 7327 // allow silent coercion. Finally, if the types are 7328 // incompatible then make sure to use 'id' as the composite 7329 // type so the result is acceptable for sending messages to. 7330 7331 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 7332 // It could return the composite type. 7333 if (!(compositeType = 7334 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 7335 // Nothing more to do. 7336 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 7337 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 7338 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 7339 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 7340 } else if ((LHSTy->isObjCQualifiedIdType() || 7341 RHSTy->isObjCQualifiedIdType()) && 7342 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 7343 // Need to handle "id<xx>" explicitly. 7344 // GCC allows qualified id and any Objective-C type to devolve to 7345 // id. Currently localizing to here until clear this should be 7346 // part of ObjCQualifiedIdTypesAreCompatible. 7347 compositeType = Context.getObjCIdType(); 7348 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 7349 compositeType = Context.getObjCIdType(); 7350 } else { 7351 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 7352 << LHSTy << RHSTy 7353 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7354 QualType incompatTy = Context.getObjCIdType(); 7355 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 7356 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 7357 return incompatTy; 7358 } 7359 // The object pointer types are compatible. 7360 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 7361 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 7362 return compositeType; 7363 } 7364 // Check Objective-C object pointer types and 'void *' 7365 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 7366 if (getLangOpts().ObjCAutoRefCount) { 7367 // ARC forbids the implicit conversion of object pointers to 'void *', 7368 // so these types are not compatible. 7369 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7370 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7371 LHS = RHS = true; 7372 return QualType(); 7373 } 7374 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 7375 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 7376 QualType destPointee 7377 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7378 QualType destType = Context.getPointerType(destPointee); 7379 // Add qualifiers if necessary. 7380 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7381 // Promote to void*. 7382 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7383 return destType; 7384 } 7385 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 7386 if (getLangOpts().ObjCAutoRefCount) { 7387 // ARC forbids the implicit conversion of object pointers to 'void *', 7388 // so these types are not compatible. 7389 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7390 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7391 LHS = RHS = true; 7392 return QualType(); 7393 } 7394 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 7395 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 7396 QualType destPointee 7397 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7398 QualType destType = Context.getPointerType(destPointee); 7399 // Add qualifiers if necessary. 7400 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7401 // Promote to void*. 7402 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7403 return destType; 7404 } 7405 return QualType(); 7406 } 7407 7408 /// SuggestParentheses - Emit a note with a fixit hint that wraps 7409 /// ParenRange in parentheses. 7410 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 7411 const PartialDiagnostic &Note, 7412 SourceRange ParenRange) { 7413 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 7414 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 7415 EndLoc.isValid()) { 7416 Self.Diag(Loc, Note) 7417 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 7418 << FixItHint::CreateInsertion(EndLoc, ")"); 7419 } else { 7420 // We can't display the parentheses, so just show the bare note. 7421 Self.Diag(Loc, Note) << ParenRange; 7422 } 7423 } 7424 7425 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 7426 return BinaryOperator::isAdditiveOp(Opc) || 7427 BinaryOperator::isMultiplicativeOp(Opc) || 7428 BinaryOperator::isShiftOp(Opc); 7429 } 7430 7431 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 7432 /// expression, either using a built-in or overloaded operator, 7433 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 7434 /// expression. 7435 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 7436 Expr **RHSExprs) { 7437 // Don't strip parenthesis: we should not warn if E is in parenthesis. 7438 E = E->IgnoreImpCasts(); 7439 E = E->IgnoreConversionOperator(); 7440 E = E->IgnoreImpCasts(); 7441 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 7442 E = MTE->GetTemporaryExpr(); 7443 E = E->IgnoreImpCasts(); 7444 } 7445 7446 // Built-in binary operator. 7447 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 7448 if (IsArithmeticOp(OP->getOpcode())) { 7449 *Opcode = OP->getOpcode(); 7450 *RHSExprs = OP->getRHS(); 7451 return true; 7452 } 7453 } 7454 7455 // Overloaded operator. 7456 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 7457 if (Call->getNumArgs() != 2) 7458 return false; 7459 7460 // Make sure this is really a binary operator that is safe to pass into 7461 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 7462 OverloadedOperatorKind OO = Call->getOperator(); 7463 if (OO < OO_Plus || OO > OO_Arrow || 7464 OO == OO_PlusPlus || OO == OO_MinusMinus) 7465 return false; 7466 7467 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 7468 if (IsArithmeticOp(OpKind)) { 7469 *Opcode = OpKind; 7470 *RHSExprs = Call->getArg(1); 7471 return true; 7472 } 7473 } 7474 7475 return false; 7476 } 7477 7478 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 7479 /// or is a logical expression such as (x==y) which has int type, but is 7480 /// commonly interpreted as boolean. 7481 static bool ExprLooksBoolean(Expr *E) { 7482 E = E->IgnoreParenImpCasts(); 7483 7484 if (E->getType()->isBooleanType()) 7485 return true; 7486 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 7487 return OP->isComparisonOp() || OP->isLogicalOp(); 7488 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 7489 return OP->getOpcode() == UO_LNot; 7490 if (E->getType()->isPointerType()) 7491 return true; 7492 // FIXME: What about overloaded operator calls returning "unspecified boolean 7493 // type"s (commonly pointer-to-members)? 7494 7495 return false; 7496 } 7497 7498 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 7499 /// and binary operator are mixed in a way that suggests the programmer assumed 7500 /// the conditional operator has higher precedence, for example: 7501 /// "int x = a + someBinaryCondition ? 1 : 2". 7502 static void DiagnoseConditionalPrecedence(Sema &Self, 7503 SourceLocation OpLoc, 7504 Expr *Condition, 7505 Expr *LHSExpr, 7506 Expr *RHSExpr) { 7507 BinaryOperatorKind CondOpcode; 7508 Expr *CondRHS; 7509 7510 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 7511 return; 7512 if (!ExprLooksBoolean(CondRHS)) 7513 return; 7514 7515 // The condition is an arithmetic binary expression, with a right- 7516 // hand side that looks boolean, so warn. 7517 7518 Self.Diag(OpLoc, diag::warn_precedence_conditional) 7519 << Condition->getSourceRange() 7520 << BinaryOperator::getOpcodeStr(CondOpcode); 7521 7522 SuggestParentheses( 7523 Self, OpLoc, 7524 Self.PDiag(diag::note_precedence_silence) 7525 << BinaryOperator::getOpcodeStr(CondOpcode), 7526 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 7527 7528 SuggestParentheses(Self, OpLoc, 7529 Self.PDiag(diag::note_precedence_conditional_first), 7530 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 7531 } 7532 7533 /// Compute the nullability of a conditional expression. 7534 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 7535 QualType LHSTy, QualType RHSTy, 7536 ASTContext &Ctx) { 7537 if (!ResTy->isAnyPointerType()) 7538 return ResTy; 7539 7540 auto GetNullability = [&Ctx](QualType Ty) { 7541 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 7542 if (Kind) 7543 return *Kind; 7544 return NullabilityKind::Unspecified; 7545 }; 7546 7547 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 7548 NullabilityKind MergedKind; 7549 7550 // Compute nullability of a binary conditional expression. 7551 if (IsBin) { 7552 if (LHSKind == NullabilityKind::NonNull) 7553 MergedKind = NullabilityKind::NonNull; 7554 else 7555 MergedKind = RHSKind; 7556 // Compute nullability of a normal conditional expression. 7557 } else { 7558 if (LHSKind == NullabilityKind::Nullable || 7559 RHSKind == NullabilityKind::Nullable) 7560 MergedKind = NullabilityKind::Nullable; 7561 else if (LHSKind == NullabilityKind::NonNull) 7562 MergedKind = RHSKind; 7563 else if (RHSKind == NullabilityKind::NonNull) 7564 MergedKind = LHSKind; 7565 else 7566 MergedKind = NullabilityKind::Unspecified; 7567 } 7568 7569 // Return if ResTy already has the correct nullability. 7570 if (GetNullability(ResTy) == MergedKind) 7571 return ResTy; 7572 7573 // Strip all nullability from ResTy. 7574 while (ResTy->getNullability(Ctx)) 7575 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 7576 7577 // Create a new AttributedType with the new nullability kind. 7578 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 7579 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 7580 } 7581 7582 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7583 /// in the case of a the GNU conditional expr extension. 7584 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7585 SourceLocation ColonLoc, 7586 Expr *CondExpr, Expr *LHSExpr, 7587 Expr *RHSExpr) { 7588 if (!getLangOpts().CPlusPlus) { 7589 // C cannot handle TypoExpr nodes in the condition because it 7590 // doesn't handle dependent types properly, so make sure any TypoExprs have 7591 // been dealt with before checking the operands. 7592 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7593 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7594 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7595 7596 if (!CondResult.isUsable()) 7597 return ExprError(); 7598 7599 if (LHSExpr) { 7600 if (!LHSResult.isUsable()) 7601 return ExprError(); 7602 } 7603 7604 if (!RHSResult.isUsable()) 7605 return ExprError(); 7606 7607 CondExpr = CondResult.get(); 7608 LHSExpr = LHSResult.get(); 7609 RHSExpr = RHSResult.get(); 7610 } 7611 7612 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7613 // was the condition. 7614 OpaqueValueExpr *opaqueValue = nullptr; 7615 Expr *commonExpr = nullptr; 7616 if (!LHSExpr) { 7617 commonExpr = CondExpr; 7618 // Lower out placeholder types first. This is important so that we don't 7619 // try to capture a placeholder. This happens in few cases in C++; such 7620 // as Objective-C++'s dictionary subscripting syntax. 7621 if (commonExpr->hasPlaceholderType()) { 7622 ExprResult result = CheckPlaceholderExpr(commonExpr); 7623 if (!result.isUsable()) return ExprError(); 7624 commonExpr = result.get(); 7625 } 7626 // We usually want to apply unary conversions *before* saving, except 7627 // in the special case of a C++ l-value conditional. 7628 if (!(getLangOpts().CPlusPlus 7629 && !commonExpr->isTypeDependent() 7630 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7631 && commonExpr->isGLValue() 7632 && commonExpr->isOrdinaryOrBitFieldObject() 7633 && RHSExpr->isOrdinaryOrBitFieldObject() 7634 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7635 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7636 if (commonRes.isInvalid()) 7637 return ExprError(); 7638 commonExpr = commonRes.get(); 7639 } 7640 7641 // If the common expression is a class or array prvalue, materialize it 7642 // so that we can safely refer to it multiple times. 7643 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 7644 commonExpr->getType()->isArrayType())) { 7645 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 7646 if (MatExpr.isInvalid()) 7647 return ExprError(); 7648 commonExpr = MatExpr.get(); 7649 } 7650 7651 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7652 commonExpr->getType(), 7653 commonExpr->getValueKind(), 7654 commonExpr->getObjectKind(), 7655 commonExpr); 7656 LHSExpr = CondExpr = opaqueValue; 7657 } 7658 7659 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 7660 ExprValueKind VK = VK_RValue; 7661 ExprObjectKind OK = OK_Ordinary; 7662 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7663 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7664 VK, OK, QuestionLoc); 7665 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7666 RHS.isInvalid()) 7667 return ExprError(); 7668 7669 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7670 RHS.get()); 7671 7672 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 7673 7674 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 7675 Context); 7676 7677 if (!commonExpr) 7678 return new (Context) 7679 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 7680 RHS.get(), result, VK, OK); 7681 7682 return new (Context) BinaryConditionalOperator( 7683 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 7684 ColonLoc, result, VK, OK); 7685 } 7686 7687 // checkPointerTypesForAssignment - This is a very tricky routine (despite 7688 // being closely modeled after the C99 spec:-). The odd characteristic of this 7689 // routine is it effectively iqnores the qualifiers on the top level pointee. 7690 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 7691 // FIXME: add a couple examples in this comment. 7692 static Sema::AssignConvertType 7693 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 7694 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7695 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7696 7697 // get the "pointed to" type (ignoring qualifiers at the top level) 7698 const Type *lhptee, *rhptee; 7699 Qualifiers lhq, rhq; 7700 std::tie(lhptee, lhq) = 7701 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 7702 std::tie(rhptee, rhq) = 7703 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 7704 7705 Sema::AssignConvertType ConvTy = Sema::Compatible; 7706 7707 // C99 6.5.16.1p1: This following citation is common to constraints 7708 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 7709 // qualifiers of the type *pointed to* by the right; 7710 7711 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 7712 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 7713 lhq.compatiblyIncludesObjCLifetime(rhq)) { 7714 // Ignore lifetime for further calculation. 7715 lhq.removeObjCLifetime(); 7716 rhq.removeObjCLifetime(); 7717 } 7718 7719 if (!lhq.compatiblyIncludes(rhq)) { 7720 // Treat address-space mismatches as fatal. TODO: address subspaces 7721 if (!lhq.isAddressSpaceSupersetOf(rhq)) 7722 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7723 7724 // It's okay to add or remove GC or lifetime qualifiers when converting to 7725 // and from void*. 7726 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 7727 .compatiblyIncludes( 7728 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 7729 && (lhptee->isVoidType() || rhptee->isVoidType())) 7730 ; // keep old 7731 7732 // Treat lifetime mismatches as fatal. 7733 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 7734 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7735 7736 // For GCC/MS compatibility, other qualifier mismatches are treated 7737 // as still compatible in C. 7738 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7739 } 7740 7741 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 7742 // incomplete type and the other is a pointer to a qualified or unqualified 7743 // version of void... 7744 if (lhptee->isVoidType()) { 7745 if (rhptee->isIncompleteOrObjectType()) 7746 return ConvTy; 7747 7748 // As an extension, we allow cast to/from void* to function pointer. 7749 assert(rhptee->isFunctionType()); 7750 return Sema::FunctionVoidPointer; 7751 } 7752 7753 if (rhptee->isVoidType()) { 7754 if (lhptee->isIncompleteOrObjectType()) 7755 return ConvTy; 7756 7757 // As an extension, we allow cast to/from void* to function pointer. 7758 assert(lhptee->isFunctionType()); 7759 return Sema::FunctionVoidPointer; 7760 } 7761 7762 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7763 // unqualified versions of compatible types, ... 7764 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7765 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7766 // Check if the pointee types are compatible ignoring the sign. 7767 // We explicitly check for char so that we catch "char" vs 7768 // "unsigned char" on systems where "char" is unsigned. 7769 if (lhptee->isCharType()) 7770 ltrans = S.Context.UnsignedCharTy; 7771 else if (lhptee->hasSignedIntegerRepresentation()) 7772 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7773 7774 if (rhptee->isCharType()) 7775 rtrans = S.Context.UnsignedCharTy; 7776 else if (rhptee->hasSignedIntegerRepresentation()) 7777 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 7778 7779 if (ltrans == rtrans) { 7780 // Types are compatible ignoring the sign. Qualifier incompatibility 7781 // takes priority over sign incompatibility because the sign 7782 // warning can be disabled. 7783 if (ConvTy != Sema::Compatible) 7784 return ConvTy; 7785 7786 return Sema::IncompatiblePointerSign; 7787 } 7788 7789 // If we are a multi-level pointer, it's possible that our issue is simply 7790 // one of qualification - e.g. char ** -> const char ** is not allowed. If 7791 // the eventual target type is the same and the pointers have the same 7792 // level of indirection, this must be the issue. 7793 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 7794 do { 7795 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 7796 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 7797 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 7798 7799 if (lhptee == rhptee) 7800 return Sema::IncompatibleNestedPointerQualifiers; 7801 } 7802 7803 // General pointer incompatibility takes priority over qualifiers. 7804 return Sema::IncompatiblePointer; 7805 } 7806 if (!S.getLangOpts().CPlusPlus && 7807 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 7808 return Sema::IncompatiblePointer; 7809 return ConvTy; 7810 } 7811 7812 /// checkBlockPointerTypesForAssignment - This routine determines whether two 7813 /// block pointer types are compatible or whether a block and normal pointer 7814 /// are compatible. It is more restrict than comparing two function pointer 7815 // types. 7816 static Sema::AssignConvertType 7817 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 7818 QualType RHSType) { 7819 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7820 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7821 7822 QualType lhptee, rhptee; 7823 7824 // get the "pointed to" type (ignoring qualifiers at the top level) 7825 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 7826 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 7827 7828 // In C++, the types have to match exactly. 7829 if (S.getLangOpts().CPlusPlus) 7830 return Sema::IncompatibleBlockPointer; 7831 7832 Sema::AssignConvertType ConvTy = Sema::Compatible; 7833 7834 // For blocks we enforce that qualifiers are identical. 7835 Qualifiers LQuals = lhptee.getLocalQualifiers(); 7836 Qualifiers RQuals = rhptee.getLocalQualifiers(); 7837 if (S.getLangOpts().OpenCL) { 7838 LQuals.removeAddressSpace(); 7839 RQuals.removeAddressSpace(); 7840 } 7841 if (LQuals != RQuals) 7842 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7843 7844 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 7845 // assignment. 7846 // The current behavior is similar to C++ lambdas. A block might be 7847 // assigned to a variable iff its return type and parameters are compatible 7848 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 7849 // an assignment. Presumably it should behave in way that a function pointer 7850 // assignment does in C, so for each parameter and return type: 7851 // * CVR and address space of LHS should be a superset of CVR and address 7852 // space of RHS. 7853 // * unqualified types should be compatible. 7854 if (S.getLangOpts().OpenCL) { 7855 if (!S.Context.typesAreBlockPointerCompatible( 7856 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 7857 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 7858 return Sema::IncompatibleBlockPointer; 7859 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 7860 return Sema::IncompatibleBlockPointer; 7861 7862 return ConvTy; 7863 } 7864 7865 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 7866 /// for assignment compatibility. 7867 static Sema::AssignConvertType 7868 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 7869 QualType RHSType) { 7870 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 7871 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 7872 7873 if (LHSType->isObjCBuiltinType()) { 7874 // Class is not compatible with ObjC object pointers. 7875 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 7876 !RHSType->isObjCQualifiedClassType()) 7877 return Sema::IncompatiblePointer; 7878 return Sema::Compatible; 7879 } 7880 if (RHSType->isObjCBuiltinType()) { 7881 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 7882 !LHSType->isObjCQualifiedClassType()) 7883 return Sema::IncompatiblePointer; 7884 return Sema::Compatible; 7885 } 7886 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7887 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7888 7889 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 7890 // make an exception for id<P> 7891 !LHSType->isObjCQualifiedIdType()) 7892 return Sema::CompatiblePointerDiscardsQualifiers; 7893 7894 if (S.Context.typesAreCompatible(LHSType, RHSType)) 7895 return Sema::Compatible; 7896 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 7897 return Sema::IncompatibleObjCQualifiedId; 7898 return Sema::IncompatiblePointer; 7899 } 7900 7901 Sema::AssignConvertType 7902 Sema::CheckAssignmentConstraints(SourceLocation Loc, 7903 QualType LHSType, QualType RHSType) { 7904 // Fake up an opaque expression. We don't actually care about what 7905 // cast operations are required, so if CheckAssignmentConstraints 7906 // adds casts to this they'll be wasted, but fortunately that doesn't 7907 // usually happen on valid code. 7908 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 7909 ExprResult RHSPtr = &RHSExpr; 7910 CastKind K; 7911 7912 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 7913 } 7914 7915 /// This helper function returns true if QT is a vector type that has element 7916 /// type ElementType. 7917 static bool isVector(QualType QT, QualType ElementType) { 7918 if (const VectorType *VT = QT->getAs<VectorType>()) 7919 return VT->getElementType() == ElementType; 7920 return false; 7921 } 7922 7923 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 7924 /// has code to accommodate several GCC extensions when type checking 7925 /// pointers. Here are some objectionable examples that GCC considers warnings: 7926 /// 7927 /// int a, *pint; 7928 /// short *pshort; 7929 /// struct foo *pfoo; 7930 /// 7931 /// pint = pshort; // warning: assignment from incompatible pointer type 7932 /// a = pint; // warning: assignment makes integer from pointer without a cast 7933 /// pint = a; // warning: assignment makes pointer from integer without a cast 7934 /// pint = pfoo; // warning: assignment from incompatible pointer type 7935 /// 7936 /// As a result, the code for dealing with pointers is more complex than the 7937 /// C99 spec dictates. 7938 /// 7939 /// Sets 'Kind' for any result kind except Incompatible. 7940 Sema::AssignConvertType 7941 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 7942 CastKind &Kind, bool ConvertRHS) { 7943 QualType RHSType = RHS.get()->getType(); 7944 QualType OrigLHSType = LHSType; 7945 7946 // Get canonical types. We're not formatting these types, just comparing 7947 // them. 7948 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 7949 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 7950 7951 // Common case: no conversion required. 7952 if (LHSType == RHSType) { 7953 Kind = CK_NoOp; 7954 return Compatible; 7955 } 7956 7957 // If we have an atomic type, try a non-atomic assignment, then just add an 7958 // atomic qualification step. 7959 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 7960 Sema::AssignConvertType result = 7961 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 7962 if (result != Compatible) 7963 return result; 7964 if (Kind != CK_NoOp && ConvertRHS) 7965 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 7966 Kind = CK_NonAtomicToAtomic; 7967 return Compatible; 7968 } 7969 7970 // If the left-hand side is a reference type, then we are in a 7971 // (rare!) case where we've allowed the use of references in C, 7972 // e.g., as a parameter type in a built-in function. In this case, 7973 // just make sure that the type referenced is compatible with the 7974 // right-hand side type. The caller is responsible for adjusting 7975 // LHSType so that the resulting expression does not have reference 7976 // type. 7977 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 7978 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 7979 Kind = CK_LValueBitCast; 7980 return Compatible; 7981 } 7982 return Incompatible; 7983 } 7984 7985 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 7986 // to the same ExtVector type. 7987 if (LHSType->isExtVectorType()) { 7988 if (RHSType->isExtVectorType()) 7989 return Incompatible; 7990 if (RHSType->isArithmeticType()) { 7991 // CK_VectorSplat does T -> vector T, so first cast to the element type. 7992 if (ConvertRHS) 7993 RHS = prepareVectorSplat(LHSType, RHS.get()); 7994 Kind = CK_VectorSplat; 7995 return Compatible; 7996 } 7997 } 7998 7999 // Conversions to or from vector type. 8000 if (LHSType->isVectorType() || RHSType->isVectorType()) { 8001 if (LHSType->isVectorType() && RHSType->isVectorType()) { 8002 // Allow assignments of an AltiVec vector type to an equivalent GCC 8003 // vector type and vice versa 8004 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8005 Kind = CK_BitCast; 8006 return Compatible; 8007 } 8008 8009 // If we are allowing lax vector conversions, and LHS and RHS are both 8010 // vectors, the total size only needs to be the same. This is a bitcast; 8011 // no bits are changed but the result type is different. 8012 if (isLaxVectorConversion(RHSType, LHSType)) { 8013 Kind = CK_BitCast; 8014 return IncompatibleVectors; 8015 } 8016 } 8017 8018 // When the RHS comes from another lax conversion (e.g. binops between 8019 // scalars and vectors) the result is canonicalized as a vector. When the 8020 // LHS is also a vector, the lax is allowed by the condition above. Handle 8021 // the case where LHS is a scalar. 8022 if (LHSType->isScalarType()) { 8023 const VectorType *VecType = RHSType->getAs<VectorType>(); 8024 if (VecType && VecType->getNumElements() == 1 && 8025 isLaxVectorConversion(RHSType, LHSType)) { 8026 ExprResult *VecExpr = &RHS; 8027 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 8028 Kind = CK_BitCast; 8029 return Compatible; 8030 } 8031 } 8032 8033 return Incompatible; 8034 } 8035 8036 // Diagnose attempts to convert between __float128 and long double where 8037 // such conversions currently can't be handled. 8038 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 8039 return Incompatible; 8040 8041 // Disallow assigning a _Complex to a real type in C++ mode since it simply 8042 // discards the imaginary part. 8043 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 8044 !LHSType->getAs<ComplexType>()) 8045 return Incompatible; 8046 8047 // Arithmetic conversions. 8048 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 8049 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 8050 if (ConvertRHS) 8051 Kind = PrepareScalarCast(RHS, LHSType); 8052 return Compatible; 8053 } 8054 8055 // Conversions to normal pointers. 8056 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 8057 // U* -> T* 8058 if (isa<PointerType>(RHSType)) { 8059 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 8060 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 8061 if (AddrSpaceL != AddrSpaceR) 8062 Kind = CK_AddressSpaceConversion; 8063 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 8064 Kind = CK_NoOp; 8065 else 8066 Kind = CK_BitCast; 8067 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 8068 } 8069 8070 // int -> T* 8071 if (RHSType->isIntegerType()) { 8072 Kind = CK_IntegralToPointer; // FIXME: null? 8073 return IntToPointer; 8074 } 8075 8076 // C pointers are not compatible with ObjC object pointers, 8077 // with two exceptions: 8078 if (isa<ObjCObjectPointerType>(RHSType)) { 8079 // - conversions to void* 8080 if (LHSPointer->getPointeeType()->isVoidType()) { 8081 Kind = CK_BitCast; 8082 return Compatible; 8083 } 8084 8085 // - conversions from 'Class' to the redefinition type 8086 if (RHSType->isObjCClassType() && 8087 Context.hasSameType(LHSType, 8088 Context.getObjCClassRedefinitionType())) { 8089 Kind = CK_BitCast; 8090 return Compatible; 8091 } 8092 8093 Kind = CK_BitCast; 8094 return IncompatiblePointer; 8095 } 8096 8097 // U^ -> void* 8098 if (RHSType->getAs<BlockPointerType>()) { 8099 if (LHSPointer->getPointeeType()->isVoidType()) { 8100 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 8101 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 8102 ->getPointeeType() 8103 .getAddressSpace(); 8104 Kind = 8105 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 8106 return Compatible; 8107 } 8108 } 8109 8110 return Incompatible; 8111 } 8112 8113 // Conversions to block pointers. 8114 if (isa<BlockPointerType>(LHSType)) { 8115 // U^ -> T^ 8116 if (RHSType->isBlockPointerType()) { 8117 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 8118 ->getPointeeType() 8119 .getAddressSpace(); 8120 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 8121 ->getPointeeType() 8122 .getAddressSpace(); 8123 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 8124 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 8125 } 8126 8127 // int or null -> T^ 8128 if (RHSType->isIntegerType()) { 8129 Kind = CK_IntegralToPointer; // FIXME: null 8130 return IntToBlockPointer; 8131 } 8132 8133 // id -> T^ 8134 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 8135 Kind = CK_AnyPointerToBlockPointerCast; 8136 return Compatible; 8137 } 8138 8139 // void* -> T^ 8140 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 8141 if (RHSPT->getPointeeType()->isVoidType()) { 8142 Kind = CK_AnyPointerToBlockPointerCast; 8143 return Compatible; 8144 } 8145 8146 return Incompatible; 8147 } 8148 8149 // Conversions to Objective-C pointers. 8150 if (isa<ObjCObjectPointerType>(LHSType)) { 8151 // A* -> B* 8152 if (RHSType->isObjCObjectPointerType()) { 8153 Kind = CK_BitCast; 8154 Sema::AssignConvertType result = 8155 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 8156 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8157 result == Compatible && 8158 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 8159 result = IncompatibleObjCWeakRef; 8160 return result; 8161 } 8162 8163 // int or null -> A* 8164 if (RHSType->isIntegerType()) { 8165 Kind = CK_IntegralToPointer; // FIXME: null 8166 return IntToPointer; 8167 } 8168 8169 // In general, C pointers are not compatible with ObjC object pointers, 8170 // with two exceptions: 8171 if (isa<PointerType>(RHSType)) { 8172 Kind = CK_CPointerToObjCPointerCast; 8173 8174 // - conversions from 'void*' 8175 if (RHSType->isVoidPointerType()) { 8176 return Compatible; 8177 } 8178 8179 // - conversions to 'Class' from its redefinition type 8180 if (LHSType->isObjCClassType() && 8181 Context.hasSameType(RHSType, 8182 Context.getObjCClassRedefinitionType())) { 8183 return Compatible; 8184 } 8185 8186 return IncompatiblePointer; 8187 } 8188 8189 // Only under strict condition T^ is compatible with an Objective-C pointer. 8190 if (RHSType->isBlockPointerType() && 8191 LHSType->isBlockCompatibleObjCPointerType(Context)) { 8192 if (ConvertRHS) 8193 maybeExtendBlockObject(RHS); 8194 Kind = CK_BlockPointerToObjCPointerCast; 8195 return Compatible; 8196 } 8197 8198 return Incompatible; 8199 } 8200 8201 // Conversions from pointers that are not covered by the above. 8202 if (isa<PointerType>(RHSType)) { 8203 // T* -> _Bool 8204 if (LHSType == Context.BoolTy) { 8205 Kind = CK_PointerToBoolean; 8206 return Compatible; 8207 } 8208 8209 // T* -> int 8210 if (LHSType->isIntegerType()) { 8211 Kind = CK_PointerToIntegral; 8212 return PointerToInt; 8213 } 8214 8215 return Incompatible; 8216 } 8217 8218 // Conversions from Objective-C pointers that are not covered by the above. 8219 if (isa<ObjCObjectPointerType>(RHSType)) { 8220 // T* -> _Bool 8221 if (LHSType == Context.BoolTy) { 8222 Kind = CK_PointerToBoolean; 8223 return Compatible; 8224 } 8225 8226 // T* -> int 8227 if (LHSType->isIntegerType()) { 8228 Kind = CK_PointerToIntegral; 8229 return PointerToInt; 8230 } 8231 8232 return Incompatible; 8233 } 8234 8235 // struct A -> struct B 8236 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 8237 if (Context.typesAreCompatible(LHSType, RHSType)) { 8238 Kind = CK_NoOp; 8239 return Compatible; 8240 } 8241 } 8242 8243 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 8244 Kind = CK_IntToOCLSampler; 8245 return Compatible; 8246 } 8247 8248 return Incompatible; 8249 } 8250 8251 /// Constructs a transparent union from an expression that is 8252 /// used to initialize the transparent union. 8253 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 8254 ExprResult &EResult, QualType UnionType, 8255 FieldDecl *Field) { 8256 // Build an initializer list that designates the appropriate member 8257 // of the transparent union. 8258 Expr *E = EResult.get(); 8259 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 8260 E, SourceLocation()); 8261 Initializer->setType(UnionType); 8262 Initializer->setInitializedFieldInUnion(Field); 8263 8264 // Build a compound literal constructing a value of the transparent 8265 // union type from this initializer list. 8266 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 8267 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 8268 VK_RValue, Initializer, false); 8269 } 8270 8271 Sema::AssignConvertType 8272 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 8273 ExprResult &RHS) { 8274 QualType RHSType = RHS.get()->getType(); 8275 8276 // If the ArgType is a Union type, we want to handle a potential 8277 // transparent_union GCC extension. 8278 const RecordType *UT = ArgType->getAsUnionType(); 8279 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 8280 return Incompatible; 8281 8282 // The field to initialize within the transparent union. 8283 RecordDecl *UD = UT->getDecl(); 8284 FieldDecl *InitField = nullptr; 8285 // It's compatible if the expression matches any of the fields. 8286 for (auto *it : UD->fields()) { 8287 if (it->getType()->isPointerType()) { 8288 // If the transparent union contains a pointer type, we allow: 8289 // 1) void pointer 8290 // 2) null pointer constant 8291 if (RHSType->isPointerType()) 8292 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 8293 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 8294 InitField = it; 8295 break; 8296 } 8297 8298 if (RHS.get()->isNullPointerConstant(Context, 8299 Expr::NPC_ValueDependentIsNull)) { 8300 RHS = ImpCastExprToType(RHS.get(), it->getType(), 8301 CK_NullToPointer); 8302 InitField = it; 8303 break; 8304 } 8305 } 8306 8307 CastKind Kind; 8308 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 8309 == Compatible) { 8310 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 8311 InitField = it; 8312 break; 8313 } 8314 } 8315 8316 if (!InitField) 8317 return Incompatible; 8318 8319 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 8320 return Compatible; 8321 } 8322 8323 Sema::AssignConvertType 8324 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 8325 bool Diagnose, 8326 bool DiagnoseCFAudited, 8327 bool ConvertRHS) { 8328 // We need to be able to tell the caller whether we diagnosed a problem, if 8329 // they ask us to issue diagnostics. 8330 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 8331 8332 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 8333 // we can't avoid *all* modifications at the moment, so we need some somewhere 8334 // to put the updated value. 8335 ExprResult LocalRHS = CallerRHS; 8336 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 8337 8338 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 8339 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 8340 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 8341 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 8342 Diag(RHS.get()->getExprLoc(), 8343 diag::warn_noderef_to_dereferenceable_pointer) 8344 << RHS.get()->getSourceRange(); 8345 } 8346 } 8347 } 8348 8349 if (getLangOpts().CPlusPlus) { 8350 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 8351 // C++ 5.17p3: If the left operand is not of class type, the 8352 // expression is implicitly converted (C++ 4) to the 8353 // cv-unqualified type of the left operand. 8354 QualType RHSType = RHS.get()->getType(); 8355 if (Diagnose) { 8356 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8357 AA_Assigning); 8358 } else { 8359 ImplicitConversionSequence ICS = 8360 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8361 /*SuppressUserConversions=*/false, 8362 /*AllowExplicit=*/false, 8363 /*InOverloadResolution=*/false, 8364 /*CStyle=*/false, 8365 /*AllowObjCWritebackConversion=*/false); 8366 if (ICS.isFailure()) 8367 return Incompatible; 8368 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8369 ICS, AA_Assigning); 8370 } 8371 if (RHS.isInvalid()) 8372 return Incompatible; 8373 Sema::AssignConvertType result = Compatible; 8374 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8375 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 8376 result = IncompatibleObjCWeakRef; 8377 return result; 8378 } 8379 8380 // FIXME: Currently, we fall through and treat C++ classes like C 8381 // structures. 8382 // FIXME: We also fall through for atomics; not sure what should 8383 // happen there, though. 8384 } else if (RHS.get()->getType() == Context.OverloadTy) { 8385 // As a set of extensions to C, we support overloading on functions. These 8386 // functions need to be resolved here. 8387 DeclAccessPair DAP; 8388 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 8389 RHS.get(), LHSType, /*Complain=*/false, DAP)) 8390 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 8391 else 8392 return Incompatible; 8393 } 8394 8395 // C99 6.5.16.1p1: the left operand is a pointer and the right is 8396 // a null pointer constant. 8397 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 8398 LHSType->isBlockPointerType()) && 8399 RHS.get()->isNullPointerConstant(Context, 8400 Expr::NPC_ValueDependentIsNull)) { 8401 if (Diagnose || ConvertRHS) { 8402 CastKind Kind; 8403 CXXCastPath Path; 8404 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 8405 /*IgnoreBaseAccess=*/false, Diagnose); 8406 if (ConvertRHS) 8407 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 8408 } 8409 return Compatible; 8410 } 8411 8412 // OpenCL queue_t type assignment. 8413 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 8414 Context, Expr::NPC_ValueDependentIsNull)) { 8415 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 8416 return Compatible; 8417 } 8418 8419 // This check seems unnatural, however it is necessary to ensure the proper 8420 // conversion of functions/arrays. If the conversion were done for all 8421 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 8422 // expressions that suppress this implicit conversion (&, sizeof). 8423 // 8424 // Suppress this for references: C++ 8.5.3p5. 8425 if (!LHSType->isReferenceType()) { 8426 // FIXME: We potentially allocate here even if ConvertRHS is false. 8427 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 8428 if (RHS.isInvalid()) 8429 return Incompatible; 8430 } 8431 CastKind Kind; 8432 Sema::AssignConvertType result = 8433 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 8434 8435 // C99 6.5.16.1p2: The value of the right operand is converted to the 8436 // type of the assignment expression. 8437 // CheckAssignmentConstraints allows the left-hand side to be a reference, 8438 // so that we can use references in built-in functions even in C. 8439 // The getNonReferenceType() call makes sure that the resulting expression 8440 // does not have reference type. 8441 if (result != Incompatible && RHS.get()->getType() != LHSType) { 8442 QualType Ty = LHSType.getNonLValueExprType(Context); 8443 Expr *E = RHS.get(); 8444 8445 // Check for various Objective-C errors. If we are not reporting 8446 // diagnostics and just checking for errors, e.g., during overload 8447 // resolution, return Incompatible to indicate the failure. 8448 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8449 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 8450 Diagnose, DiagnoseCFAudited) != ACR_okay) { 8451 if (!Diagnose) 8452 return Incompatible; 8453 } 8454 if (getLangOpts().ObjC && 8455 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 8456 E->getType(), E, Diagnose) || 8457 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 8458 if (!Diagnose) 8459 return Incompatible; 8460 // Replace the expression with a corrected version and continue so we 8461 // can find further errors. 8462 RHS = E; 8463 return Compatible; 8464 } 8465 8466 if (ConvertRHS) 8467 RHS = ImpCastExprToType(E, Ty, Kind); 8468 } 8469 8470 return result; 8471 } 8472 8473 namespace { 8474 /// The original operand to an operator, prior to the application of the usual 8475 /// arithmetic conversions and converting the arguments of a builtin operator 8476 /// candidate. 8477 struct OriginalOperand { 8478 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 8479 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 8480 Op = MTE->GetTemporaryExpr(); 8481 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 8482 Op = BTE->getSubExpr(); 8483 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 8484 Orig = ICE->getSubExprAsWritten(); 8485 Conversion = ICE->getConversionFunction(); 8486 } 8487 } 8488 8489 QualType getType() const { return Orig->getType(); } 8490 8491 Expr *Orig; 8492 NamedDecl *Conversion; 8493 }; 8494 } 8495 8496 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 8497 ExprResult &RHS) { 8498 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 8499 8500 Diag(Loc, diag::err_typecheck_invalid_operands) 8501 << OrigLHS.getType() << OrigRHS.getType() 8502 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8503 8504 // If a user-defined conversion was applied to either of the operands prior 8505 // to applying the built-in operator rules, tell the user about it. 8506 if (OrigLHS.Conversion) { 8507 Diag(OrigLHS.Conversion->getLocation(), 8508 diag::note_typecheck_invalid_operands_converted) 8509 << 0 << LHS.get()->getType(); 8510 } 8511 if (OrigRHS.Conversion) { 8512 Diag(OrigRHS.Conversion->getLocation(), 8513 diag::note_typecheck_invalid_operands_converted) 8514 << 1 << RHS.get()->getType(); 8515 } 8516 8517 return QualType(); 8518 } 8519 8520 // Diagnose cases where a scalar was implicitly converted to a vector and 8521 // diagnose the underlying types. Otherwise, diagnose the error 8522 // as invalid vector logical operands for non-C++ cases. 8523 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 8524 ExprResult &RHS) { 8525 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 8526 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 8527 8528 bool LHSNatVec = LHSType->isVectorType(); 8529 bool RHSNatVec = RHSType->isVectorType(); 8530 8531 if (!(LHSNatVec && RHSNatVec)) { 8532 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 8533 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 8534 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8535 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 8536 << Vector->getSourceRange(); 8537 return QualType(); 8538 } 8539 8540 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8541 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 8542 << RHS.get()->getSourceRange(); 8543 8544 return QualType(); 8545 } 8546 8547 /// Try to convert a value of non-vector type to a vector type by converting 8548 /// the type to the element type of the vector and then performing a splat. 8549 /// If the language is OpenCL, we only use conversions that promote scalar 8550 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 8551 /// for float->int. 8552 /// 8553 /// OpenCL V2.0 6.2.6.p2: 8554 /// An error shall occur if any scalar operand type has greater rank 8555 /// than the type of the vector element. 8556 /// 8557 /// \param scalar - if non-null, actually perform the conversions 8558 /// \return true if the operation fails (but without diagnosing the failure) 8559 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 8560 QualType scalarTy, 8561 QualType vectorEltTy, 8562 QualType vectorTy, 8563 unsigned &DiagID) { 8564 // The conversion to apply to the scalar before splatting it, 8565 // if necessary. 8566 CastKind scalarCast = CK_NoOp; 8567 8568 if (vectorEltTy->isIntegralType(S.Context)) { 8569 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 8570 (scalarTy->isIntegerType() && 8571 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 8572 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8573 return true; 8574 } 8575 if (!scalarTy->isIntegralType(S.Context)) 8576 return true; 8577 scalarCast = CK_IntegralCast; 8578 } else if (vectorEltTy->isRealFloatingType()) { 8579 if (scalarTy->isRealFloatingType()) { 8580 if (S.getLangOpts().OpenCL && 8581 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 8582 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8583 return true; 8584 } 8585 scalarCast = CK_FloatingCast; 8586 } 8587 else if (scalarTy->isIntegralType(S.Context)) 8588 scalarCast = CK_IntegralToFloating; 8589 else 8590 return true; 8591 } else { 8592 return true; 8593 } 8594 8595 // Adjust scalar if desired. 8596 if (scalar) { 8597 if (scalarCast != CK_NoOp) 8598 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 8599 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 8600 } 8601 return false; 8602 } 8603 8604 /// Convert vector E to a vector with the same number of elements but different 8605 /// element type. 8606 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 8607 const auto *VecTy = E->getType()->getAs<VectorType>(); 8608 assert(VecTy && "Expression E must be a vector"); 8609 QualType NewVecTy = S.Context.getVectorType(ElementType, 8610 VecTy->getNumElements(), 8611 VecTy->getVectorKind()); 8612 8613 // Look through the implicit cast. Return the subexpression if its type is 8614 // NewVecTy. 8615 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 8616 if (ICE->getSubExpr()->getType() == NewVecTy) 8617 return ICE->getSubExpr(); 8618 8619 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 8620 return S.ImpCastExprToType(E, NewVecTy, Cast); 8621 } 8622 8623 /// Test if a (constant) integer Int can be casted to another integer type 8624 /// IntTy without losing precision. 8625 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 8626 QualType OtherIntTy) { 8627 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8628 8629 // Reject cases where the value of the Int is unknown as that would 8630 // possibly cause truncation, but accept cases where the scalar can be 8631 // demoted without loss of precision. 8632 Expr::EvalResult EVResult; 8633 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 8634 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 8635 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 8636 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 8637 8638 if (CstInt) { 8639 // If the scalar is constant and is of a higher order and has more active 8640 // bits that the vector element type, reject it. 8641 llvm::APSInt Result = EVResult.Val.getInt(); 8642 unsigned NumBits = IntSigned 8643 ? (Result.isNegative() ? Result.getMinSignedBits() 8644 : Result.getActiveBits()) 8645 : Result.getActiveBits(); 8646 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 8647 return true; 8648 8649 // If the signedness of the scalar type and the vector element type 8650 // differs and the number of bits is greater than that of the vector 8651 // element reject it. 8652 return (IntSigned != OtherIntSigned && 8653 NumBits > S.Context.getIntWidth(OtherIntTy)); 8654 } 8655 8656 // Reject cases where the value of the scalar is not constant and it's 8657 // order is greater than that of the vector element type. 8658 return (Order < 0); 8659 } 8660 8661 /// Test if a (constant) integer Int can be casted to floating point type 8662 /// FloatTy without losing precision. 8663 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 8664 QualType FloatTy) { 8665 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8666 8667 // Determine if the integer constant can be expressed as a floating point 8668 // number of the appropriate type. 8669 Expr::EvalResult EVResult; 8670 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 8671 8672 uint64_t Bits = 0; 8673 if (CstInt) { 8674 // Reject constants that would be truncated if they were converted to 8675 // the floating point type. Test by simple to/from conversion. 8676 // FIXME: Ideally the conversion to an APFloat and from an APFloat 8677 // could be avoided if there was a convertFromAPInt method 8678 // which could signal back if implicit truncation occurred. 8679 llvm::APSInt Result = EVResult.Val.getInt(); 8680 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 8681 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 8682 llvm::APFloat::rmTowardZero); 8683 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 8684 !IntTy->hasSignedIntegerRepresentation()); 8685 bool Ignored = false; 8686 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 8687 &Ignored); 8688 if (Result != ConvertBack) 8689 return true; 8690 } else { 8691 // Reject types that cannot be fully encoded into the mantissa of 8692 // the float. 8693 Bits = S.Context.getTypeSize(IntTy); 8694 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 8695 S.Context.getFloatTypeSemantics(FloatTy)); 8696 if (Bits > FloatPrec) 8697 return true; 8698 } 8699 8700 return false; 8701 } 8702 8703 /// Attempt to convert and splat Scalar into a vector whose types matches 8704 /// Vector following GCC conversion rules. The rule is that implicit 8705 /// conversion can occur when Scalar can be casted to match Vector's element 8706 /// type without causing truncation of Scalar. 8707 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 8708 ExprResult *Vector) { 8709 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 8710 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 8711 const VectorType *VT = VectorTy->getAs<VectorType>(); 8712 8713 assert(!isa<ExtVectorType>(VT) && 8714 "ExtVectorTypes should not be handled here!"); 8715 8716 QualType VectorEltTy = VT->getElementType(); 8717 8718 // Reject cases where the vector element type or the scalar element type are 8719 // not integral or floating point types. 8720 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 8721 return true; 8722 8723 // The conversion to apply to the scalar before splatting it, 8724 // if necessary. 8725 CastKind ScalarCast = CK_NoOp; 8726 8727 // Accept cases where the vector elements are integers and the scalar is 8728 // an integer. 8729 // FIXME: Notionally if the scalar was a floating point value with a precise 8730 // integral representation, we could cast it to an appropriate integer 8731 // type and then perform the rest of the checks here. GCC will perform 8732 // this conversion in some cases as determined by the input language. 8733 // We should accept it on a language independent basis. 8734 if (VectorEltTy->isIntegralType(S.Context) && 8735 ScalarTy->isIntegralType(S.Context) && 8736 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 8737 8738 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 8739 return true; 8740 8741 ScalarCast = CK_IntegralCast; 8742 } else if (VectorEltTy->isRealFloatingType()) { 8743 if (ScalarTy->isRealFloatingType()) { 8744 8745 // Reject cases where the scalar type is not a constant and has a higher 8746 // Order than the vector element type. 8747 llvm::APFloat Result(0.0); 8748 bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context); 8749 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 8750 if (!CstScalar && Order < 0) 8751 return true; 8752 8753 // If the scalar cannot be safely casted to the vector element type, 8754 // reject it. 8755 if (CstScalar) { 8756 bool Truncated = false; 8757 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 8758 llvm::APFloat::rmNearestTiesToEven, &Truncated); 8759 if (Truncated) 8760 return true; 8761 } 8762 8763 ScalarCast = CK_FloatingCast; 8764 } else if (ScalarTy->isIntegralType(S.Context)) { 8765 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 8766 return true; 8767 8768 ScalarCast = CK_IntegralToFloating; 8769 } else 8770 return true; 8771 } 8772 8773 // Adjust scalar if desired. 8774 if (Scalar) { 8775 if (ScalarCast != CK_NoOp) 8776 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 8777 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 8778 } 8779 return false; 8780 } 8781 8782 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 8783 SourceLocation Loc, bool IsCompAssign, 8784 bool AllowBothBool, 8785 bool AllowBoolConversions) { 8786 if (!IsCompAssign) { 8787 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 8788 if (LHS.isInvalid()) 8789 return QualType(); 8790 } 8791 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 8792 if (RHS.isInvalid()) 8793 return QualType(); 8794 8795 // For conversion purposes, we ignore any qualifiers. 8796 // For example, "const float" and "float" are equivalent. 8797 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 8798 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 8799 8800 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 8801 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 8802 assert(LHSVecType || RHSVecType); 8803 8804 // AltiVec-style "vector bool op vector bool" combinations are allowed 8805 // for some operators but not others. 8806 if (!AllowBothBool && 8807 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8808 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8809 return InvalidOperands(Loc, LHS, RHS); 8810 8811 // If the vector types are identical, return. 8812 if (Context.hasSameType(LHSType, RHSType)) 8813 return LHSType; 8814 8815 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 8816 if (LHSVecType && RHSVecType && 8817 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8818 if (isa<ExtVectorType>(LHSVecType)) { 8819 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8820 return LHSType; 8821 } 8822 8823 if (!IsCompAssign) 8824 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8825 return RHSType; 8826 } 8827 8828 // AllowBoolConversions says that bool and non-bool AltiVec vectors 8829 // can be mixed, with the result being the non-bool type. The non-bool 8830 // operand must have integer element type. 8831 if (AllowBoolConversions && LHSVecType && RHSVecType && 8832 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 8833 (Context.getTypeSize(LHSVecType->getElementType()) == 8834 Context.getTypeSize(RHSVecType->getElementType()))) { 8835 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 8836 LHSVecType->getElementType()->isIntegerType() && 8837 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 8838 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8839 return LHSType; 8840 } 8841 if (!IsCompAssign && 8842 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8843 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 8844 RHSVecType->getElementType()->isIntegerType()) { 8845 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8846 return RHSType; 8847 } 8848 } 8849 8850 // If there's a vector type and a scalar, try to convert the scalar to 8851 // the vector element type and splat. 8852 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 8853 if (!RHSVecType) { 8854 if (isa<ExtVectorType>(LHSVecType)) { 8855 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 8856 LHSVecType->getElementType(), LHSType, 8857 DiagID)) 8858 return LHSType; 8859 } else { 8860 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 8861 return LHSType; 8862 } 8863 } 8864 if (!LHSVecType) { 8865 if (isa<ExtVectorType>(RHSVecType)) { 8866 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 8867 LHSType, RHSVecType->getElementType(), 8868 RHSType, DiagID)) 8869 return RHSType; 8870 } else { 8871 if (LHS.get()->getValueKind() == VK_LValue || 8872 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 8873 return RHSType; 8874 } 8875 } 8876 8877 // FIXME: The code below also handles conversion between vectors and 8878 // non-scalars, we should break this down into fine grained specific checks 8879 // and emit proper diagnostics. 8880 QualType VecType = LHSVecType ? LHSType : RHSType; 8881 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 8882 QualType OtherType = LHSVecType ? RHSType : LHSType; 8883 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 8884 if (isLaxVectorConversion(OtherType, VecType)) { 8885 // If we're allowing lax vector conversions, only the total (data) size 8886 // needs to be the same. For non compound assignment, if one of the types is 8887 // scalar, the result is always the vector type. 8888 if (!IsCompAssign) { 8889 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 8890 return VecType; 8891 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 8892 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 8893 // type. Note that this is already done by non-compound assignments in 8894 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 8895 // <1 x T> -> T. The result is also a vector type. 8896 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 8897 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 8898 ExprResult *RHSExpr = &RHS; 8899 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 8900 return VecType; 8901 } 8902 } 8903 8904 // Okay, the expression is invalid. 8905 8906 // If there's a non-vector, non-real operand, diagnose that. 8907 if ((!RHSVecType && !RHSType->isRealType()) || 8908 (!LHSVecType && !LHSType->isRealType())) { 8909 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 8910 << LHSType << RHSType 8911 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8912 return QualType(); 8913 } 8914 8915 // OpenCL V1.1 6.2.6.p1: 8916 // If the operands are of more than one vector type, then an error shall 8917 // occur. Implicit conversions between vector types are not permitted, per 8918 // section 6.2.1. 8919 if (getLangOpts().OpenCL && 8920 RHSVecType && isa<ExtVectorType>(RHSVecType) && 8921 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 8922 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 8923 << RHSType; 8924 return QualType(); 8925 } 8926 8927 8928 // If there is a vector type that is not a ExtVector and a scalar, we reach 8929 // this point if scalar could not be converted to the vector's element type 8930 // without truncation. 8931 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 8932 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 8933 QualType Scalar = LHSVecType ? RHSType : LHSType; 8934 QualType Vector = LHSVecType ? LHSType : RHSType; 8935 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 8936 Diag(Loc, 8937 diag::err_typecheck_vector_not_convertable_implict_truncation) 8938 << ScalarOrVector << Scalar << Vector; 8939 8940 return QualType(); 8941 } 8942 8943 // Otherwise, use the generic diagnostic. 8944 Diag(Loc, DiagID) 8945 << LHSType << RHSType 8946 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8947 return QualType(); 8948 } 8949 8950 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 8951 // expression. These are mainly cases where the null pointer is used as an 8952 // integer instead of a pointer. 8953 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 8954 SourceLocation Loc, bool IsCompare) { 8955 // The canonical way to check for a GNU null is with isNullPointerConstant, 8956 // but we use a bit of a hack here for speed; this is a relatively 8957 // hot path, and isNullPointerConstant is slow. 8958 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 8959 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 8960 8961 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 8962 8963 // Avoid analyzing cases where the result will either be invalid (and 8964 // diagnosed as such) or entirely valid and not something to warn about. 8965 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 8966 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 8967 return; 8968 8969 // Comparison operations would not make sense with a null pointer no matter 8970 // what the other expression is. 8971 if (!IsCompare) { 8972 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 8973 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 8974 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 8975 return; 8976 } 8977 8978 // The rest of the operations only make sense with a null pointer 8979 // if the other expression is a pointer. 8980 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 8981 NonNullType->canDecayToPointerType()) 8982 return; 8983 8984 S.Diag(Loc, diag::warn_null_in_comparison_operation) 8985 << LHSNull /* LHS is NULL */ << NonNullType 8986 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8987 } 8988 8989 static void DiagnoseDivisionSizeofPointer(Sema &S, Expr *LHS, Expr *RHS, 8990 SourceLocation Loc) { 8991 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 8992 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 8993 if (!LUE || !RUE) 8994 return; 8995 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 8996 RUE->getKind() != UETT_SizeOf) 8997 return; 8998 8999 QualType LHSTy = LUE->getArgumentExpr()->IgnoreParens()->getType(); 9000 QualType RHSTy; 9001 9002 if (RUE->isArgumentType()) 9003 RHSTy = RUE->getArgumentType(); 9004 else 9005 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 9006 9007 if (!LHSTy->isPointerType() || RHSTy->isPointerType()) 9008 return; 9009 if (LHSTy->getPointeeType() != RHSTy) 9010 return; 9011 9012 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 9013 } 9014 9015 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 9016 ExprResult &RHS, 9017 SourceLocation Loc, bool IsDiv) { 9018 // Check for division/remainder by zero. 9019 Expr::EvalResult RHSValue; 9020 if (!RHS.get()->isValueDependent() && 9021 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 9022 RHSValue.Val.getInt() == 0) 9023 S.DiagRuntimeBehavior(Loc, RHS.get(), 9024 S.PDiag(diag::warn_remainder_division_by_zero) 9025 << IsDiv << RHS.get()->getSourceRange()); 9026 } 9027 9028 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 9029 SourceLocation Loc, 9030 bool IsCompAssign, bool IsDiv) { 9031 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9032 9033 if (LHS.get()->getType()->isVectorType() || 9034 RHS.get()->getType()->isVectorType()) 9035 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9036 /*AllowBothBool*/getLangOpts().AltiVec, 9037 /*AllowBoolConversions*/false); 9038 9039 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 9040 if (LHS.isInvalid() || RHS.isInvalid()) 9041 return QualType(); 9042 9043 9044 if (compType.isNull() || !compType->isArithmeticType()) 9045 return InvalidOperands(Loc, LHS, RHS); 9046 if (IsDiv) { 9047 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 9048 DiagnoseDivisionSizeofPointer(*this, LHS.get(), RHS.get(), Loc); 9049 } 9050 return compType; 9051 } 9052 9053 QualType Sema::CheckRemainderOperands( 9054 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 9055 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9056 9057 if (LHS.get()->getType()->isVectorType() || 9058 RHS.get()->getType()->isVectorType()) { 9059 if (LHS.get()->getType()->hasIntegerRepresentation() && 9060 RHS.get()->getType()->hasIntegerRepresentation()) 9061 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9062 /*AllowBothBool*/getLangOpts().AltiVec, 9063 /*AllowBoolConversions*/false); 9064 return InvalidOperands(Loc, LHS, RHS); 9065 } 9066 9067 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 9068 if (LHS.isInvalid() || RHS.isInvalid()) 9069 return QualType(); 9070 9071 if (compType.isNull() || !compType->isIntegerType()) 9072 return InvalidOperands(Loc, LHS, RHS); 9073 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 9074 return compType; 9075 } 9076 9077 /// Diagnose invalid arithmetic on two void pointers. 9078 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 9079 Expr *LHSExpr, Expr *RHSExpr) { 9080 S.Diag(Loc, S.getLangOpts().CPlusPlus 9081 ? diag::err_typecheck_pointer_arith_void_type 9082 : diag::ext_gnu_void_ptr) 9083 << 1 /* two pointers */ << LHSExpr->getSourceRange() 9084 << RHSExpr->getSourceRange(); 9085 } 9086 9087 /// Diagnose invalid arithmetic on a void pointer. 9088 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 9089 Expr *Pointer) { 9090 S.Diag(Loc, S.getLangOpts().CPlusPlus 9091 ? diag::err_typecheck_pointer_arith_void_type 9092 : diag::ext_gnu_void_ptr) 9093 << 0 /* one pointer */ << Pointer->getSourceRange(); 9094 } 9095 9096 /// Diagnose invalid arithmetic on a null pointer. 9097 /// 9098 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 9099 /// idiom, which we recognize as a GNU extension. 9100 /// 9101 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 9102 Expr *Pointer, bool IsGNUIdiom) { 9103 if (IsGNUIdiom) 9104 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 9105 << Pointer->getSourceRange(); 9106 else 9107 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 9108 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 9109 } 9110 9111 /// Diagnose invalid arithmetic on two function pointers. 9112 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 9113 Expr *LHS, Expr *RHS) { 9114 assert(LHS->getType()->isAnyPointerType()); 9115 assert(RHS->getType()->isAnyPointerType()); 9116 S.Diag(Loc, S.getLangOpts().CPlusPlus 9117 ? diag::err_typecheck_pointer_arith_function_type 9118 : diag::ext_gnu_ptr_func_arith) 9119 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 9120 // We only show the second type if it differs from the first. 9121 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 9122 RHS->getType()) 9123 << RHS->getType()->getPointeeType() 9124 << LHS->getSourceRange() << RHS->getSourceRange(); 9125 } 9126 9127 /// Diagnose invalid arithmetic on a function pointer. 9128 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 9129 Expr *Pointer) { 9130 assert(Pointer->getType()->isAnyPointerType()); 9131 S.Diag(Loc, S.getLangOpts().CPlusPlus 9132 ? diag::err_typecheck_pointer_arith_function_type 9133 : diag::ext_gnu_ptr_func_arith) 9134 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 9135 << 0 /* one pointer, so only one type */ 9136 << Pointer->getSourceRange(); 9137 } 9138 9139 /// Emit error if Operand is incomplete pointer type 9140 /// 9141 /// \returns True if pointer has incomplete type 9142 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 9143 Expr *Operand) { 9144 QualType ResType = Operand->getType(); 9145 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 9146 ResType = ResAtomicType->getValueType(); 9147 9148 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 9149 QualType PointeeTy = ResType->getPointeeType(); 9150 return S.RequireCompleteType(Loc, PointeeTy, 9151 diag::err_typecheck_arithmetic_incomplete_type, 9152 PointeeTy, Operand->getSourceRange()); 9153 } 9154 9155 /// Check the validity of an arithmetic pointer operand. 9156 /// 9157 /// If the operand has pointer type, this code will check for pointer types 9158 /// which are invalid in arithmetic operations. These will be diagnosed 9159 /// appropriately, including whether or not the use is supported as an 9160 /// extension. 9161 /// 9162 /// \returns True when the operand is valid to use (even if as an extension). 9163 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 9164 Expr *Operand) { 9165 QualType ResType = Operand->getType(); 9166 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 9167 ResType = ResAtomicType->getValueType(); 9168 9169 if (!ResType->isAnyPointerType()) return true; 9170 9171 QualType PointeeTy = ResType->getPointeeType(); 9172 if (PointeeTy->isVoidType()) { 9173 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 9174 return !S.getLangOpts().CPlusPlus; 9175 } 9176 if (PointeeTy->isFunctionType()) { 9177 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 9178 return !S.getLangOpts().CPlusPlus; 9179 } 9180 9181 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 9182 9183 return true; 9184 } 9185 9186 /// Check the validity of a binary arithmetic operation w.r.t. pointer 9187 /// operands. 9188 /// 9189 /// This routine will diagnose any invalid arithmetic on pointer operands much 9190 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 9191 /// for emitting a single diagnostic even for operations where both LHS and RHS 9192 /// are (potentially problematic) pointers. 9193 /// 9194 /// \returns True when the operand is valid to use (even if as an extension). 9195 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 9196 Expr *LHSExpr, Expr *RHSExpr) { 9197 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 9198 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 9199 if (!isLHSPointer && !isRHSPointer) return true; 9200 9201 QualType LHSPointeeTy, RHSPointeeTy; 9202 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 9203 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 9204 9205 // if both are pointers check if operation is valid wrt address spaces 9206 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 9207 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 9208 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 9209 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 9210 S.Diag(Loc, 9211 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 9212 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 9213 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 9214 return false; 9215 } 9216 } 9217 9218 // Check for arithmetic on pointers to incomplete types. 9219 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 9220 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 9221 if (isLHSVoidPtr || isRHSVoidPtr) { 9222 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 9223 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 9224 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 9225 9226 return !S.getLangOpts().CPlusPlus; 9227 } 9228 9229 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 9230 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 9231 if (isLHSFuncPtr || isRHSFuncPtr) { 9232 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 9233 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 9234 RHSExpr); 9235 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 9236 9237 return !S.getLangOpts().CPlusPlus; 9238 } 9239 9240 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 9241 return false; 9242 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 9243 return false; 9244 9245 return true; 9246 } 9247 9248 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 9249 /// literal. 9250 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 9251 Expr *LHSExpr, Expr *RHSExpr) { 9252 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 9253 Expr* IndexExpr = RHSExpr; 9254 if (!StrExpr) { 9255 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 9256 IndexExpr = LHSExpr; 9257 } 9258 9259 bool IsStringPlusInt = StrExpr && 9260 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 9261 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 9262 return; 9263 9264 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 9265 Self.Diag(OpLoc, diag::warn_string_plus_int) 9266 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 9267 9268 // Only print a fixit for "str" + int, not for int + "str". 9269 if (IndexExpr == RHSExpr) { 9270 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 9271 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 9272 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 9273 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 9274 << FixItHint::CreateInsertion(EndLoc, "]"); 9275 } else 9276 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 9277 } 9278 9279 /// Emit a warning when adding a char literal to a string. 9280 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 9281 Expr *LHSExpr, Expr *RHSExpr) { 9282 const Expr *StringRefExpr = LHSExpr; 9283 const CharacterLiteral *CharExpr = 9284 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 9285 9286 if (!CharExpr) { 9287 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 9288 StringRefExpr = RHSExpr; 9289 } 9290 9291 if (!CharExpr || !StringRefExpr) 9292 return; 9293 9294 const QualType StringType = StringRefExpr->getType(); 9295 9296 // Return if not a PointerType. 9297 if (!StringType->isAnyPointerType()) 9298 return; 9299 9300 // Return if not a CharacterType. 9301 if (!StringType->getPointeeType()->isAnyCharacterType()) 9302 return; 9303 9304 ASTContext &Ctx = Self.getASTContext(); 9305 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 9306 9307 const QualType CharType = CharExpr->getType(); 9308 if (!CharType->isAnyCharacterType() && 9309 CharType->isIntegerType() && 9310 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 9311 Self.Diag(OpLoc, diag::warn_string_plus_char) 9312 << DiagRange << Ctx.CharTy; 9313 } else { 9314 Self.Diag(OpLoc, diag::warn_string_plus_char) 9315 << DiagRange << CharExpr->getType(); 9316 } 9317 9318 // Only print a fixit for str + char, not for char + str. 9319 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 9320 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 9321 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 9322 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 9323 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 9324 << FixItHint::CreateInsertion(EndLoc, "]"); 9325 } else { 9326 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 9327 } 9328 } 9329 9330 /// Emit error when two pointers are incompatible. 9331 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 9332 Expr *LHSExpr, Expr *RHSExpr) { 9333 assert(LHSExpr->getType()->isAnyPointerType()); 9334 assert(RHSExpr->getType()->isAnyPointerType()); 9335 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 9336 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 9337 << RHSExpr->getSourceRange(); 9338 } 9339 9340 // C99 6.5.6 9341 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 9342 SourceLocation Loc, BinaryOperatorKind Opc, 9343 QualType* CompLHSTy) { 9344 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9345 9346 if (LHS.get()->getType()->isVectorType() || 9347 RHS.get()->getType()->isVectorType()) { 9348 QualType compType = CheckVectorOperands( 9349 LHS, RHS, Loc, CompLHSTy, 9350 /*AllowBothBool*/getLangOpts().AltiVec, 9351 /*AllowBoolConversions*/getLangOpts().ZVector); 9352 if (CompLHSTy) *CompLHSTy = compType; 9353 return compType; 9354 } 9355 9356 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 9357 if (LHS.isInvalid() || RHS.isInvalid()) 9358 return QualType(); 9359 9360 // Diagnose "string literal" '+' int and string '+' "char literal". 9361 if (Opc == BO_Add) { 9362 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 9363 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 9364 } 9365 9366 // handle the common case first (both operands are arithmetic). 9367 if (!compType.isNull() && compType->isArithmeticType()) { 9368 if (CompLHSTy) *CompLHSTy = compType; 9369 return compType; 9370 } 9371 9372 // Type-checking. Ultimately the pointer's going to be in PExp; 9373 // note that we bias towards the LHS being the pointer. 9374 Expr *PExp = LHS.get(), *IExp = RHS.get(); 9375 9376 bool isObjCPointer; 9377 if (PExp->getType()->isPointerType()) { 9378 isObjCPointer = false; 9379 } else if (PExp->getType()->isObjCObjectPointerType()) { 9380 isObjCPointer = true; 9381 } else { 9382 std::swap(PExp, IExp); 9383 if (PExp->getType()->isPointerType()) { 9384 isObjCPointer = false; 9385 } else if (PExp->getType()->isObjCObjectPointerType()) { 9386 isObjCPointer = true; 9387 } else { 9388 return InvalidOperands(Loc, LHS, RHS); 9389 } 9390 } 9391 assert(PExp->getType()->isAnyPointerType()); 9392 9393 if (!IExp->getType()->isIntegerType()) 9394 return InvalidOperands(Loc, LHS, RHS); 9395 9396 // Adding to a null pointer results in undefined behavior. 9397 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 9398 Context, Expr::NPC_ValueDependentIsNotNull)) { 9399 // In C++ adding zero to a null pointer is defined. 9400 Expr::EvalResult KnownVal; 9401 if (!getLangOpts().CPlusPlus || 9402 (!IExp->isValueDependent() && 9403 (!IExp->EvaluateAsInt(KnownVal, Context) || 9404 KnownVal.Val.getInt() != 0))) { 9405 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 9406 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 9407 Context, BO_Add, PExp, IExp); 9408 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 9409 } 9410 } 9411 9412 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 9413 return QualType(); 9414 9415 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 9416 return QualType(); 9417 9418 // Check array bounds for pointer arithemtic 9419 CheckArrayAccess(PExp, IExp); 9420 9421 if (CompLHSTy) { 9422 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 9423 if (LHSTy.isNull()) { 9424 LHSTy = LHS.get()->getType(); 9425 if (LHSTy->isPromotableIntegerType()) 9426 LHSTy = Context.getPromotedIntegerType(LHSTy); 9427 } 9428 *CompLHSTy = LHSTy; 9429 } 9430 9431 return PExp->getType(); 9432 } 9433 9434 // C99 6.5.6 9435 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 9436 SourceLocation Loc, 9437 QualType* CompLHSTy) { 9438 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9439 9440 if (LHS.get()->getType()->isVectorType() || 9441 RHS.get()->getType()->isVectorType()) { 9442 QualType compType = CheckVectorOperands( 9443 LHS, RHS, Loc, CompLHSTy, 9444 /*AllowBothBool*/getLangOpts().AltiVec, 9445 /*AllowBoolConversions*/getLangOpts().ZVector); 9446 if (CompLHSTy) *CompLHSTy = compType; 9447 return compType; 9448 } 9449 9450 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 9451 if (LHS.isInvalid() || RHS.isInvalid()) 9452 return QualType(); 9453 9454 // Enforce type constraints: C99 6.5.6p3. 9455 9456 // Handle the common case first (both operands are arithmetic). 9457 if (!compType.isNull() && compType->isArithmeticType()) { 9458 if (CompLHSTy) *CompLHSTy = compType; 9459 return compType; 9460 } 9461 9462 // Either ptr - int or ptr - ptr. 9463 if (LHS.get()->getType()->isAnyPointerType()) { 9464 QualType lpointee = LHS.get()->getType()->getPointeeType(); 9465 9466 // Diagnose bad cases where we step over interface counts. 9467 if (LHS.get()->getType()->isObjCObjectPointerType() && 9468 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 9469 return QualType(); 9470 9471 // The result type of a pointer-int computation is the pointer type. 9472 if (RHS.get()->getType()->isIntegerType()) { 9473 // Subtracting from a null pointer should produce a warning. 9474 // The last argument to the diagnose call says this doesn't match the 9475 // GNU int-to-pointer idiom. 9476 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 9477 Expr::NPC_ValueDependentIsNotNull)) { 9478 // In C++ adding zero to a null pointer is defined. 9479 Expr::EvalResult KnownVal; 9480 if (!getLangOpts().CPlusPlus || 9481 (!RHS.get()->isValueDependent() && 9482 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 9483 KnownVal.Val.getInt() != 0))) { 9484 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 9485 } 9486 } 9487 9488 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 9489 return QualType(); 9490 9491 // Check array bounds for pointer arithemtic 9492 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 9493 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 9494 9495 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9496 return LHS.get()->getType(); 9497 } 9498 9499 // Handle pointer-pointer subtractions. 9500 if (const PointerType *RHSPTy 9501 = RHS.get()->getType()->getAs<PointerType>()) { 9502 QualType rpointee = RHSPTy->getPointeeType(); 9503 9504 if (getLangOpts().CPlusPlus) { 9505 // Pointee types must be the same: C++ [expr.add] 9506 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 9507 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9508 } 9509 } else { 9510 // Pointee types must be compatible C99 6.5.6p3 9511 if (!Context.typesAreCompatible( 9512 Context.getCanonicalType(lpointee).getUnqualifiedType(), 9513 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 9514 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9515 return QualType(); 9516 } 9517 } 9518 9519 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 9520 LHS.get(), RHS.get())) 9521 return QualType(); 9522 9523 // FIXME: Add warnings for nullptr - ptr. 9524 9525 // The pointee type may have zero size. As an extension, a structure or 9526 // union may have zero size or an array may have zero length. In this 9527 // case subtraction does not make sense. 9528 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 9529 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 9530 if (ElementSize.isZero()) { 9531 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 9532 << rpointee.getUnqualifiedType() 9533 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9534 } 9535 } 9536 9537 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9538 return Context.getPointerDiffType(); 9539 } 9540 } 9541 9542 return InvalidOperands(Loc, LHS, RHS); 9543 } 9544 9545 static bool isScopedEnumerationType(QualType T) { 9546 if (const EnumType *ET = T->getAs<EnumType>()) 9547 return ET->getDecl()->isScoped(); 9548 return false; 9549 } 9550 9551 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 9552 SourceLocation Loc, BinaryOperatorKind Opc, 9553 QualType LHSType) { 9554 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 9555 // so skip remaining warnings as we don't want to modify values within Sema. 9556 if (S.getLangOpts().OpenCL) 9557 return; 9558 9559 // Check right/shifter operand 9560 Expr::EvalResult RHSResult; 9561 if (RHS.get()->isValueDependent() || 9562 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 9563 return; 9564 llvm::APSInt Right = RHSResult.Val.getInt(); 9565 9566 if (Right.isNegative()) { 9567 S.DiagRuntimeBehavior(Loc, RHS.get(), 9568 S.PDiag(diag::warn_shift_negative) 9569 << RHS.get()->getSourceRange()); 9570 return; 9571 } 9572 llvm::APInt LeftBits(Right.getBitWidth(), 9573 S.Context.getTypeSize(LHS.get()->getType())); 9574 if (Right.uge(LeftBits)) { 9575 S.DiagRuntimeBehavior(Loc, RHS.get(), 9576 S.PDiag(diag::warn_shift_gt_typewidth) 9577 << RHS.get()->getSourceRange()); 9578 return; 9579 } 9580 if (Opc != BO_Shl) 9581 return; 9582 9583 // When left shifting an ICE which is signed, we can check for overflow which 9584 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 9585 // integers have defined behavior modulo one more than the maximum value 9586 // representable in the result type, so never warn for those. 9587 Expr::EvalResult LHSResult; 9588 if (LHS.get()->isValueDependent() || 9589 LHSType->hasUnsignedIntegerRepresentation() || 9590 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 9591 return; 9592 llvm::APSInt Left = LHSResult.Val.getInt(); 9593 9594 // If LHS does not have a signed type and non-negative value 9595 // then, the behavior is undefined. Warn about it. 9596 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) { 9597 S.DiagRuntimeBehavior(Loc, LHS.get(), 9598 S.PDiag(diag::warn_shift_lhs_negative) 9599 << LHS.get()->getSourceRange()); 9600 return; 9601 } 9602 9603 llvm::APInt ResultBits = 9604 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 9605 if (LeftBits.uge(ResultBits)) 9606 return; 9607 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 9608 Result = Result.shl(Right); 9609 9610 // Print the bit representation of the signed integer as an unsigned 9611 // hexadecimal number. 9612 SmallString<40> HexResult; 9613 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 9614 9615 // If we are only missing a sign bit, this is less likely to result in actual 9616 // bugs -- if the result is cast back to an unsigned type, it will have the 9617 // expected value. Thus we place this behind a different warning that can be 9618 // turned off separately if needed. 9619 if (LeftBits == ResultBits - 1) { 9620 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 9621 << HexResult << LHSType 9622 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9623 return; 9624 } 9625 9626 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 9627 << HexResult.str() << Result.getMinSignedBits() << LHSType 9628 << Left.getBitWidth() << LHS.get()->getSourceRange() 9629 << RHS.get()->getSourceRange(); 9630 } 9631 9632 /// Return the resulting type when a vector is shifted 9633 /// by a scalar or vector shift amount. 9634 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 9635 SourceLocation Loc, bool IsCompAssign) { 9636 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 9637 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 9638 !LHS.get()->getType()->isVectorType()) { 9639 S.Diag(Loc, diag::err_shift_rhs_only_vector) 9640 << RHS.get()->getType() << LHS.get()->getType() 9641 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9642 return QualType(); 9643 } 9644 9645 if (!IsCompAssign) { 9646 LHS = S.UsualUnaryConversions(LHS.get()); 9647 if (LHS.isInvalid()) return QualType(); 9648 } 9649 9650 RHS = S.UsualUnaryConversions(RHS.get()); 9651 if (RHS.isInvalid()) return QualType(); 9652 9653 QualType LHSType = LHS.get()->getType(); 9654 // Note that LHS might be a scalar because the routine calls not only in 9655 // OpenCL case. 9656 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 9657 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 9658 9659 // Note that RHS might not be a vector. 9660 QualType RHSType = RHS.get()->getType(); 9661 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 9662 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 9663 9664 // The operands need to be integers. 9665 if (!LHSEleType->isIntegerType()) { 9666 S.Diag(Loc, diag::err_typecheck_expect_int) 9667 << LHS.get()->getType() << LHS.get()->getSourceRange(); 9668 return QualType(); 9669 } 9670 9671 if (!RHSEleType->isIntegerType()) { 9672 S.Diag(Loc, diag::err_typecheck_expect_int) 9673 << RHS.get()->getType() << RHS.get()->getSourceRange(); 9674 return QualType(); 9675 } 9676 9677 if (!LHSVecTy) { 9678 assert(RHSVecTy); 9679 if (IsCompAssign) 9680 return RHSType; 9681 if (LHSEleType != RHSEleType) { 9682 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 9683 LHSEleType = RHSEleType; 9684 } 9685 QualType VecTy = 9686 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 9687 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 9688 LHSType = VecTy; 9689 } else if (RHSVecTy) { 9690 // OpenCL v1.1 s6.3.j says that for vector types, the operators 9691 // are applied component-wise. So if RHS is a vector, then ensure 9692 // that the number of elements is the same as LHS... 9693 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 9694 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 9695 << LHS.get()->getType() << RHS.get()->getType() 9696 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9697 return QualType(); 9698 } 9699 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 9700 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 9701 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 9702 if (LHSBT != RHSBT && 9703 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 9704 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 9705 << LHS.get()->getType() << RHS.get()->getType() 9706 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9707 } 9708 } 9709 } else { 9710 // ...else expand RHS to match the number of elements in LHS. 9711 QualType VecTy = 9712 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 9713 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 9714 } 9715 9716 return LHSType; 9717 } 9718 9719 // C99 6.5.7 9720 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 9721 SourceLocation Loc, BinaryOperatorKind Opc, 9722 bool IsCompAssign) { 9723 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9724 9725 // Vector shifts promote their scalar inputs to vector type. 9726 if (LHS.get()->getType()->isVectorType() || 9727 RHS.get()->getType()->isVectorType()) { 9728 if (LangOpts.ZVector) { 9729 // The shift operators for the z vector extensions work basically 9730 // like general shifts, except that neither the LHS nor the RHS is 9731 // allowed to be a "vector bool". 9732 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 9733 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 9734 return InvalidOperands(Loc, LHS, RHS); 9735 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 9736 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9737 return InvalidOperands(Loc, LHS, RHS); 9738 } 9739 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 9740 } 9741 9742 // Shifts don't perform usual arithmetic conversions, they just do integer 9743 // promotions on each operand. C99 6.5.7p3 9744 9745 // For the LHS, do usual unary conversions, but then reset them away 9746 // if this is a compound assignment. 9747 ExprResult OldLHS = LHS; 9748 LHS = UsualUnaryConversions(LHS.get()); 9749 if (LHS.isInvalid()) 9750 return QualType(); 9751 QualType LHSType = LHS.get()->getType(); 9752 if (IsCompAssign) LHS = OldLHS; 9753 9754 // The RHS is simpler. 9755 RHS = UsualUnaryConversions(RHS.get()); 9756 if (RHS.isInvalid()) 9757 return QualType(); 9758 QualType RHSType = RHS.get()->getType(); 9759 9760 // C99 6.5.7p2: Each of the operands shall have integer type. 9761 if (!LHSType->hasIntegerRepresentation() || 9762 !RHSType->hasIntegerRepresentation()) 9763 return InvalidOperands(Loc, LHS, RHS); 9764 9765 // C++0x: Don't allow scoped enums. FIXME: Use something better than 9766 // hasIntegerRepresentation() above instead of this. 9767 if (isScopedEnumerationType(LHSType) || 9768 isScopedEnumerationType(RHSType)) { 9769 return InvalidOperands(Loc, LHS, RHS); 9770 } 9771 // Sanity-check shift operands 9772 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 9773 9774 // "The type of the result is that of the promoted left operand." 9775 return LHSType; 9776 } 9777 9778 /// If two different enums are compared, raise a warning. 9779 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 9780 Expr *RHS) { 9781 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 9782 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 9783 9784 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 9785 if (!LHSEnumType) 9786 return; 9787 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 9788 if (!RHSEnumType) 9789 return; 9790 9791 // Ignore anonymous enums. 9792 if (!LHSEnumType->getDecl()->getIdentifier() && 9793 !LHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 9794 return; 9795 if (!RHSEnumType->getDecl()->getIdentifier() && 9796 !RHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 9797 return; 9798 9799 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 9800 return; 9801 9802 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 9803 << LHSStrippedType << RHSStrippedType 9804 << LHS->getSourceRange() << RHS->getSourceRange(); 9805 } 9806 9807 /// Diagnose bad pointer comparisons. 9808 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 9809 ExprResult &LHS, ExprResult &RHS, 9810 bool IsError) { 9811 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 9812 : diag::ext_typecheck_comparison_of_distinct_pointers) 9813 << LHS.get()->getType() << RHS.get()->getType() 9814 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9815 } 9816 9817 /// Returns false if the pointers are converted to a composite type, 9818 /// true otherwise. 9819 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 9820 ExprResult &LHS, ExprResult &RHS) { 9821 // C++ [expr.rel]p2: 9822 // [...] Pointer conversions (4.10) and qualification 9823 // conversions (4.4) are performed on pointer operands (or on 9824 // a pointer operand and a null pointer constant) to bring 9825 // them to their composite pointer type. [...] 9826 // 9827 // C++ [expr.eq]p1 uses the same notion for (in)equality 9828 // comparisons of pointers. 9829 9830 QualType LHSType = LHS.get()->getType(); 9831 QualType RHSType = RHS.get()->getType(); 9832 assert(LHSType->isPointerType() || RHSType->isPointerType() || 9833 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 9834 9835 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 9836 if (T.isNull()) { 9837 if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) && 9838 (RHSType->isPointerType() || RHSType->isMemberPointerType())) 9839 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 9840 else 9841 S.InvalidOperands(Loc, LHS, RHS); 9842 return true; 9843 } 9844 9845 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 9846 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 9847 return false; 9848 } 9849 9850 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 9851 ExprResult &LHS, 9852 ExprResult &RHS, 9853 bool IsError) { 9854 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 9855 : diag::ext_typecheck_comparison_of_fptr_to_void) 9856 << LHS.get()->getType() << RHS.get()->getType() 9857 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9858 } 9859 9860 static bool isObjCObjectLiteral(ExprResult &E) { 9861 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 9862 case Stmt::ObjCArrayLiteralClass: 9863 case Stmt::ObjCDictionaryLiteralClass: 9864 case Stmt::ObjCStringLiteralClass: 9865 case Stmt::ObjCBoxedExprClass: 9866 return true; 9867 default: 9868 // Note that ObjCBoolLiteral is NOT an object literal! 9869 return false; 9870 } 9871 } 9872 9873 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 9874 const ObjCObjectPointerType *Type = 9875 LHS->getType()->getAs<ObjCObjectPointerType>(); 9876 9877 // If this is not actually an Objective-C object, bail out. 9878 if (!Type) 9879 return false; 9880 9881 // Get the LHS object's interface type. 9882 QualType InterfaceType = Type->getPointeeType(); 9883 9884 // If the RHS isn't an Objective-C object, bail out. 9885 if (!RHS->getType()->isObjCObjectPointerType()) 9886 return false; 9887 9888 // Try to find the -isEqual: method. 9889 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 9890 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 9891 InterfaceType, 9892 /*instance=*/true); 9893 if (!Method) { 9894 if (Type->isObjCIdType()) { 9895 // For 'id', just check the global pool. 9896 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 9897 /*receiverId=*/true); 9898 } else { 9899 // Check protocols. 9900 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 9901 /*instance=*/true); 9902 } 9903 } 9904 9905 if (!Method) 9906 return false; 9907 9908 QualType T = Method->parameters()[0]->getType(); 9909 if (!T->isObjCObjectPointerType()) 9910 return false; 9911 9912 QualType R = Method->getReturnType(); 9913 if (!R->isScalarType()) 9914 return false; 9915 9916 return true; 9917 } 9918 9919 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 9920 FromE = FromE->IgnoreParenImpCasts(); 9921 switch (FromE->getStmtClass()) { 9922 default: 9923 break; 9924 case Stmt::ObjCStringLiteralClass: 9925 // "string literal" 9926 return LK_String; 9927 case Stmt::ObjCArrayLiteralClass: 9928 // "array literal" 9929 return LK_Array; 9930 case Stmt::ObjCDictionaryLiteralClass: 9931 // "dictionary literal" 9932 return LK_Dictionary; 9933 case Stmt::BlockExprClass: 9934 return LK_Block; 9935 case Stmt::ObjCBoxedExprClass: { 9936 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 9937 switch (Inner->getStmtClass()) { 9938 case Stmt::IntegerLiteralClass: 9939 case Stmt::FloatingLiteralClass: 9940 case Stmt::CharacterLiteralClass: 9941 case Stmt::ObjCBoolLiteralExprClass: 9942 case Stmt::CXXBoolLiteralExprClass: 9943 // "numeric literal" 9944 return LK_Numeric; 9945 case Stmt::ImplicitCastExprClass: { 9946 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 9947 // Boolean literals can be represented by implicit casts. 9948 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 9949 return LK_Numeric; 9950 break; 9951 } 9952 default: 9953 break; 9954 } 9955 return LK_Boxed; 9956 } 9957 } 9958 return LK_None; 9959 } 9960 9961 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 9962 ExprResult &LHS, ExprResult &RHS, 9963 BinaryOperator::Opcode Opc){ 9964 Expr *Literal; 9965 Expr *Other; 9966 if (isObjCObjectLiteral(LHS)) { 9967 Literal = LHS.get(); 9968 Other = RHS.get(); 9969 } else { 9970 Literal = RHS.get(); 9971 Other = LHS.get(); 9972 } 9973 9974 // Don't warn on comparisons against nil. 9975 Other = Other->IgnoreParenCasts(); 9976 if (Other->isNullPointerConstant(S.getASTContext(), 9977 Expr::NPC_ValueDependentIsNotNull)) 9978 return; 9979 9980 // This should be kept in sync with warn_objc_literal_comparison. 9981 // LK_String should always be after the other literals, since it has its own 9982 // warning flag. 9983 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 9984 assert(LiteralKind != Sema::LK_Block); 9985 if (LiteralKind == Sema::LK_None) { 9986 llvm_unreachable("Unknown Objective-C object literal kind"); 9987 } 9988 9989 if (LiteralKind == Sema::LK_String) 9990 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 9991 << Literal->getSourceRange(); 9992 else 9993 S.Diag(Loc, diag::warn_objc_literal_comparison) 9994 << LiteralKind << Literal->getSourceRange(); 9995 9996 if (BinaryOperator::isEqualityOp(Opc) && 9997 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 9998 SourceLocation Start = LHS.get()->getBeginLoc(); 9999 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 10000 CharSourceRange OpRange = 10001 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 10002 10003 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 10004 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 10005 << FixItHint::CreateReplacement(OpRange, " isEqual:") 10006 << FixItHint::CreateInsertion(End, "]"); 10007 } 10008 } 10009 10010 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 10011 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 10012 ExprResult &RHS, SourceLocation Loc, 10013 BinaryOperatorKind Opc) { 10014 // Check that left hand side is !something. 10015 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 10016 if (!UO || UO->getOpcode() != UO_LNot) return; 10017 10018 // Only check if the right hand side is non-bool arithmetic type. 10019 if (RHS.get()->isKnownToHaveBooleanValue()) return; 10020 10021 // Make sure that the something in !something is not bool. 10022 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 10023 if (SubExpr->isKnownToHaveBooleanValue()) return; 10024 10025 // Emit warning. 10026 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 10027 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 10028 << Loc << IsBitwiseOp; 10029 10030 // First note suggest !(x < y) 10031 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 10032 SourceLocation FirstClose = RHS.get()->getEndLoc(); 10033 FirstClose = S.getLocForEndOfToken(FirstClose); 10034 if (FirstClose.isInvalid()) 10035 FirstOpen = SourceLocation(); 10036 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 10037 << IsBitwiseOp 10038 << FixItHint::CreateInsertion(FirstOpen, "(") 10039 << FixItHint::CreateInsertion(FirstClose, ")"); 10040 10041 // Second note suggests (!x) < y 10042 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 10043 SourceLocation SecondClose = LHS.get()->getEndLoc(); 10044 SecondClose = S.getLocForEndOfToken(SecondClose); 10045 if (SecondClose.isInvalid()) 10046 SecondOpen = SourceLocation(); 10047 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 10048 << FixItHint::CreateInsertion(SecondOpen, "(") 10049 << FixItHint::CreateInsertion(SecondClose, ")"); 10050 } 10051 10052 // Get the decl for a simple expression: a reference to a variable, 10053 // an implicit C++ field reference, or an implicit ObjC ivar reference. 10054 static ValueDecl *getCompareDecl(Expr *E) { 10055 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) 10056 return DR->getDecl(); 10057 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 10058 if (Ivar->isFreeIvar()) 10059 return Ivar->getDecl(); 10060 } 10061 if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 10062 if (Mem->isImplicitAccess()) 10063 return Mem->getMemberDecl(); 10064 } 10065 return nullptr; 10066 } 10067 10068 /// Diagnose some forms of syntactically-obvious tautological comparison. 10069 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 10070 Expr *LHS, Expr *RHS, 10071 BinaryOperatorKind Opc) { 10072 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 10073 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 10074 10075 QualType LHSType = LHS->getType(); 10076 QualType RHSType = RHS->getType(); 10077 if (LHSType->hasFloatingRepresentation() || 10078 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 10079 LHS->getBeginLoc().isMacroID() || RHS->getBeginLoc().isMacroID() || 10080 S.inTemplateInstantiation()) 10081 return; 10082 10083 // Comparisons between two array types are ill-formed for operator<=>, so 10084 // we shouldn't emit any additional warnings about it. 10085 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 10086 return; 10087 10088 // For non-floating point types, check for self-comparisons of the form 10089 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 10090 // often indicate logic errors in the program. 10091 // 10092 // NOTE: Don't warn about comparison expressions resulting from macro 10093 // expansion. Also don't warn about comparisons which are only self 10094 // comparisons within a template instantiation. The warnings should catch 10095 // obvious cases in the definition of the template anyways. The idea is to 10096 // warn when the typed comparison operator will always evaluate to the same 10097 // result. 10098 ValueDecl *DL = getCompareDecl(LHSStripped); 10099 ValueDecl *DR = getCompareDecl(RHSStripped); 10100 if (DL && DR && declaresSameEntity(DL, DR)) { 10101 StringRef Result; 10102 switch (Opc) { 10103 case BO_EQ: case BO_LE: case BO_GE: 10104 Result = "true"; 10105 break; 10106 case BO_NE: case BO_LT: case BO_GT: 10107 Result = "false"; 10108 break; 10109 case BO_Cmp: 10110 Result = "'std::strong_ordering::equal'"; 10111 break; 10112 default: 10113 break; 10114 } 10115 S.DiagRuntimeBehavior(Loc, nullptr, 10116 S.PDiag(diag::warn_comparison_always) 10117 << 0 /*self-comparison*/ << !Result.empty() 10118 << Result); 10119 } else if (DL && DR && 10120 DL->getType()->isArrayType() && DR->getType()->isArrayType() && 10121 !DL->isWeak() && !DR->isWeak()) { 10122 // What is it always going to evaluate to? 10123 StringRef Result; 10124 switch(Opc) { 10125 case BO_EQ: // e.g. array1 == array2 10126 Result = "false"; 10127 break; 10128 case BO_NE: // e.g. array1 != array2 10129 Result = "true"; 10130 break; 10131 default: // e.g. array1 <= array2 10132 // The best we can say is 'a constant' 10133 break; 10134 } 10135 S.DiagRuntimeBehavior(Loc, nullptr, 10136 S.PDiag(diag::warn_comparison_always) 10137 << 1 /*array comparison*/ 10138 << !Result.empty() << Result); 10139 } 10140 10141 if (isa<CastExpr>(LHSStripped)) 10142 LHSStripped = LHSStripped->IgnoreParenCasts(); 10143 if (isa<CastExpr>(RHSStripped)) 10144 RHSStripped = RHSStripped->IgnoreParenCasts(); 10145 10146 // Warn about comparisons against a string constant (unless the other 10147 // operand is null); the user probably wants strcmp. 10148 Expr *LiteralString = nullptr; 10149 Expr *LiteralStringStripped = nullptr; 10150 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 10151 !RHSStripped->isNullPointerConstant(S.Context, 10152 Expr::NPC_ValueDependentIsNull)) { 10153 LiteralString = LHS; 10154 LiteralStringStripped = LHSStripped; 10155 } else if ((isa<StringLiteral>(RHSStripped) || 10156 isa<ObjCEncodeExpr>(RHSStripped)) && 10157 !LHSStripped->isNullPointerConstant(S.Context, 10158 Expr::NPC_ValueDependentIsNull)) { 10159 LiteralString = RHS; 10160 LiteralStringStripped = RHSStripped; 10161 } 10162 10163 if (LiteralString) { 10164 S.DiagRuntimeBehavior(Loc, nullptr, 10165 S.PDiag(diag::warn_stringcompare) 10166 << isa<ObjCEncodeExpr>(LiteralStringStripped) 10167 << LiteralString->getSourceRange()); 10168 } 10169 } 10170 10171 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 10172 switch (CK) { 10173 default: { 10174 #ifndef NDEBUG 10175 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 10176 << "\n"; 10177 #endif 10178 llvm_unreachable("unhandled cast kind"); 10179 } 10180 case CK_UserDefinedConversion: 10181 return ICK_Identity; 10182 case CK_LValueToRValue: 10183 return ICK_Lvalue_To_Rvalue; 10184 case CK_ArrayToPointerDecay: 10185 return ICK_Array_To_Pointer; 10186 case CK_FunctionToPointerDecay: 10187 return ICK_Function_To_Pointer; 10188 case CK_IntegralCast: 10189 return ICK_Integral_Conversion; 10190 case CK_FloatingCast: 10191 return ICK_Floating_Conversion; 10192 case CK_IntegralToFloating: 10193 case CK_FloatingToIntegral: 10194 return ICK_Floating_Integral; 10195 case CK_IntegralComplexCast: 10196 case CK_FloatingComplexCast: 10197 case CK_FloatingComplexToIntegralComplex: 10198 case CK_IntegralComplexToFloatingComplex: 10199 return ICK_Complex_Conversion; 10200 case CK_FloatingComplexToReal: 10201 case CK_FloatingRealToComplex: 10202 case CK_IntegralComplexToReal: 10203 case CK_IntegralRealToComplex: 10204 return ICK_Complex_Real; 10205 } 10206 } 10207 10208 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 10209 QualType FromType, 10210 SourceLocation Loc) { 10211 // Check for a narrowing implicit conversion. 10212 StandardConversionSequence SCS; 10213 SCS.setAsIdentityConversion(); 10214 SCS.setToType(0, FromType); 10215 SCS.setToType(1, ToType); 10216 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 10217 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 10218 10219 APValue PreNarrowingValue; 10220 QualType PreNarrowingType; 10221 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 10222 PreNarrowingType, 10223 /*IgnoreFloatToIntegralConversion*/ true)) { 10224 case NK_Dependent_Narrowing: 10225 // Implicit conversion to a narrower type, but the expression is 10226 // value-dependent so we can't tell whether it's actually narrowing. 10227 case NK_Not_Narrowing: 10228 return false; 10229 10230 case NK_Constant_Narrowing: 10231 // Implicit conversion to a narrower type, and the value is not a constant 10232 // expression. 10233 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 10234 << /*Constant*/ 1 10235 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 10236 return true; 10237 10238 case NK_Variable_Narrowing: 10239 // Implicit conversion to a narrower type, and the value is not a constant 10240 // expression. 10241 case NK_Type_Narrowing: 10242 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 10243 << /*Constant*/ 0 << FromType << ToType; 10244 // TODO: It's not a constant expression, but what if the user intended it 10245 // to be? Can we produce notes to help them figure out why it isn't? 10246 return true; 10247 } 10248 llvm_unreachable("unhandled case in switch"); 10249 } 10250 10251 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 10252 ExprResult &LHS, 10253 ExprResult &RHS, 10254 SourceLocation Loc) { 10255 using CCT = ComparisonCategoryType; 10256 10257 QualType LHSType = LHS.get()->getType(); 10258 QualType RHSType = RHS.get()->getType(); 10259 // Dig out the original argument type and expression before implicit casts 10260 // were applied. These are the types/expressions we need to check the 10261 // [expr.spaceship] requirements against. 10262 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 10263 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 10264 QualType LHSStrippedType = LHSStripped.get()->getType(); 10265 QualType RHSStrippedType = RHSStripped.get()->getType(); 10266 10267 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 10268 // other is not, the program is ill-formed. 10269 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 10270 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 10271 return QualType(); 10272 } 10273 10274 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 10275 RHSStrippedType->isEnumeralType(); 10276 if (NumEnumArgs == 1) { 10277 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 10278 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 10279 if (OtherTy->hasFloatingRepresentation()) { 10280 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 10281 return QualType(); 10282 } 10283 } 10284 if (NumEnumArgs == 2) { 10285 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 10286 // type E, the operator yields the result of converting the operands 10287 // to the underlying type of E and applying <=> to the converted operands. 10288 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 10289 S.InvalidOperands(Loc, LHS, RHS); 10290 return QualType(); 10291 } 10292 QualType IntType = 10293 LHSStrippedType->getAs<EnumType>()->getDecl()->getIntegerType(); 10294 assert(IntType->isArithmeticType()); 10295 10296 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 10297 // promote the boolean type, and all other promotable integer types, to 10298 // avoid this. 10299 if (IntType->isPromotableIntegerType()) 10300 IntType = S.Context.getPromotedIntegerType(IntType); 10301 10302 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 10303 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 10304 LHSType = RHSType = IntType; 10305 } 10306 10307 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 10308 // usual arithmetic conversions are applied to the operands. 10309 QualType Type = S.UsualArithmeticConversions(LHS, RHS); 10310 if (LHS.isInvalid() || RHS.isInvalid()) 10311 return QualType(); 10312 if (Type.isNull()) 10313 return S.InvalidOperands(Loc, LHS, RHS); 10314 assert(Type->isArithmeticType() || Type->isEnumeralType()); 10315 10316 bool HasNarrowing = checkThreeWayNarrowingConversion( 10317 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 10318 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 10319 RHS.get()->getBeginLoc()); 10320 if (HasNarrowing) 10321 return QualType(); 10322 10323 assert(!Type.isNull() && "composite type for <=> has not been set"); 10324 10325 auto TypeKind = [&]() { 10326 if (const ComplexType *CT = Type->getAs<ComplexType>()) { 10327 if (CT->getElementType()->hasFloatingRepresentation()) 10328 return CCT::WeakEquality; 10329 return CCT::StrongEquality; 10330 } 10331 if (Type->isIntegralOrEnumerationType()) 10332 return CCT::StrongOrdering; 10333 if (Type->hasFloatingRepresentation()) 10334 return CCT::PartialOrdering; 10335 llvm_unreachable("other types are unimplemented"); 10336 }(); 10337 10338 return S.CheckComparisonCategoryType(TypeKind, Loc); 10339 } 10340 10341 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 10342 ExprResult &RHS, 10343 SourceLocation Loc, 10344 BinaryOperatorKind Opc) { 10345 if (Opc == BO_Cmp) 10346 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 10347 10348 // C99 6.5.8p3 / C99 6.5.9p4 10349 QualType Type = S.UsualArithmeticConversions(LHS, RHS); 10350 if (LHS.isInvalid() || RHS.isInvalid()) 10351 return QualType(); 10352 if (Type.isNull()) 10353 return S.InvalidOperands(Loc, LHS, RHS); 10354 assert(Type->isArithmeticType() || Type->isEnumeralType()); 10355 10356 checkEnumComparison(S, Loc, LHS.get(), RHS.get()); 10357 10358 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 10359 return S.InvalidOperands(Loc, LHS, RHS); 10360 10361 // Check for comparisons of floating point operands using != and ==. 10362 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 10363 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 10364 10365 // The result of comparisons is 'bool' in C++, 'int' in C. 10366 return S.Context.getLogicalOperationType(); 10367 } 10368 10369 // C99 6.5.8, C++ [expr.rel] 10370 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 10371 SourceLocation Loc, 10372 BinaryOperatorKind Opc) { 10373 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 10374 bool IsThreeWay = Opc == BO_Cmp; 10375 auto IsAnyPointerType = [](ExprResult E) { 10376 QualType Ty = E.get()->getType(); 10377 return Ty->isPointerType() || Ty->isMemberPointerType(); 10378 }; 10379 10380 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 10381 // type, array-to-pointer, ..., conversions are performed on both operands to 10382 // bring them to their composite type. 10383 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 10384 // any type-related checks. 10385 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 10386 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10387 if (LHS.isInvalid()) 10388 return QualType(); 10389 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10390 if (RHS.isInvalid()) 10391 return QualType(); 10392 } else { 10393 LHS = DefaultLvalueConversion(LHS.get()); 10394 if (LHS.isInvalid()) 10395 return QualType(); 10396 RHS = DefaultLvalueConversion(RHS.get()); 10397 if (RHS.isInvalid()) 10398 return QualType(); 10399 } 10400 10401 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 10402 10403 // Handle vector comparisons separately. 10404 if (LHS.get()->getType()->isVectorType() || 10405 RHS.get()->getType()->isVectorType()) 10406 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 10407 10408 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 10409 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 10410 10411 QualType LHSType = LHS.get()->getType(); 10412 QualType RHSType = RHS.get()->getType(); 10413 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 10414 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 10415 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 10416 10417 const Expr::NullPointerConstantKind LHSNullKind = 10418 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 10419 const Expr::NullPointerConstantKind RHSNullKind = 10420 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 10421 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 10422 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 10423 10424 auto computeResultTy = [&]() { 10425 if (Opc != BO_Cmp) 10426 return Context.getLogicalOperationType(); 10427 assert(getLangOpts().CPlusPlus); 10428 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 10429 10430 QualType CompositeTy = LHS.get()->getType(); 10431 assert(!CompositeTy->isReferenceType()); 10432 10433 auto buildResultTy = [&](ComparisonCategoryType Kind) { 10434 return CheckComparisonCategoryType(Kind, Loc); 10435 }; 10436 10437 // C++2a [expr.spaceship]p7: If the composite pointer type is a function 10438 // pointer type, a pointer-to-member type, or std::nullptr_t, the 10439 // result is of type std::strong_equality 10440 if (CompositeTy->isFunctionPointerType() || 10441 CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType()) 10442 // FIXME: consider making the function pointer case produce 10443 // strong_ordering not strong_equality, per P0946R0-Jax18 discussion 10444 // and direction polls 10445 return buildResultTy(ComparisonCategoryType::StrongEquality); 10446 10447 // C++2a [expr.spaceship]p8: If the composite pointer type is an object 10448 // pointer type, p <=> q is of type std::strong_ordering. 10449 if (CompositeTy->isPointerType()) { 10450 // P0946R0: Comparisons between a null pointer constant and an object 10451 // pointer result in std::strong_equality 10452 if (LHSIsNull != RHSIsNull) 10453 return buildResultTy(ComparisonCategoryType::StrongEquality); 10454 return buildResultTy(ComparisonCategoryType::StrongOrdering); 10455 } 10456 // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed. 10457 // TODO: Extend support for operator<=> to ObjC types. 10458 return InvalidOperands(Loc, LHS, RHS); 10459 }; 10460 10461 10462 if (!IsRelational && LHSIsNull != RHSIsNull) { 10463 bool IsEquality = Opc == BO_EQ; 10464 if (RHSIsNull) 10465 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 10466 RHS.get()->getSourceRange()); 10467 else 10468 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 10469 LHS.get()->getSourceRange()); 10470 } 10471 10472 if ((LHSType->isIntegerType() && !LHSIsNull) || 10473 (RHSType->isIntegerType() && !RHSIsNull)) { 10474 // Skip normal pointer conversion checks in this case; we have better 10475 // diagnostics for this below. 10476 } else if (getLangOpts().CPlusPlus) { 10477 // Equality comparison of a function pointer to a void pointer is invalid, 10478 // but we allow it as an extension. 10479 // FIXME: If we really want to allow this, should it be part of composite 10480 // pointer type computation so it works in conditionals too? 10481 if (!IsRelational && 10482 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 10483 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 10484 // This is a gcc extension compatibility comparison. 10485 // In a SFINAE context, we treat this as a hard error to maintain 10486 // conformance with the C++ standard. 10487 diagnoseFunctionPointerToVoidComparison( 10488 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 10489 10490 if (isSFINAEContext()) 10491 return QualType(); 10492 10493 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10494 return computeResultTy(); 10495 } 10496 10497 // C++ [expr.eq]p2: 10498 // If at least one operand is a pointer [...] bring them to their 10499 // composite pointer type. 10500 // C++ [expr.spaceship]p6 10501 // If at least one of the operands is of pointer type, [...] bring them 10502 // to their composite pointer type. 10503 // C++ [expr.rel]p2: 10504 // If both operands are pointers, [...] bring them to their composite 10505 // pointer type. 10506 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 10507 (IsRelational ? 2 : 1) && 10508 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 10509 RHSType->isObjCObjectPointerType()))) { 10510 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 10511 return QualType(); 10512 return computeResultTy(); 10513 } 10514 } else if (LHSType->isPointerType() && 10515 RHSType->isPointerType()) { // C99 6.5.8p2 10516 // All of the following pointer-related warnings are GCC extensions, except 10517 // when handling null pointer constants. 10518 QualType LCanPointeeTy = 10519 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 10520 QualType RCanPointeeTy = 10521 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 10522 10523 // C99 6.5.9p2 and C99 6.5.8p2 10524 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 10525 RCanPointeeTy.getUnqualifiedType())) { 10526 // Valid unless a relational comparison of function pointers 10527 if (IsRelational && LCanPointeeTy->isFunctionType()) { 10528 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 10529 << LHSType << RHSType << LHS.get()->getSourceRange() 10530 << RHS.get()->getSourceRange(); 10531 } 10532 } else if (!IsRelational && 10533 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 10534 // Valid unless comparison between non-null pointer and function pointer 10535 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 10536 && !LHSIsNull && !RHSIsNull) 10537 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 10538 /*isError*/false); 10539 } else { 10540 // Invalid 10541 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 10542 } 10543 if (LCanPointeeTy != RCanPointeeTy) { 10544 // Treat NULL constant as a special case in OpenCL. 10545 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 10546 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 10547 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 10548 Diag(Loc, 10549 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10550 << LHSType << RHSType << 0 /* comparison */ 10551 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10552 } 10553 } 10554 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 10555 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 10556 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 10557 : CK_BitCast; 10558 if (LHSIsNull && !RHSIsNull) 10559 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 10560 else 10561 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 10562 } 10563 return computeResultTy(); 10564 } 10565 10566 if (getLangOpts().CPlusPlus) { 10567 // C++ [expr.eq]p4: 10568 // Two operands of type std::nullptr_t or one operand of type 10569 // std::nullptr_t and the other a null pointer constant compare equal. 10570 if (!IsRelational && LHSIsNull && RHSIsNull) { 10571 if (LHSType->isNullPtrType()) { 10572 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10573 return computeResultTy(); 10574 } 10575 if (RHSType->isNullPtrType()) { 10576 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10577 return computeResultTy(); 10578 } 10579 } 10580 10581 // Comparison of Objective-C pointers and block pointers against nullptr_t. 10582 // These aren't covered by the composite pointer type rules. 10583 if (!IsRelational && RHSType->isNullPtrType() && 10584 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 10585 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10586 return computeResultTy(); 10587 } 10588 if (!IsRelational && LHSType->isNullPtrType() && 10589 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 10590 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10591 return computeResultTy(); 10592 } 10593 10594 if (IsRelational && 10595 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 10596 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 10597 // HACK: Relational comparison of nullptr_t against a pointer type is 10598 // invalid per DR583, but we allow it within std::less<> and friends, 10599 // since otherwise common uses of it break. 10600 // FIXME: Consider removing this hack once LWG fixes std::less<> and 10601 // friends to have std::nullptr_t overload candidates. 10602 DeclContext *DC = CurContext; 10603 if (isa<FunctionDecl>(DC)) 10604 DC = DC->getParent(); 10605 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 10606 if (CTSD->isInStdNamespace() && 10607 llvm::StringSwitch<bool>(CTSD->getName()) 10608 .Cases("less", "less_equal", "greater", "greater_equal", true) 10609 .Default(false)) { 10610 if (RHSType->isNullPtrType()) 10611 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10612 else 10613 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10614 return computeResultTy(); 10615 } 10616 } 10617 } 10618 10619 // C++ [expr.eq]p2: 10620 // If at least one operand is a pointer to member, [...] bring them to 10621 // their composite pointer type. 10622 if (!IsRelational && 10623 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 10624 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 10625 return QualType(); 10626 else 10627 return computeResultTy(); 10628 } 10629 } 10630 10631 // Handle block pointer types. 10632 if (!IsRelational && LHSType->isBlockPointerType() && 10633 RHSType->isBlockPointerType()) { 10634 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 10635 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 10636 10637 if (!LHSIsNull && !RHSIsNull && 10638 !Context.typesAreCompatible(lpointee, rpointee)) { 10639 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 10640 << LHSType << RHSType << LHS.get()->getSourceRange() 10641 << RHS.get()->getSourceRange(); 10642 } 10643 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10644 return computeResultTy(); 10645 } 10646 10647 // Allow block pointers to be compared with null pointer constants. 10648 if (!IsRelational 10649 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 10650 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 10651 if (!LHSIsNull && !RHSIsNull) { 10652 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 10653 ->getPointeeType()->isVoidType()) 10654 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 10655 ->getPointeeType()->isVoidType()))) 10656 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 10657 << LHSType << RHSType << LHS.get()->getSourceRange() 10658 << RHS.get()->getSourceRange(); 10659 } 10660 if (LHSIsNull && !RHSIsNull) 10661 LHS = ImpCastExprToType(LHS.get(), RHSType, 10662 RHSType->isPointerType() ? CK_BitCast 10663 : CK_AnyPointerToBlockPointerCast); 10664 else 10665 RHS = ImpCastExprToType(RHS.get(), LHSType, 10666 LHSType->isPointerType() ? CK_BitCast 10667 : CK_AnyPointerToBlockPointerCast); 10668 return computeResultTy(); 10669 } 10670 10671 if (LHSType->isObjCObjectPointerType() || 10672 RHSType->isObjCObjectPointerType()) { 10673 const PointerType *LPT = LHSType->getAs<PointerType>(); 10674 const PointerType *RPT = RHSType->getAs<PointerType>(); 10675 if (LPT || RPT) { 10676 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 10677 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 10678 10679 if (!LPtrToVoid && !RPtrToVoid && 10680 !Context.typesAreCompatible(LHSType, RHSType)) { 10681 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 10682 /*isError*/false); 10683 } 10684 if (LHSIsNull && !RHSIsNull) { 10685 Expr *E = LHS.get(); 10686 if (getLangOpts().ObjCAutoRefCount) 10687 CheckObjCConversion(SourceRange(), RHSType, E, 10688 CCK_ImplicitConversion); 10689 LHS = ImpCastExprToType(E, RHSType, 10690 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 10691 } 10692 else { 10693 Expr *E = RHS.get(); 10694 if (getLangOpts().ObjCAutoRefCount) 10695 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 10696 /*Diagnose=*/true, 10697 /*DiagnoseCFAudited=*/false, Opc); 10698 RHS = ImpCastExprToType(E, LHSType, 10699 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 10700 } 10701 return computeResultTy(); 10702 } 10703 if (LHSType->isObjCObjectPointerType() && 10704 RHSType->isObjCObjectPointerType()) { 10705 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 10706 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 10707 /*isError*/false); 10708 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 10709 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 10710 10711 if (LHSIsNull && !RHSIsNull) 10712 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10713 else 10714 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10715 return computeResultTy(); 10716 } 10717 10718 if (!IsRelational && LHSType->isBlockPointerType() && 10719 RHSType->isBlockCompatibleObjCPointerType(Context)) { 10720 LHS = ImpCastExprToType(LHS.get(), RHSType, 10721 CK_BlockPointerToObjCPointerCast); 10722 return computeResultTy(); 10723 } else if (!IsRelational && 10724 LHSType->isBlockCompatibleObjCPointerType(Context) && 10725 RHSType->isBlockPointerType()) { 10726 RHS = ImpCastExprToType(RHS.get(), LHSType, 10727 CK_BlockPointerToObjCPointerCast); 10728 return computeResultTy(); 10729 } 10730 } 10731 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 10732 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 10733 unsigned DiagID = 0; 10734 bool isError = false; 10735 if (LangOpts.DebuggerSupport) { 10736 // Under a debugger, allow the comparison of pointers to integers, 10737 // since users tend to want to compare addresses. 10738 } else if ((LHSIsNull && LHSType->isIntegerType()) || 10739 (RHSIsNull && RHSType->isIntegerType())) { 10740 if (IsRelational) { 10741 isError = getLangOpts().CPlusPlus; 10742 DiagID = 10743 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 10744 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 10745 } 10746 } else if (getLangOpts().CPlusPlus) { 10747 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 10748 isError = true; 10749 } else if (IsRelational) 10750 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 10751 else 10752 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 10753 10754 if (DiagID) { 10755 Diag(Loc, DiagID) 10756 << LHSType << RHSType << LHS.get()->getSourceRange() 10757 << RHS.get()->getSourceRange(); 10758 if (isError) 10759 return QualType(); 10760 } 10761 10762 if (LHSType->isIntegerType()) 10763 LHS = ImpCastExprToType(LHS.get(), RHSType, 10764 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 10765 else 10766 RHS = ImpCastExprToType(RHS.get(), LHSType, 10767 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 10768 return computeResultTy(); 10769 } 10770 10771 // Handle block pointers. 10772 if (!IsRelational && RHSIsNull 10773 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 10774 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10775 return computeResultTy(); 10776 } 10777 if (!IsRelational && LHSIsNull 10778 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 10779 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10780 return computeResultTy(); 10781 } 10782 10783 if (getLangOpts().OpenCLVersion >= 200) { 10784 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 10785 return computeResultTy(); 10786 } 10787 10788 if (LHSType->isQueueT() && RHSType->isQueueT()) { 10789 return computeResultTy(); 10790 } 10791 10792 if (LHSIsNull && RHSType->isQueueT()) { 10793 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10794 return computeResultTy(); 10795 } 10796 10797 if (LHSType->isQueueT() && RHSIsNull) { 10798 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10799 return computeResultTy(); 10800 } 10801 } 10802 10803 return InvalidOperands(Loc, LHS, RHS); 10804 } 10805 10806 // Return a signed ext_vector_type that is of identical size and number of 10807 // elements. For floating point vectors, return an integer type of identical 10808 // size and number of elements. In the non ext_vector_type case, search from 10809 // the largest type to the smallest type to avoid cases where long long == long, 10810 // where long gets picked over long long. 10811 QualType Sema::GetSignedVectorType(QualType V) { 10812 const VectorType *VTy = V->getAs<VectorType>(); 10813 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 10814 10815 if (isa<ExtVectorType>(VTy)) { 10816 if (TypeSize == Context.getTypeSize(Context.CharTy)) 10817 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 10818 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 10819 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 10820 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 10821 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 10822 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 10823 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 10824 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 10825 "Unhandled vector element size in vector compare"); 10826 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 10827 } 10828 10829 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 10830 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 10831 VectorType::GenericVector); 10832 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 10833 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 10834 VectorType::GenericVector); 10835 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 10836 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 10837 VectorType::GenericVector); 10838 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 10839 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 10840 VectorType::GenericVector); 10841 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 10842 "Unhandled vector element size in vector compare"); 10843 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 10844 VectorType::GenericVector); 10845 } 10846 10847 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 10848 /// operates on extended vector types. Instead of producing an IntTy result, 10849 /// like a scalar comparison, a vector comparison produces a vector of integer 10850 /// types. 10851 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 10852 SourceLocation Loc, 10853 BinaryOperatorKind Opc) { 10854 // Check to make sure we're operating on vectors of the same type and width, 10855 // Allowing one side to be a scalar of element type. 10856 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 10857 /*AllowBothBool*/true, 10858 /*AllowBoolConversions*/getLangOpts().ZVector); 10859 if (vType.isNull()) 10860 return vType; 10861 10862 QualType LHSType = LHS.get()->getType(); 10863 10864 // If AltiVec, the comparison results in a numeric type, i.e. 10865 // bool for C++, int for C 10866 if (getLangOpts().AltiVec && 10867 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 10868 return Context.getLogicalOperationType(); 10869 10870 // For non-floating point types, check for self-comparisons of the form 10871 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 10872 // often indicate logic errors in the program. 10873 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 10874 10875 // Check for comparisons of floating point operands using != and ==. 10876 if (BinaryOperator::isEqualityOp(Opc) && 10877 LHSType->hasFloatingRepresentation()) { 10878 assert(RHS.get()->getType()->hasFloatingRepresentation()); 10879 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 10880 } 10881 10882 // Return a signed type for the vector. 10883 return GetSignedVectorType(vType); 10884 } 10885 10886 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 10887 SourceLocation Loc) { 10888 // Ensure that either both operands are of the same vector type, or 10889 // one operand is of a vector type and the other is of its element type. 10890 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 10891 /*AllowBothBool*/true, 10892 /*AllowBoolConversions*/false); 10893 if (vType.isNull()) 10894 return InvalidOperands(Loc, LHS, RHS); 10895 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 10896 vType->hasFloatingRepresentation()) 10897 return InvalidOperands(Loc, LHS, RHS); 10898 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 10899 // usage of the logical operators && and || with vectors in C. This 10900 // check could be notionally dropped. 10901 if (!getLangOpts().CPlusPlus && 10902 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 10903 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 10904 10905 return GetSignedVectorType(LHS.get()->getType()); 10906 } 10907 10908 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 10909 SourceLocation Loc, 10910 BinaryOperatorKind Opc) { 10911 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 10912 10913 bool IsCompAssign = 10914 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 10915 10916 if (LHS.get()->getType()->isVectorType() || 10917 RHS.get()->getType()->isVectorType()) { 10918 if (LHS.get()->getType()->hasIntegerRepresentation() && 10919 RHS.get()->getType()->hasIntegerRepresentation()) 10920 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10921 /*AllowBothBool*/true, 10922 /*AllowBoolConversions*/getLangOpts().ZVector); 10923 return InvalidOperands(Loc, LHS, RHS); 10924 } 10925 10926 if (Opc == BO_And) 10927 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 10928 10929 ExprResult LHSResult = LHS, RHSResult = RHS; 10930 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 10931 IsCompAssign); 10932 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 10933 return QualType(); 10934 LHS = LHSResult.get(); 10935 RHS = RHSResult.get(); 10936 10937 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 10938 return compType; 10939 return InvalidOperands(Loc, LHS, RHS); 10940 } 10941 10942 // C99 6.5.[13,14] 10943 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 10944 SourceLocation Loc, 10945 BinaryOperatorKind Opc) { 10946 // Check vector operands differently. 10947 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 10948 return CheckVectorLogicalOperands(LHS, RHS, Loc); 10949 10950 // Diagnose cases where the user write a logical and/or but probably meant a 10951 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 10952 // is a constant. 10953 if (LHS.get()->getType()->isIntegerType() && 10954 !LHS.get()->getType()->isBooleanType() && 10955 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 10956 // Don't warn in macros or template instantiations. 10957 !Loc.isMacroID() && !inTemplateInstantiation()) { 10958 // If the RHS can be constant folded, and if it constant folds to something 10959 // that isn't 0 or 1 (which indicate a potential logical operation that 10960 // happened to fold to true/false) then warn. 10961 // Parens on the RHS are ignored. 10962 Expr::EvalResult EVResult; 10963 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 10964 llvm::APSInt Result = EVResult.Val.getInt(); 10965 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 10966 !RHS.get()->getExprLoc().isMacroID()) || 10967 (Result != 0 && Result != 1)) { 10968 Diag(Loc, diag::warn_logical_instead_of_bitwise) 10969 << RHS.get()->getSourceRange() 10970 << (Opc == BO_LAnd ? "&&" : "||"); 10971 // Suggest replacing the logical operator with the bitwise version 10972 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 10973 << (Opc == BO_LAnd ? "&" : "|") 10974 << FixItHint::CreateReplacement(SourceRange( 10975 Loc, getLocForEndOfToken(Loc)), 10976 Opc == BO_LAnd ? "&" : "|"); 10977 if (Opc == BO_LAnd) 10978 // Suggest replacing "Foo() && kNonZero" with "Foo()" 10979 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 10980 << FixItHint::CreateRemoval( 10981 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 10982 RHS.get()->getEndLoc())); 10983 } 10984 } 10985 } 10986 10987 if (!Context.getLangOpts().CPlusPlus) { 10988 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 10989 // not operate on the built-in scalar and vector float types. 10990 if (Context.getLangOpts().OpenCL && 10991 Context.getLangOpts().OpenCLVersion < 120) { 10992 if (LHS.get()->getType()->isFloatingType() || 10993 RHS.get()->getType()->isFloatingType()) 10994 return InvalidOperands(Loc, LHS, RHS); 10995 } 10996 10997 LHS = UsualUnaryConversions(LHS.get()); 10998 if (LHS.isInvalid()) 10999 return QualType(); 11000 11001 RHS = UsualUnaryConversions(RHS.get()); 11002 if (RHS.isInvalid()) 11003 return QualType(); 11004 11005 if (!LHS.get()->getType()->isScalarType() || 11006 !RHS.get()->getType()->isScalarType()) 11007 return InvalidOperands(Loc, LHS, RHS); 11008 11009 return Context.IntTy; 11010 } 11011 11012 // The following is safe because we only use this method for 11013 // non-overloadable operands. 11014 11015 // C++ [expr.log.and]p1 11016 // C++ [expr.log.or]p1 11017 // The operands are both contextually converted to type bool. 11018 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 11019 if (LHSRes.isInvalid()) 11020 return InvalidOperands(Loc, LHS, RHS); 11021 LHS = LHSRes; 11022 11023 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 11024 if (RHSRes.isInvalid()) 11025 return InvalidOperands(Loc, LHS, RHS); 11026 RHS = RHSRes; 11027 11028 // C++ [expr.log.and]p2 11029 // C++ [expr.log.or]p2 11030 // The result is a bool. 11031 return Context.BoolTy; 11032 } 11033 11034 static bool IsReadonlyMessage(Expr *E, Sema &S) { 11035 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 11036 if (!ME) return false; 11037 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 11038 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 11039 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 11040 if (!Base) return false; 11041 return Base->getMethodDecl() != nullptr; 11042 } 11043 11044 /// Is the given expression (which must be 'const') a reference to a 11045 /// variable which was originally non-const, but which has become 11046 /// 'const' due to being captured within a block? 11047 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 11048 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 11049 assert(E->isLValue() && E->getType().isConstQualified()); 11050 E = E->IgnoreParens(); 11051 11052 // Must be a reference to a declaration from an enclosing scope. 11053 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 11054 if (!DRE) return NCCK_None; 11055 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 11056 11057 // The declaration must be a variable which is not declared 'const'. 11058 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 11059 if (!var) return NCCK_None; 11060 if (var->getType().isConstQualified()) return NCCK_None; 11061 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 11062 11063 // Decide whether the first capture was for a block or a lambda. 11064 DeclContext *DC = S.CurContext, *Prev = nullptr; 11065 // Decide whether the first capture was for a block or a lambda. 11066 while (DC) { 11067 // For init-capture, it is possible that the variable belongs to the 11068 // template pattern of the current context. 11069 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 11070 if (var->isInitCapture() && 11071 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 11072 break; 11073 if (DC == var->getDeclContext()) 11074 break; 11075 Prev = DC; 11076 DC = DC->getParent(); 11077 } 11078 // Unless we have an init-capture, we've gone one step too far. 11079 if (!var->isInitCapture()) 11080 DC = Prev; 11081 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 11082 } 11083 11084 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 11085 Ty = Ty.getNonReferenceType(); 11086 if (IsDereference && Ty->isPointerType()) 11087 Ty = Ty->getPointeeType(); 11088 return !Ty.isConstQualified(); 11089 } 11090 11091 // Update err_typecheck_assign_const and note_typecheck_assign_const 11092 // when this enum is changed. 11093 enum { 11094 ConstFunction, 11095 ConstVariable, 11096 ConstMember, 11097 ConstMethod, 11098 NestedConstMember, 11099 ConstUnknown, // Keep as last element 11100 }; 11101 11102 /// Emit the "read-only variable not assignable" error and print notes to give 11103 /// more information about why the variable is not assignable, such as pointing 11104 /// to the declaration of a const variable, showing that a method is const, or 11105 /// that the function is returning a const reference. 11106 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 11107 SourceLocation Loc) { 11108 SourceRange ExprRange = E->getSourceRange(); 11109 11110 // Only emit one error on the first const found. All other consts will emit 11111 // a note to the error. 11112 bool DiagnosticEmitted = false; 11113 11114 // Track if the current expression is the result of a dereference, and if the 11115 // next checked expression is the result of a dereference. 11116 bool IsDereference = false; 11117 bool NextIsDereference = false; 11118 11119 // Loop to process MemberExpr chains. 11120 while (true) { 11121 IsDereference = NextIsDereference; 11122 11123 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 11124 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 11125 NextIsDereference = ME->isArrow(); 11126 const ValueDecl *VD = ME->getMemberDecl(); 11127 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 11128 // Mutable fields can be modified even if the class is const. 11129 if (Field->isMutable()) { 11130 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 11131 break; 11132 } 11133 11134 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 11135 if (!DiagnosticEmitted) { 11136 S.Diag(Loc, diag::err_typecheck_assign_const) 11137 << ExprRange << ConstMember << false /*static*/ << Field 11138 << Field->getType(); 11139 DiagnosticEmitted = true; 11140 } 11141 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11142 << ConstMember << false /*static*/ << Field << Field->getType() 11143 << Field->getSourceRange(); 11144 } 11145 E = ME->getBase(); 11146 continue; 11147 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 11148 if (VDecl->getType().isConstQualified()) { 11149 if (!DiagnosticEmitted) { 11150 S.Diag(Loc, diag::err_typecheck_assign_const) 11151 << ExprRange << ConstMember << true /*static*/ << VDecl 11152 << VDecl->getType(); 11153 DiagnosticEmitted = true; 11154 } 11155 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11156 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 11157 << VDecl->getSourceRange(); 11158 } 11159 // Static fields do not inherit constness from parents. 11160 break; 11161 } 11162 break; // End MemberExpr 11163 } else if (const ArraySubscriptExpr *ASE = 11164 dyn_cast<ArraySubscriptExpr>(E)) { 11165 E = ASE->getBase()->IgnoreParenImpCasts(); 11166 continue; 11167 } else if (const ExtVectorElementExpr *EVE = 11168 dyn_cast<ExtVectorElementExpr>(E)) { 11169 E = EVE->getBase()->IgnoreParenImpCasts(); 11170 continue; 11171 } 11172 break; 11173 } 11174 11175 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 11176 // Function calls 11177 const FunctionDecl *FD = CE->getDirectCallee(); 11178 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 11179 if (!DiagnosticEmitted) { 11180 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 11181 << ConstFunction << FD; 11182 DiagnosticEmitted = true; 11183 } 11184 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 11185 diag::note_typecheck_assign_const) 11186 << ConstFunction << FD << FD->getReturnType() 11187 << FD->getReturnTypeSourceRange(); 11188 } 11189 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11190 // Point to variable declaration. 11191 if (const ValueDecl *VD = DRE->getDecl()) { 11192 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 11193 if (!DiagnosticEmitted) { 11194 S.Diag(Loc, diag::err_typecheck_assign_const) 11195 << ExprRange << ConstVariable << VD << VD->getType(); 11196 DiagnosticEmitted = true; 11197 } 11198 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11199 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 11200 } 11201 } 11202 } else if (isa<CXXThisExpr>(E)) { 11203 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 11204 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 11205 if (MD->isConst()) { 11206 if (!DiagnosticEmitted) { 11207 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 11208 << ConstMethod << MD; 11209 DiagnosticEmitted = true; 11210 } 11211 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 11212 << ConstMethod << MD << MD->getSourceRange(); 11213 } 11214 } 11215 } 11216 } 11217 11218 if (DiagnosticEmitted) 11219 return; 11220 11221 // Can't determine a more specific message, so display the generic error. 11222 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 11223 } 11224 11225 enum OriginalExprKind { 11226 OEK_Variable, 11227 OEK_Member, 11228 OEK_LValue 11229 }; 11230 11231 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 11232 const RecordType *Ty, 11233 SourceLocation Loc, SourceRange Range, 11234 OriginalExprKind OEK, 11235 bool &DiagnosticEmitted) { 11236 std::vector<const RecordType *> RecordTypeList; 11237 RecordTypeList.push_back(Ty); 11238 unsigned NextToCheckIndex = 0; 11239 // We walk the record hierarchy breadth-first to ensure that we print 11240 // diagnostics in field nesting order. 11241 while (RecordTypeList.size() > NextToCheckIndex) { 11242 bool IsNested = NextToCheckIndex > 0; 11243 for (const FieldDecl *Field : 11244 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 11245 // First, check every field for constness. 11246 QualType FieldTy = Field->getType(); 11247 if (FieldTy.isConstQualified()) { 11248 if (!DiagnosticEmitted) { 11249 S.Diag(Loc, diag::err_typecheck_assign_const) 11250 << Range << NestedConstMember << OEK << VD 11251 << IsNested << Field; 11252 DiagnosticEmitted = true; 11253 } 11254 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 11255 << NestedConstMember << IsNested << Field 11256 << FieldTy << Field->getSourceRange(); 11257 } 11258 11259 // Then we append it to the list to check next in order. 11260 FieldTy = FieldTy.getCanonicalType(); 11261 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 11262 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) 11263 RecordTypeList.push_back(FieldRecTy); 11264 } 11265 } 11266 ++NextToCheckIndex; 11267 } 11268 } 11269 11270 /// Emit an error for the case where a record we are trying to assign to has a 11271 /// const-qualified field somewhere in its hierarchy. 11272 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 11273 SourceLocation Loc) { 11274 QualType Ty = E->getType(); 11275 assert(Ty->isRecordType() && "lvalue was not record?"); 11276 SourceRange Range = E->getSourceRange(); 11277 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 11278 bool DiagEmitted = false; 11279 11280 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 11281 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 11282 Range, OEK_Member, DiagEmitted); 11283 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11284 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 11285 Range, OEK_Variable, DiagEmitted); 11286 else 11287 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 11288 Range, OEK_LValue, DiagEmitted); 11289 if (!DiagEmitted) 11290 DiagnoseConstAssignment(S, E, Loc); 11291 } 11292 11293 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 11294 /// emit an error and return true. If so, return false. 11295 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 11296 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 11297 11298 S.CheckShadowingDeclModification(E, Loc); 11299 11300 SourceLocation OrigLoc = Loc; 11301 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 11302 &Loc); 11303 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 11304 IsLV = Expr::MLV_InvalidMessageExpression; 11305 if (IsLV == Expr::MLV_Valid) 11306 return false; 11307 11308 unsigned DiagID = 0; 11309 bool NeedType = false; 11310 switch (IsLV) { // C99 6.5.16p2 11311 case Expr::MLV_ConstQualified: 11312 // Use a specialized diagnostic when we're assigning to an object 11313 // from an enclosing function or block. 11314 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 11315 if (NCCK == NCCK_Block) 11316 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 11317 else 11318 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 11319 break; 11320 } 11321 11322 // In ARC, use some specialized diagnostics for occasions where we 11323 // infer 'const'. These are always pseudo-strong variables. 11324 if (S.getLangOpts().ObjCAutoRefCount) { 11325 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 11326 if (declRef && isa<VarDecl>(declRef->getDecl())) { 11327 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 11328 11329 // Use the normal diagnostic if it's pseudo-__strong but the 11330 // user actually wrote 'const'. 11331 if (var->isARCPseudoStrong() && 11332 (!var->getTypeSourceInfo() || 11333 !var->getTypeSourceInfo()->getType().isConstQualified())) { 11334 // There are three pseudo-strong cases: 11335 // - self 11336 ObjCMethodDecl *method = S.getCurMethodDecl(); 11337 if (method && var == method->getSelfDecl()) { 11338 DiagID = method->isClassMethod() 11339 ? diag::err_typecheck_arc_assign_self_class_method 11340 : diag::err_typecheck_arc_assign_self; 11341 11342 // - Objective-C externally_retained attribute. 11343 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 11344 isa<ParmVarDecl>(var)) { 11345 DiagID = diag::err_typecheck_arc_assign_externally_retained; 11346 11347 // - fast enumeration variables 11348 } else { 11349 DiagID = diag::err_typecheck_arr_assign_enumeration; 11350 } 11351 11352 SourceRange Assign; 11353 if (Loc != OrigLoc) 11354 Assign = SourceRange(OrigLoc, OrigLoc); 11355 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 11356 // We need to preserve the AST regardless, so migration tool 11357 // can do its job. 11358 return false; 11359 } 11360 } 11361 } 11362 11363 // If none of the special cases above are triggered, then this is a 11364 // simple const assignment. 11365 if (DiagID == 0) { 11366 DiagnoseConstAssignment(S, E, Loc); 11367 return true; 11368 } 11369 11370 break; 11371 case Expr::MLV_ConstAddrSpace: 11372 DiagnoseConstAssignment(S, E, Loc); 11373 return true; 11374 case Expr::MLV_ConstQualifiedField: 11375 DiagnoseRecursiveConstFields(S, E, Loc); 11376 return true; 11377 case Expr::MLV_ArrayType: 11378 case Expr::MLV_ArrayTemporary: 11379 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 11380 NeedType = true; 11381 break; 11382 case Expr::MLV_NotObjectType: 11383 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 11384 NeedType = true; 11385 break; 11386 case Expr::MLV_LValueCast: 11387 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 11388 break; 11389 case Expr::MLV_Valid: 11390 llvm_unreachable("did not take early return for MLV_Valid"); 11391 case Expr::MLV_InvalidExpression: 11392 case Expr::MLV_MemberFunction: 11393 case Expr::MLV_ClassTemporary: 11394 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 11395 break; 11396 case Expr::MLV_IncompleteType: 11397 case Expr::MLV_IncompleteVoidType: 11398 return S.RequireCompleteType(Loc, E->getType(), 11399 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 11400 case Expr::MLV_DuplicateVectorComponents: 11401 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 11402 break; 11403 case Expr::MLV_NoSetterProperty: 11404 llvm_unreachable("readonly properties should be processed differently"); 11405 case Expr::MLV_InvalidMessageExpression: 11406 DiagID = diag::err_readonly_message_assignment; 11407 break; 11408 case Expr::MLV_SubObjCPropertySetting: 11409 DiagID = diag::err_no_subobject_property_setting; 11410 break; 11411 } 11412 11413 SourceRange Assign; 11414 if (Loc != OrigLoc) 11415 Assign = SourceRange(OrigLoc, OrigLoc); 11416 if (NeedType) 11417 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 11418 else 11419 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 11420 return true; 11421 } 11422 11423 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 11424 SourceLocation Loc, 11425 Sema &Sema) { 11426 if (Sema.inTemplateInstantiation()) 11427 return; 11428 if (Sema.isUnevaluatedContext()) 11429 return; 11430 if (Loc.isInvalid() || Loc.isMacroID()) 11431 return; 11432 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 11433 return; 11434 11435 // C / C++ fields 11436 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 11437 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 11438 if (ML && MR) { 11439 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 11440 return; 11441 const ValueDecl *LHSDecl = 11442 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 11443 const ValueDecl *RHSDecl = 11444 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 11445 if (LHSDecl != RHSDecl) 11446 return; 11447 if (LHSDecl->getType().isVolatileQualified()) 11448 return; 11449 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 11450 if (RefTy->getPointeeType().isVolatileQualified()) 11451 return; 11452 11453 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 11454 } 11455 11456 // Objective-C instance variables 11457 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 11458 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 11459 if (OL && OR && OL->getDecl() == OR->getDecl()) { 11460 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 11461 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 11462 if (RL && RR && RL->getDecl() == RR->getDecl()) 11463 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 11464 } 11465 } 11466 11467 // C99 6.5.16.1 11468 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 11469 SourceLocation Loc, 11470 QualType CompoundType) { 11471 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 11472 11473 // Verify that LHS is a modifiable lvalue, and emit error if not. 11474 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 11475 return QualType(); 11476 11477 QualType LHSType = LHSExpr->getType(); 11478 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 11479 CompoundType; 11480 // OpenCL v1.2 s6.1.1.1 p2: 11481 // The half data type can only be used to declare a pointer to a buffer that 11482 // contains half values 11483 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 11484 LHSType->isHalfType()) { 11485 Diag(Loc, diag::err_opencl_half_load_store) << 1 11486 << LHSType.getUnqualifiedType(); 11487 return QualType(); 11488 } 11489 11490 AssignConvertType ConvTy; 11491 if (CompoundType.isNull()) { 11492 Expr *RHSCheck = RHS.get(); 11493 11494 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 11495 11496 QualType LHSTy(LHSType); 11497 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 11498 if (RHS.isInvalid()) 11499 return QualType(); 11500 // Special case of NSObject attributes on c-style pointer types. 11501 if (ConvTy == IncompatiblePointer && 11502 ((Context.isObjCNSObjectType(LHSType) && 11503 RHSType->isObjCObjectPointerType()) || 11504 (Context.isObjCNSObjectType(RHSType) && 11505 LHSType->isObjCObjectPointerType()))) 11506 ConvTy = Compatible; 11507 11508 if (ConvTy == Compatible && 11509 LHSType->isObjCObjectType()) 11510 Diag(Loc, diag::err_objc_object_assignment) 11511 << LHSType; 11512 11513 // If the RHS is a unary plus or minus, check to see if they = and + are 11514 // right next to each other. If so, the user may have typo'd "x =+ 4" 11515 // instead of "x += 4". 11516 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 11517 RHSCheck = ICE->getSubExpr(); 11518 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 11519 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 11520 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 11521 // Only if the two operators are exactly adjacent. 11522 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 11523 // And there is a space or other character before the subexpr of the 11524 // unary +/-. We don't want to warn on "x=-1". 11525 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 11526 UO->getSubExpr()->getBeginLoc().isFileID()) { 11527 Diag(Loc, diag::warn_not_compound_assign) 11528 << (UO->getOpcode() == UO_Plus ? "+" : "-") 11529 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 11530 } 11531 } 11532 11533 if (ConvTy == Compatible) { 11534 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 11535 // Warn about retain cycles where a block captures the LHS, but 11536 // not if the LHS is a simple variable into which the block is 11537 // being stored...unless that variable can be captured by reference! 11538 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 11539 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 11540 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 11541 checkRetainCycles(LHSExpr, RHS.get()); 11542 } 11543 11544 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 11545 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 11546 // It is safe to assign a weak reference into a strong variable. 11547 // Although this code can still have problems: 11548 // id x = self.weakProp; 11549 // id y = self.weakProp; 11550 // we do not warn to warn spuriously when 'x' and 'y' are on separate 11551 // paths through the function. This should be revisited if 11552 // -Wrepeated-use-of-weak is made flow-sensitive. 11553 // For ObjCWeak only, we do not warn if the assign is to a non-weak 11554 // variable, which will be valid for the current autorelease scope. 11555 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 11556 RHS.get()->getBeginLoc())) 11557 getCurFunction()->markSafeWeakUse(RHS.get()); 11558 11559 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 11560 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 11561 } 11562 } 11563 } else { 11564 // Compound assignment "x += y" 11565 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 11566 } 11567 11568 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 11569 RHS.get(), AA_Assigning)) 11570 return QualType(); 11571 11572 CheckForNullPointerDereference(*this, LHSExpr); 11573 11574 // C99 6.5.16p3: The type of an assignment expression is the type of the 11575 // left operand unless the left operand has qualified type, in which case 11576 // it is the unqualified version of the type of the left operand. 11577 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 11578 // is converted to the type of the assignment expression (above). 11579 // C++ 5.17p1: the type of the assignment expression is that of its left 11580 // operand. 11581 return (getLangOpts().CPlusPlus 11582 ? LHSType : LHSType.getUnqualifiedType()); 11583 } 11584 11585 // Only ignore explicit casts to void. 11586 static bool IgnoreCommaOperand(const Expr *E) { 11587 E = E->IgnoreParens(); 11588 11589 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 11590 if (CE->getCastKind() == CK_ToVoid) { 11591 return true; 11592 } 11593 11594 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 11595 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 11596 CE->getSubExpr()->getType()->isDependentType()) { 11597 return true; 11598 } 11599 } 11600 11601 return false; 11602 } 11603 11604 // Look for instances where it is likely the comma operator is confused with 11605 // another operator. There is a whitelist of acceptable expressions for the 11606 // left hand side of the comma operator, otherwise emit a warning. 11607 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 11608 // No warnings in macros 11609 if (Loc.isMacroID()) 11610 return; 11611 11612 // Don't warn in template instantiations. 11613 if (inTemplateInstantiation()) 11614 return; 11615 11616 // Scope isn't fine-grained enough to whitelist the specific cases, so 11617 // instead, skip more than needed, then call back into here with the 11618 // CommaVisitor in SemaStmt.cpp. 11619 // The whitelisted locations are the initialization and increment portions 11620 // of a for loop. The additional checks are on the condition of 11621 // if statements, do/while loops, and for loops. 11622 // Differences in scope flags for C89 mode requires the extra logic. 11623 const unsigned ForIncrementFlags = 11624 getLangOpts().C99 || getLangOpts().CPlusPlus 11625 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 11626 : Scope::ContinueScope | Scope::BreakScope; 11627 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 11628 const unsigned ScopeFlags = getCurScope()->getFlags(); 11629 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 11630 (ScopeFlags & ForInitFlags) == ForInitFlags) 11631 return; 11632 11633 // If there are multiple comma operators used together, get the RHS of the 11634 // of the comma operator as the LHS. 11635 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 11636 if (BO->getOpcode() != BO_Comma) 11637 break; 11638 LHS = BO->getRHS(); 11639 } 11640 11641 // Only allow some expressions on LHS to not warn. 11642 if (IgnoreCommaOperand(LHS)) 11643 return; 11644 11645 Diag(Loc, diag::warn_comma_operator); 11646 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 11647 << LHS->getSourceRange() 11648 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 11649 LangOpts.CPlusPlus ? "static_cast<void>(" 11650 : "(void)(") 11651 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 11652 ")"); 11653 } 11654 11655 // C99 6.5.17 11656 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 11657 SourceLocation Loc) { 11658 LHS = S.CheckPlaceholderExpr(LHS.get()); 11659 RHS = S.CheckPlaceholderExpr(RHS.get()); 11660 if (LHS.isInvalid() || RHS.isInvalid()) 11661 return QualType(); 11662 11663 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 11664 // operands, but not unary promotions. 11665 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 11666 11667 // So we treat the LHS as a ignored value, and in C++ we allow the 11668 // containing site to determine what should be done with the RHS. 11669 LHS = S.IgnoredValueConversions(LHS.get()); 11670 if (LHS.isInvalid()) 11671 return QualType(); 11672 11673 S.DiagnoseUnusedExprResult(LHS.get()); 11674 11675 if (!S.getLangOpts().CPlusPlus) { 11676 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 11677 if (RHS.isInvalid()) 11678 return QualType(); 11679 if (!RHS.get()->getType()->isVoidType()) 11680 S.RequireCompleteType(Loc, RHS.get()->getType(), 11681 diag::err_incomplete_type); 11682 } 11683 11684 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 11685 S.DiagnoseCommaOperator(LHS.get(), Loc); 11686 11687 return RHS.get()->getType(); 11688 } 11689 11690 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 11691 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 11692 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 11693 ExprValueKind &VK, 11694 ExprObjectKind &OK, 11695 SourceLocation OpLoc, 11696 bool IsInc, bool IsPrefix) { 11697 if (Op->isTypeDependent()) 11698 return S.Context.DependentTy; 11699 11700 QualType ResType = Op->getType(); 11701 // Atomic types can be used for increment / decrement where the non-atomic 11702 // versions can, so ignore the _Atomic() specifier for the purpose of 11703 // checking. 11704 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 11705 ResType = ResAtomicType->getValueType(); 11706 11707 assert(!ResType.isNull() && "no type for increment/decrement expression"); 11708 11709 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 11710 // Decrement of bool is not allowed. 11711 if (!IsInc) { 11712 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 11713 return QualType(); 11714 } 11715 // Increment of bool sets it to true, but is deprecated. 11716 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 11717 : diag::warn_increment_bool) 11718 << Op->getSourceRange(); 11719 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 11720 // Error on enum increments and decrements in C++ mode 11721 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 11722 return QualType(); 11723 } else if (ResType->isRealType()) { 11724 // OK! 11725 } else if (ResType->isPointerType()) { 11726 // C99 6.5.2.4p2, 6.5.6p2 11727 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 11728 return QualType(); 11729 } else if (ResType->isObjCObjectPointerType()) { 11730 // On modern runtimes, ObjC pointer arithmetic is forbidden. 11731 // Otherwise, we just need a complete type. 11732 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 11733 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 11734 return QualType(); 11735 } else if (ResType->isAnyComplexType()) { 11736 // C99 does not support ++/-- on complex types, we allow as an extension. 11737 S.Diag(OpLoc, diag::ext_integer_increment_complex) 11738 << ResType << Op->getSourceRange(); 11739 } else if (ResType->isPlaceholderType()) { 11740 ExprResult PR = S.CheckPlaceholderExpr(Op); 11741 if (PR.isInvalid()) return QualType(); 11742 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 11743 IsInc, IsPrefix); 11744 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 11745 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 11746 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 11747 (ResType->getAs<VectorType>()->getVectorKind() != 11748 VectorType::AltiVecBool)) { 11749 // The z vector extensions allow ++ and -- for non-bool vectors. 11750 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 11751 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 11752 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 11753 } else { 11754 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 11755 << ResType << int(IsInc) << Op->getSourceRange(); 11756 return QualType(); 11757 } 11758 // At this point, we know we have a real, complex or pointer type. 11759 // Now make sure the operand is a modifiable lvalue. 11760 if (CheckForModifiableLvalue(Op, OpLoc, S)) 11761 return QualType(); 11762 // In C++, a prefix increment is the same type as the operand. Otherwise 11763 // (in C or with postfix), the increment is the unqualified type of the 11764 // operand. 11765 if (IsPrefix && S.getLangOpts().CPlusPlus) { 11766 VK = VK_LValue; 11767 OK = Op->getObjectKind(); 11768 return ResType; 11769 } else { 11770 VK = VK_RValue; 11771 return ResType.getUnqualifiedType(); 11772 } 11773 } 11774 11775 11776 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 11777 /// This routine allows us to typecheck complex/recursive expressions 11778 /// where the declaration is needed for type checking. We only need to 11779 /// handle cases when the expression references a function designator 11780 /// or is an lvalue. Here are some examples: 11781 /// - &(x) => x 11782 /// - &*****f => f for f a function designator. 11783 /// - &s.xx => s 11784 /// - &s.zz[1].yy -> s, if zz is an array 11785 /// - *(x + 1) -> x, if x is an array 11786 /// - &"123"[2] -> 0 11787 /// - & __real__ x -> x 11788 static ValueDecl *getPrimaryDecl(Expr *E) { 11789 switch (E->getStmtClass()) { 11790 case Stmt::DeclRefExprClass: 11791 return cast<DeclRefExpr>(E)->getDecl(); 11792 case Stmt::MemberExprClass: 11793 // If this is an arrow operator, the address is an offset from 11794 // the base's value, so the object the base refers to is 11795 // irrelevant. 11796 if (cast<MemberExpr>(E)->isArrow()) 11797 return nullptr; 11798 // Otherwise, the expression refers to a part of the base 11799 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 11800 case Stmt::ArraySubscriptExprClass: { 11801 // FIXME: This code shouldn't be necessary! We should catch the implicit 11802 // promotion of register arrays earlier. 11803 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 11804 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 11805 if (ICE->getSubExpr()->getType()->isArrayType()) 11806 return getPrimaryDecl(ICE->getSubExpr()); 11807 } 11808 return nullptr; 11809 } 11810 case Stmt::UnaryOperatorClass: { 11811 UnaryOperator *UO = cast<UnaryOperator>(E); 11812 11813 switch(UO->getOpcode()) { 11814 case UO_Real: 11815 case UO_Imag: 11816 case UO_Extension: 11817 return getPrimaryDecl(UO->getSubExpr()); 11818 default: 11819 return nullptr; 11820 } 11821 } 11822 case Stmt::ParenExprClass: 11823 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 11824 case Stmt::ImplicitCastExprClass: 11825 // If the result of an implicit cast is an l-value, we care about 11826 // the sub-expression; otherwise, the result here doesn't matter. 11827 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 11828 default: 11829 return nullptr; 11830 } 11831 } 11832 11833 namespace { 11834 enum { 11835 AO_Bit_Field = 0, 11836 AO_Vector_Element = 1, 11837 AO_Property_Expansion = 2, 11838 AO_Register_Variable = 3, 11839 AO_No_Error = 4 11840 }; 11841 } 11842 /// Diagnose invalid operand for address of operations. 11843 /// 11844 /// \param Type The type of operand which cannot have its address taken. 11845 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 11846 Expr *E, unsigned Type) { 11847 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 11848 } 11849 11850 /// CheckAddressOfOperand - The operand of & must be either a function 11851 /// designator or an lvalue designating an object. If it is an lvalue, the 11852 /// object cannot be declared with storage class register or be a bit field. 11853 /// Note: The usual conversions are *not* applied to the operand of the & 11854 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 11855 /// In C++, the operand might be an overloaded function name, in which case 11856 /// we allow the '&' but retain the overloaded-function type. 11857 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 11858 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 11859 if (PTy->getKind() == BuiltinType::Overload) { 11860 Expr *E = OrigOp.get()->IgnoreParens(); 11861 if (!isa<OverloadExpr>(E)) { 11862 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 11863 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 11864 << OrigOp.get()->getSourceRange(); 11865 return QualType(); 11866 } 11867 11868 OverloadExpr *Ovl = cast<OverloadExpr>(E); 11869 if (isa<UnresolvedMemberExpr>(Ovl)) 11870 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 11871 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11872 << OrigOp.get()->getSourceRange(); 11873 return QualType(); 11874 } 11875 11876 return Context.OverloadTy; 11877 } 11878 11879 if (PTy->getKind() == BuiltinType::UnknownAny) 11880 return Context.UnknownAnyTy; 11881 11882 if (PTy->getKind() == BuiltinType::BoundMember) { 11883 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11884 << OrigOp.get()->getSourceRange(); 11885 return QualType(); 11886 } 11887 11888 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 11889 if (OrigOp.isInvalid()) return QualType(); 11890 } 11891 11892 if (OrigOp.get()->isTypeDependent()) 11893 return Context.DependentTy; 11894 11895 assert(!OrigOp.get()->getType()->isPlaceholderType()); 11896 11897 // Make sure to ignore parentheses in subsequent checks 11898 Expr *op = OrigOp.get()->IgnoreParens(); 11899 11900 // In OpenCL captures for blocks called as lambda functions 11901 // are located in the private address space. Blocks used in 11902 // enqueue_kernel can be located in a different address space 11903 // depending on a vendor implementation. Thus preventing 11904 // taking an address of the capture to avoid invalid AS casts. 11905 if (LangOpts.OpenCL) { 11906 auto* VarRef = dyn_cast<DeclRefExpr>(op); 11907 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 11908 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 11909 return QualType(); 11910 } 11911 } 11912 11913 if (getLangOpts().C99) { 11914 // Implement C99-only parts of addressof rules. 11915 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 11916 if (uOp->getOpcode() == UO_Deref) 11917 // Per C99 6.5.3.2, the address of a deref always returns a valid result 11918 // (assuming the deref expression is valid). 11919 return uOp->getSubExpr()->getType(); 11920 } 11921 // Technically, there should be a check for array subscript 11922 // expressions here, but the result of one is always an lvalue anyway. 11923 } 11924 ValueDecl *dcl = getPrimaryDecl(op); 11925 11926 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 11927 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 11928 op->getBeginLoc())) 11929 return QualType(); 11930 11931 Expr::LValueClassification lval = op->ClassifyLValue(Context); 11932 unsigned AddressOfError = AO_No_Error; 11933 11934 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 11935 bool sfinae = (bool)isSFINAEContext(); 11936 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 11937 : diag::ext_typecheck_addrof_temporary) 11938 << op->getType() << op->getSourceRange(); 11939 if (sfinae) 11940 return QualType(); 11941 // Materialize the temporary as an lvalue so that we can take its address. 11942 OrigOp = op = 11943 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 11944 } else if (isa<ObjCSelectorExpr>(op)) { 11945 return Context.getPointerType(op->getType()); 11946 } else if (lval == Expr::LV_MemberFunction) { 11947 // If it's an instance method, make a member pointer. 11948 // The expression must have exactly the form &A::foo. 11949 11950 // If the underlying expression isn't a decl ref, give up. 11951 if (!isa<DeclRefExpr>(op)) { 11952 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11953 << OrigOp.get()->getSourceRange(); 11954 return QualType(); 11955 } 11956 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 11957 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 11958 11959 // The id-expression was parenthesized. 11960 if (OrigOp.get() != DRE) { 11961 Diag(OpLoc, diag::err_parens_pointer_member_function) 11962 << OrigOp.get()->getSourceRange(); 11963 11964 // The method was named without a qualifier. 11965 } else if (!DRE->getQualifier()) { 11966 if (MD->getParent()->getName().empty()) 11967 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 11968 << op->getSourceRange(); 11969 else { 11970 SmallString<32> Str; 11971 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 11972 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 11973 << op->getSourceRange() 11974 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 11975 } 11976 } 11977 11978 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 11979 if (isa<CXXDestructorDecl>(MD)) 11980 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 11981 11982 QualType MPTy = Context.getMemberPointerType( 11983 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 11984 // Under the MS ABI, lock down the inheritance model now. 11985 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11986 (void)isCompleteType(OpLoc, MPTy); 11987 return MPTy; 11988 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 11989 // C99 6.5.3.2p1 11990 // The operand must be either an l-value or a function designator 11991 if (!op->getType()->isFunctionType()) { 11992 // Use a special diagnostic for loads from property references. 11993 if (isa<PseudoObjectExpr>(op)) { 11994 AddressOfError = AO_Property_Expansion; 11995 } else { 11996 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 11997 << op->getType() << op->getSourceRange(); 11998 return QualType(); 11999 } 12000 } 12001 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 12002 // The operand cannot be a bit-field 12003 AddressOfError = AO_Bit_Field; 12004 } else if (op->getObjectKind() == OK_VectorComponent) { 12005 // The operand cannot be an element of a vector 12006 AddressOfError = AO_Vector_Element; 12007 } else if (dcl) { // C99 6.5.3.2p1 12008 // We have an lvalue with a decl. Make sure the decl is not declared 12009 // with the register storage-class specifier. 12010 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 12011 // in C++ it is not error to take address of a register 12012 // variable (c++03 7.1.1P3) 12013 if (vd->getStorageClass() == SC_Register && 12014 !getLangOpts().CPlusPlus) { 12015 AddressOfError = AO_Register_Variable; 12016 } 12017 } else if (isa<MSPropertyDecl>(dcl)) { 12018 AddressOfError = AO_Property_Expansion; 12019 } else if (isa<FunctionTemplateDecl>(dcl)) { 12020 return Context.OverloadTy; 12021 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 12022 // Okay: we can take the address of a field. 12023 // Could be a pointer to member, though, if there is an explicit 12024 // scope qualifier for the class. 12025 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 12026 DeclContext *Ctx = dcl->getDeclContext(); 12027 if (Ctx && Ctx->isRecord()) { 12028 if (dcl->getType()->isReferenceType()) { 12029 Diag(OpLoc, 12030 diag::err_cannot_form_pointer_to_member_of_reference_type) 12031 << dcl->getDeclName() << dcl->getType(); 12032 return QualType(); 12033 } 12034 12035 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 12036 Ctx = Ctx->getParent(); 12037 12038 QualType MPTy = Context.getMemberPointerType( 12039 op->getType(), 12040 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 12041 // Under the MS ABI, lock down the inheritance model now. 12042 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 12043 (void)isCompleteType(OpLoc, MPTy); 12044 return MPTy; 12045 } 12046 } 12047 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 12048 !isa<BindingDecl>(dcl)) 12049 llvm_unreachable("Unknown/unexpected decl type"); 12050 } 12051 12052 if (AddressOfError != AO_No_Error) { 12053 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 12054 return QualType(); 12055 } 12056 12057 if (lval == Expr::LV_IncompleteVoidType) { 12058 // Taking the address of a void variable is technically illegal, but we 12059 // allow it in cases which are otherwise valid. 12060 // Example: "extern void x; void* y = &x;". 12061 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 12062 } 12063 12064 // If the operand has type "type", the result has type "pointer to type". 12065 if (op->getType()->isObjCObjectType()) 12066 return Context.getObjCObjectPointerType(op->getType()); 12067 12068 CheckAddressOfPackedMember(op); 12069 12070 return Context.getPointerType(op->getType()); 12071 } 12072 12073 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 12074 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 12075 if (!DRE) 12076 return; 12077 const Decl *D = DRE->getDecl(); 12078 if (!D) 12079 return; 12080 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 12081 if (!Param) 12082 return; 12083 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 12084 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 12085 return; 12086 if (FunctionScopeInfo *FD = S.getCurFunction()) 12087 if (!FD->ModifiedNonNullParams.count(Param)) 12088 FD->ModifiedNonNullParams.insert(Param); 12089 } 12090 12091 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 12092 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 12093 SourceLocation OpLoc) { 12094 if (Op->isTypeDependent()) 12095 return S.Context.DependentTy; 12096 12097 ExprResult ConvResult = S.UsualUnaryConversions(Op); 12098 if (ConvResult.isInvalid()) 12099 return QualType(); 12100 Op = ConvResult.get(); 12101 QualType OpTy = Op->getType(); 12102 QualType Result; 12103 12104 if (isa<CXXReinterpretCastExpr>(Op)) { 12105 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 12106 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 12107 Op->getSourceRange()); 12108 } 12109 12110 if (const PointerType *PT = OpTy->getAs<PointerType>()) 12111 { 12112 Result = PT->getPointeeType(); 12113 } 12114 else if (const ObjCObjectPointerType *OPT = 12115 OpTy->getAs<ObjCObjectPointerType>()) 12116 Result = OPT->getPointeeType(); 12117 else { 12118 ExprResult PR = S.CheckPlaceholderExpr(Op); 12119 if (PR.isInvalid()) return QualType(); 12120 if (PR.get() != Op) 12121 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 12122 } 12123 12124 if (Result.isNull()) { 12125 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 12126 << OpTy << Op->getSourceRange(); 12127 return QualType(); 12128 } 12129 12130 // Note that per both C89 and C99, indirection is always legal, even if Result 12131 // is an incomplete type or void. It would be possible to warn about 12132 // dereferencing a void pointer, but it's completely well-defined, and such a 12133 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 12134 // for pointers to 'void' but is fine for any other pointer type: 12135 // 12136 // C++ [expr.unary.op]p1: 12137 // [...] the expression to which [the unary * operator] is applied shall 12138 // be a pointer to an object type, or a pointer to a function type 12139 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 12140 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 12141 << OpTy << Op->getSourceRange(); 12142 12143 // Dereferences are usually l-values... 12144 VK = VK_LValue; 12145 12146 // ...except that certain expressions are never l-values in C. 12147 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 12148 VK = VK_RValue; 12149 12150 return Result; 12151 } 12152 12153 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 12154 BinaryOperatorKind Opc; 12155 switch (Kind) { 12156 default: llvm_unreachable("Unknown binop!"); 12157 case tok::periodstar: Opc = BO_PtrMemD; break; 12158 case tok::arrowstar: Opc = BO_PtrMemI; break; 12159 case tok::star: Opc = BO_Mul; break; 12160 case tok::slash: Opc = BO_Div; break; 12161 case tok::percent: Opc = BO_Rem; break; 12162 case tok::plus: Opc = BO_Add; break; 12163 case tok::minus: Opc = BO_Sub; break; 12164 case tok::lessless: Opc = BO_Shl; break; 12165 case tok::greatergreater: Opc = BO_Shr; break; 12166 case tok::lessequal: Opc = BO_LE; break; 12167 case tok::less: Opc = BO_LT; break; 12168 case tok::greaterequal: Opc = BO_GE; break; 12169 case tok::greater: Opc = BO_GT; break; 12170 case tok::exclaimequal: Opc = BO_NE; break; 12171 case tok::equalequal: Opc = BO_EQ; break; 12172 case tok::spaceship: Opc = BO_Cmp; break; 12173 case tok::amp: Opc = BO_And; break; 12174 case tok::caret: Opc = BO_Xor; break; 12175 case tok::pipe: Opc = BO_Or; break; 12176 case tok::ampamp: Opc = BO_LAnd; break; 12177 case tok::pipepipe: Opc = BO_LOr; break; 12178 case tok::equal: Opc = BO_Assign; break; 12179 case tok::starequal: Opc = BO_MulAssign; break; 12180 case tok::slashequal: Opc = BO_DivAssign; break; 12181 case tok::percentequal: Opc = BO_RemAssign; break; 12182 case tok::plusequal: Opc = BO_AddAssign; break; 12183 case tok::minusequal: Opc = BO_SubAssign; break; 12184 case tok::lesslessequal: Opc = BO_ShlAssign; break; 12185 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 12186 case tok::ampequal: Opc = BO_AndAssign; break; 12187 case tok::caretequal: Opc = BO_XorAssign; break; 12188 case tok::pipeequal: Opc = BO_OrAssign; break; 12189 case tok::comma: Opc = BO_Comma; break; 12190 } 12191 return Opc; 12192 } 12193 12194 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 12195 tok::TokenKind Kind) { 12196 UnaryOperatorKind Opc; 12197 switch (Kind) { 12198 default: llvm_unreachable("Unknown unary op!"); 12199 case tok::plusplus: Opc = UO_PreInc; break; 12200 case tok::minusminus: Opc = UO_PreDec; break; 12201 case tok::amp: Opc = UO_AddrOf; break; 12202 case tok::star: Opc = UO_Deref; break; 12203 case tok::plus: Opc = UO_Plus; break; 12204 case tok::minus: Opc = UO_Minus; break; 12205 case tok::tilde: Opc = UO_Not; break; 12206 case tok::exclaim: Opc = UO_LNot; break; 12207 case tok::kw___real: Opc = UO_Real; break; 12208 case tok::kw___imag: Opc = UO_Imag; break; 12209 case tok::kw___extension__: Opc = UO_Extension; break; 12210 } 12211 return Opc; 12212 } 12213 12214 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 12215 /// This warning suppressed in the event of macro expansions. 12216 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 12217 SourceLocation OpLoc, bool IsBuiltin) { 12218 if (S.inTemplateInstantiation()) 12219 return; 12220 if (S.isUnevaluatedContext()) 12221 return; 12222 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 12223 return; 12224 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 12225 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 12226 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 12227 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 12228 if (!LHSDeclRef || !RHSDeclRef || 12229 LHSDeclRef->getLocation().isMacroID() || 12230 RHSDeclRef->getLocation().isMacroID()) 12231 return; 12232 const ValueDecl *LHSDecl = 12233 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 12234 const ValueDecl *RHSDecl = 12235 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 12236 if (LHSDecl != RHSDecl) 12237 return; 12238 if (LHSDecl->getType().isVolatileQualified()) 12239 return; 12240 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 12241 if (RefTy->getPointeeType().isVolatileQualified()) 12242 return; 12243 12244 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 12245 : diag::warn_self_assignment_overloaded) 12246 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 12247 << RHSExpr->getSourceRange(); 12248 } 12249 12250 /// Check if a bitwise-& is performed on an Objective-C pointer. This 12251 /// is usually indicative of introspection within the Objective-C pointer. 12252 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 12253 SourceLocation OpLoc) { 12254 if (!S.getLangOpts().ObjC) 12255 return; 12256 12257 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 12258 const Expr *LHS = L.get(); 12259 const Expr *RHS = R.get(); 12260 12261 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 12262 ObjCPointerExpr = LHS; 12263 OtherExpr = RHS; 12264 } 12265 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 12266 ObjCPointerExpr = RHS; 12267 OtherExpr = LHS; 12268 } 12269 12270 // This warning is deliberately made very specific to reduce false 12271 // positives with logic that uses '&' for hashing. This logic mainly 12272 // looks for code trying to introspect into tagged pointers, which 12273 // code should generally never do. 12274 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 12275 unsigned Diag = diag::warn_objc_pointer_masking; 12276 // Determine if we are introspecting the result of performSelectorXXX. 12277 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 12278 // Special case messages to -performSelector and friends, which 12279 // can return non-pointer values boxed in a pointer value. 12280 // Some clients may wish to silence warnings in this subcase. 12281 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 12282 Selector S = ME->getSelector(); 12283 StringRef SelArg0 = S.getNameForSlot(0); 12284 if (SelArg0.startswith("performSelector")) 12285 Diag = diag::warn_objc_pointer_masking_performSelector; 12286 } 12287 12288 S.Diag(OpLoc, Diag) 12289 << ObjCPointerExpr->getSourceRange(); 12290 } 12291 } 12292 12293 static NamedDecl *getDeclFromExpr(Expr *E) { 12294 if (!E) 12295 return nullptr; 12296 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 12297 return DRE->getDecl(); 12298 if (auto *ME = dyn_cast<MemberExpr>(E)) 12299 return ME->getMemberDecl(); 12300 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 12301 return IRE->getDecl(); 12302 return nullptr; 12303 } 12304 12305 // This helper function promotes a binary operator's operands (which are of a 12306 // half vector type) to a vector of floats and then truncates the result to 12307 // a vector of either half or short. 12308 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 12309 BinaryOperatorKind Opc, QualType ResultTy, 12310 ExprValueKind VK, ExprObjectKind OK, 12311 bool IsCompAssign, SourceLocation OpLoc, 12312 FPOptions FPFeatures) { 12313 auto &Context = S.getASTContext(); 12314 assert((isVector(ResultTy, Context.HalfTy) || 12315 isVector(ResultTy, Context.ShortTy)) && 12316 "Result must be a vector of half or short"); 12317 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 12318 isVector(RHS.get()->getType(), Context.HalfTy) && 12319 "both operands expected to be a half vector"); 12320 12321 RHS = convertVector(RHS.get(), Context.FloatTy, S); 12322 QualType BinOpResTy = RHS.get()->getType(); 12323 12324 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 12325 // change BinOpResTy to a vector of ints. 12326 if (isVector(ResultTy, Context.ShortTy)) 12327 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 12328 12329 if (IsCompAssign) 12330 return new (Context) CompoundAssignOperator( 12331 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy, 12332 OpLoc, FPFeatures); 12333 12334 LHS = convertVector(LHS.get(), Context.FloatTy, S); 12335 auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy, 12336 VK, OK, OpLoc, FPFeatures); 12337 return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S); 12338 } 12339 12340 static std::pair<ExprResult, ExprResult> 12341 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 12342 Expr *RHSExpr) { 12343 ExprResult LHS = LHSExpr, RHS = RHSExpr; 12344 if (!S.getLangOpts().CPlusPlus) { 12345 // C cannot handle TypoExpr nodes on either side of a binop because it 12346 // doesn't handle dependent types properly, so make sure any TypoExprs have 12347 // been dealt with before checking the operands. 12348 LHS = S.CorrectDelayedTyposInExpr(LHS); 12349 RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) { 12350 if (Opc != BO_Assign) 12351 return ExprResult(E); 12352 // Avoid correcting the RHS to the same Expr as the LHS. 12353 Decl *D = getDeclFromExpr(E); 12354 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 12355 }); 12356 } 12357 return std::make_pair(LHS, RHS); 12358 } 12359 12360 /// Returns true if conversion between vectors of halfs and vectors of floats 12361 /// is needed. 12362 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 12363 QualType SrcType) { 12364 return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType && 12365 !Ctx.getTargetInfo().useFP16ConversionIntrinsics() && 12366 isVector(SrcType, Ctx.HalfTy); 12367 } 12368 12369 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 12370 /// operator @p Opc at location @c TokLoc. This routine only supports 12371 /// built-in operations; ActOnBinOp handles overloaded operators. 12372 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 12373 BinaryOperatorKind Opc, 12374 Expr *LHSExpr, Expr *RHSExpr) { 12375 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 12376 // The syntax only allows initializer lists on the RHS of assignment, 12377 // so we don't need to worry about accepting invalid code for 12378 // non-assignment operators. 12379 // C++11 5.17p9: 12380 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 12381 // of x = {} is x = T(). 12382 InitializationKind Kind = InitializationKind::CreateDirectList( 12383 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 12384 InitializedEntity Entity = 12385 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 12386 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 12387 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 12388 if (Init.isInvalid()) 12389 return Init; 12390 RHSExpr = Init.get(); 12391 } 12392 12393 ExprResult LHS = LHSExpr, RHS = RHSExpr; 12394 QualType ResultTy; // Result type of the binary operator. 12395 // The following two variables are used for compound assignment operators 12396 QualType CompLHSTy; // Type of LHS after promotions for computation 12397 QualType CompResultTy; // Type of computation result 12398 ExprValueKind VK = VK_RValue; 12399 ExprObjectKind OK = OK_Ordinary; 12400 bool ConvertHalfVec = false; 12401 12402 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 12403 if (!LHS.isUsable() || !RHS.isUsable()) 12404 return ExprError(); 12405 12406 if (getLangOpts().OpenCL) { 12407 QualType LHSTy = LHSExpr->getType(); 12408 QualType RHSTy = RHSExpr->getType(); 12409 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 12410 // the ATOMIC_VAR_INIT macro. 12411 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 12412 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 12413 if (BO_Assign == Opc) 12414 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 12415 else 12416 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 12417 return ExprError(); 12418 } 12419 12420 // OpenCL special types - image, sampler, pipe, and blocks are to be used 12421 // only with a builtin functions and therefore should be disallowed here. 12422 if (LHSTy->isImageType() || RHSTy->isImageType() || 12423 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 12424 LHSTy->isPipeType() || RHSTy->isPipeType() || 12425 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 12426 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 12427 return ExprError(); 12428 } 12429 } 12430 12431 // Diagnose operations on the unsupported types for OpenMP device compilation. 12432 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) { 12433 if (Opc != BO_Assign && Opc != BO_Comma) { 12434 checkOpenMPDeviceExpr(LHSExpr); 12435 checkOpenMPDeviceExpr(RHSExpr); 12436 } 12437 } 12438 12439 switch (Opc) { 12440 case BO_Assign: 12441 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 12442 if (getLangOpts().CPlusPlus && 12443 LHS.get()->getObjectKind() != OK_ObjCProperty) { 12444 VK = LHS.get()->getValueKind(); 12445 OK = LHS.get()->getObjectKind(); 12446 } 12447 if (!ResultTy.isNull()) { 12448 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 12449 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 12450 12451 // Avoid copying a block to the heap if the block is assigned to a local 12452 // auto variable that is declared in the same scope as the block. This 12453 // optimization is unsafe if the local variable is declared in an outer 12454 // scope. For example: 12455 // 12456 // BlockTy b; 12457 // { 12458 // b = ^{...}; 12459 // } 12460 // // It is unsafe to invoke the block here if it wasn't copied to the 12461 // // heap. 12462 // b(); 12463 12464 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 12465 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 12466 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 12467 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 12468 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 12469 } 12470 RecordModifiableNonNullParam(*this, LHS.get()); 12471 break; 12472 case BO_PtrMemD: 12473 case BO_PtrMemI: 12474 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 12475 Opc == BO_PtrMemI); 12476 break; 12477 case BO_Mul: 12478 case BO_Div: 12479 ConvertHalfVec = true; 12480 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 12481 Opc == BO_Div); 12482 break; 12483 case BO_Rem: 12484 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 12485 break; 12486 case BO_Add: 12487 ConvertHalfVec = true; 12488 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 12489 break; 12490 case BO_Sub: 12491 ConvertHalfVec = true; 12492 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 12493 break; 12494 case BO_Shl: 12495 case BO_Shr: 12496 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 12497 break; 12498 case BO_LE: 12499 case BO_LT: 12500 case BO_GE: 12501 case BO_GT: 12502 ConvertHalfVec = true; 12503 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12504 break; 12505 case BO_EQ: 12506 case BO_NE: 12507 ConvertHalfVec = true; 12508 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12509 break; 12510 case BO_Cmp: 12511 ConvertHalfVec = true; 12512 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12513 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 12514 break; 12515 case BO_And: 12516 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 12517 LLVM_FALLTHROUGH; 12518 case BO_Xor: 12519 case BO_Or: 12520 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 12521 break; 12522 case BO_LAnd: 12523 case BO_LOr: 12524 ConvertHalfVec = true; 12525 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 12526 break; 12527 case BO_MulAssign: 12528 case BO_DivAssign: 12529 ConvertHalfVec = true; 12530 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 12531 Opc == BO_DivAssign); 12532 CompLHSTy = CompResultTy; 12533 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12534 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12535 break; 12536 case BO_RemAssign: 12537 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 12538 CompLHSTy = CompResultTy; 12539 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12540 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12541 break; 12542 case BO_AddAssign: 12543 ConvertHalfVec = true; 12544 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 12545 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12546 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12547 break; 12548 case BO_SubAssign: 12549 ConvertHalfVec = true; 12550 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 12551 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12552 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12553 break; 12554 case BO_ShlAssign: 12555 case BO_ShrAssign: 12556 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 12557 CompLHSTy = CompResultTy; 12558 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12559 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12560 break; 12561 case BO_AndAssign: 12562 case BO_OrAssign: // fallthrough 12563 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 12564 LLVM_FALLTHROUGH; 12565 case BO_XorAssign: 12566 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 12567 CompLHSTy = CompResultTy; 12568 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12569 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12570 break; 12571 case BO_Comma: 12572 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 12573 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 12574 VK = RHS.get()->getValueKind(); 12575 OK = RHS.get()->getObjectKind(); 12576 } 12577 break; 12578 } 12579 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 12580 return ExprError(); 12581 12582 // Some of the binary operations require promoting operands of half vector to 12583 // float vectors and truncating the result back to half vector. For now, we do 12584 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 12585 // arm64). 12586 assert(isVector(RHS.get()->getType(), Context.HalfTy) == 12587 isVector(LHS.get()->getType(), Context.HalfTy) && 12588 "both sides are half vectors or neither sides are"); 12589 ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context, 12590 LHS.get()->getType()); 12591 12592 // Check for array bounds violations for both sides of the BinaryOperator 12593 CheckArrayAccess(LHS.get()); 12594 CheckArrayAccess(RHS.get()); 12595 12596 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 12597 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 12598 &Context.Idents.get("object_setClass"), 12599 SourceLocation(), LookupOrdinaryName); 12600 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 12601 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 12602 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 12603 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 12604 "object_setClass(") 12605 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 12606 ",") 12607 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 12608 } 12609 else 12610 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 12611 } 12612 else if (const ObjCIvarRefExpr *OIRE = 12613 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 12614 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 12615 12616 // Opc is not a compound assignment if CompResultTy is null. 12617 if (CompResultTy.isNull()) { 12618 if (ConvertHalfVec) 12619 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 12620 OpLoc, FPFeatures); 12621 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 12622 OK, OpLoc, FPFeatures); 12623 } 12624 12625 // Handle compound assignments. 12626 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 12627 OK_ObjCProperty) { 12628 VK = VK_LValue; 12629 OK = LHS.get()->getObjectKind(); 12630 } 12631 12632 if (ConvertHalfVec) 12633 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 12634 OpLoc, FPFeatures); 12635 12636 return new (Context) CompoundAssignOperator( 12637 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 12638 OpLoc, FPFeatures); 12639 } 12640 12641 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 12642 /// operators are mixed in a way that suggests that the programmer forgot that 12643 /// comparison operators have higher precedence. The most typical example of 12644 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 12645 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 12646 SourceLocation OpLoc, Expr *LHSExpr, 12647 Expr *RHSExpr) { 12648 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 12649 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 12650 12651 // Check that one of the sides is a comparison operator and the other isn't. 12652 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 12653 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 12654 if (isLeftComp == isRightComp) 12655 return; 12656 12657 // Bitwise operations are sometimes used as eager logical ops. 12658 // Don't diagnose this. 12659 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 12660 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 12661 if (isLeftBitwise || isRightBitwise) 12662 return; 12663 12664 SourceRange DiagRange = isLeftComp 12665 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 12666 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 12667 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 12668 SourceRange ParensRange = 12669 isLeftComp 12670 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 12671 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 12672 12673 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 12674 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 12675 SuggestParentheses(Self, OpLoc, 12676 Self.PDiag(diag::note_precedence_silence) << OpStr, 12677 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 12678 SuggestParentheses(Self, OpLoc, 12679 Self.PDiag(diag::note_precedence_bitwise_first) 12680 << BinaryOperator::getOpcodeStr(Opc), 12681 ParensRange); 12682 } 12683 12684 /// It accepts a '&&' expr that is inside a '||' one. 12685 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 12686 /// in parentheses. 12687 static void 12688 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 12689 BinaryOperator *Bop) { 12690 assert(Bop->getOpcode() == BO_LAnd); 12691 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 12692 << Bop->getSourceRange() << OpLoc; 12693 SuggestParentheses(Self, Bop->getOperatorLoc(), 12694 Self.PDiag(diag::note_precedence_silence) 12695 << Bop->getOpcodeStr(), 12696 Bop->getSourceRange()); 12697 } 12698 12699 /// Returns true if the given expression can be evaluated as a constant 12700 /// 'true'. 12701 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 12702 bool Res; 12703 return !E->isValueDependent() && 12704 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 12705 } 12706 12707 /// Returns true if the given expression can be evaluated as a constant 12708 /// 'false'. 12709 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 12710 bool Res; 12711 return !E->isValueDependent() && 12712 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 12713 } 12714 12715 /// Look for '&&' in the left hand of a '||' expr. 12716 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 12717 Expr *LHSExpr, Expr *RHSExpr) { 12718 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 12719 if (Bop->getOpcode() == BO_LAnd) { 12720 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 12721 if (EvaluatesAsFalse(S, RHSExpr)) 12722 return; 12723 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 12724 if (!EvaluatesAsTrue(S, Bop->getLHS())) 12725 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 12726 } else if (Bop->getOpcode() == BO_LOr) { 12727 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 12728 // If it's "a || b && 1 || c" we didn't warn earlier for 12729 // "a || b && 1", but warn now. 12730 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 12731 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 12732 } 12733 } 12734 } 12735 } 12736 12737 /// Look for '&&' in the right hand of a '||' expr. 12738 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 12739 Expr *LHSExpr, Expr *RHSExpr) { 12740 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 12741 if (Bop->getOpcode() == BO_LAnd) { 12742 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 12743 if (EvaluatesAsFalse(S, LHSExpr)) 12744 return; 12745 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 12746 if (!EvaluatesAsTrue(S, Bop->getRHS())) 12747 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 12748 } 12749 } 12750 } 12751 12752 /// Look for bitwise op in the left or right hand of a bitwise op with 12753 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 12754 /// the '&' expression in parentheses. 12755 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 12756 SourceLocation OpLoc, Expr *SubExpr) { 12757 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 12758 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 12759 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 12760 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 12761 << Bop->getSourceRange() << OpLoc; 12762 SuggestParentheses(S, Bop->getOperatorLoc(), 12763 S.PDiag(diag::note_precedence_silence) 12764 << Bop->getOpcodeStr(), 12765 Bop->getSourceRange()); 12766 } 12767 } 12768 } 12769 12770 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 12771 Expr *SubExpr, StringRef Shift) { 12772 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 12773 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 12774 StringRef Op = Bop->getOpcodeStr(); 12775 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 12776 << Bop->getSourceRange() << OpLoc << Shift << Op; 12777 SuggestParentheses(S, Bop->getOperatorLoc(), 12778 S.PDiag(diag::note_precedence_silence) << Op, 12779 Bop->getSourceRange()); 12780 } 12781 } 12782 } 12783 12784 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 12785 Expr *LHSExpr, Expr *RHSExpr) { 12786 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 12787 if (!OCE) 12788 return; 12789 12790 FunctionDecl *FD = OCE->getDirectCallee(); 12791 if (!FD || !FD->isOverloadedOperator()) 12792 return; 12793 12794 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 12795 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 12796 return; 12797 12798 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 12799 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 12800 << (Kind == OO_LessLess); 12801 SuggestParentheses(S, OCE->getOperatorLoc(), 12802 S.PDiag(diag::note_precedence_silence) 12803 << (Kind == OO_LessLess ? "<<" : ">>"), 12804 OCE->getSourceRange()); 12805 SuggestParentheses( 12806 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 12807 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 12808 } 12809 12810 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 12811 /// precedence. 12812 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 12813 SourceLocation OpLoc, Expr *LHSExpr, 12814 Expr *RHSExpr){ 12815 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 12816 if (BinaryOperator::isBitwiseOp(Opc)) 12817 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 12818 12819 // Diagnose "arg1 & arg2 | arg3" 12820 if ((Opc == BO_Or || Opc == BO_Xor) && 12821 !OpLoc.isMacroID()/* Don't warn in macros. */) { 12822 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 12823 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 12824 } 12825 12826 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 12827 // We don't warn for 'assert(a || b && "bad")' since this is safe. 12828 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 12829 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 12830 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 12831 } 12832 12833 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 12834 || Opc == BO_Shr) { 12835 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 12836 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 12837 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 12838 } 12839 12840 // Warn on overloaded shift operators and comparisons, such as: 12841 // cout << 5 == 4; 12842 if (BinaryOperator::isComparisonOp(Opc)) 12843 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 12844 } 12845 12846 // Binary Operators. 'Tok' is the token for the operator. 12847 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 12848 tok::TokenKind Kind, 12849 Expr *LHSExpr, Expr *RHSExpr) { 12850 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 12851 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 12852 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 12853 12854 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 12855 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 12856 12857 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 12858 } 12859 12860 /// Build an overloaded binary operator expression in the given scope. 12861 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 12862 BinaryOperatorKind Opc, 12863 Expr *LHS, Expr *RHS) { 12864 switch (Opc) { 12865 case BO_Assign: 12866 case BO_DivAssign: 12867 case BO_RemAssign: 12868 case BO_SubAssign: 12869 case BO_AndAssign: 12870 case BO_OrAssign: 12871 case BO_XorAssign: 12872 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 12873 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 12874 break; 12875 default: 12876 break; 12877 } 12878 12879 // Find all of the overloaded operators visible from this 12880 // point. We perform both an operator-name lookup from the local 12881 // scope and an argument-dependent lookup based on the types of 12882 // the arguments. 12883 UnresolvedSet<16> Functions; 12884 OverloadedOperatorKind OverOp 12885 = BinaryOperator::getOverloadedOperator(Opc); 12886 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 12887 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 12888 RHS->getType(), Functions); 12889 12890 // Build the (potentially-overloaded, potentially-dependent) 12891 // binary operation. 12892 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 12893 } 12894 12895 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 12896 BinaryOperatorKind Opc, 12897 Expr *LHSExpr, Expr *RHSExpr) { 12898 ExprResult LHS, RHS; 12899 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 12900 if (!LHS.isUsable() || !RHS.isUsable()) 12901 return ExprError(); 12902 LHSExpr = LHS.get(); 12903 RHSExpr = RHS.get(); 12904 12905 // We want to end up calling one of checkPseudoObjectAssignment 12906 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 12907 // both expressions are overloadable or either is type-dependent), 12908 // or CreateBuiltinBinOp (in any other case). We also want to get 12909 // any placeholder types out of the way. 12910 12911 // Handle pseudo-objects in the LHS. 12912 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 12913 // Assignments with a pseudo-object l-value need special analysis. 12914 if (pty->getKind() == BuiltinType::PseudoObject && 12915 BinaryOperator::isAssignmentOp(Opc)) 12916 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 12917 12918 // Don't resolve overloads if the other type is overloadable. 12919 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 12920 // We can't actually test that if we still have a placeholder, 12921 // though. Fortunately, none of the exceptions we see in that 12922 // code below are valid when the LHS is an overload set. Note 12923 // that an overload set can be dependently-typed, but it never 12924 // instantiates to having an overloadable type. 12925 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 12926 if (resolvedRHS.isInvalid()) return ExprError(); 12927 RHSExpr = resolvedRHS.get(); 12928 12929 if (RHSExpr->isTypeDependent() || 12930 RHSExpr->getType()->isOverloadableType()) 12931 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12932 } 12933 12934 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 12935 // template, diagnose the missing 'template' keyword instead of diagnosing 12936 // an invalid use of a bound member function. 12937 // 12938 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 12939 // to C++1z [over.over]/1.4, but we already checked for that case above. 12940 if (Opc == BO_LT && inTemplateInstantiation() && 12941 (pty->getKind() == BuiltinType::BoundMember || 12942 pty->getKind() == BuiltinType::Overload)) { 12943 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 12944 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 12945 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 12946 return isa<FunctionTemplateDecl>(ND); 12947 })) { 12948 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 12949 : OE->getNameLoc(), 12950 diag::err_template_kw_missing) 12951 << OE->getName().getAsString() << ""; 12952 return ExprError(); 12953 } 12954 } 12955 12956 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 12957 if (LHS.isInvalid()) return ExprError(); 12958 LHSExpr = LHS.get(); 12959 } 12960 12961 // Handle pseudo-objects in the RHS. 12962 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 12963 // An overload in the RHS can potentially be resolved by the type 12964 // being assigned to. 12965 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 12966 if (getLangOpts().CPlusPlus && 12967 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 12968 LHSExpr->getType()->isOverloadableType())) 12969 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12970 12971 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 12972 } 12973 12974 // Don't resolve overloads if the other type is overloadable. 12975 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 12976 LHSExpr->getType()->isOverloadableType()) 12977 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12978 12979 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 12980 if (!resolvedRHS.isUsable()) return ExprError(); 12981 RHSExpr = resolvedRHS.get(); 12982 } 12983 12984 if (getLangOpts().CPlusPlus) { 12985 // If either expression is type-dependent, always build an 12986 // overloaded op. 12987 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 12988 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12989 12990 // Otherwise, build an overloaded op if either expression has an 12991 // overloadable type. 12992 if (LHSExpr->getType()->isOverloadableType() || 12993 RHSExpr->getType()->isOverloadableType()) 12994 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12995 } 12996 12997 // Build a built-in binary operation. 12998 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 12999 } 13000 13001 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 13002 if (T.isNull() || T->isDependentType()) 13003 return false; 13004 13005 if (!T->isPromotableIntegerType()) 13006 return true; 13007 13008 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 13009 } 13010 13011 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 13012 UnaryOperatorKind Opc, 13013 Expr *InputExpr) { 13014 ExprResult Input = InputExpr; 13015 ExprValueKind VK = VK_RValue; 13016 ExprObjectKind OK = OK_Ordinary; 13017 QualType resultType; 13018 bool CanOverflow = false; 13019 13020 bool ConvertHalfVec = false; 13021 if (getLangOpts().OpenCL) { 13022 QualType Ty = InputExpr->getType(); 13023 // The only legal unary operation for atomics is '&'. 13024 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 13025 // OpenCL special types - image, sampler, pipe, and blocks are to be used 13026 // only with a builtin functions and therefore should be disallowed here. 13027 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 13028 || Ty->isBlockPointerType())) { 13029 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13030 << InputExpr->getType() 13031 << Input.get()->getSourceRange()); 13032 } 13033 } 13034 // Diagnose operations on the unsupported types for OpenMP device compilation. 13035 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) { 13036 if (UnaryOperator::isIncrementDecrementOp(Opc) || 13037 UnaryOperator::isArithmeticOp(Opc)) 13038 checkOpenMPDeviceExpr(InputExpr); 13039 } 13040 13041 switch (Opc) { 13042 case UO_PreInc: 13043 case UO_PreDec: 13044 case UO_PostInc: 13045 case UO_PostDec: 13046 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 13047 OpLoc, 13048 Opc == UO_PreInc || 13049 Opc == UO_PostInc, 13050 Opc == UO_PreInc || 13051 Opc == UO_PreDec); 13052 CanOverflow = isOverflowingIntegerType(Context, resultType); 13053 break; 13054 case UO_AddrOf: 13055 resultType = CheckAddressOfOperand(Input, OpLoc); 13056 CheckAddressOfNoDeref(InputExpr); 13057 RecordModifiableNonNullParam(*this, InputExpr); 13058 break; 13059 case UO_Deref: { 13060 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 13061 if (Input.isInvalid()) return ExprError(); 13062 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 13063 break; 13064 } 13065 case UO_Plus: 13066 case UO_Minus: 13067 CanOverflow = Opc == UO_Minus && 13068 isOverflowingIntegerType(Context, Input.get()->getType()); 13069 Input = UsualUnaryConversions(Input.get()); 13070 if (Input.isInvalid()) return ExprError(); 13071 // Unary plus and minus require promoting an operand of half vector to a 13072 // float vector and truncating the result back to a half vector. For now, we 13073 // do this only when HalfArgsAndReturns is set (that is, when the target is 13074 // arm or arm64). 13075 ConvertHalfVec = 13076 needsConversionOfHalfVec(true, Context, Input.get()->getType()); 13077 13078 // If the operand is a half vector, promote it to a float vector. 13079 if (ConvertHalfVec) 13080 Input = convertVector(Input.get(), Context.FloatTy, *this); 13081 resultType = Input.get()->getType(); 13082 if (resultType->isDependentType()) 13083 break; 13084 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 13085 break; 13086 else if (resultType->isVectorType() && 13087 // The z vector extensions don't allow + or - with bool vectors. 13088 (!Context.getLangOpts().ZVector || 13089 resultType->getAs<VectorType>()->getVectorKind() != 13090 VectorType::AltiVecBool)) 13091 break; 13092 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 13093 Opc == UO_Plus && 13094 resultType->isPointerType()) 13095 break; 13096 13097 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13098 << resultType << Input.get()->getSourceRange()); 13099 13100 case UO_Not: // bitwise complement 13101 Input = UsualUnaryConversions(Input.get()); 13102 if (Input.isInvalid()) 13103 return ExprError(); 13104 resultType = Input.get()->getType(); 13105 13106 if (resultType->isDependentType()) 13107 break; 13108 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 13109 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 13110 // C99 does not support '~' for complex conjugation. 13111 Diag(OpLoc, diag::ext_integer_complement_complex) 13112 << resultType << Input.get()->getSourceRange(); 13113 else if (resultType->hasIntegerRepresentation()) 13114 break; 13115 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 13116 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 13117 // on vector float types. 13118 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 13119 if (!T->isIntegerType()) 13120 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13121 << resultType << Input.get()->getSourceRange()); 13122 } else { 13123 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13124 << resultType << Input.get()->getSourceRange()); 13125 } 13126 break; 13127 13128 case UO_LNot: // logical negation 13129 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 13130 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 13131 if (Input.isInvalid()) return ExprError(); 13132 resultType = Input.get()->getType(); 13133 13134 // Though we still have to promote half FP to float... 13135 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 13136 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 13137 resultType = Context.FloatTy; 13138 } 13139 13140 if (resultType->isDependentType()) 13141 break; 13142 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 13143 // C99 6.5.3.3p1: ok, fallthrough; 13144 if (Context.getLangOpts().CPlusPlus) { 13145 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 13146 // operand contextually converted to bool. 13147 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 13148 ScalarTypeToBooleanCastKind(resultType)); 13149 } else if (Context.getLangOpts().OpenCL && 13150 Context.getLangOpts().OpenCLVersion < 120) { 13151 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 13152 // operate on scalar float types. 13153 if (!resultType->isIntegerType() && !resultType->isPointerType()) 13154 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13155 << resultType << Input.get()->getSourceRange()); 13156 } 13157 } else if (resultType->isExtVectorType()) { 13158 if (Context.getLangOpts().OpenCL && 13159 Context.getLangOpts().OpenCLVersion < 120) { 13160 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 13161 // operate on vector float types. 13162 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 13163 if (!T->isIntegerType()) 13164 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13165 << resultType << Input.get()->getSourceRange()); 13166 } 13167 // Vector logical not returns the signed variant of the operand type. 13168 resultType = GetSignedVectorType(resultType); 13169 break; 13170 } else { 13171 // FIXME: GCC's vector extension permits the usage of '!' with a vector 13172 // type in C++. We should allow that here too. 13173 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13174 << resultType << Input.get()->getSourceRange()); 13175 } 13176 13177 // LNot always has type int. C99 6.5.3.3p5. 13178 // In C++, it's bool. C++ 5.3.1p8 13179 resultType = Context.getLogicalOperationType(); 13180 break; 13181 case UO_Real: 13182 case UO_Imag: 13183 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 13184 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 13185 // complex l-values to ordinary l-values and all other values to r-values. 13186 if (Input.isInvalid()) return ExprError(); 13187 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 13188 if (Input.get()->getValueKind() != VK_RValue && 13189 Input.get()->getObjectKind() == OK_Ordinary) 13190 VK = Input.get()->getValueKind(); 13191 } else if (!getLangOpts().CPlusPlus) { 13192 // In C, a volatile scalar is read by __imag. In C++, it is not. 13193 Input = DefaultLvalueConversion(Input.get()); 13194 } 13195 break; 13196 case UO_Extension: 13197 resultType = Input.get()->getType(); 13198 VK = Input.get()->getValueKind(); 13199 OK = Input.get()->getObjectKind(); 13200 break; 13201 case UO_Coawait: 13202 // It's unnecessary to represent the pass-through operator co_await in the 13203 // AST; just return the input expression instead. 13204 assert(!Input.get()->getType()->isDependentType() && 13205 "the co_await expression must be non-dependant before " 13206 "building operator co_await"); 13207 return Input; 13208 } 13209 if (resultType.isNull() || Input.isInvalid()) 13210 return ExprError(); 13211 13212 // Check for array bounds violations in the operand of the UnaryOperator, 13213 // except for the '*' and '&' operators that have to be handled specially 13214 // by CheckArrayAccess (as there are special cases like &array[arraysize] 13215 // that are explicitly defined as valid by the standard). 13216 if (Opc != UO_AddrOf && Opc != UO_Deref) 13217 CheckArrayAccess(Input.get()); 13218 13219 auto *UO = new (Context) 13220 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow); 13221 13222 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 13223 !isa<ArrayType>(UO->getType().getDesugaredType(Context))) 13224 ExprEvalContexts.back().PossibleDerefs.insert(UO); 13225 13226 // Convert the result back to a half vector. 13227 if (ConvertHalfVec) 13228 return convertVector(UO, Context.HalfTy, *this); 13229 return UO; 13230 } 13231 13232 /// Determine whether the given expression is a qualified member 13233 /// access expression, of a form that could be turned into a pointer to member 13234 /// with the address-of operator. 13235 bool Sema::isQualifiedMemberAccess(Expr *E) { 13236 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13237 if (!DRE->getQualifier()) 13238 return false; 13239 13240 ValueDecl *VD = DRE->getDecl(); 13241 if (!VD->isCXXClassMember()) 13242 return false; 13243 13244 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 13245 return true; 13246 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 13247 return Method->isInstance(); 13248 13249 return false; 13250 } 13251 13252 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 13253 if (!ULE->getQualifier()) 13254 return false; 13255 13256 for (NamedDecl *D : ULE->decls()) { 13257 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 13258 if (Method->isInstance()) 13259 return true; 13260 } else { 13261 // Overload set does not contain methods. 13262 break; 13263 } 13264 } 13265 13266 return false; 13267 } 13268 13269 return false; 13270 } 13271 13272 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 13273 UnaryOperatorKind Opc, Expr *Input) { 13274 // First things first: handle placeholders so that the 13275 // overloaded-operator check considers the right type. 13276 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 13277 // Increment and decrement of pseudo-object references. 13278 if (pty->getKind() == BuiltinType::PseudoObject && 13279 UnaryOperator::isIncrementDecrementOp(Opc)) 13280 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 13281 13282 // extension is always a builtin operator. 13283 if (Opc == UO_Extension) 13284 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13285 13286 // & gets special logic for several kinds of placeholder. 13287 // The builtin code knows what to do. 13288 if (Opc == UO_AddrOf && 13289 (pty->getKind() == BuiltinType::Overload || 13290 pty->getKind() == BuiltinType::UnknownAny || 13291 pty->getKind() == BuiltinType::BoundMember)) 13292 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13293 13294 // Anything else needs to be handled now. 13295 ExprResult Result = CheckPlaceholderExpr(Input); 13296 if (Result.isInvalid()) return ExprError(); 13297 Input = Result.get(); 13298 } 13299 13300 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 13301 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 13302 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 13303 // Find all of the overloaded operators visible from this 13304 // point. We perform both an operator-name lookup from the local 13305 // scope and an argument-dependent lookup based on the types of 13306 // the arguments. 13307 UnresolvedSet<16> Functions; 13308 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 13309 if (S && OverOp != OO_None) 13310 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 13311 Functions); 13312 13313 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 13314 } 13315 13316 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13317 } 13318 13319 // Unary Operators. 'Tok' is the token for the operator. 13320 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 13321 tok::TokenKind Op, Expr *Input) { 13322 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 13323 } 13324 13325 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 13326 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 13327 LabelDecl *TheDecl) { 13328 TheDecl->markUsed(Context); 13329 // Create the AST node. The address of a label always has type 'void*'. 13330 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 13331 Context.getPointerType(Context.VoidTy)); 13332 } 13333 13334 void Sema::ActOnStartStmtExpr() { 13335 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 13336 } 13337 13338 void Sema::ActOnStmtExprError() { 13339 // Note that function is also called by TreeTransform when leaving a 13340 // StmtExpr scope without rebuilding anything. 13341 13342 DiscardCleanupsInEvaluationContext(); 13343 PopExpressionEvaluationContext(); 13344 } 13345 13346 ExprResult 13347 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 13348 SourceLocation RPLoc) { // "({..})" 13349 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 13350 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 13351 13352 if (hasAnyUnrecoverableErrorsInThisFunction()) 13353 DiscardCleanupsInEvaluationContext(); 13354 assert(!Cleanup.exprNeedsCleanups() && 13355 "cleanups within StmtExpr not correctly bound!"); 13356 PopExpressionEvaluationContext(); 13357 13358 // FIXME: there are a variety of strange constraints to enforce here, for 13359 // example, it is not possible to goto into a stmt expression apparently. 13360 // More semantic analysis is needed. 13361 13362 // If there are sub-stmts in the compound stmt, take the type of the last one 13363 // as the type of the stmtexpr. 13364 QualType Ty = Context.VoidTy; 13365 bool StmtExprMayBindToTemp = false; 13366 if (!Compound->body_empty()) { 13367 if (const auto *LastStmt = dyn_cast<ValueStmt>(Compound->body_back())) { 13368 if (const Expr *Value = LastStmt->getExprStmt()) { 13369 StmtExprMayBindToTemp = true; 13370 Ty = Value->getType(); 13371 } 13372 } 13373 } 13374 13375 // FIXME: Check that expression type is complete/non-abstract; statement 13376 // expressions are not lvalues. 13377 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 13378 if (StmtExprMayBindToTemp) 13379 return MaybeBindToTemporary(ResStmtExpr); 13380 return ResStmtExpr; 13381 } 13382 13383 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 13384 if (ER.isInvalid()) 13385 return ExprError(); 13386 13387 // Do function/array conversion on the last expression, but not 13388 // lvalue-to-rvalue. However, initialize an unqualified type. 13389 ER = DefaultFunctionArrayConversion(ER.get()); 13390 if (ER.isInvalid()) 13391 return ExprError(); 13392 Expr *E = ER.get(); 13393 13394 if (E->isTypeDependent()) 13395 return E; 13396 13397 // In ARC, if the final expression ends in a consume, splice 13398 // the consume out and bind it later. In the alternate case 13399 // (when dealing with a retainable type), the result 13400 // initialization will create a produce. In both cases the 13401 // result will be +1, and we'll need to balance that out with 13402 // a bind. 13403 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 13404 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 13405 return Cast->getSubExpr(); 13406 13407 // FIXME: Provide a better location for the initialization. 13408 return PerformCopyInitialization( 13409 InitializedEntity::InitializeStmtExprResult( 13410 E->getBeginLoc(), E->getType().getUnqualifiedType()), 13411 SourceLocation(), E); 13412 } 13413 13414 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 13415 TypeSourceInfo *TInfo, 13416 ArrayRef<OffsetOfComponent> Components, 13417 SourceLocation RParenLoc) { 13418 QualType ArgTy = TInfo->getType(); 13419 bool Dependent = ArgTy->isDependentType(); 13420 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 13421 13422 // We must have at least one component that refers to the type, and the first 13423 // one is known to be a field designator. Verify that the ArgTy represents 13424 // a struct/union/class. 13425 if (!Dependent && !ArgTy->isRecordType()) 13426 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 13427 << ArgTy << TypeRange); 13428 13429 // Type must be complete per C99 7.17p3 because a declaring a variable 13430 // with an incomplete type would be ill-formed. 13431 if (!Dependent 13432 && RequireCompleteType(BuiltinLoc, ArgTy, 13433 diag::err_offsetof_incomplete_type, TypeRange)) 13434 return ExprError(); 13435 13436 bool DidWarnAboutNonPOD = false; 13437 QualType CurrentType = ArgTy; 13438 SmallVector<OffsetOfNode, 4> Comps; 13439 SmallVector<Expr*, 4> Exprs; 13440 for (const OffsetOfComponent &OC : Components) { 13441 if (OC.isBrackets) { 13442 // Offset of an array sub-field. TODO: Should we allow vector elements? 13443 if (!CurrentType->isDependentType()) { 13444 const ArrayType *AT = Context.getAsArrayType(CurrentType); 13445 if(!AT) 13446 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 13447 << CurrentType); 13448 CurrentType = AT->getElementType(); 13449 } else 13450 CurrentType = Context.DependentTy; 13451 13452 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 13453 if (IdxRval.isInvalid()) 13454 return ExprError(); 13455 Expr *Idx = IdxRval.get(); 13456 13457 // The expression must be an integral expression. 13458 // FIXME: An integral constant expression? 13459 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 13460 !Idx->getType()->isIntegerType()) 13461 return ExprError( 13462 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 13463 << Idx->getSourceRange()); 13464 13465 // Record this array index. 13466 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 13467 Exprs.push_back(Idx); 13468 continue; 13469 } 13470 13471 // Offset of a field. 13472 if (CurrentType->isDependentType()) { 13473 // We have the offset of a field, but we can't look into the dependent 13474 // type. Just record the identifier of the field. 13475 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 13476 CurrentType = Context.DependentTy; 13477 continue; 13478 } 13479 13480 // We need to have a complete type to look into. 13481 if (RequireCompleteType(OC.LocStart, CurrentType, 13482 diag::err_offsetof_incomplete_type)) 13483 return ExprError(); 13484 13485 // Look for the designated field. 13486 const RecordType *RC = CurrentType->getAs<RecordType>(); 13487 if (!RC) 13488 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 13489 << CurrentType); 13490 RecordDecl *RD = RC->getDecl(); 13491 13492 // C++ [lib.support.types]p5: 13493 // The macro offsetof accepts a restricted set of type arguments in this 13494 // International Standard. type shall be a POD structure or a POD union 13495 // (clause 9). 13496 // C++11 [support.types]p4: 13497 // If type is not a standard-layout class (Clause 9), the results are 13498 // undefined. 13499 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 13500 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 13501 unsigned DiagID = 13502 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 13503 : diag::ext_offsetof_non_pod_type; 13504 13505 if (!IsSafe && !DidWarnAboutNonPOD && 13506 DiagRuntimeBehavior(BuiltinLoc, nullptr, 13507 PDiag(DiagID) 13508 << SourceRange(Components[0].LocStart, OC.LocEnd) 13509 << CurrentType)) 13510 DidWarnAboutNonPOD = true; 13511 } 13512 13513 // Look for the field. 13514 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 13515 LookupQualifiedName(R, RD); 13516 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 13517 IndirectFieldDecl *IndirectMemberDecl = nullptr; 13518 if (!MemberDecl) { 13519 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 13520 MemberDecl = IndirectMemberDecl->getAnonField(); 13521 } 13522 13523 if (!MemberDecl) 13524 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 13525 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 13526 OC.LocEnd)); 13527 13528 // C99 7.17p3: 13529 // (If the specified member is a bit-field, the behavior is undefined.) 13530 // 13531 // We diagnose this as an error. 13532 if (MemberDecl->isBitField()) { 13533 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 13534 << MemberDecl->getDeclName() 13535 << SourceRange(BuiltinLoc, RParenLoc); 13536 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 13537 return ExprError(); 13538 } 13539 13540 RecordDecl *Parent = MemberDecl->getParent(); 13541 if (IndirectMemberDecl) 13542 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 13543 13544 // If the member was found in a base class, introduce OffsetOfNodes for 13545 // the base class indirections. 13546 CXXBasePaths Paths; 13547 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 13548 Paths)) { 13549 if (Paths.getDetectedVirtual()) { 13550 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 13551 << MemberDecl->getDeclName() 13552 << SourceRange(BuiltinLoc, RParenLoc); 13553 return ExprError(); 13554 } 13555 13556 CXXBasePath &Path = Paths.front(); 13557 for (const CXXBasePathElement &B : Path) 13558 Comps.push_back(OffsetOfNode(B.Base)); 13559 } 13560 13561 if (IndirectMemberDecl) { 13562 for (auto *FI : IndirectMemberDecl->chain()) { 13563 assert(isa<FieldDecl>(FI)); 13564 Comps.push_back(OffsetOfNode(OC.LocStart, 13565 cast<FieldDecl>(FI), OC.LocEnd)); 13566 } 13567 } else 13568 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 13569 13570 CurrentType = MemberDecl->getType().getNonReferenceType(); 13571 } 13572 13573 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 13574 Comps, Exprs, RParenLoc); 13575 } 13576 13577 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 13578 SourceLocation BuiltinLoc, 13579 SourceLocation TypeLoc, 13580 ParsedType ParsedArgTy, 13581 ArrayRef<OffsetOfComponent> Components, 13582 SourceLocation RParenLoc) { 13583 13584 TypeSourceInfo *ArgTInfo; 13585 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 13586 if (ArgTy.isNull()) 13587 return ExprError(); 13588 13589 if (!ArgTInfo) 13590 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 13591 13592 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 13593 } 13594 13595 13596 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 13597 Expr *CondExpr, 13598 Expr *LHSExpr, Expr *RHSExpr, 13599 SourceLocation RPLoc) { 13600 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 13601 13602 ExprValueKind VK = VK_RValue; 13603 ExprObjectKind OK = OK_Ordinary; 13604 QualType resType; 13605 bool ValueDependent = false; 13606 bool CondIsTrue = false; 13607 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 13608 resType = Context.DependentTy; 13609 ValueDependent = true; 13610 } else { 13611 // The conditional expression is required to be a constant expression. 13612 llvm::APSInt condEval(32); 13613 ExprResult CondICE 13614 = VerifyIntegerConstantExpression(CondExpr, &condEval, 13615 diag::err_typecheck_choose_expr_requires_constant, false); 13616 if (CondICE.isInvalid()) 13617 return ExprError(); 13618 CondExpr = CondICE.get(); 13619 CondIsTrue = condEval.getZExtValue(); 13620 13621 // If the condition is > zero, then the AST type is the same as the LHSExpr. 13622 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 13623 13624 resType = ActiveExpr->getType(); 13625 ValueDependent = ActiveExpr->isValueDependent(); 13626 VK = ActiveExpr->getValueKind(); 13627 OK = ActiveExpr->getObjectKind(); 13628 } 13629 13630 return new (Context) 13631 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 13632 CondIsTrue, resType->isDependentType(), ValueDependent); 13633 } 13634 13635 //===----------------------------------------------------------------------===// 13636 // Clang Extensions. 13637 //===----------------------------------------------------------------------===// 13638 13639 /// ActOnBlockStart - This callback is invoked when a block literal is started. 13640 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 13641 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 13642 13643 if (LangOpts.CPlusPlus) { 13644 Decl *ManglingContextDecl; 13645 if (MangleNumberingContext *MCtx = 13646 getCurrentMangleNumberContext(Block->getDeclContext(), 13647 ManglingContextDecl)) { 13648 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 13649 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 13650 } 13651 } 13652 13653 PushBlockScope(CurScope, Block); 13654 CurContext->addDecl(Block); 13655 if (CurScope) 13656 PushDeclContext(CurScope, Block); 13657 else 13658 CurContext = Block; 13659 13660 getCurBlock()->HasImplicitReturnType = true; 13661 13662 // Enter a new evaluation context to insulate the block from any 13663 // cleanups from the enclosing full-expression. 13664 PushExpressionEvaluationContext( 13665 ExpressionEvaluationContext::PotentiallyEvaluated); 13666 } 13667 13668 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 13669 Scope *CurScope) { 13670 assert(ParamInfo.getIdentifier() == nullptr && 13671 "block-id should have no identifier!"); 13672 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext); 13673 BlockScopeInfo *CurBlock = getCurBlock(); 13674 13675 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 13676 QualType T = Sig->getType(); 13677 13678 // FIXME: We should allow unexpanded parameter packs here, but that would, 13679 // in turn, make the block expression contain unexpanded parameter packs. 13680 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 13681 // Drop the parameters. 13682 FunctionProtoType::ExtProtoInfo EPI; 13683 EPI.HasTrailingReturn = false; 13684 EPI.TypeQuals.addConst(); 13685 T = Context.getFunctionType(Context.DependentTy, None, EPI); 13686 Sig = Context.getTrivialTypeSourceInfo(T); 13687 } 13688 13689 // GetTypeForDeclarator always produces a function type for a block 13690 // literal signature. Furthermore, it is always a FunctionProtoType 13691 // unless the function was written with a typedef. 13692 assert(T->isFunctionType() && 13693 "GetTypeForDeclarator made a non-function block signature"); 13694 13695 // Look for an explicit signature in that function type. 13696 FunctionProtoTypeLoc ExplicitSignature; 13697 13698 if ((ExplicitSignature = 13699 Sig->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>())) { 13700 13701 // Check whether that explicit signature was synthesized by 13702 // GetTypeForDeclarator. If so, don't save that as part of the 13703 // written signature. 13704 if (ExplicitSignature.getLocalRangeBegin() == 13705 ExplicitSignature.getLocalRangeEnd()) { 13706 // This would be much cheaper if we stored TypeLocs instead of 13707 // TypeSourceInfos. 13708 TypeLoc Result = ExplicitSignature.getReturnLoc(); 13709 unsigned Size = Result.getFullDataSize(); 13710 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 13711 Sig->getTypeLoc().initializeFullCopy(Result, Size); 13712 13713 ExplicitSignature = FunctionProtoTypeLoc(); 13714 } 13715 } 13716 13717 CurBlock->TheDecl->setSignatureAsWritten(Sig); 13718 CurBlock->FunctionType = T; 13719 13720 const FunctionType *Fn = T->getAs<FunctionType>(); 13721 QualType RetTy = Fn->getReturnType(); 13722 bool isVariadic = 13723 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 13724 13725 CurBlock->TheDecl->setIsVariadic(isVariadic); 13726 13727 // Context.DependentTy is used as a placeholder for a missing block 13728 // return type. TODO: what should we do with declarators like: 13729 // ^ * { ... } 13730 // If the answer is "apply template argument deduction".... 13731 if (RetTy != Context.DependentTy) { 13732 CurBlock->ReturnType = RetTy; 13733 CurBlock->TheDecl->setBlockMissingReturnType(false); 13734 CurBlock->HasImplicitReturnType = false; 13735 } 13736 13737 // Push block parameters from the declarator if we had them. 13738 SmallVector<ParmVarDecl*, 8> Params; 13739 if (ExplicitSignature) { 13740 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 13741 ParmVarDecl *Param = ExplicitSignature.getParam(I); 13742 if (Param->getIdentifier() == nullptr && 13743 !Param->isImplicit() && 13744 !Param->isInvalidDecl() && 13745 !getLangOpts().CPlusPlus) 13746 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 13747 Params.push_back(Param); 13748 } 13749 13750 // Fake up parameter variables if we have a typedef, like 13751 // ^ fntype { ... } 13752 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 13753 for (const auto &I : Fn->param_types()) { 13754 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 13755 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 13756 Params.push_back(Param); 13757 } 13758 } 13759 13760 // Set the parameters on the block decl. 13761 if (!Params.empty()) { 13762 CurBlock->TheDecl->setParams(Params); 13763 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 13764 /*CheckParameterNames=*/false); 13765 } 13766 13767 // Finally we can process decl attributes. 13768 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 13769 13770 // Put the parameter variables in scope. 13771 for (auto AI : CurBlock->TheDecl->parameters()) { 13772 AI->setOwningFunction(CurBlock->TheDecl); 13773 13774 // If this has an identifier, add it to the scope stack. 13775 if (AI->getIdentifier()) { 13776 CheckShadow(CurBlock->TheScope, AI); 13777 13778 PushOnScopeChains(AI, CurBlock->TheScope); 13779 } 13780 } 13781 } 13782 13783 /// ActOnBlockError - If there is an error parsing a block, this callback 13784 /// is invoked to pop the information about the block from the action impl. 13785 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 13786 // Leave the expression-evaluation context. 13787 DiscardCleanupsInEvaluationContext(); 13788 PopExpressionEvaluationContext(); 13789 13790 // Pop off CurBlock, handle nested blocks. 13791 PopDeclContext(); 13792 PopFunctionScopeInfo(); 13793 } 13794 13795 /// ActOnBlockStmtExpr - This is called when the body of a block statement 13796 /// literal was successfully completed. ^(int x){...} 13797 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 13798 Stmt *Body, Scope *CurScope) { 13799 // If blocks are disabled, emit an error. 13800 if (!LangOpts.Blocks) 13801 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 13802 13803 // Leave the expression-evaluation context. 13804 if (hasAnyUnrecoverableErrorsInThisFunction()) 13805 DiscardCleanupsInEvaluationContext(); 13806 assert(!Cleanup.exprNeedsCleanups() && 13807 "cleanups within block not correctly bound!"); 13808 PopExpressionEvaluationContext(); 13809 13810 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 13811 BlockDecl *BD = BSI->TheDecl; 13812 13813 if (BSI->HasImplicitReturnType) 13814 deduceClosureReturnType(*BSI); 13815 13816 PopDeclContext(); 13817 13818 QualType RetTy = Context.VoidTy; 13819 if (!BSI->ReturnType.isNull()) 13820 RetTy = BSI->ReturnType; 13821 13822 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 13823 QualType BlockTy; 13824 13825 // Set the captured variables on the block. 13826 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 13827 SmallVector<BlockDecl::Capture, 4> Captures; 13828 for (Capture &Cap : BSI->Captures) { 13829 if (Cap.isThisCapture()) 13830 continue; 13831 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 13832 Cap.isNested(), Cap.getInitExpr()); 13833 Captures.push_back(NewCap); 13834 } 13835 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 13836 13837 // If the user wrote a function type in some form, try to use that. 13838 if (!BSI->FunctionType.isNull()) { 13839 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 13840 13841 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 13842 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 13843 13844 // Turn protoless block types into nullary block types. 13845 if (isa<FunctionNoProtoType>(FTy)) { 13846 FunctionProtoType::ExtProtoInfo EPI; 13847 EPI.ExtInfo = Ext; 13848 BlockTy = Context.getFunctionType(RetTy, None, EPI); 13849 13850 // Otherwise, if we don't need to change anything about the function type, 13851 // preserve its sugar structure. 13852 } else if (FTy->getReturnType() == RetTy && 13853 (!NoReturn || FTy->getNoReturnAttr())) { 13854 BlockTy = BSI->FunctionType; 13855 13856 // Otherwise, make the minimal modifications to the function type. 13857 } else { 13858 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 13859 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 13860 EPI.TypeQuals = Qualifiers(); 13861 EPI.ExtInfo = Ext; 13862 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 13863 } 13864 13865 // If we don't have a function type, just build one from nothing. 13866 } else { 13867 FunctionProtoType::ExtProtoInfo EPI; 13868 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 13869 BlockTy = Context.getFunctionType(RetTy, None, EPI); 13870 } 13871 13872 DiagnoseUnusedParameters(BD->parameters()); 13873 BlockTy = Context.getBlockPointerType(BlockTy); 13874 13875 // If needed, diagnose invalid gotos and switches in the block. 13876 if (getCurFunction()->NeedsScopeChecking() && 13877 !PP.isCodeCompletionEnabled()) 13878 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 13879 13880 BD->setBody(cast<CompoundStmt>(Body)); 13881 13882 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 13883 DiagnoseUnguardedAvailabilityViolations(BD); 13884 13885 // Try to apply the named return value optimization. We have to check again 13886 // if we can do this, though, because blocks keep return statements around 13887 // to deduce an implicit return type. 13888 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 13889 !BD->isDependentContext()) 13890 computeNRVO(Body, BSI); 13891 13892 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 13893 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 13894 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 13895 13896 // If the block isn't obviously global, i.e. it captures anything at 13897 // all, then we need to do a few things in the surrounding context: 13898 if (Result->getBlockDecl()->hasCaptures()) { 13899 // First, this expression has a new cleanup object. 13900 ExprCleanupObjects.push_back(Result->getBlockDecl()); 13901 Cleanup.setExprNeedsCleanups(true); 13902 13903 // It also gets a branch-protected scope if any of the captured 13904 // variables needs destruction. 13905 for (const auto &CI : Result->getBlockDecl()->captures()) { 13906 const VarDecl *var = CI.getVariable(); 13907 if (var->getType().isDestructedType() != QualType::DK_none) { 13908 setFunctionHasBranchProtectedScope(); 13909 break; 13910 } 13911 } 13912 } 13913 13914 if (getCurFunction()) 13915 getCurFunction()->addBlock(BD); 13916 13917 return Result; 13918 } 13919 13920 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 13921 SourceLocation RPLoc) { 13922 TypeSourceInfo *TInfo; 13923 GetTypeFromParser(Ty, &TInfo); 13924 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 13925 } 13926 13927 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 13928 Expr *E, TypeSourceInfo *TInfo, 13929 SourceLocation RPLoc) { 13930 Expr *OrigExpr = E; 13931 bool IsMS = false; 13932 13933 // CUDA device code does not support varargs. 13934 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 13935 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 13936 CUDAFunctionTarget T = IdentifyCUDATarget(F); 13937 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 13938 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 13939 } 13940 } 13941 13942 // NVPTX does not support va_arg expression. 13943 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 13944 Context.getTargetInfo().getTriple().isNVPTX()) 13945 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 13946 13947 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 13948 // as Microsoft ABI on an actual Microsoft platform, where 13949 // __builtin_ms_va_list and __builtin_va_list are the same.) 13950 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 13951 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 13952 QualType MSVaListType = Context.getBuiltinMSVaListType(); 13953 if (Context.hasSameType(MSVaListType, E->getType())) { 13954 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 13955 return ExprError(); 13956 IsMS = true; 13957 } 13958 } 13959 13960 // Get the va_list type 13961 QualType VaListType = Context.getBuiltinVaListType(); 13962 if (!IsMS) { 13963 if (VaListType->isArrayType()) { 13964 // Deal with implicit array decay; for example, on x86-64, 13965 // va_list is an array, but it's supposed to decay to 13966 // a pointer for va_arg. 13967 VaListType = Context.getArrayDecayedType(VaListType); 13968 // Make sure the input expression also decays appropriately. 13969 ExprResult Result = UsualUnaryConversions(E); 13970 if (Result.isInvalid()) 13971 return ExprError(); 13972 E = Result.get(); 13973 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 13974 // If va_list is a record type and we are compiling in C++ mode, 13975 // check the argument using reference binding. 13976 InitializedEntity Entity = InitializedEntity::InitializeParameter( 13977 Context, Context.getLValueReferenceType(VaListType), false); 13978 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 13979 if (Init.isInvalid()) 13980 return ExprError(); 13981 E = Init.getAs<Expr>(); 13982 } else { 13983 // Otherwise, the va_list argument must be an l-value because 13984 // it is modified by va_arg. 13985 if (!E->isTypeDependent() && 13986 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 13987 return ExprError(); 13988 } 13989 } 13990 13991 if (!IsMS && !E->isTypeDependent() && 13992 !Context.hasSameType(VaListType, E->getType())) 13993 return ExprError( 13994 Diag(E->getBeginLoc(), 13995 diag::err_first_argument_to_va_arg_not_of_type_va_list) 13996 << OrigExpr->getType() << E->getSourceRange()); 13997 13998 if (!TInfo->getType()->isDependentType()) { 13999 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 14000 diag::err_second_parameter_to_va_arg_incomplete, 14001 TInfo->getTypeLoc())) 14002 return ExprError(); 14003 14004 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 14005 TInfo->getType(), 14006 diag::err_second_parameter_to_va_arg_abstract, 14007 TInfo->getTypeLoc())) 14008 return ExprError(); 14009 14010 if (!TInfo->getType().isPODType(Context)) { 14011 Diag(TInfo->getTypeLoc().getBeginLoc(), 14012 TInfo->getType()->isObjCLifetimeType() 14013 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 14014 : diag::warn_second_parameter_to_va_arg_not_pod) 14015 << TInfo->getType() 14016 << TInfo->getTypeLoc().getSourceRange(); 14017 } 14018 14019 // Check for va_arg where arguments of the given type will be promoted 14020 // (i.e. this va_arg is guaranteed to have undefined behavior). 14021 QualType PromoteType; 14022 if (TInfo->getType()->isPromotableIntegerType()) { 14023 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 14024 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 14025 PromoteType = QualType(); 14026 } 14027 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 14028 PromoteType = Context.DoubleTy; 14029 if (!PromoteType.isNull()) 14030 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 14031 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 14032 << TInfo->getType() 14033 << PromoteType 14034 << TInfo->getTypeLoc().getSourceRange()); 14035 } 14036 14037 QualType T = TInfo->getType().getNonLValueExprType(Context); 14038 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 14039 } 14040 14041 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 14042 // The type of __null will be int or long, depending on the size of 14043 // pointers on the target. 14044 QualType Ty; 14045 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 14046 if (pw == Context.getTargetInfo().getIntWidth()) 14047 Ty = Context.IntTy; 14048 else if (pw == Context.getTargetInfo().getLongWidth()) 14049 Ty = Context.LongTy; 14050 else if (pw == Context.getTargetInfo().getLongLongWidth()) 14051 Ty = Context.LongLongTy; 14052 else { 14053 llvm_unreachable("I don't know size of pointer!"); 14054 } 14055 14056 return new (Context) GNUNullExpr(Ty, TokenLoc); 14057 } 14058 14059 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 14060 bool Diagnose) { 14061 if (!getLangOpts().ObjC) 14062 return false; 14063 14064 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 14065 if (!PT) 14066 return false; 14067 14068 if (!PT->isObjCIdType()) { 14069 // Check if the destination is the 'NSString' interface. 14070 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 14071 if (!ID || !ID->getIdentifier()->isStr("NSString")) 14072 return false; 14073 } 14074 14075 // Ignore any parens, implicit casts (should only be 14076 // array-to-pointer decays), and not-so-opaque values. The last is 14077 // important for making this trigger for property assignments. 14078 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 14079 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 14080 if (OV->getSourceExpr()) 14081 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 14082 14083 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 14084 if (!SL || !SL->isAscii()) 14085 return false; 14086 if (Diagnose) { 14087 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 14088 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 14089 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 14090 } 14091 return true; 14092 } 14093 14094 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 14095 const Expr *SrcExpr) { 14096 if (!DstType->isFunctionPointerType() || 14097 !SrcExpr->getType()->isFunctionType()) 14098 return false; 14099 14100 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 14101 if (!DRE) 14102 return false; 14103 14104 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 14105 if (!FD) 14106 return false; 14107 14108 return !S.checkAddressOfFunctionIsAvailable(FD, 14109 /*Complain=*/true, 14110 SrcExpr->getBeginLoc()); 14111 } 14112 14113 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 14114 SourceLocation Loc, 14115 QualType DstType, QualType SrcType, 14116 Expr *SrcExpr, AssignmentAction Action, 14117 bool *Complained) { 14118 if (Complained) 14119 *Complained = false; 14120 14121 // Decode the result (notice that AST's are still created for extensions). 14122 bool CheckInferredResultType = false; 14123 bool isInvalid = false; 14124 unsigned DiagKind = 0; 14125 FixItHint Hint; 14126 ConversionFixItGenerator ConvHints; 14127 bool MayHaveConvFixit = false; 14128 bool MayHaveFunctionDiff = false; 14129 const ObjCInterfaceDecl *IFace = nullptr; 14130 const ObjCProtocolDecl *PDecl = nullptr; 14131 14132 switch (ConvTy) { 14133 case Compatible: 14134 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 14135 return false; 14136 14137 case PointerToInt: 14138 DiagKind = diag::ext_typecheck_convert_pointer_int; 14139 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14140 MayHaveConvFixit = true; 14141 break; 14142 case IntToPointer: 14143 DiagKind = diag::ext_typecheck_convert_int_pointer; 14144 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14145 MayHaveConvFixit = true; 14146 break; 14147 case IncompatiblePointer: 14148 if (Action == AA_Passing_CFAudited) 14149 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 14150 else if (SrcType->isFunctionPointerType() && 14151 DstType->isFunctionPointerType()) 14152 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 14153 else 14154 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 14155 14156 CheckInferredResultType = DstType->isObjCObjectPointerType() && 14157 SrcType->isObjCObjectPointerType(); 14158 if (Hint.isNull() && !CheckInferredResultType) { 14159 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14160 } 14161 else if (CheckInferredResultType) { 14162 SrcType = SrcType.getUnqualifiedType(); 14163 DstType = DstType.getUnqualifiedType(); 14164 } 14165 MayHaveConvFixit = true; 14166 break; 14167 case IncompatiblePointerSign: 14168 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 14169 break; 14170 case FunctionVoidPointer: 14171 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 14172 break; 14173 case IncompatiblePointerDiscardsQualifiers: { 14174 // Perform array-to-pointer decay if necessary. 14175 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 14176 14177 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 14178 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 14179 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 14180 DiagKind = diag::err_typecheck_incompatible_address_space; 14181 break; 14182 14183 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 14184 DiagKind = diag::err_typecheck_incompatible_ownership; 14185 break; 14186 } 14187 14188 llvm_unreachable("unknown error case for discarding qualifiers!"); 14189 // fallthrough 14190 } 14191 case CompatiblePointerDiscardsQualifiers: 14192 // If the qualifiers lost were because we were applying the 14193 // (deprecated) C++ conversion from a string literal to a char* 14194 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 14195 // Ideally, this check would be performed in 14196 // checkPointerTypesForAssignment. However, that would require a 14197 // bit of refactoring (so that the second argument is an 14198 // expression, rather than a type), which should be done as part 14199 // of a larger effort to fix checkPointerTypesForAssignment for 14200 // C++ semantics. 14201 if (getLangOpts().CPlusPlus && 14202 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 14203 return false; 14204 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 14205 break; 14206 case IncompatibleNestedPointerQualifiers: 14207 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 14208 break; 14209 case IntToBlockPointer: 14210 DiagKind = diag::err_int_to_block_pointer; 14211 break; 14212 case IncompatibleBlockPointer: 14213 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 14214 break; 14215 case IncompatibleObjCQualifiedId: { 14216 if (SrcType->isObjCQualifiedIdType()) { 14217 const ObjCObjectPointerType *srcOPT = 14218 SrcType->getAs<ObjCObjectPointerType>(); 14219 for (auto *srcProto : srcOPT->quals()) { 14220 PDecl = srcProto; 14221 break; 14222 } 14223 if (const ObjCInterfaceType *IFaceT = 14224 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 14225 IFace = IFaceT->getDecl(); 14226 } 14227 else if (DstType->isObjCQualifiedIdType()) { 14228 const ObjCObjectPointerType *dstOPT = 14229 DstType->getAs<ObjCObjectPointerType>(); 14230 for (auto *dstProto : dstOPT->quals()) { 14231 PDecl = dstProto; 14232 break; 14233 } 14234 if (const ObjCInterfaceType *IFaceT = 14235 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 14236 IFace = IFaceT->getDecl(); 14237 } 14238 DiagKind = diag::warn_incompatible_qualified_id; 14239 break; 14240 } 14241 case IncompatibleVectors: 14242 DiagKind = diag::warn_incompatible_vectors; 14243 break; 14244 case IncompatibleObjCWeakRef: 14245 DiagKind = diag::err_arc_weak_unavailable_assign; 14246 break; 14247 case Incompatible: 14248 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 14249 if (Complained) 14250 *Complained = true; 14251 return true; 14252 } 14253 14254 DiagKind = diag::err_typecheck_convert_incompatible; 14255 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14256 MayHaveConvFixit = true; 14257 isInvalid = true; 14258 MayHaveFunctionDiff = true; 14259 break; 14260 } 14261 14262 QualType FirstType, SecondType; 14263 switch (Action) { 14264 case AA_Assigning: 14265 case AA_Initializing: 14266 // The destination type comes first. 14267 FirstType = DstType; 14268 SecondType = SrcType; 14269 break; 14270 14271 case AA_Returning: 14272 case AA_Passing: 14273 case AA_Passing_CFAudited: 14274 case AA_Converting: 14275 case AA_Sending: 14276 case AA_Casting: 14277 // The source type comes first. 14278 FirstType = SrcType; 14279 SecondType = DstType; 14280 break; 14281 } 14282 14283 PartialDiagnostic FDiag = PDiag(DiagKind); 14284 if (Action == AA_Passing_CFAudited) 14285 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 14286 else 14287 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 14288 14289 // If we can fix the conversion, suggest the FixIts. 14290 assert(ConvHints.isNull() || Hint.isNull()); 14291 if (!ConvHints.isNull()) { 14292 for (FixItHint &H : ConvHints.Hints) 14293 FDiag << H; 14294 } else { 14295 FDiag << Hint; 14296 } 14297 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 14298 14299 if (MayHaveFunctionDiff) 14300 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 14301 14302 Diag(Loc, FDiag); 14303 if (DiagKind == diag::warn_incompatible_qualified_id && 14304 PDecl && IFace && !IFace->hasDefinition()) 14305 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 14306 << IFace << PDecl; 14307 14308 if (SecondType == Context.OverloadTy) 14309 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 14310 FirstType, /*TakingAddress=*/true); 14311 14312 if (CheckInferredResultType) 14313 EmitRelatedResultTypeNote(SrcExpr); 14314 14315 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 14316 EmitRelatedResultTypeNoteForReturn(DstType); 14317 14318 if (Complained) 14319 *Complained = true; 14320 return isInvalid; 14321 } 14322 14323 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 14324 llvm::APSInt *Result) { 14325 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 14326 public: 14327 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 14328 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 14329 } 14330 } Diagnoser; 14331 14332 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 14333 } 14334 14335 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 14336 llvm::APSInt *Result, 14337 unsigned DiagID, 14338 bool AllowFold) { 14339 class IDDiagnoser : public VerifyICEDiagnoser { 14340 unsigned DiagID; 14341 14342 public: 14343 IDDiagnoser(unsigned DiagID) 14344 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 14345 14346 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 14347 S.Diag(Loc, DiagID) << SR; 14348 } 14349 } Diagnoser(DiagID); 14350 14351 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 14352 } 14353 14354 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 14355 SourceRange SR) { 14356 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 14357 } 14358 14359 ExprResult 14360 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 14361 VerifyICEDiagnoser &Diagnoser, 14362 bool AllowFold) { 14363 SourceLocation DiagLoc = E->getBeginLoc(); 14364 14365 if (getLangOpts().CPlusPlus11) { 14366 // C++11 [expr.const]p5: 14367 // If an expression of literal class type is used in a context where an 14368 // integral constant expression is required, then that class type shall 14369 // have a single non-explicit conversion function to an integral or 14370 // unscoped enumeration type 14371 ExprResult Converted; 14372 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 14373 public: 14374 CXX11ConvertDiagnoser(bool Silent) 14375 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 14376 Silent, true) {} 14377 14378 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 14379 QualType T) override { 14380 return S.Diag(Loc, diag::err_ice_not_integral) << T; 14381 } 14382 14383 SemaDiagnosticBuilder diagnoseIncomplete( 14384 Sema &S, SourceLocation Loc, QualType T) override { 14385 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 14386 } 14387 14388 SemaDiagnosticBuilder diagnoseExplicitConv( 14389 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 14390 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 14391 } 14392 14393 SemaDiagnosticBuilder noteExplicitConv( 14394 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 14395 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 14396 << ConvTy->isEnumeralType() << ConvTy; 14397 } 14398 14399 SemaDiagnosticBuilder diagnoseAmbiguous( 14400 Sema &S, SourceLocation Loc, QualType T) override { 14401 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 14402 } 14403 14404 SemaDiagnosticBuilder noteAmbiguous( 14405 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 14406 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 14407 << ConvTy->isEnumeralType() << ConvTy; 14408 } 14409 14410 SemaDiagnosticBuilder diagnoseConversion( 14411 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 14412 llvm_unreachable("conversion functions are permitted"); 14413 } 14414 } ConvertDiagnoser(Diagnoser.Suppress); 14415 14416 Converted = PerformContextualImplicitConversion(DiagLoc, E, 14417 ConvertDiagnoser); 14418 if (Converted.isInvalid()) 14419 return Converted; 14420 E = Converted.get(); 14421 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 14422 return ExprError(); 14423 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 14424 // An ICE must be of integral or unscoped enumeration type. 14425 if (!Diagnoser.Suppress) 14426 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 14427 return ExprError(); 14428 } 14429 14430 if (!isa<ConstantExpr>(E)) 14431 E = ConstantExpr::Create(Context, E); 14432 14433 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 14434 // in the non-ICE case. 14435 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 14436 if (Result) 14437 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 14438 return E; 14439 } 14440 14441 Expr::EvalResult EvalResult; 14442 SmallVector<PartialDiagnosticAt, 8> Notes; 14443 EvalResult.Diag = &Notes; 14444 14445 // Try to evaluate the expression, and produce diagnostics explaining why it's 14446 // not a constant expression as a side-effect. 14447 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 14448 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 14449 14450 // In C++11, we can rely on diagnostics being produced for any expression 14451 // which is not a constant expression. If no diagnostics were produced, then 14452 // this is a constant expression. 14453 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 14454 if (Result) 14455 *Result = EvalResult.Val.getInt(); 14456 return E; 14457 } 14458 14459 // If our only note is the usual "invalid subexpression" note, just point 14460 // the caret at its location rather than producing an essentially 14461 // redundant note. 14462 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 14463 diag::note_invalid_subexpr_in_const_expr) { 14464 DiagLoc = Notes[0].first; 14465 Notes.clear(); 14466 } 14467 14468 if (!Folded || !AllowFold) { 14469 if (!Diagnoser.Suppress) { 14470 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 14471 for (const PartialDiagnosticAt &Note : Notes) 14472 Diag(Note.first, Note.second); 14473 } 14474 14475 return ExprError(); 14476 } 14477 14478 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 14479 for (const PartialDiagnosticAt &Note : Notes) 14480 Diag(Note.first, Note.second); 14481 14482 if (Result) 14483 *Result = EvalResult.Val.getInt(); 14484 return E; 14485 } 14486 14487 namespace { 14488 // Handle the case where we conclude a expression which we speculatively 14489 // considered to be unevaluated is actually evaluated. 14490 class TransformToPE : public TreeTransform<TransformToPE> { 14491 typedef TreeTransform<TransformToPE> BaseTransform; 14492 14493 public: 14494 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 14495 14496 // Make sure we redo semantic analysis 14497 bool AlwaysRebuild() { return true; } 14498 14499 // We need to special-case DeclRefExprs referring to FieldDecls which 14500 // are not part of a member pointer formation; normal TreeTransforming 14501 // doesn't catch this case because of the way we represent them in the AST. 14502 // FIXME: This is a bit ugly; is it really the best way to handle this 14503 // case? 14504 // 14505 // Error on DeclRefExprs referring to FieldDecls. 14506 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 14507 if (isa<FieldDecl>(E->getDecl()) && 14508 !SemaRef.isUnevaluatedContext()) 14509 return SemaRef.Diag(E->getLocation(), 14510 diag::err_invalid_non_static_member_use) 14511 << E->getDecl() << E->getSourceRange(); 14512 14513 return BaseTransform::TransformDeclRefExpr(E); 14514 } 14515 14516 // Exception: filter out member pointer formation 14517 ExprResult TransformUnaryOperator(UnaryOperator *E) { 14518 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 14519 return E; 14520 14521 return BaseTransform::TransformUnaryOperator(E); 14522 } 14523 14524 ExprResult TransformLambdaExpr(LambdaExpr *E) { 14525 // Lambdas never need to be transformed. 14526 return E; 14527 } 14528 }; 14529 } 14530 14531 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 14532 assert(isUnevaluatedContext() && 14533 "Should only transform unevaluated expressions"); 14534 ExprEvalContexts.back().Context = 14535 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 14536 if (isUnevaluatedContext()) 14537 return E; 14538 return TransformToPE(*this).TransformExpr(E); 14539 } 14540 14541 void 14542 Sema::PushExpressionEvaluationContext( 14543 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 14544 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 14545 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 14546 LambdaContextDecl, ExprContext); 14547 Cleanup.reset(); 14548 if (!MaybeODRUseExprs.empty()) 14549 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 14550 } 14551 14552 void 14553 Sema::PushExpressionEvaluationContext( 14554 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 14555 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 14556 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 14557 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 14558 } 14559 14560 namespace { 14561 14562 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 14563 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 14564 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 14565 if (E->getOpcode() == UO_Deref) 14566 return CheckPossibleDeref(S, E->getSubExpr()); 14567 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 14568 return CheckPossibleDeref(S, E->getBase()); 14569 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 14570 return CheckPossibleDeref(S, E->getBase()); 14571 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 14572 QualType Inner; 14573 QualType Ty = E->getType(); 14574 if (const auto *Ptr = Ty->getAs<PointerType>()) 14575 Inner = Ptr->getPointeeType(); 14576 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 14577 Inner = Arr->getElementType(); 14578 else 14579 return nullptr; 14580 14581 if (Inner->hasAttr(attr::NoDeref)) 14582 return E; 14583 } 14584 return nullptr; 14585 } 14586 14587 } // namespace 14588 14589 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 14590 for (const Expr *E : Rec.PossibleDerefs) { 14591 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 14592 if (DeclRef) { 14593 const ValueDecl *Decl = DeclRef->getDecl(); 14594 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 14595 << Decl->getName() << E->getSourceRange(); 14596 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 14597 } else { 14598 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 14599 << E->getSourceRange(); 14600 } 14601 } 14602 Rec.PossibleDerefs.clear(); 14603 } 14604 14605 void Sema::PopExpressionEvaluationContext() { 14606 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 14607 unsigned NumTypos = Rec.NumTypos; 14608 14609 if (!Rec.Lambdas.empty()) { 14610 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 14611 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() || 14612 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) { 14613 unsigned D; 14614 if (Rec.isUnevaluated()) { 14615 // C++11 [expr.prim.lambda]p2: 14616 // A lambda-expression shall not appear in an unevaluated operand 14617 // (Clause 5). 14618 D = diag::err_lambda_unevaluated_operand; 14619 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 14620 // C++1y [expr.const]p2: 14621 // A conditional-expression e is a core constant expression unless the 14622 // evaluation of e, following the rules of the abstract machine, would 14623 // evaluate [...] a lambda-expression. 14624 D = diag::err_lambda_in_constant_expression; 14625 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 14626 // C++17 [expr.prim.lamda]p2: 14627 // A lambda-expression shall not appear [...] in a template-argument. 14628 D = diag::err_lambda_in_invalid_context; 14629 } else 14630 llvm_unreachable("Couldn't infer lambda error message."); 14631 14632 for (const auto *L : Rec.Lambdas) 14633 Diag(L->getBeginLoc(), D); 14634 } else { 14635 // Mark the capture expressions odr-used. This was deferred 14636 // during lambda expression creation. 14637 for (auto *Lambda : Rec.Lambdas) { 14638 for (auto *C : Lambda->capture_inits()) 14639 MarkDeclarationsReferencedInExpr(C); 14640 } 14641 } 14642 } 14643 14644 WarnOnPendingNoDerefs(Rec); 14645 14646 // When are coming out of an unevaluated context, clear out any 14647 // temporaries that we may have created as part of the evaluation of 14648 // the expression in that context: they aren't relevant because they 14649 // will never be constructed. 14650 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 14651 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 14652 ExprCleanupObjects.end()); 14653 Cleanup = Rec.ParentCleanup; 14654 CleanupVarDeclMarking(); 14655 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 14656 // Otherwise, merge the contexts together. 14657 } else { 14658 Cleanup.mergeFrom(Rec.ParentCleanup); 14659 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 14660 Rec.SavedMaybeODRUseExprs.end()); 14661 } 14662 14663 // Pop the current expression evaluation context off the stack. 14664 ExprEvalContexts.pop_back(); 14665 14666 // The global expression evaluation context record is never popped. 14667 ExprEvalContexts.back().NumTypos += NumTypos; 14668 } 14669 14670 void Sema::DiscardCleanupsInEvaluationContext() { 14671 ExprCleanupObjects.erase( 14672 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 14673 ExprCleanupObjects.end()); 14674 Cleanup.reset(); 14675 MaybeODRUseExprs.clear(); 14676 } 14677 14678 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 14679 ExprResult Result = CheckPlaceholderExpr(E); 14680 if (Result.isInvalid()) 14681 return ExprError(); 14682 E = Result.get(); 14683 if (!E->getType()->isVariablyModifiedType()) 14684 return E; 14685 return TransformToPotentiallyEvaluated(E); 14686 } 14687 14688 /// Are we within a context in which some evaluation could be performed (be it 14689 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite 14690 /// captured by C++'s idea of an "unevaluated context". 14691 static bool isEvaluatableContext(Sema &SemaRef) { 14692 switch (SemaRef.ExprEvalContexts.back().Context) { 14693 case Sema::ExpressionEvaluationContext::Unevaluated: 14694 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 14695 // Expressions in this context are never evaluated. 14696 return false; 14697 14698 case Sema::ExpressionEvaluationContext::UnevaluatedList: 14699 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 14700 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 14701 case Sema::ExpressionEvaluationContext::DiscardedStatement: 14702 // Expressions in this context could be evaluated. 14703 return true; 14704 14705 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 14706 // Referenced declarations will only be used if the construct in the 14707 // containing expression is used, at which point we'll be given another 14708 // turn to mark them. 14709 return false; 14710 } 14711 llvm_unreachable("Invalid context"); 14712 } 14713 14714 /// Are we within a context in which references to resolved functions or to 14715 /// variables result in odr-use? 14716 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) { 14717 // An expression in a template is not really an expression until it's been 14718 // instantiated, so it doesn't trigger odr-use. 14719 if (SkipDependentUses && SemaRef.CurContext->isDependentContext()) 14720 return false; 14721 14722 switch (SemaRef.ExprEvalContexts.back().Context) { 14723 case Sema::ExpressionEvaluationContext::Unevaluated: 14724 case Sema::ExpressionEvaluationContext::UnevaluatedList: 14725 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 14726 case Sema::ExpressionEvaluationContext::DiscardedStatement: 14727 return false; 14728 14729 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 14730 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 14731 return true; 14732 14733 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 14734 return false; 14735 } 14736 llvm_unreachable("Invalid context"); 14737 } 14738 14739 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 14740 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 14741 return Func->isConstexpr() && 14742 (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided())); 14743 } 14744 14745 /// Mark a function referenced, and check whether it is odr-used 14746 /// (C++ [basic.def.odr]p2, C99 6.9p3) 14747 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 14748 bool MightBeOdrUse) { 14749 assert(Func && "No function?"); 14750 14751 Func->setReferenced(); 14752 14753 // C++11 [basic.def.odr]p3: 14754 // A function whose name appears as a potentially-evaluated expression is 14755 // odr-used if it is the unique lookup result or the selected member of a 14756 // set of overloaded functions [...]. 14757 // 14758 // We (incorrectly) mark overload resolution as an unevaluated context, so we 14759 // can just check that here. 14760 bool OdrUse = MightBeOdrUse && isOdrUseContext(*this); 14761 14762 // Determine whether we require a function definition to exist, per 14763 // C++11 [temp.inst]p3: 14764 // Unless a function template specialization has been explicitly 14765 // instantiated or explicitly specialized, the function template 14766 // specialization is implicitly instantiated when the specialization is 14767 // referenced in a context that requires a function definition to exist. 14768 // 14769 // That is either when this is an odr-use, or when a usage of a constexpr 14770 // function occurs within an evaluatable context. 14771 bool NeedDefinition = 14772 OdrUse || (isEvaluatableContext(*this) && 14773 isImplicitlyDefinableConstexprFunction(Func)); 14774 14775 // C++14 [temp.expl.spec]p6: 14776 // If a template [...] is explicitly specialized then that specialization 14777 // shall be declared before the first use of that specialization that would 14778 // cause an implicit instantiation to take place, in every translation unit 14779 // in which such a use occurs 14780 if (NeedDefinition && 14781 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 14782 Func->getMemberSpecializationInfo())) 14783 checkSpecializationVisibility(Loc, Func); 14784 14785 // C++14 [except.spec]p17: 14786 // An exception-specification is considered to be needed when: 14787 // - the function is odr-used or, if it appears in an unevaluated operand, 14788 // would be odr-used if the expression were potentially-evaluated; 14789 // 14790 // Note, we do this even if MightBeOdrUse is false. That indicates that the 14791 // function is a pure virtual function we're calling, and in that case the 14792 // function was selected by overload resolution and we need to resolve its 14793 // exception specification for a different reason. 14794 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 14795 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 14796 ResolveExceptionSpec(Loc, FPT); 14797 14798 if (getLangOpts().CUDA) 14799 CheckCUDACall(Loc, Func); 14800 14801 // If we don't need to mark the function as used, and we don't need to 14802 // try to provide a definition, there's nothing more to do. 14803 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) && 14804 (!NeedDefinition || Func->getBody())) 14805 return; 14806 14807 // Note that this declaration has been used. 14808 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 14809 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 14810 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 14811 if (Constructor->isDefaultConstructor()) { 14812 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 14813 return; 14814 DefineImplicitDefaultConstructor(Loc, Constructor); 14815 } else if (Constructor->isCopyConstructor()) { 14816 DefineImplicitCopyConstructor(Loc, Constructor); 14817 } else if (Constructor->isMoveConstructor()) { 14818 DefineImplicitMoveConstructor(Loc, Constructor); 14819 } 14820 } else if (Constructor->getInheritedConstructor()) { 14821 DefineInheritingConstructor(Loc, Constructor); 14822 } 14823 } else if (CXXDestructorDecl *Destructor = 14824 dyn_cast<CXXDestructorDecl>(Func)) { 14825 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 14826 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 14827 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 14828 return; 14829 DefineImplicitDestructor(Loc, Destructor); 14830 } 14831 if (Destructor->isVirtual() && getLangOpts().AppleKext) 14832 MarkVTableUsed(Loc, Destructor->getParent()); 14833 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 14834 if (MethodDecl->isOverloadedOperator() && 14835 MethodDecl->getOverloadedOperator() == OO_Equal) { 14836 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 14837 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 14838 if (MethodDecl->isCopyAssignmentOperator()) 14839 DefineImplicitCopyAssignment(Loc, MethodDecl); 14840 else if (MethodDecl->isMoveAssignmentOperator()) 14841 DefineImplicitMoveAssignment(Loc, MethodDecl); 14842 } 14843 } else if (isa<CXXConversionDecl>(MethodDecl) && 14844 MethodDecl->getParent()->isLambda()) { 14845 CXXConversionDecl *Conversion = 14846 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 14847 if (Conversion->isLambdaToBlockPointerConversion()) 14848 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 14849 else 14850 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 14851 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 14852 MarkVTableUsed(Loc, MethodDecl->getParent()); 14853 } 14854 14855 // Recursive functions should be marked when used from another function. 14856 // FIXME: Is this really right? 14857 if (CurContext == Func) return; 14858 14859 // Implicit instantiation of function templates and member functions of 14860 // class templates. 14861 if (Func->isImplicitlyInstantiable()) { 14862 TemplateSpecializationKind TSK = Func->getTemplateSpecializationKind(); 14863 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 14864 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 14865 if (FirstInstantiation) { 14866 PointOfInstantiation = Loc; 14867 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 14868 } else if (TSK != TSK_ImplicitInstantiation) { 14869 // Use the point of use as the point of instantiation, instead of the 14870 // point of explicit instantiation (which we track as the actual point of 14871 // instantiation). This gives better backtraces in diagnostics. 14872 PointOfInstantiation = Loc; 14873 } 14874 14875 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 14876 Func->isConstexpr()) { 14877 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 14878 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 14879 CodeSynthesisContexts.size()) 14880 PendingLocalImplicitInstantiations.push_back( 14881 std::make_pair(Func, PointOfInstantiation)); 14882 else if (Func->isConstexpr()) 14883 // Do not defer instantiations of constexpr functions, to avoid the 14884 // expression evaluator needing to call back into Sema if it sees a 14885 // call to such a function. 14886 InstantiateFunctionDefinition(PointOfInstantiation, Func); 14887 else { 14888 Func->setInstantiationIsPending(true); 14889 PendingInstantiations.push_back(std::make_pair(Func, 14890 PointOfInstantiation)); 14891 // Notify the consumer that a function was implicitly instantiated. 14892 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 14893 } 14894 } 14895 } else { 14896 // Walk redefinitions, as some of them may be instantiable. 14897 for (auto i : Func->redecls()) { 14898 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 14899 MarkFunctionReferenced(Loc, i, OdrUse); 14900 } 14901 } 14902 14903 if (!OdrUse) return; 14904 14905 // Keep track of used but undefined functions. 14906 if (!Func->isDefined()) { 14907 if (mightHaveNonExternalLinkage(Func)) 14908 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14909 else if (Func->getMostRecentDecl()->isInlined() && 14910 !LangOpts.GNUInline && 14911 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 14912 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14913 else if (isExternalWithNoLinkageType(Func)) 14914 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14915 } 14916 14917 Func->markUsed(Context); 14918 14919 if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice) 14920 checkOpenMPDeviceFunction(Loc, Func); 14921 } 14922 14923 static void 14924 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 14925 ValueDecl *var, DeclContext *DC) { 14926 DeclContext *VarDC = var->getDeclContext(); 14927 14928 // If the parameter still belongs to the translation unit, then 14929 // we're actually just using one parameter in the declaration of 14930 // the next. 14931 if (isa<ParmVarDecl>(var) && 14932 isa<TranslationUnitDecl>(VarDC)) 14933 return; 14934 14935 // For C code, don't diagnose about capture if we're not actually in code 14936 // right now; it's impossible to write a non-constant expression outside of 14937 // function context, so we'll get other (more useful) diagnostics later. 14938 // 14939 // For C++, things get a bit more nasty... it would be nice to suppress this 14940 // diagnostic for certain cases like using a local variable in an array bound 14941 // for a member of a local class, but the correct predicate is not obvious. 14942 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 14943 return; 14944 14945 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 14946 unsigned ContextKind = 3; // unknown 14947 if (isa<CXXMethodDecl>(VarDC) && 14948 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 14949 ContextKind = 2; 14950 } else if (isa<FunctionDecl>(VarDC)) { 14951 ContextKind = 0; 14952 } else if (isa<BlockDecl>(VarDC)) { 14953 ContextKind = 1; 14954 } 14955 14956 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 14957 << var << ValueKind << ContextKind << VarDC; 14958 S.Diag(var->getLocation(), diag::note_entity_declared_at) 14959 << var; 14960 14961 // FIXME: Add additional diagnostic info about class etc. which prevents 14962 // capture. 14963 } 14964 14965 14966 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 14967 bool &SubCapturesAreNested, 14968 QualType &CaptureType, 14969 QualType &DeclRefType) { 14970 // Check whether we've already captured it. 14971 if (CSI->CaptureMap.count(Var)) { 14972 // If we found a capture, any subcaptures are nested. 14973 SubCapturesAreNested = true; 14974 14975 // Retrieve the capture type for this variable. 14976 CaptureType = CSI->getCapture(Var).getCaptureType(); 14977 14978 // Compute the type of an expression that refers to this variable. 14979 DeclRefType = CaptureType.getNonReferenceType(); 14980 14981 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 14982 // are mutable in the sense that user can change their value - they are 14983 // private instances of the captured declarations. 14984 const Capture &Cap = CSI->getCapture(Var); 14985 if (Cap.isCopyCapture() && 14986 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 14987 !(isa<CapturedRegionScopeInfo>(CSI) && 14988 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 14989 DeclRefType.addConst(); 14990 return true; 14991 } 14992 return false; 14993 } 14994 14995 // Only block literals, captured statements, and lambda expressions can 14996 // capture; other scopes don't work. 14997 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 14998 SourceLocation Loc, 14999 const bool Diagnose, Sema &S) { 15000 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 15001 return getLambdaAwareParentOfDeclContext(DC); 15002 else if (Var->hasLocalStorage()) { 15003 if (Diagnose) 15004 diagnoseUncapturableValueReference(S, Loc, Var, DC); 15005 } 15006 return nullptr; 15007 } 15008 15009 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 15010 // certain types of variables (unnamed, variably modified types etc.) 15011 // so check for eligibility. 15012 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 15013 SourceLocation Loc, 15014 const bool Diagnose, Sema &S) { 15015 15016 bool IsBlock = isa<BlockScopeInfo>(CSI); 15017 bool IsLambda = isa<LambdaScopeInfo>(CSI); 15018 15019 // Lambdas are not allowed to capture unnamed variables 15020 // (e.g. anonymous unions). 15021 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 15022 // assuming that's the intent. 15023 if (IsLambda && !Var->getDeclName()) { 15024 if (Diagnose) { 15025 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 15026 S.Diag(Var->getLocation(), diag::note_declared_at); 15027 } 15028 return false; 15029 } 15030 15031 // Prohibit variably-modified types in blocks; they're difficult to deal with. 15032 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 15033 if (Diagnose) { 15034 S.Diag(Loc, diag::err_ref_vm_type); 15035 S.Diag(Var->getLocation(), diag::note_previous_decl) 15036 << Var->getDeclName(); 15037 } 15038 return false; 15039 } 15040 // Prohibit structs with flexible array members too. 15041 // We cannot capture what is in the tail end of the struct. 15042 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 15043 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 15044 if (Diagnose) { 15045 if (IsBlock) 15046 S.Diag(Loc, diag::err_ref_flexarray_type); 15047 else 15048 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 15049 << Var->getDeclName(); 15050 S.Diag(Var->getLocation(), diag::note_previous_decl) 15051 << Var->getDeclName(); 15052 } 15053 return false; 15054 } 15055 } 15056 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 15057 // Lambdas and captured statements are not allowed to capture __block 15058 // variables; they don't support the expected semantics. 15059 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 15060 if (Diagnose) { 15061 S.Diag(Loc, diag::err_capture_block_variable) 15062 << Var->getDeclName() << !IsLambda; 15063 S.Diag(Var->getLocation(), diag::note_previous_decl) 15064 << Var->getDeclName(); 15065 } 15066 return false; 15067 } 15068 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 15069 if (S.getLangOpts().OpenCL && IsBlock && 15070 Var->getType()->isBlockPointerType()) { 15071 if (Diagnose) 15072 S.Diag(Loc, diag::err_opencl_block_ref_block); 15073 return false; 15074 } 15075 15076 return true; 15077 } 15078 15079 // Returns true if the capture by block was successful. 15080 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 15081 SourceLocation Loc, 15082 const bool BuildAndDiagnose, 15083 QualType &CaptureType, 15084 QualType &DeclRefType, 15085 const bool Nested, 15086 Sema &S) { 15087 Expr *CopyExpr = nullptr; 15088 bool ByRef = false; 15089 15090 // Blocks are not allowed to capture arrays, excepting OpenCL. 15091 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 15092 // (decayed to pointers). 15093 if (!S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 15094 if (BuildAndDiagnose) { 15095 S.Diag(Loc, diag::err_ref_array_type); 15096 S.Diag(Var->getLocation(), diag::note_previous_decl) 15097 << Var->getDeclName(); 15098 } 15099 return false; 15100 } 15101 15102 // Forbid the block-capture of autoreleasing variables. 15103 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 15104 if (BuildAndDiagnose) { 15105 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 15106 << /*block*/ 0; 15107 S.Diag(Var->getLocation(), diag::note_previous_decl) 15108 << Var->getDeclName(); 15109 } 15110 return false; 15111 } 15112 15113 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 15114 if (const auto *PT = CaptureType->getAs<PointerType>()) { 15115 // This function finds out whether there is an AttributedType of kind 15116 // attr::ObjCOwnership in Ty. The existence of AttributedType of kind 15117 // attr::ObjCOwnership implies __autoreleasing was explicitly specified 15118 // rather than being added implicitly by the compiler. 15119 auto IsObjCOwnershipAttributedType = [](QualType Ty) { 15120 while (const auto *AttrTy = Ty->getAs<AttributedType>()) { 15121 if (AttrTy->getAttrKind() == attr::ObjCOwnership) 15122 return true; 15123 15124 // Peel off AttributedTypes that are not of kind ObjCOwnership. 15125 Ty = AttrTy->getModifiedType(); 15126 } 15127 15128 return false; 15129 }; 15130 15131 QualType PointeeTy = PT->getPointeeType(); 15132 15133 if (PointeeTy->getAs<ObjCObjectPointerType>() && 15134 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 15135 !IsObjCOwnershipAttributedType(PointeeTy)) { 15136 if (BuildAndDiagnose) { 15137 SourceLocation VarLoc = Var->getLocation(); 15138 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 15139 S.Diag(VarLoc, diag::note_declare_parameter_strong); 15140 } 15141 } 15142 } 15143 15144 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 15145 if (HasBlocksAttr || CaptureType->isReferenceType() || 15146 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 15147 // Block capture by reference does not change the capture or 15148 // declaration reference types. 15149 ByRef = true; 15150 } else { 15151 // Block capture by copy introduces 'const'. 15152 CaptureType = CaptureType.getNonReferenceType().withConst(); 15153 DeclRefType = CaptureType; 15154 15155 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 15156 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 15157 // The capture logic needs the destructor, so make sure we mark it. 15158 // Usually this is unnecessary because most local variables have 15159 // their destructors marked at declaration time, but parameters are 15160 // an exception because it's technically only the call site that 15161 // actually requires the destructor. 15162 if (isa<ParmVarDecl>(Var)) 15163 S.FinalizeVarWithDestructor(Var, Record); 15164 15165 // Enter a new evaluation context to insulate the copy 15166 // full-expression. 15167 EnterExpressionEvaluationContext scope( 15168 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 15169 15170 // According to the blocks spec, the capture of a variable from 15171 // the stack requires a const copy constructor. This is not true 15172 // of the copy/move done to move a __block variable to the heap. 15173 Expr *DeclRef = new (S.Context) DeclRefExpr( 15174 S.Context, Var, Nested, DeclRefType.withConst(), VK_LValue, Loc); 15175 15176 ExprResult Result 15177 = S.PerformCopyInitialization( 15178 InitializedEntity::InitializeBlock(Var->getLocation(), 15179 CaptureType, false), 15180 Loc, DeclRef); 15181 15182 // Build a full-expression copy expression if initialization 15183 // succeeded and used a non-trivial constructor. Recover from 15184 // errors by pretending that the copy isn't necessary. 15185 if (!Result.isInvalid() && 15186 !cast<CXXConstructExpr>(Result.get())->getConstructor() 15187 ->isTrivial()) { 15188 Result = S.MaybeCreateExprWithCleanups(Result); 15189 CopyExpr = Result.get(); 15190 } 15191 } 15192 } 15193 } 15194 15195 // Actually capture the variable. 15196 if (BuildAndDiagnose) 15197 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 15198 SourceLocation(), CaptureType, CopyExpr); 15199 15200 return true; 15201 15202 } 15203 15204 15205 /// Capture the given variable in the captured region. 15206 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 15207 VarDecl *Var, 15208 SourceLocation Loc, 15209 const bool BuildAndDiagnose, 15210 QualType &CaptureType, 15211 QualType &DeclRefType, 15212 const bool RefersToCapturedVariable, 15213 Sema &S) { 15214 // By default, capture variables by reference. 15215 bool ByRef = true; 15216 // Using an LValue reference type is consistent with Lambdas (see below). 15217 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 15218 if (S.isOpenMPCapturedDecl(Var)) { 15219 bool HasConst = DeclRefType.isConstQualified(); 15220 DeclRefType = DeclRefType.getUnqualifiedType(); 15221 // Don't lose diagnostics about assignments to const. 15222 if (HasConst) 15223 DeclRefType.addConst(); 15224 } 15225 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel); 15226 } 15227 15228 if (ByRef) 15229 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 15230 else 15231 CaptureType = DeclRefType; 15232 15233 Expr *CopyExpr = nullptr; 15234 if (BuildAndDiagnose) { 15235 // The current implementation assumes that all variables are captured 15236 // by references. Since there is no capture by copy, no expression 15237 // evaluation will be needed. 15238 RecordDecl *RD = RSI->TheRecordDecl; 15239 15240 FieldDecl *Field 15241 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 15242 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 15243 nullptr, false, ICIS_NoInit); 15244 Field->setImplicit(true); 15245 Field->setAccess(AS_private); 15246 RD->addDecl(Field); 15247 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) 15248 S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel); 15249 15250 CopyExpr = new (S.Context) DeclRefExpr( 15251 S.Context, Var, RefersToCapturedVariable, DeclRefType, VK_LValue, Loc); 15252 Var->setReferenced(true); 15253 Var->markUsed(S.Context); 15254 } 15255 15256 // Actually capture the variable. 15257 if (BuildAndDiagnose) 15258 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 15259 SourceLocation(), CaptureType, CopyExpr); 15260 15261 15262 return true; 15263 } 15264 15265 /// Create a field within the lambda class for the variable 15266 /// being captured. 15267 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, 15268 QualType FieldType, QualType DeclRefType, 15269 SourceLocation Loc, 15270 bool RefersToCapturedVariable) { 15271 CXXRecordDecl *Lambda = LSI->Lambda; 15272 15273 // Build the non-static data member. 15274 FieldDecl *Field 15275 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 15276 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 15277 nullptr, false, ICIS_NoInit); 15278 // If the variable being captured has an invalid type, mark the lambda class 15279 // as invalid as well. 15280 if (!FieldType->isDependentType()) { 15281 if (S.RequireCompleteType(Loc, FieldType, diag::err_field_incomplete)) { 15282 Lambda->setInvalidDecl(); 15283 Field->setInvalidDecl(); 15284 } else { 15285 NamedDecl *Def; 15286 FieldType->isIncompleteType(&Def); 15287 if (Def && Def->isInvalidDecl()) { 15288 Lambda->setInvalidDecl(); 15289 Field->setInvalidDecl(); 15290 } 15291 } 15292 } 15293 Field->setImplicit(true); 15294 Field->setAccess(AS_private); 15295 Lambda->addDecl(Field); 15296 } 15297 15298 /// Capture the given variable in the lambda. 15299 static bool captureInLambda(LambdaScopeInfo *LSI, 15300 VarDecl *Var, 15301 SourceLocation Loc, 15302 const bool BuildAndDiagnose, 15303 QualType &CaptureType, 15304 QualType &DeclRefType, 15305 const bool RefersToCapturedVariable, 15306 const Sema::TryCaptureKind Kind, 15307 SourceLocation EllipsisLoc, 15308 const bool IsTopScope, 15309 Sema &S) { 15310 15311 // Determine whether we are capturing by reference or by value. 15312 bool ByRef = false; 15313 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 15314 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 15315 } else { 15316 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 15317 } 15318 15319 // Compute the type of the field that will capture this variable. 15320 if (ByRef) { 15321 // C++11 [expr.prim.lambda]p15: 15322 // An entity is captured by reference if it is implicitly or 15323 // explicitly captured but not captured by copy. It is 15324 // unspecified whether additional unnamed non-static data 15325 // members are declared in the closure type for entities 15326 // captured by reference. 15327 // 15328 // FIXME: It is not clear whether we want to build an lvalue reference 15329 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 15330 // to do the former, while EDG does the latter. Core issue 1249 will 15331 // clarify, but for now we follow GCC because it's a more permissive and 15332 // easily defensible position. 15333 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 15334 } else { 15335 // C++11 [expr.prim.lambda]p14: 15336 // For each entity captured by copy, an unnamed non-static 15337 // data member is declared in the closure type. The 15338 // declaration order of these members is unspecified. The type 15339 // of such a data member is the type of the corresponding 15340 // captured entity if the entity is not a reference to an 15341 // object, or the referenced type otherwise. [Note: If the 15342 // captured entity is a reference to a function, the 15343 // corresponding data member is also a reference to a 15344 // function. - end note ] 15345 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 15346 if (!RefType->getPointeeType()->isFunctionType()) 15347 CaptureType = RefType->getPointeeType(); 15348 } 15349 15350 // Forbid the lambda copy-capture of autoreleasing variables. 15351 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 15352 if (BuildAndDiagnose) { 15353 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 15354 S.Diag(Var->getLocation(), diag::note_previous_decl) 15355 << Var->getDeclName(); 15356 } 15357 return false; 15358 } 15359 15360 // Make sure that by-copy captures are of a complete and non-abstract type. 15361 if (BuildAndDiagnose) { 15362 if (!CaptureType->isDependentType() && 15363 S.RequireCompleteType(Loc, CaptureType, 15364 diag::err_capture_of_incomplete_type, 15365 Var->getDeclName())) 15366 return false; 15367 15368 if (S.RequireNonAbstractType(Loc, CaptureType, 15369 diag::err_capture_of_abstract_type)) 15370 return false; 15371 } 15372 } 15373 15374 // Capture this variable in the lambda. 15375 if (BuildAndDiagnose) 15376 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc, 15377 RefersToCapturedVariable); 15378 15379 // Compute the type of a reference to this captured variable. 15380 if (ByRef) 15381 DeclRefType = CaptureType.getNonReferenceType(); 15382 else { 15383 // C++ [expr.prim.lambda]p5: 15384 // The closure type for a lambda-expression has a public inline 15385 // function call operator [...]. This function call operator is 15386 // declared const (9.3.1) if and only if the lambda-expression's 15387 // parameter-declaration-clause is not followed by mutable. 15388 DeclRefType = CaptureType.getNonReferenceType(); 15389 if (!LSI->Mutable && !CaptureType->isReferenceType()) 15390 DeclRefType.addConst(); 15391 } 15392 15393 // Add the capture. 15394 if (BuildAndDiagnose) 15395 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 15396 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 15397 15398 return true; 15399 } 15400 15401 bool Sema::tryCaptureVariable( 15402 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 15403 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 15404 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 15405 // An init-capture is notionally from the context surrounding its 15406 // declaration, but its parent DC is the lambda class. 15407 DeclContext *VarDC = Var->getDeclContext(); 15408 if (Var->isInitCapture()) 15409 VarDC = VarDC->getParent(); 15410 15411 DeclContext *DC = CurContext; 15412 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 15413 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 15414 // We need to sync up the Declaration Context with the 15415 // FunctionScopeIndexToStopAt 15416 if (FunctionScopeIndexToStopAt) { 15417 unsigned FSIndex = FunctionScopes.size() - 1; 15418 while (FSIndex != MaxFunctionScopesIndex) { 15419 DC = getLambdaAwareParentOfDeclContext(DC); 15420 --FSIndex; 15421 } 15422 } 15423 15424 15425 // If the variable is declared in the current context, there is no need to 15426 // capture it. 15427 if (VarDC == DC) return true; 15428 15429 // Capture global variables if it is required to use private copy of this 15430 // variable. 15431 bool IsGlobal = !Var->hasLocalStorage(); 15432 if (IsGlobal && !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var))) 15433 return true; 15434 Var = Var->getCanonicalDecl(); 15435 15436 // Walk up the stack to determine whether we can capture the variable, 15437 // performing the "simple" checks that don't depend on type. We stop when 15438 // we've either hit the declared scope of the variable or find an existing 15439 // capture of that variable. We start from the innermost capturing-entity 15440 // (the DC) and ensure that all intervening capturing-entities 15441 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 15442 // declcontext can either capture the variable or have already captured 15443 // the variable. 15444 CaptureType = Var->getType(); 15445 DeclRefType = CaptureType.getNonReferenceType(); 15446 bool Nested = false; 15447 bool Explicit = (Kind != TryCapture_Implicit); 15448 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 15449 do { 15450 // Only block literals, captured statements, and lambda expressions can 15451 // capture; other scopes don't work. 15452 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 15453 ExprLoc, 15454 BuildAndDiagnose, 15455 *this); 15456 // We need to check for the parent *first* because, if we *have* 15457 // private-captured a global variable, we need to recursively capture it in 15458 // intermediate blocks, lambdas, etc. 15459 if (!ParentDC) { 15460 if (IsGlobal) { 15461 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 15462 break; 15463 } 15464 return true; 15465 } 15466 15467 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 15468 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 15469 15470 15471 // Check whether we've already captured it. 15472 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 15473 DeclRefType)) { 15474 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 15475 break; 15476 } 15477 // If we are instantiating a generic lambda call operator body, 15478 // we do not want to capture new variables. What was captured 15479 // during either a lambdas transformation or initial parsing 15480 // should be used. 15481 if (isGenericLambdaCallOperatorSpecialization(DC)) { 15482 if (BuildAndDiagnose) { 15483 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 15484 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 15485 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 15486 Diag(Var->getLocation(), diag::note_previous_decl) 15487 << Var->getDeclName(); 15488 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 15489 } else 15490 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 15491 } 15492 return true; 15493 } 15494 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 15495 // certain types of variables (unnamed, variably modified types etc.) 15496 // so check for eligibility. 15497 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 15498 return true; 15499 15500 // Try to capture variable-length arrays types. 15501 if (Var->getType()->isVariablyModifiedType()) { 15502 // We're going to walk down into the type and look for VLA 15503 // expressions. 15504 QualType QTy = Var->getType(); 15505 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 15506 QTy = PVD->getOriginalType(); 15507 captureVariablyModifiedType(Context, QTy, CSI); 15508 } 15509 15510 if (getLangOpts().OpenMP) { 15511 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 15512 // OpenMP private variables should not be captured in outer scope, so 15513 // just break here. Similarly, global variables that are captured in a 15514 // target region should not be captured outside the scope of the region. 15515 if (RSI->CapRegionKind == CR_OpenMP) { 15516 bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel); 15517 auto IsTargetCap = !IsOpenMPPrivateDecl && 15518 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 15519 // When we detect target captures we are looking from inside the 15520 // target region, therefore we need to propagate the capture from the 15521 // enclosing region. Therefore, the capture is not initially nested. 15522 if (IsTargetCap) 15523 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 15524 15525 if (IsTargetCap || IsOpenMPPrivateDecl) { 15526 Nested = !IsTargetCap; 15527 DeclRefType = DeclRefType.getUnqualifiedType(); 15528 CaptureType = Context.getLValueReferenceType(DeclRefType); 15529 break; 15530 } 15531 } 15532 } 15533 } 15534 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 15535 // No capture-default, and this is not an explicit capture 15536 // so cannot capture this variable. 15537 if (BuildAndDiagnose) { 15538 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 15539 Diag(Var->getLocation(), diag::note_previous_decl) 15540 << Var->getDeclName(); 15541 if (cast<LambdaScopeInfo>(CSI)->Lambda) 15542 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(), 15543 diag::note_lambda_decl); 15544 // FIXME: If we error out because an outer lambda can not implicitly 15545 // capture a variable that an inner lambda explicitly captures, we 15546 // should have the inner lambda do the explicit capture - because 15547 // it makes for cleaner diagnostics later. This would purely be done 15548 // so that the diagnostic does not misleadingly claim that a variable 15549 // can not be captured by a lambda implicitly even though it is captured 15550 // explicitly. Suggestion: 15551 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 15552 // at the function head 15553 // - cache the StartingDeclContext - this must be a lambda 15554 // - captureInLambda in the innermost lambda the variable. 15555 } 15556 return true; 15557 } 15558 15559 FunctionScopesIndex--; 15560 DC = ParentDC; 15561 Explicit = false; 15562 } while (!VarDC->Equals(DC)); 15563 15564 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 15565 // computing the type of the capture at each step, checking type-specific 15566 // requirements, and adding captures if requested. 15567 // If the variable had already been captured previously, we start capturing 15568 // at the lambda nested within that one. 15569 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 15570 ++I) { 15571 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 15572 15573 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 15574 if (!captureInBlock(BSI, Var, ExprLoc, 15575 BuildAndDiagnose, CaptureType, 15576 DeclRefType, Nested, *this)) 15577 return true; 15578 Nested = true; 15579 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 15580 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 15581 BuildAndDiagnose, CaptureType, 15582 DeclRefType, Nested, *this)) 15583 return true; 15584 Nested = true; 15585 } else { 15586 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 15587 if (!captureInLambda(LSI, Var, ExprLoc, 15588 BuildAndDiagnose, CaptureType, 15589 DeclRefType, Nested, Kind, EllipsisLoc, 15590 /*IsTopScope*/I == N - 1, *this)) 15591 return true; 15592 Nested = true; 15593 } 15594 } 15595 return false; 15596 } 15597 15598 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 15599 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 15600 QualType CaptureType; 15601 QualType DeclRefType; 15602 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 15603 /*BuildAndDiagnose=*/true, CaptureType, 15604 DeclRefType, nullptr); 15605 } 15606 15607 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 15608 QualType CaptureType; 15609 QualType DeclRefType; 15610 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 15611 /*BuildAndDiagnose=*/false, CaptureType, 15612 DeclRefType, nullptr); 15613 } 15614 15615 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 15616 QualType CaptureType; 15617 QualType DeclRefType; 15618 15619 // Determine whether we can capture this variable. 15620 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 15621 /*BuildAndDiagnose=*/false, CaptureType, 15622 DeclRefType, nullptr)) 15623 return QualType(); 15624 15625 return DeclRefType; 15626 } 15627 15628 15629 15630 // If either the type of the variable or the initializer is dependent, 15631 // return false. Otherwise, determine whether the variable is a constant 15632 // expression. Use this if you need to know if a variable that might or 15633 // might not be dependent is truly a constant expression. 15634 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 15635 ASTContext &Context) { 15636 15637 if (Var->getType()->isDependentType()) 15638 return false; 15639 const VarDecl *DefVD = nullptr; 15640 Var->getAnyInitializer(DefVD); 15641 if (!DefVD) 15642 return false; 15643 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 15644 Expr *Init = cast<Expr>(Eval->Value); 15645 if (Init->isValueDependent()) 15646 return false; 15647 return IsVariableAConstantExpression(Var, Context); 15648 } 15649 15650 15651 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 15652 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 15653 // an object that satisfies the requirements for appearing in a 15654 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 15655 // is immediately applied." This function handles the lvalue-to-rvalue 15656 // conversion part. 15657 MaybeODRUseExprs.erase(E->IgnoreParens()); 15658 15659 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 15660 // to a variable that is a constant expression, and if so, identify it as 15661 // a reference to a variable that does not involve an odr-use of that 15662 // variable. 15663 if (LambdaScopeInfo *LSI = getCurLambda()) { 15664 Expr *SansParensExpr = E->IgnoreParens(); 15665 VarDecl *Var = nullptr; 15666 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 15667 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 15668 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 15669 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 15670 15671 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 15672 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 15673 } 15674 } 15675 15676 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 15677 Res = CorrectDelayedTyposInExpr(Res); 15678 15679 if (!Res.isUsable()) 15680 return Res; 15681 15682 // If a constant-expression is a reference to a variable where we delay 15683 // deciding whether it is an odr-use, just assume we will apply the 15684 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 15685 // (a non-type template argument), we have special handling anyway. 15686 UpdateMarkingForLValueToRValue(Res.get()); 15687 return Res; 15688 } 15689 15690 void Sema::CleanupVarDeclMarking() { 15691 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 15692 // call. 15693 MaybeODRUseExprSet LocalMaybeODRUseExprs; 15694 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 15695 15696 for (Expr *E : LocalMaybeODRUseExprs) { 15697 VarDecl *Var; 15698 SourceLocation Loc; 15699 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 15700 Var = cast<VarDecl>(DRE->getDecl()); 15701 Loc = DRE->getLocation(); 15702 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 15703 Var = cast<VarDecl>(ME->getMemberDecl()); 15704 Loc = ME->getMemberLoc(); 15705 } else { 15706 llvm_unreachable("Unexpected expression"); 15707 } 15708 15709 MarkVarDeclODRUsed(Var, Loc, *this, 15710 /*MaxFunctionScopeIndex Pointer*/ nullptr); 15711 } 15712 15713 assert(MaybeODRUseExprs.empty() && 15714 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 15715 } 15716 15717 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 15718 VarDecl *Var, Expr *E) { 15719 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 15720 "Invalid Expr argument to DoMarkVarDeclReferenced"); 15721 Var->setReferenced(); 15722 15723 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 15724 15725 bool OdrUseContext = isOdrUseContext(SemaRef); 15726 bool UsableInConstantExpr = 15727 Var->isUsableInConstantExpressions(SemaRef.Context); 15728 bool NeedDefinition = 15729 OdrUseContext || (isEvaluatableContext(SemaRef) && UsableInConstantExpr); 15730 15731 VarTemplateSpecializationDecl *VarSpec = 15732 dyn_cast<VarTemplateSpecializationDecl>(Var); 15733 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 15734 "Can't instantiate a partial template specialization."); 15735 15736 // If this might be a member specialization of a static data member, check 15737 // the specialization is visible. We already did the checks for variable 15738 // template specializations when we created them. 15739 if (NeedDefinition && TSK != TSK_Undeclared && 15740 !isa<VarTemplateSpecializationDecl>(Var)) 15741 SemaRef.checkSpecializationVisibility(Loc, Var); 15742 15743 // Perform implicit instantiation of static data members, static data member 15744 // templates of class templates, and variable template specializations. Delay 15745 // instantiations of variable templates, except for those that could be used 15746 // in a constant expression. 15747 if (NeedDefinition && isTemplateInstantiation(TSK)) { 15748 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 15749 // instantiation declaration if a variable is usable in a constant 15750 // expression (among other cases). 15751 bool TryInstantiating = 15752 TSK == TSK_ImplicitInstantiation || 15753 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 15754 15755 if (TryInstantiating) { 15756 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 15757 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 15758 if (FirstInstantiation) { 15759 PointOfInstantiation = Loc; 15760 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 15761 } 15762 15763 bool InstantiationDependent = false; 15764 bool IsNonDependent = 15765 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 15766 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 15767 : true; 15768 15769 // Do not instantiate specializations that are still type-dependent. 15770 if (IsNonDependent) { 15771 if (UsableInConstantExpr) { 15772 // Do not defer instantiations of variables that could be used in a 15773 // constant expression. 15774 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 15775 } else if (FirstInstantiation || 15776 isa<VarTemplateSpecializationDecl>(Var)) { 15777 // FIXME: For a specialization of a variable template, we don't 15778 // distinguish between "declaration and type implicitly instantiated" 15779 // and "implicit instantiation of definition requested", so we have 15780 // no direct way to avoid enqueueing the pending instantiation 15781 // multiple times. 15782 SemaRef.PendingInstantiations 15783 .push_back(std::make_pair(Var, PointOfInstantiation)); 15784 } 15785 } 15786 } 15787 } 15788 15789 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 15790 // the requirements for appearing in a constant expression (5.19) and, if 15791 // it is an object, the lvalue-to-rvalue conversion (4.1) 15792 // is immediately applied." We check the first part here, and 15793 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 15794 // Note that we use the C++11 definition everywhere because nothing in 15795 // C++03 depends on whether we get the C++03 version correct. The second 15796 // part does not apply to references, since they are not objects. 15797 if (OdrUseContext && E && 15798 IsVariableAConstantExpression(Var, SemaRef.Context)) { 15799 // A reference initialized by a constant expression can never be 15800 // odr-used, so simply ignore it. 15801 if (!Var->getType()->isReferenceType() || 15802 (SemaRef.LangOpts.OpenMP && SemaRef.isOpenMPCapturedDecl(Var))) 15803 SemaRef.MaybeODRUseExprs.insert(E); 15804 } else if (OdrUseContext) { 15805 MarkVarDeclODRUsed(Var, Loc, SemaRef, 15806 /*MaxFunctionScopeIndex ptr*/ nullptr); 15807 } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) { 15808 // If this is a dependent context, we don't need to mark variables as 15809 // odr-used, but we may still need to track them for lambda capture. 15810 // FIXME: Do we also need to do this inside dependent typeid expressions 15811 // (which are modeled as unevaluated at this point)? 15812 const bool RefersToEnclosingScope = 15813 (SemaRef.CurContext != Var->getDeclContext() && 15814 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 15815 if (RefersToEnclosingScope) { 15816 LambdaScopeInfo *const LSI = 15817 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 15818 if (LSI && (!LSI->CallOperator || 15819 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 15820 // If a variable could potentially be odr-used, defer marking it so 15821 // until we finish analyzing the full expression for any 15822 // lvalue-to-rvalue 15823 // or discarded value conversions that would obviate odr-use. 15824 // Add it to the list of potential captures that will be analyzed 15825 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 15826 // unless the variable is a reference that was initialized by a constant 15827 // expression (this will never need to be captured or odr-used). 15828 assert(E && "Capture variable should be used in an expression."); 15829 if (!Var->getType()->isReferenceType() || 15830 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 15831 LSI->addPotentialCapture(E->IgnoreParens()); 15832 } 15833 } 15834 } 15835 } 15836 15837 /// Mark a variable referenced, and check whether it is odr-used 15838 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 15839 /// used directly for normal expressions referring to VarDecl. 15840 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 15841 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 15842 } 15843 15844 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 15845 Decl *D, Expr *E, bool MightBeOdrUse) { 15846 if (SemaRef.isInOpenMPDeclareTargetContext()) 15847 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 15848 15849 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 15850 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 15851 return; 15852 } 15853 15854 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 15855 15856 // If this is a call to a method via a cast, also mark the method in the 15857 // derived class used in case codegen can devirtualize the call. 15858 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 15859 if (!ME) 15860 return; 15861 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 15862 if (!MD) 15863 return; 15864 // Only attempt to devirtualize if this is truly a virtual call. 15865 bool IsVirtualCall = MD->isVirtual() && 15866 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 15867 if (!IsVirtualCall) 15868 return; 15869 15870 // If it's possible to devirtualize the call, mark the called function 15871 // referenced. 15872 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 15873 ME->getBase(), SemaRef.getLangOpts().AppleKext); 15874 if (DM) 15875 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 15876 } 15877 15878 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 15879 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 15880 // TODO: update this with DR# once a defect report is filed. 15881 // C++11 defect. The address of a pure member should not be an ODR use, even 15882 // if it's a qualified reference. 15883 bool OdrUse = true; 15884 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 15885 if (Method->isVirtual() && 15886 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 15887 OdrUse = false; 15888 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 15889 } 15890 15891 /// Perform reference-marking and odr-use handling for a MemberExpr. 15892 void Sema::MarkMemberReferenced(MemberExpr *E) { 15893 // C++11 [basic.def.odr]p2: 15894 // A non-overloaded function whose name appears as a potentially-evaluated 15895 // expression or a member of a set of candidate functions, if selected by 15896 // overload resolution when referred to from a potentially-evaluated 15897 // expression, is odr-used, unless it is a pure virtual function and its 15898 // name is not explicitly qualified. 15899 bool MightBeOdrUse = true; 15900 if (E->performsVirtualDispatch(getLangOpts())) { 15901 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 15902 if (Method->isPure()) 15903 MightBeOdrUse = false; 15904 } 15905 SourceLocation Loc = 15906 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 15907 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 15908 } 15909 15910 /// Perform marking for a reference to an arbitrary declaration. It 15911 /// marks the declaration referenced, and performs odr-use checking for 15912 /// functions and variables. This method should not be used when building a 15913 /// normal expression which refers to a variable. 15914 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 15915 bool MightBeOdrUse) { 15916 if (MightBeOdrUse) { 15917 if (auto *VD = dyn_cast<VarDecl>(D)) { 15918 MarkVariableReferenced(Loc, VD); 15919 return; 15920 } 15921 } 15922 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 15923 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 15924 return; 15925 } 15926 D->setReferenced(); 15927 } 15928 15929 namespace { 15930 // Mark all of the declarations used by a type as referenced. 15931 // FIXME: Not fully implemented yet! We need to have a better understanding 15932 // of when we're entering a context we should not recurse into. 15933 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 15934 // TreeTransforms rebuilding the type in a new context. Rather than 15935 // duplicating the TreeTransform logic, we should consider reusing it here. 15936 // Currently that causes problems when rebuilding LambdaExprs. 15937 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 15938 Sema &S; 15939 SourceLocation Loc; 15940 15941 public: 15942 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 15943 15944 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 15945 15946 bool TraverseTemplateArgument(const TemplateArgument &Arg); 15947 }; 15948 } 15949 15950 bool MarkReferencedDecls::TraverseTemplateArgument( 15951 const TemplateArgument &Arg) { 15952 { 15953 // A non-type template argument is a constant-evaluated context. 15954 EnterExpressionEvaluationContext Evaluated( 15955 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 15956 if (Arg.getKind() == TemplateArgument::Declaration) { 15957 if (Decl *D = Arg.getAsDecl()) 15958 S.MarkAnyDeclReferenced(Loc, D, true); 15959 } else if (Arg.getKind() == TemplateArgument::Expression) { 15960 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 15961 } 15962 } 15963 15964 return Inherited::TraverseTemplateArgument(Arg); 15965 } 15966 15967 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 15968 MarkReferencedDecls Marker(*this, Loc); 15969 Marker.TraverseType(T); 15970 } 15971 15972 namespace { 15973 /// Helper class that marks all of the declarations referenced by 15974 /// potentially-evaluated subexpressions as "referenced". 15975 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 15976 Sema &S; 15977 bool SkipLocalVariables; 15978 15979 public: 15980 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 15981 15982 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 15983 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 15984 15985 void VisitDeclRefExpr(DeclRefExpr *E) { 15986 // If we were asked not to visit local variables, don't. 15987 if (SkipLocalVariables) { 15988 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 15989 if (VD->hasLocalStorage()) 15990 return; 15991 } 15992 15993 S.MarkDeclRefReferenced(E); 15994 } 15995 15996 void VisitMemberExpr(MemberExpr *E) { 15997 S.MarkMemberReferenced(E); 15998 Inherited::VisitMemberExpr(E); 15999 } 16000 16001 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 16002 S.MarkFunctionReferenced( 16003 E->getBeginLoc(), 16004 const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor())); 16005 Visit(E->getSubExpr()); 16006 } 16007 16008 void VisitCXXNewExpr(CXXNewExpr *E) { 16009 if (E->getOperatorNew()) 16010 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew()); 16011 if (E->getOperatorDelete()) 16012 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete()); 16013 Inherited::VisitCXXNewExpr(E); 16014 } 16015 16016 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 16017 if (E->getOperatorDelete()) 16018 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete()); 16019 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 16020 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 16021 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 16022 S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record)); 16023 } 16024 16025 Inherited::VisitCXXDeleteExpr(E); 16026 } 16027 16028 void VisitCXXConstructExpr(CXXConstructExpr *E) { 16029 S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor()); 16030 Inherited::VisitCXXConstructExpr(E); 16031 } 16032 16033 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 16034 Visit(E->getExpr()); 16035 } 16036 16037 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 16038 Inherited::VisitImplicitCastExpr(E); 16039 16040 if (E->getCastKind() == CK_LValueToRValue) 16041 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 16042 } 16043 }; 16044 } 16045 16046 /// Mark any declarations that appear within this expression or any 16047 /// potentially-evaluated subexpressions as "referenced". 16048 /// 16049 /// \param SkipLocalVariables If true, don't mark local variables as 16050 /// 'referenced'. 16051 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 16052 bool SkipLocalVariables) { 16053 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 16054 } 16055 16056 /// Emit a diagnostic that describes an effect on the run-time behavior 16057 /// of the program being compiled. 16058 /// 16059 /// This routine emits the given diagnostic when the code currently being 16060 /// type-checked is "potentially evaluated", meaning that there is a 16061 /// possibility that the code will actually be executable. Code in sizeof() 16062 /// expressions, code used only during overload resolution, etc., are not 16063 /// potentially evaluated. This routine will suppress such diagnostics or, 16064 /// in the absolutely nutty case of potentially potentially evaluated 16065 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 16066 /// later. 16067 /// 16068 /// This routine should be used for all diagnostics that describe the run-time 16069 /// behavior of a program, such as passing a non-POD value through an ellipsis. 16070 /// Failure to do so will likely result in spurious diagnostics or failures 16071 /// during overload resolution or within sizeof/alignof/typeof/typeid. 16072 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 16073 const PartialDiagnostic &PD) { 16074 switch (ExprEvalContexts.back().Context) { 16075 case ExpressionEvaluationContext::Unevaluated: 16076 case ExpressionEvaluationContext::UnevaluatedList: 16077 case ExpressionEvaluationContext::UnevaluatedAbstract: 16078 case ExpressionEvaluationContext::DiscardedStatement: 16079 // The argument will never be evaluated, so don't complain. 16080 break; 16081 16082 case ExpressionEvaluationContext::ConstantEvaluated: 16083 // Relevant diagnostics should be produced by constant evaluation. 16084 break; 16085 16086 case ExpressionEvaluationContext::PotentiallyEvaluated: 16087 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16088 if (Statement && getCurFunctionOrMethodDecl()) { 16089 FunctionScopes.back()->PossiblyUnreachableDiags. 16090 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 16091 return true; 16092 } 16093 16094 // The initializer of a constexpr variable or of the first declaration of a 16095 // static data member is not syntactically a constant evaluated constant, 16096 // but nonetheless is always required to be a constant expression, so we 16097 // can skip diagnosing. 16098 // FIXME: Using the mangling context here is a hack. 16099 if (auto *VD = dyn_cast_or_null<VarDecl>( 16100 ExprEvalContexts.back().ManglingContextDecl)) { 16101 if (VD->isConstexpr() || 16102 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 16103 break; 16104 // FIXME: For any other kind of variable, we should build a CFG for its 16105 // initializer and check whether the context in question is reachable. 16106 } 16107 16108 Diag(Loc, PD); 16109 return true; 16110 } 16111 16112 return false; 16113 } 16114 16115 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 16116 CallExpr *CE, FunctionDecl *FD) { 16117 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 16118 return false; 16119 16120 // If we're inside a decltype's expression, don't check for a valid return 16121 // type or construct temporaries until we know whether this is the last call. 16122 if (ExprEvalContexts.back().ExprContext == 16123 ExpressionEvaluationContextRecord::EK_Decltype) { 16124 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 16125 return false; 16126 } 16127 16128 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 16129 FunctionDecl *FD; 16130 CallExpr *CE; 16131 16132 public: 16133 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 16134 : FD(FD), CE(CE) { } 16135 16136 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 16137 if (!FD) { 16138 S.Diag(Loc, diag::err_call_incomplete_return) 16139 << T << CE->getSourceRange(); 16140 return; 16141 } 16142 16143 S.Diag(Loc, diag::err_call_function_incomplete_return) 16144 << CE->getSourceRange() << FD->getDeclName() << T; 16145 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 16146 << FD->getDeclName(); 16147 } 16148 } Diagnoser(FD, CE); 16149 16150 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 16151 return true; 16152 16153 return false; 16154 } 16155 16156 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 16157 // will prevent this condition from triggering, which is what we want. 16158 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 16159 SourceLocation Loc; 16160 16161 unsigned diagnostic = diag::warn_condition_is_assignment; 16162 bool IsOrAssign = false; 16163 16164 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 16165 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 16166 return; 16167 16168 IsOrAssign = Op->getOpcode() == BO_OrAssign; 16169 16170 // Greylist some idioms by putting them into a warning subcategory. 16171 if (ObjCMessageExpr *ME 16172 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 16173 Selector Sel = ME->getSelector(); 16174 16175 // self = [<foo> init...] 16176 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 16177 diagnostic = diag::warn_condition_is_idiomatic_assignment; 16178 16179 // <foo> = [<bar> nextObject] 16180 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 16181 diagnostic = diag::warn_condition_is_idiomatic_assignment; 16182 } 16183 16184 Loc = Op->getOperatorLoc(); 16185 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 16186 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 16187 return; 16188 16189 IsOrAssign = Op->getOperator() == OO_PipeEqual; 16190 Loc = Op->getOperatorLoc(); 16191 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 16192 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 16193 else { 16194 // Not an assignment. 16195 return; 16196 } 16197 16198 Diag(Loc, diagnostic) << E->getSourceRange(); 16199 16200 SourceLocation Open = E->getBeginLoc(); 16201 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 16202 Diag(Loc, diag::note_condition_assign_silence) 16203 << FixItHint::CreateInsertion(Open, "(") 16204 << FixItHint::CreateInsertion(Close, ")"); 16205 16206 if (IsOrAssign) 16207 Diag(Loc, diag::note_condition_or_assign_to_comparison) 16208 << FixItHint::CreateReplacement(Loc, "!="); 16209 else 16210 Diag(Loc, diag::note_condition_assign_to_comparison) 16211 << FixItHint::CreateReplacement(Loc, "=="); 16212 } 16213 16214 /// Redundant parentheses over an equality comparison can indicate 16215 /// that the user intended an assignment used as condition. 16216 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 16217 // Don't warn if the parens came from a macro. 16218 SourceLocation parenLoc = ParenE->getBeginLoc(); 16219 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 16220 return; 16221 // Don't warn for dependent expressions. 16222 if (ParenE->isTypeDependent()) 16223 return; 16224 16225 Expr *E = ParenE->IgnoreParens(); 16226 16227 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 16228 if (opE->getOpcode() == BO_EQ && 16229 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 16230 == Expr::MLV_Valid) { 16231 SourceLocation Loc = opE->getOperatorLoc(); 16232 16233 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 16234 SourceRange ParenERange = ParenE->getSourceRange(); 16235 Diag(Loc, diag::note_equality_comparison_silence) 16236 << FixItHint::CreateRemoval(ParenERange.getBegin()) 16237 << FixItHint::CreateRemoval(ParenERange.getEnd()); 16238 Diag(Loc, diag::note_equality_comparison_to_assign) 16239 << FixItHint::CreateReplacement(Loc, "="); 16240 } 16241 } 16242 16243 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 16244 bool IsConstexpr) { 16245 DiagnoseAssignmentAsCondition(E); 16246 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 16247 DiagnoseEqualityWithExtraParens(parenE); 16248 16249 ExprResult result = CheckPlaceholderExpr(E); 16250 if (result.isInvalid()) return ExprError(); 16251 E = result.get(); 16252 16253 if (!E->isTypeDependent()) { 16254 if (getLangOpts().CPlusPlus) 16255 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 16256 16257 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 16258 if (ERes.isInvalid()) 16259 return ExprError(); 16260 E = ERes.get(); 16261 16262 QualType T = E->getType(); 16263 if (!T->isScalarType()) { // C99 6.8.4.1p1 16264 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 16265 << T << E->getSourceRange(); 16266 return ExprError(); 16267 } 16268 CheckBoolLikeConversion(E, Loc); 16269 } 16270 16271 return E; 16272 } 16273 16274 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 16275 Expr *SubExpr, ConditionKind CK) { 16276 // Empty conditions are valid in for-statements. 16277 if (!SubExpr) 16278 return ConditionResult(); 16279 16280 ExprResult Cond; 16281 switch (CK) { 16282 case ConditionKind::Boolean: 16283 Cond = CheckBooleanCondition(Loc, SubExpr); 16284 break; 16285 16286 case ConditionKind::ConstexprIf: 16287 Cond = CheckBooleanCondition(Loc, SubExpr, true); 16288 break; 16289 16290 case ConditionKind::Switch: 16291 Cond = CheckSwitchCondition(Loc, SubExpr); 16292 break; 16293 } 16294 if (Cond.isInvalid()) 16295 return ConditionError(); 16296 16297 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 16298 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 16299 if (!FullExpr.get()) 16300 return ConditionError(); 16301 16302 return ConditionResult(*this, nullptr, FullExpr, 16303 CK == ConditionKind::ConstexprIf); 16304 } 16305 16306 namespace { 16307 /// A visitor for rebuilding a call to an __unknown_any expression 16308 /// to have an appropriate type. 16309 struct RebuildUnknownAnyFunction 16310 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 16311 16312 Sema &S; 16313 16314 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 16315 16316 ExprResult VisitStmt(Stmt *S) { 16317 llvm_unreachable("unexpected statement!"); 16318 } 16319 16320 ExprResult VisitExpr(Expr *E) { 16321 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 16322 << E->getSourceRange(); 16323 return ExprError(); 16324 } 16325 16326 /// Rebuild an expression which simply semantically wraps another 16327 /// expression which it shares the type and value kind of. 16328 template <class T> ExprResult rebuildSugarExpr(T *E) { 16329 ExprResult SubResult = Visit(E->getSubExpr()); 16330 if (SubResult.isInvalid()) return ExprError(); 16331 16332 Expr *SubExpr = SubResult.get(); 16333 E->setSubExpr(SubExpr); 16334 E->setType(SubExpr->getType()); 16335 E->setValueKind(SubExpr->getValueKind()); 16336 assert(E->getObjectKind() == OK_Ordinary); 16337 return E; 16338 } 16339 16340 ExprResult VisitParenExpr(ParenExpr *E) { 16341 return rebuildSugarExpr(E); 16342 } 16343 16344 ExprResult VisitUnaryExtension(UnaryOperator *E) { 16345 return rebuildSugarExpr(E); 16346 } 16347 16348 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 16349 ExprResult SubResult = Visit(E->getSubExpr()); 16350 if (SubResult.isInvalid()) return ExprError(); 16351 16352 Expr *SubExpr = SubResult.get(); 16353 E->setSubExpr(SubExpr); 16354 E->setType(S.Context.getPointerType(SubExpr->getType())); 16355 assert(E->getValueKind() == VK_RValue); 16356 assert(E->getObjectKind() == OK_Ordinary); 16357 return E; 16358 } 16359 16360 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 16361 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 16362 16363 E->setType(VD->getType()); 16364 16365 assert(E->getValueKind() == VK_RValue); 16366 if (S.getLangOpts().CPlusPlus && 16367 !(isa<CXXMethodDecl>(VD) && 16368 cast<CXXMethodDecl>(VD)->isInstance())) 16369 E->setValueKind(VK_LValue); 16370 16371 return E; 16372 } 16373 16374 ExprResult VisitMemberExpr(MemberExpr *E) { 16375 return resolveDecl(E, E->getMemberDecl()); 16376 } 16377 16378 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 16379 return resolveDecl(E, E->getDecl()); 16380 } 16381 }; 16382 } 16383 16384 /// Given a function expression of unknown-any type, try to rebuild it 16385 /// to have a function type. 16386 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 16387 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 16388 if (Result.isInvalid()) return ExprError(); 16389 return S.DefaultFunctionArrayConversion(Result.get()); 16390 } 16391 16392 namespace { 16393 /// A visitor for rebuilding an expression of type __unknown_anytype 16394 /// into one which resolves the type directly on the referring 16395 /// expression. Strict preservation of the original source 16396 /// structure is not a goal. 16397 struct RebuildUnknownAnyExpr 16398 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 16399 16400 Sema &S; 16401 16402 /// The current destination type. 16403 QualType DestType; 16404 16405 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 16406 : S(S), DestType(CastType) {} 16407 16408 ExprResult VisitStmt(Stmt *S) { 16409 llvm_unreachable("unexpected statement!"); 16410 } 16411 16412 ExprResult VisitExpr(Expr *E) { 16413 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 16414 << E->getSourceRange(); 16415 return ExprError(); 16416 } 16417 16418 ExprResult VisitCallExpr(CallExpr *E); 16419 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 16420 16421 /// Rebuild an expression which simply semantically wraps another 16422 /// expression which it shares the type and value kind of. 16423 template <class T> ExprResult rebuildSugarExpr(T *E) { 16424 ExprResult SubResult = Visit(E->getSubExpr()); 16425 if (SubResult.isInvalid()) return ExprError(); 16426 Expr *SubExpr = SubResult.get(); 16427 E->setSubExpr(SubExpr); 16428 E->setType(SubExpr->getType()); 16429 E->setValueKind(SubExpr->getValueKind()); 16430 assert(E->getObjectKind() == OK_Ordinary); 16431 return E; 16432 } 16433 16434 ExprResult VisitParenExpr(ParenExpr *E) { 16435 return rebuildSugarExpr(E); 16436 } 16437 16438 ExprResult VisitUnaryExtension(UnaryOperator *E) { 16439 return rebuildSugarExpr(E); 16440 } 16441 16442 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 16443 const PointerType *Ptr = DestType->getAs<PointerType>(); 16444 if (!Ptr) { 16445 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 16446 << E->getSourceRange(); 16447 return ExprError(); 16448 } 16449 16450 if (isa<CallExpr>(E->getSubExpr())) { 16451 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 16452 << E->getSourceRange(); 16453 return ExprError(); 16454 } 16455 16456 assert(E->getValueKind() == VK_RValue); 16457 assert(E->getObjectKind() == OK_Ordinary); 16458 E->setType(DestType); 16459 16460 // Build the sub-expression as if it were an object of the pointee type. 16461 DestType = Ptr->getPointeeType(); 16462 ExprResult SubResult = Visit(E->getSubExpr()); 16463 if (SubResult.isInvalid()) return ExprError(); 16464 E->setSubExpr(SubResult.get()); 16465 return E; 16466 } 16467 16468 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 16469 16470 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 16471 16472 ExprResult VisitMemberExpr(MemberExpr *E) { 16473 return resolveDecl(E, E->getMemberDecl()); 16474 } 16475 16476 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 16477 return resolveDecl(E, E->getDecl()); 16478 } 16479 }; 16480 } 16481 16482 /// Rebuilds a call expression which yielded __unknown_anytype. 16483 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 16484 Expr *CalleeExpr = E->getCallee(); 16485 16486 enum FnKind { 16487 FK_MemberFunction, 16488 FK_FunctionPointer, 16489 FK_BlockPointer 16490 }; 16491 16492 FnKind Kind; 16493 QualType CalleeType = CalleeExpr->getType(); 16494 if (CalleeType == S.Context.BoundMemberTy) { 16495 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 16496 Kind = FK_MemberFunction; 16497 CalleeType = Expr::findBoundMemberType(CalleeExpr); 16498 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 16499 CalleeType = Ptr->getPointeeType(); 16500 Kind = FK_FunctionPointer; 16501 } else { 16502 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 16503 Kind = FK_BlockPointer; 16504 } 16505 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 16506 16507 // Verify that this is a legal result type of a function. 16508 if (DestType->isArrayType() || DestType->isFunctionType()) { 16509 unsigned diagID = diag::err_func_returning_array_function; 16510 if (Kind == FK_BlockPointer) 16511 diagID = diag::err_block_returning_array_function; 16512 16513 S.Diag(E->getExprLoc(), diagID) 16514 << DestType->isFunctionType() << DestType; 16515 return ExprError(); 16516 } 16517 16518 // Otherwise, go ahead and set DestType as the call's result. 16519 E->setType(DestType.getNonLValueExprType(S.Context)); 16520 E->setValueKind(Expr::getValueKindForType(DestType)); 16521 assert(E->getObjectKind() == OK_Ordinary); 16522 16523 // Rebuild the function type, replacing the result type with DestType. 16524 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 16525 if (Proto) { 16526 // __unknown_anytype(...) is a special case used by the debugger when 16527 // it has no idea what a function's signature is. 16528 // 16529 // We want to build this call essentially under the K&R 16530 // unprototyped rules, but making a FunctionNoProtoType in C++ 16531 // would foul up all sorts of assumptions. However, we cannot 16532 // simply pass all arguments as variadic arguments, nor can we 16533 // portably just call the function under a non-variadic type; see 16534 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 16535 // However, it turns out that in practice it is generally safe to 16536 // call a function declared as "A foo(B,C,D);" under the prototype 16537 // "A foo(B,C,D,...);". The only known exception is with the 16538 // Windows ABI, where any variadic function is implicitly cdecl 16539 // regardless of its normal CC. Therefore we change the parameter 16540 // types to match the types of the arguments. 16541 // 16542 // This is a hack, but it is far superior to moving the 16543 // corresponding target-specific code from IR-gen to Sema/AST. 16544 16545 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 16546 SmallVector<QualType, 8> ArgTypes; 16547 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 16548 ArgTypes.reserve(E->getNumArgs()); 16549 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 16550 Expr *Arg = E->getArg(i); 16551 QualType ArgType = Arg->getType(); 16552 if (E->isLValue()) { 16553 ArgType = S.Context.getLValueReferenceType(ArgType); 16554 } else if (E->isXValue()) { 16555 ArgType = S.Context.getRValueReferenceType(ArgType); 16556 } 16557 ArgTypes.push_back(ArgType); 16558 } 16559 ParamTypes = ArgTypes; 16560 } 16561 DestType = S.Context.getFunctionType(DestType, ParamTypes, 16562 Proto->getExtProtoInfo()); 16563 } else { 16564 DestType = S.Context.getFunctionNoProtoType(DestType, 16565 FnType->getExtInfo()); 16566 } 16567 16568 // Rebuild the appropriate pointer-to-function type. 16569 switch (Kind) { 16570 case FK_MemberFunction: 16571 // Nothing to do. 16572 break; 16573 16574 case FK_FunctionPointer: 16575 DestType = S.Context.getPointerType(DestType); 16576 break; 16577 16578 case FK_BlockPointer: 16579 DestType = S.Context.getBlockPointerType(DestType); 16580 break; 16581 } 16582 16583 // Finally, we can recurse. 16584 ExprResult CalleeResult = Visit(CalleeExpr); 16585 if (!CalleeResult.isUsable()) return ExprError(); 16586 E->setCallee(CalleeResult.get()); 16587 16588 // Bind a temporary if necessary. 16589 return S.MaybeBindToTemporary(E); 16590 } 16591 16592 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 16593 // Verify that this is a legal result type of a call. 16594 if (DestType->isArrayType() || DestType->isFunctionType()) { 16595 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 16596 << DestType->isFunctionType() << DestType; 16597 return ExprError(); 16598 } 16599 16600 // Rewrite the method result type if available. 16601 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 16602 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 16603 Method->setReturnType(DestType); 16604 } 16605 16606 // Change the type of the message. 16607 E->setType(DestType.getNonReferenceType()); 16608 E->setValueKind(Expr::getValueKindForType(DestType)); 16609 16610 return S.MaybeBindToTemporary(E); 16611 } 16612 16613 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 16614 // The only case we should ever see here is a function-to-pointer decay. 16615 if (E->getCastKind() == CK_FunctionToPointerDecay) { 16616 assert(E->getValueKind() == VK_RValue); 16617 assert(E->getObjectKind() == OK_Ordinary); 16618 16619 E->setType(DestType); 16620 16621 // Rebuild the sub-expression as the pointee (function) type. 16622 DestType = DestType->castAs<PointerType>()->getPointeeType(); 16623 16624 ExprResult Result = Visit(E->getSubExpr()); 16625 if (!Result.isUsable()) return ExprError(); 16626 16627 E->setSubExpr(Result.get()); 16628 return E; 16629 } else if (E->getCastKind() == CK_LValueToRValue) { 16630 assert(E->getValueKind() == VK_RValue); 16631 assert(E->getObjectKind() == OK_Ordinary); 16632 16633 assert(isa<BlockPointerType>(E->getType())); 16634 16635 E->setType(DestType); 16636 16637 // The sub-expression has to be a lvalue reference, so rebuild it as such. 16638 DestType = S.Context.getLValueReferenceType(DestType); 16639 16640 ExprResult Result = Visit(E->getSubExpr()); 16641 if (!Result.isUsable()) return ExprError(); 16642 16643 E->setSubExpr(Result.get()); 16644 return E; 16645 } else { 16646 llvm_unreachable("Unhandled cast type!"); 16647 } 16648 } 16649 16650 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 16651 ExprValueKind ValueKind = VK_LValue; 16652 QualType Type = DestType; 16653 16654 // We know how to make this work for certain kinds of decls: 16655 16656 // - functions 16657 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 16658 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 16659 DestType = Ptr->getPointeeType(); 16660 ExprResult Result = resolveDecl(E, VD); 16661 if (Result.isInvalid()) return ExprError(); 16662 return S.ImpCastExprToType(Result.get(), Type, 16663 CK_FunctionToPointerDecay, VK_RValue); 16664 } 16665 16666 if (!Type->isFunctionType()) { 16667 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 16668 << VD << E->getSourceRange(); 16669 return ExprError(); 16670 } 16671 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 16672 // We must match the FunctionDecl's type to the hack introduced in 16673 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 16674 // type. See the lengthy commentary in that routine. 16675 QualType FDT = FD->getType(); 16676 const FunctionType *FnType = FDT->castAs<FunctionType>(); 16677 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 16678 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 16679 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 16680 SourceLocation Loc = FD->getLocation(); 16681 FunctionDecl *NewFD = FunctionDecl::Create(S.Context, 16682 FD->getDeclContext(), 16683 Loc, Loc, FD->getNameInfo().getName(), 16684 DestType, FD->getTypeSourceInfo(), 16685 SC_None, false/*isInlineSpecified*/, 16686 FD->hasPrototype(), 16687 false/*isConstexprSpecified*/); 16688 16689 if (FD->getQualifier()) 16690 NewFD->setQualifierInfo(FD->getQualifierLoc()); 16691 16692 SmallVector<ParmVarDecl*, 16> Params; 16693 for (const auto &AI : FT->param_types()) { 16694 ParmVarDecl *Param = 16695 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 16696 Param->setScopeInfo(0, Params.size()); 16697 Params.push_back(Param); 16698 } 16699 NewFD->setParams(Params); 16700 DRE->setDecl(NewFD); 16701 VD = DRE->getDecl(); 16702 } 16703 } 16704 16705 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 16706 if (MD->isInstance()) { 16707 ValueKind = VK_RValue; 16708 Type = S.Context.BoundMemberTy; 16709 } 16710 16711 // Function references aren't l-values in C. 16712 if (!S.getLangOpts().CPlusPlus) 16713 ValueKind = VK_RValue; 16714 16715 // - variables 16716 } else if (isa<VarDecl>(VD)) { 16717 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 16718 Type = RefTy->getPointeeType(); 16719 } else if (Type->isFunctionType()) { 16720 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 16721 << VD << E->getSourceRange(); 16722 return ExprError(); 16723 } 16724 16725 // - nothing else 16726 } else { 16727 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 16728 << VD << E->getSourceRange(); 16729 return ExprError(); 16730 } 16731 16732 // Modifying the declaration like this is friendly to IR-gen but 16733 // also really dangerous. 16734 VD->setType(DestType); 16735 E->setType(Type); 16736 E->setValueKind(ValueKind); 16737 return E; 16738 } 16739 16740 /// Check a cast of an unknown-any type. We intentionally only 16741 /// trigger this for C-style casts. 16742 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 16743 Expr *CastExpr, CastKind &CastKind, 16744 ExprValueKind &VK, CXXCastPath &Path) { 16745 // The type we're casting to must be either void or complete. 16746 if (!CastType->isVoidType() && 16747 RequireCompleteType(TypeRange.getBegin(), CastType, 16748 diag::err_typecheck_cast_to_incomplete)) 16749 return ExprError(); 16750 16751 // Rewrite the casted expression from scratch. 16752 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 16753 if (!result.isUsable()) return ExprError(); 16754 16755 CastExpr = result.get(); 16756 VK = CastExpr->getValueKind(); 16757 CastKind = CK_NoOp; 16758 16759 return CastExpr; 16760 } 16761 16762 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 16763 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 16764 } 16765 16766 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 16767 Expr *arg, QualType ¶mType) { 16768 // If the syntactic form of the argument is not an explicit cast of 16769 // any sort, just do default argument promotion. 16770 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 16771 if (!castArg) { 16772 ExprResult result = DefaultArgumentPromotion(arg); 16773 if (result.isInvalid()) return ExprError(); 16774 paramType = result.get()->getType(); 16775 return result; 16776 } 16777 16778 // Otherwise, use the type that was written in the explicit cast. 16779 assert(!arg->hasPlaceholderType()); 16780 paramType = castArg->getTypeAsWritten(); 16781 16782 // Copy-initialize a parameter of that type. 16783 InitializedEntity entity = 16784 InitializedEntity::InitializeParameter(Context, paramType, 16785 /*consumed*/ false); 16786 return PerformCopyInitialization(entity, callLoc, arg); 16787 } 16788 16789 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 16790 Expr *orig = E; 16791 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 16792 while (true) { 16793 E = E->IgnoreParenImpCasts(); 16794 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 16795 E = call->getCallee(); 16796 diagID = diag::err_uncasted_call_of_unknown_any; 16797 } else { 16798 break; 16799 } 16800 } 16801 16802 SourceLocation loc; 16803 NamedDecl *d; 16804 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 16805 loc = ref->getLocation(); 16806 d = ref->getDecl(); 16807 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 16808 loc = mem->getMemberLoc(); 16809 d = mem->getMemberDecl(); 16810 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 16811 diagID = diag::err_uncasted_call_of_unknown_any; 16812 loc = msg->getSelectorStartLoc(); 16813 d = msg->getMethodDecl(); 16814 if (!d) { 16815 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 16816 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 16817 << orig->getSourceRange(); 16818 return ExprError(); 16819 } 16820 } else { 16821 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 16822 << E->getSourceRange(); 16823 return ExprError(); 16824 } 16825 16826 S.Diag(loc, diagID) << d << orig->getSourceRange(); 16827 16828 // Never recoverable. 16829 return ExprError(); 16830 } 16831 16832 /// Check for operands with placeholder types and complain if found. 16833 /// Returns ExprError() if there was an error and no recovery was possible. 16834 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 16835 if (!getLangOpts().CPlusPlus) { 16836 // C cannot handle TypoExpr nodes on either side of a binop because it 16837 // doesn't handle dependent types properly, so make sure any TypoExprs have 16838 // been dealt with before checking the operands. 16839 ExprResult Result = CorrectDelayedTyposInExpr(E); 16840 if (!Result.isUsable()) return ExprError(); 16841 E = Result.get(); 16842 } 16843 16844 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 16845 if (!placeholderType) return E; 16846 16847 switch (placeholderType->getKind()) { 16848 16849 // Overloaded expressions. 16850 case BuiltinType::Overload: { 16851 // Try to resolve a single function template specialization. 16852 // This is obligatory. 16853 ExprResult Result = E; 16854 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 16855 return Result; 16856 16857 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 16858 // leaves Result unchanged on failure. 16859 Result = E; 16860 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) 16861 return Result; 16862 16863 // If that failed, try to recover with a call. 16864 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 16865 /*complain*/ true); 16866 return Result; 16867 } 16868 16869 // Bound member functions. 16870 case BuiltinType::BoundMember: { 16871 ExprResult result = E; 16872 const Expr *BME = E->IgnoreParens(); 16873 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 16874 // Try to give a nicer diagnostic if it is a bound member that we recognize. 16875 if (isa<CXXPseudoDestructorExpr>(BME)) { 16876 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 16877 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 16878 if (ME->getMemberNameInfo().getName().getNameKind() == 16879 DeclarationName::CXXDestructorName) 16880 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 16881 } 16882 tryToRecoverWithCall(result, PD, 16883 /*complain*/ true); 16884 return result; 16885 } 16886 16887 // ARC unbridged casts. 16888 case BuiltinType::ARCUnbridgedCast: { 16889 Expr *realCast = stripARCUnbridgedCast(E); 16890 diagnoseARCUnbridgedCast(realCast); 16891 return realCast; 16892 } 16893 16894 // Expressions of unknown type. 16895 case BuiltinType::UnknownAny: 16896 return diagnoseUnknownAnyExpr(*this, E); 16897 16898 // Pseudo-objects. 16899 case BuiltinType::PseudoObject: 16900 return checkPseudoObjectRValue(E); 16901 16902 case BuiltinType::BuiltinFn: { 16903 // Accept __noop without parens by implicitly converting it to a call expr. 16904 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 16905 if (DRE) { 16906 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 16907 if (FD->getBuiltinID() == Builtin::BI__noop) { 16908 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 16909 CK_BuiltinFnToFnPtr) 16910 .get(); 16911 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 16912 VK_RValue, SourceLocation()); 16913 } 16914 } 16915 16916 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 16917 return ExprError(); 16918 } 16919 16920 // Expressions of unknown type. 16921 case BuiltinType::OMPArraySection: 16922 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 16923 return ExprError(); 16924 16925 // Everything else should be impossible. 16926 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 16927 case BuiltinType::Id: 16928 #include "clang/Basic/OpenCLImageTypes.def" 16929 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 16930 case BuiltinType::Id: 16931 #include "clang/Basic/OpenCLExtensionTypes.def" 16932 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 16933 #define PLACEHOLDER_TYPE(Id, SingletonId) 16934 #include "clang/AST/BuiltinTypes.def" 16935 break; 16936 } 16937 16938 llvm_unreachable("invalid placeholder type!"); 16939 } 16940 16941 bool Sema::CheckCaseExpression(Expr *E) { 16942 if (E->isTypeDependent()) 16943 return true; 16944 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 16945 return E->getType()->isIntegralOrEnumerationType(); 16946 return false; 16947 } 16948 16949 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 16950 ExprResult 16951 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 16952 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 16953 "Unknown Objective-C Boolean value!"); 16954 QualType BoolT = Context.ObjCBuiltinBoolTy; 16955 if (!Context.getBOOLDecl()) { 16956 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 16957 Sema::LookupOrdinaryName); 16958 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 16959 NamedDecl *ND = Result.getFoundDecl(); 16960 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 16961 Context.setBOOLDecl(TD); 16962 } 16963 } 16964 if (Context.getBOOLDecl()) 16965 BoolT = Context.getBOOLType(); 16966 return new (Context) 16967 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 16968 } 16969 16970 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 16971 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 16972 SourceLocation RParen) { 16973 16974 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 16975 16976 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 16977 return Spec.getPlatform() == Platform; 16978 }); 16979 16980 VersionTuple Version; 16981 if (Spec != AvailSpecs.end()) 16982 Version = Spec->getVersion(); 16983 16984 // The use of `@available` in the enclosing function should be analyzed to 16985 // warn when it's used inappropriately (i.e. not if(@available)). 16986 if (getCurFunctionOrMethodDecl()) 16987 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 16988 else if (getCurBlock() || getCurLambda()) 16989 getCurFunction()->HasPotentialAvailabilityViolations = true; 16990 16991 return new (Context) 16992 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 16993 } 16994