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/Builtins.h" 29 #include "clang/Basic/FixedPoint.h" 30 #include "clang/Basic/PartialDiagnostic.h" 31 #include "clang/Basic/SourceManager.h" 32 #include "clang/Basic/TargetInfo.h" 33 #include "clang/Lex/LiteralSupport.h" 34 #include "clang/Lex/Preprocessor.h" 35 #include "clang/Sema/AnalysisBasedWarnings.h" 36 #include "clang/Sema/DeclSpec.h" 37 #include "clang/Sema/DelayedDiagnostic.h" 38 #include "clang/Sema/Designator.h" 39 #include "clang/Sema/Initialization.h" 40 #include "clang/Sema/Lookup.h" 41 #include "clang/Sema/Overload.h" 42 #include "clang/Sema/ParsedTemplate.h" 43 #include "clang/Sema/Scope.h" 44 #include "clang/Sema/ScopeInfo.h" 45 #include "clang/Sema/SemaFixItUtils.h" 46 #include "clang/Sema/SemaInternal.h" 47 #include "clang/Sema/Template.h" 48 #include "llvm/Support/ConvertUTF.h" 49 using namespace clang; 50 using namespace sema; 51 52 /// Determine whether the use of this declaration is valid, without 53 /// emitting diagnostics. 54 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 55 // See if this is an auto-typed variable whose initializer we are parsing. 56 if (ParsingInitForAutoVars.count(D)) 57 return false; 58 59 // See if this is a deleted function. 60 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 61 if (FD->isDeleted()) 62 return false; 63 64 // If the function has a deduced return type, and we can't deduce it, 65 // then we can't use it either. 66 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 67 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 68 return false; 69 70 // See if this is an aligned allocation/deallocation function that is 71 // unavailable. 72 if (TreatUnavailableAsInvalid && 73 isUnavailableAlignedAllocationFunction(*FD)) 74 return false; 75 } 76 77 // See if this function is unavailable. 78 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 79 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 80 return false; 81 82 return true; 83 } 84 85 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 86 // Warn if this is used but marked unused. 87 if (const auto *A = D->getAttr<UnusedAttr>()) { 88 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 89 // should diagnose them. 90 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 91 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 92 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 93 if (DC && !DC->hasAttr<UnusedAttr>()) 94 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 95 } 96 } 97 } 98 99 /// Emit a note explaining that this function is deleted. 100 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 101 assert(Decl && Decl->isDeleted()); 102 103 if (Decl->isDefaulted()) { 104 // If the method was explicitly defaulted, point at that declaration. 105 if (!Decl->isImplicit()) 106 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 107 108 // Try to diagnose why this special member function was implicitly 109 // deleted. This might fail, if that reason no longer applies. 110 DiagnoseDeletedDefaultedFunction(Decl); 111 return; 112 } 113 114 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 115 if (Ctor && Ctor->isInheritingConstructor()) 116 return NoteDeletedInheritingConstructor(Ctor); 117 118 Diag(Decl->getLocation(), diag::note_availability_specified_here) 119 << Decl << 1; 120 } 121 122 /// Determine whether a FunctionDecl was ever declared with an 123 /// explicit storage class. 124 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 125 for (auto I : D->redecls()) { 126 if (I->getStorageClass() != SC_None) 127 return true; 128 } 129 return false; 130 } 131 132 /// Check whether we're in an extern inline function and referring to a 133 /// variable or function with internal linkage (C11 6.7.4p3). 134 /// 135 /// This is only a warning because we used to silently accept this code, but 136 /// in many cases it will not behave correctly. This is not enabled in C++ mode 137 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 138 /// and so while there may still be user mistakes, most of the time we can't 139 /// prove that there are errors. 140 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 141 const NamedDecl *D, 142 SourceLocation Loc) { 143 // This is disabled under C++; there are too many ways for this to fire in 144 // contexts where the warning is a false positive, or where it is technically 145 // correct but benign. 146 if (S.getLangOpts().CPlusPlus) 147 return; 148 149 // Check if this is an inlined function or method. 150 FunctionDecl *Current = S.getCurFunctionDecl(); 151 if (!Current) 152 return; 153 if (!Current->isInlined()) 154 return; 155 if (!Current->isExternallyVisible()) 156 return; 157 158 // Check if the decl has internal linkage. 159 if (D->getFormalLinkage() != InternalLinkage) 160 return; 161 162 // Downgrade from ExtWarn to Extension if 163 // (1) the supposedly external inline function is in the main file, 164 // and probably won't be included anywhere else. 165 // (2) the thing we're referencing is a pure function. 166 // (3) the thing we're referencing is another inline function. 167 // This last can give us false negatives, but it's better than warning on 168 // wrappers for simple C library functions. 169 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 170 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 171 if (!DowngradeWarning && UsedFn) 172 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 173 174 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 175 : diag::ext_internal_in_extern_inline) 176 << /*IsVar=*/!UsedFn << D; 177 178 S.MaybeSuggestAddingStaticToDecl(Current); 179 180 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 181 << D; 182 } 183 184 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 185 const FunctionDecl *First = Cur->getFirstDecl(); 186 187 // Suggest "static" on the function, if possible. 188 if (!hasAnyExplicitStorageClass(First)) { 189 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 190 Diag(DeclBegin, diag::note_convert_inline_to_static) 191 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 192 } 193 } 194 195 /// Determine whether the use of this declaration is valid, and 196 /// emit any corresponding diagnostics. 197 /// 198 /// This routine diagnoses various problems with referencing 199 /// declarations that can occur when using a declaration. For example, 200 /// it might warn if a deprecated or unavailable declaration is being 201 /// used, or produce an error (and return true) if a C++0x deleted 202 /// function is being used. 203 /// 204 /// \returns true if there was an error (this declaration cannot be 205 /// referenced), false otherwise. 206 /// 207 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 208 const ObjCInterfaceDecl *UnknownObjCClass, 209 bool ObjCPropertyAccess, 210 bool AvoidPartialAvailabilityChecks, 211 ObjCInterfaceDecl *ClassReceiver) { 212 SourceLocation Loc = Locs.front(); 213 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 214 // If there were any diagnostics suppressed by template argument deduction, 215 // emit them now. 216 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 217 if (Pos != SuppressedDiagnostics.end()) { 218 for (const PartialDiagnosticAt &Suppressed : Pos->second) 219 Diag(Suppressed.first, Suppressed.second); 220 221 // Clear out the list of suppressed diagnostics, so that we don't emit 222 // them again for this specialization. However, we don't obsolete this 223 // entry from the table, because we want to avoid ever emitting these 224 // diagnostics again. 225 Pos->second.clear(); 226 } 227 228 // C++ [basic.start.main]p3: 229 // The function 'main' shall not be used within a program. 230 if (cast<FunctionDecl>(D)->isMain()) 231 Diag(Loc, diag::ext_main_used); 232 233 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); 234 } 235 236 // See if this is an auto-typed variable whose initializer we are parsing. 237 if (ParsingInitForAutoVars.count(D)) { 238 if (isa<BindingDecl>(D)) { 239 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 240 << D->getDeclName(); 241 } else { 242 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 243 << D->getDeclName() << cast<VarDecl>(D)->getType(); 244 } 245 return true; 246 } 247 248 // See if this is a deleted function. 249 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 250 if (FD->isDeleted()) { 251 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 252 if (Ctor && Ctor->isInheritingConstructor()) 253 Diag(Loc, diag::err_deleted_inherited_ctor_use) 254 << Ctor->getParent() 255 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 256 else 257 Diag(Loc, diag::err_deleted_function_use); 258 NoteDeletedFunction(FD); 259 return true; 260 } 261 262 // If the function has a deduced return type, and we can't deduce it, 263 // then we can't use it either. 264 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 265 DeduceReturnType(FD, Loc)) 266 return true; 267 268 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 269 return true; 270 } 271 272 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 273 // Lambdas are only default-constructible or assignable in C++2a onwards. 274 if (MD->getParent()->isLambda() && 275 ((isa<CXXConstructorDecl>(MD) && 276 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || 277 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { 278 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) 279 << !isa<CXXConstructorDecl>(MD); 280 } 281 } 282 283 auto getReferencedObjCProp = [](const NamedDecl *D) -> 284 const ObjCPropertyDecl * { 285 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 286 return MD->findPropertyDecl(); 287 return nullptr; 288 }; 289 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 290 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 291 return true; 292 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 293 return true; 294 } 295 296 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 297 // Only the variables omp_in and omp_out are allowed in the combiner. 298 // Only the variables omp_priv and omp_orig are allowed in the 299 // initializer-clause. 300 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 301 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 302 isa<VarDecl>(D)) { 303 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 304 << getCurFunction()->HasOMPDeclareReductionCombiner; 305 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 306 return true; 307 } 308 309 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions 310 // List-items in map clauses on this construct may only refer to the declared 311 // variable var and entities that could be referenced by a procedure defined 312 // at the same location 313 auto *DMD = dyn_cast<OMPDeclareMapperDecl>(CurContext); 314 if (LangOpts.OpenMP && DMD && !CurContext->containsDecl(D) && 315 isa<VarDecl>(D)) { 316 Diag(Loc, diag::err_omp_declare_mapper_wrong_var) 317 << DMD->getVarName().getAsString(); 318 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 319 return true; 320 } 321 322 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 323 AvoidPartialAvailabilityChecks, ClassReceiver); 324 325 DiagnoseUnusedOfDecl(*this, D, Loc); 326 327 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 328 329 return false; 330 } 331 332 /// DiagnoseSentinelCalls - This routine checks whether a call or 333 /// message-send is to a declaration with the sentinel attribute, and 334 /// if so, it checks that the requirements of the sentinel are 335 /// satisfied. 336 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 337 ArrayRef<Expr *> Args) { 338 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 339 if (!attr) 340 return; 341 342 // The number of formal parameters of the declaration. 343 unsigned numFormalParams; 344 345 // The kind of declaration. This is also an index into a %select in 346 // the diagnostic. 347 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 348 349 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 350 numFormalParams = MD->param_size(); 351 calleeType = CT_Method; 352 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 353 numFormalParams = FD->param_size(); 354 calleeType = CT_Function; 355 } else if (isa<VarDecl>(D)) { 356 QualType type = cast<ValueDecl>(D)->getType(); 357 const FunctionType *fn = nullptr; 358 if (const PointerType *ptr = type->getAs<PointerType>()) { 359 fn = ptr->getPointeeType()->getAs<FunctionType>(); 360 if (!fn) return; 361 calleeType = CT_Function; 362 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 363 fn = ptr->getPointeeType()->castAs<FunctionType>(); 364 calleeType = CT_Block; 365 } else { 366 return; 367 } 368 369 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 370 numFormalParams = proto->getNumParams(); 371 } else { 372 numFormalParams = 0; 373 } 374 } else { 375 return; 376 } 377 378 // "nullPos" is the number of formal parameters at the end which 379 // effectively count as part of the variadic arguments. This is 380 // useful if you would prefer to not have *any* formal parameters, 381 // but the language forces you to have at least one. 382 unsigned nullPos = attr->getNullPos(); 383 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 384 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 385 386 // The number of arguments which should follow the sentinel. 387 unsigned numArgsAfterSentinel = attr->getSentinel(); 388 389 // If there aren't enough arguments for all the formal parameters, 390 // the sentinel, and the args after the sentinel, complain. 391 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 392 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 393 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 394 return; 395 } 396 397 // Otherwise, find the sentinel expression. 398 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 399 if (!sentinelExpr) return; 400 if (sentinelExpr->isValueDependent()) return; 401 if (Context.isSentinelNullExpr(sentinelExpr)) return; 402 403 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 404 // or 'NULL' if those are actually defined in the context. Only use 405 // 'nil' for ObjC methods, where it's much more likely that the 406 // variadic arguments form a list of object pointers. 407 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 408 std::string NullValue; 409 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 410 NullValue = "nil"; 411 else if (getLangOpts().CPlusPlus11) 412 NullValue = "nullptr"; 413 else if (PP.isMacroDefined("NULL")) 414 NullValue = "NULL"; 415 else 416 NullValue = "(void*) 0"; 417 418 if (MissingNilLoc.isInvalid()) 419 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 420 else 421 Diag(MissingNilLoc, diag::warn_missing_sentinel) 422 << int(calleeType) 423 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 424 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 425 } 426 427 SourceRange Sema::getExprRange(Expr *E) const { 428 return E ? E->getSourceRange() : SourceRange(); 429 } 430 431 //===----------------------------------------------------------------------===// 432 // Standard Promotions and Conversions 433 //===----------------------------------------------------------------------===// 434 435 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 436 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 437 // Handle any placeholder expressions which made it here. 438 if (E->getType()->isPlaceholderType()) { 439 ExprResult result = CheckPlaceholderExpr(E); 440 if (result.isInvalid()) return ExprError(); 441 E = result.get(); 442 } 443 444 QualType Ty = E->getType(); 445 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 446 447 if (Ty->isFunctionType()) { 448 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 449 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 450 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 451 return ExprError(); 452 453 E = ImpCastExprToType(E, Context.getPointerType(Ty), 454 CK_FunctionToPointerDecay).get(); 455 } else if (Ty->isArrayType()) { 456 // In C90 mode, arrays only promote to pointers if the array expression is 457 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 458 // type 'array of type' is converted to an expression that has type 'pointer 459 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 460 // that has type 'array of type' ...". The relevant change is "an lvalue" 461 // (C90) to "an expression" (C99). 462 // 463 // C++ 4.2p1: 464 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 465 // T" can be converted to an rvalue of type "pointer to T". 466 // 467 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 468 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 469 CK_ArrayToPointerDecay).get(); 470 } 471 return E; 472 } 473 474 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 475 // Check to see if we are dereferencing a null pointer. If so, 476 // and if not volatile-qualified, this is undefined behavior that the 477 // optimizer will delete, so warn about it. People sometimes try to use this 478 // to get a deterministic trap and are surprised by clang's behavior. This 479 // only handles the pattern "*null", which is a very syntactic check. 480 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); 481 if (UO && UO->getOpcode() == UO_Deref && 482 UO->getSubExpr()->getType()->isPointerType()) { 483 const LangAS AS = 484 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); 485 if ((!isTargetAddressSpace(AS) || 486 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && 487 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( 488 S.Context, Expr::NPC_ValueDependentIsNotNull) && 489 !UO->getType().isVolatileQualified()) { 490 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 491 S.PDiag(diag::warn_indirection_through_null) 492 << UO->getSubExpr()->getSourceRange()); 493 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 494 S.PDiag(diag::note_indirection_through_null)); 495 } 496 } 497 } 498 499 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 500 SourceLocation AssignLoc, 501 const Expr* RHS) { 502 const ObjCIvarDecl *IV = OIRE->getDecl(); 503 if (!IV) 504 return; 505 506 DeclarationName MemberName = IV->getDeclName(); 507 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 508 if (!Member || !Member->isStr("isa")) 509 return; 510 511 const Expr *Base = OIRE->getBase(); 512 QualType BaseType = Base->getType(); 513 if (OIRE->isArrow()) 514 BaseType = BaseType->getPointeeType(); 515 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 516 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 517 ObjCInterfaceDecl *ClassDeclared = nullptr; 518 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 519 if (!ClassDeclared->getSuperClass() 520 && (*ClassDeclared->ivar_begin()) == IV) { 521 if (RHS) { 522 NamedDecl *ObjectSetClass = 523 S.LookupSingleName(S.TUScope, 524 &S.Context.Idents.get("object_setClass"), 525 SourceLocation(), S.LookupOrdinaryName); 526 if (ObjectSetClass) { 527 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 528 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 529 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 530 "object_setClass(") 531 << FixItHint::CreateReplacement( 532 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 533 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 534 } 535 else 536 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 537 } else { 538 NamedDecl *ObjectGetClass = 539 S.LookupSingleName(S.TUScope, 540 &S.Context.Idents.get("object_getClass"), 541 SourceLocation(), S.LookupOrdinaryName); 542 if (ObjectGetClass) 543 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 544 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 545 "object_getClass(") 546 << FixItHint::CreateReplacement( 547 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 548 else 549 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 550 } 551 S.Diag(IV->getLocation(), diag::note_ivar_decl); 552 } 553 } 554 } 555 556 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 557 // Handle any placeholder expressions which made it here. 558 if (E->getType()->isPlaceholderType()) { 559 ExprResult result = CheckPlaceholderExpr(E); 560 if (result.isInvalid()) return ExprError(); 561 E = result.get(); 562 } 563 564 // C++ [conv.lval]p1: 565 // A glvalue of a non-function, non-array type T can be 566 // converted to a prvalue. 567 if (!E->isGLValue()) return E; 568 569 QualType T = E->getType(); 570 assert(!T.isNull() && "r-value conversion on typeless expression?"); 571 572 // We don't want to throw lvalue-to-rvalue casts on top of 573 // expressions of certain types in C++. 574 if (getLangOpts().CPlusPlus && 575 (E->getType() == Context.OverloadTy || 576 T->isDependentType() || 577 T->isRecordType())) 578 return E; 579 580 // The C standard is actually really unclear on this point, and 581 // DR106 tells us what the result should be but not why. It's 582 // generally best to say that void types just doesn't undergo 583 // lvalue-to-rvalue at all. Note that expressions of unqualified 584 // 'void' type are never l-values, but qualified void can be. 585 if (T->isVoidType()) 586 return E; 587 588 // OpenCL usually rejects direct accesses to values of 'half' type. 589 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 590 T->isHalfType()) { 591 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 592 << 0 << T; 593 return ExprError(); 594 } 595 596 CheckForNullPointerDereference(*this, E); 597 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 598 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 599 &Context.Idents.get("object_getClass"), 600 SourceLocation(), LookupOrdinaryName); 601 if (ObjectGetClass) 602 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 603 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 604 << FixItHint::CreateReplacement( 605 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 606 else 607 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 608 } 609 else if (const ObjCIvarRefExpr *OIRE = 610 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 611 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 612 613 // C++ [conv.lval]p1: 614 // [...] If T is a non-class type, the type of the prvalue is the 615 // cv-unqualified version of T. Otherwise, the type of the 616 // rvalue is T. 617 // 618 // C99 6.3.2.1p2: 619 // If the lvalue has qualified type, the value has the unqualified 620 // version of the type of the lvalue; otherwise, the value has the 621 // type of the lvalue. 622 if (T.hasQualifiers()) 623 T = T.getUnqualifiedType(); 624 625 // Under the MS ABI, lock down the inheritance model now. 626 if (T->isMemberPointerType() && 627 Context.getTargetInfo().getCXXABI().isMicrosoft()) 628 (void)isCompleteType(E->getExprLoc(), T); 629 630 ExprResult Res = CheckLValueToRValueConversionOperand(E); 631 if (Res.isInvalid()) 632 return Res; 633 E = Res.get(); 634 635 // Loading a __weak object implicitly retains the value, so we need a cleanup to 636 // balance that. 637 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 638 Cleanup.setExprNeedsCleanups(true); 639 640 // C++ [conv.lval]p3: 641 // If T is cv std::nullptr_t, the result is a null pointer constant. 642 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; 643 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue); 644 645 // C11 6.3.2.1p2: 646 // ... if the lvalue has atomic type, the value has the non-atomic version 647 // of the type of the lvalue ... 648 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 649 T = Atomic->getValueType().getUnqualifiedType(); 650 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 651 nullptr, VK_RValue); 652 } 653 654 return Res; 655 } 656 657 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 658 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 659 if (Res.isInvalid()) 660 return ExprError(); 661 Res = DefaultLvalueConversion(Res.get()); 662 if (Res.isInvalid()) 663 return ExprError(); 664 return Res; 665 } 666 667 /// CallExprUnaryConversions - a special case of an unary conversion 668 /// performed on a function designator of a call expression. 669 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 670 QualType Ty = E->getType(); 671 ExprResult Res = E; 672 // Only do implicit cast for a function type, but not for a pointer 673 // to function type. 674 if (Ty->isFunctionType()) { 675 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 676 CK_FunctionToPointerDecay).get(); 677 if (Res.isInvalid()) 678 return ExprError(); 679 } 680 Res = DefaultLvalueConversion(Res.get()); 681 if (Res.isInvalid()) 682 return ExprError(); 683 return Res.get(); 684 } 685 686 /// UsualUnaryConversions - Performs various conversions that are common to most 687 /// operators (C99 6.3). The conversions of array and function types are 688 /// sometimes suppressed. For example, the array->pointer conversion doesn't 689 /// apply if the array is an argument to the sizeof or address (&) operators. 690 /// In these instances, this routine should *not* be called. 691 ExprResult Sema::UsualUnaryConversions(Expr *E) { 692 // First, convert to an r-value. 693 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 694 if (Res.isInvalid()) 695 return ExprError(); 696 E = Res.get(); 697 698 QualType Ty = E->getType(); 699 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 700 701 // Half FP have to be promoted to float unless it is natively supported 702 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 703 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 704 705 // Try to perform integral promotions if the object has a theoretically 706 // promotable type. 707 if (Ty->isIntegralOrUnscopedEnumerationType()) { 708 // C99 6.3.1.1p2: 709 // 710 // The following may be used in an expression wherever an int or 711 // unsigned int may be used: 712 // - an object or expression with an integer type whose integer 713 // conversion rank is less than or equal to the rank of int 714 // and unsigned int. 715 // - A bit-field of type _Bool, int, signed int, or unsigned int. 716 // 717 // If an int can represent all values of the original type, the 718 // value is converted to an int; otherwise, it is converted to an 719 // unsigned int. These are called the integer promotions. All 720 // other types are unchanged by the integer promotions. 721 722 QualType PTy = Context.isPromotableBitField(E); 723 if (!PTy.isNull()) { 724 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 725 return E; 726 } 727 if (Ty->isPromotableIntegerType()) { 728 QualType PT = Context.getPromotedIntegerType(Ty); 729 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 730 return E; 731 } 732 } 733 return E; 734 } 735 736 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 737 /// do not have a prototype. Arguments that have type float or __fp16 738 /// are promoted to double. All other argument types are converted by 739 /// UsualUnaryConversions(). 740 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 741 QualType Ty = E->getType(); 742 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 743 744 ExprResult Res = UsualUnaryConversions(E); 745 if (Res.isInvalid()) 746 return ExprError(); 747 E = Res.get(); 748 749 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 750 // promote to double. 751 // Note that default argument promotion applies only to float (and 752 // half/fp16); it does not apply to _Float16. 753 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 754 if (BTy && (BTy->getKind() == BuiltinType::Half || 755 BTy->getKind() == BuiltinType::Float)) { 756 if (getLangOpts().OpenCL && 757 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 758 if (BTy->getKind() == BuiltinType::Half) { 759 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 760 } 761 } else { 762 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 763 } 764 } 765 766 // C++ performs lvalue-to-rvalue conversion as a default argument 767 // promotion, even on class types, but note: 768 // C++11 [conv.lval]p2: 769 // When an lvalue-to-rvalue conversion occurs in an unevaluated 770 // operand or a subexpression thereof the value contained in the 771 // referenced object is not accessed. Otherwise, if the glvalue 772 // has a class type, the conversion copy-initializes a temporary 773 // of type T from the glvalue and the result of the conversion 774 // is a prvalue for the temporary. 775 // FIXME: add some way to gate this entire thing for correctness in 776 // potentially potentially evaluated contexts. 777 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 778 ExprResult Temp = PerformCopyInitialization( 779 InitializedEntity::InitializeTemporary(E->getType()), 780 E->getExprLoc(), E); 781 if (Temp.isInvalid()) 782 return ExprError(); 783 E = Temp.get(); 784 } 785 786 return E; 787 } 788 789 /// Determine the degree of POD-ness for an expression. 790 /// Incomplete types are considered POD, since this check can be performed 791 /// when we're in an unevaluated context. 792 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 793 if (Ty->isIncompleteType()) { 794 // C++11 [expr.call]p7: 795 // After these conversions, if the argument does not have arithmetic, 796 // enumeration, pointer, pointer to member, or class type, the program 797 // is ill-formed. 798 // 799 // Since we've already performed array-to-pointer and function-to-pointer 800 // decay, the only such type in C++ is cv void. This also handles 801 // initializer lists as variadic arguments. 802 if (Ty->isVoidType()) 803 return VAK_Invalid; 804 805 if (Ty->isObjCObjectType()) 806 return VAK_Invalid; 807 return VAK_Valid; 808 } 809 810 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 811 return VAK_Invalid; 812 813 if (Ty.isCXX98PODType(Context)) 814 return VAK_Valid; 815 816 // C++11 [expr.call]p7: 817 // Passing a potentially-evaluated argument of class type (Clause 9) 818 // having a non-trivial copy constructor, a non-trivial move constructor, 819 // or a non-trivial destructor, with no corresponding parameter, 820 // is conditionally-supported with implementation-defined semantics. 821 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 822 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 823 if (!Record->hasNonTrivialCopyConstructor() && 824 !Record->hasNonTrivialMoveConstructor() && 825 !Record->hasNonTrivialDestructor()) 826 return VAK_ValidInCXX11; 827 828 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 829 return VAK_Valid; 830 831 if (Ty->isObjCObjectType()) 832 return VAK_Invalid; 833 834 if (getLangOpts().MSVCCompat) 835 return VAK_MSVCUndefined; 836 837 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 838 // permitted to reject them. We should consider doing so. 839 return VAK_Undefined; 840 } 841 842 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 843 // Don't allow one to pass an Objective-C interface to a vararg. 844 const QualType &Ty = E->getType(); 845 VarArgKind VAK = isValidVarArgType(Ty); 846 847 // Complain about passing non-POD types through varargs. 848 switch (VAK) { 849 case VAK_ValidInCXX11: 850 DiagRuntimeBehavior( 851 E->getBeginLoc(), nullptr, 852 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 853 LLVM_FALLTHROUGH; 854 case VAK_Valid: 855 if (Ty->isRecordType()) { 856 // This is unlikely to be what the user intended. If the class has a 857 // 'c_str' member function, the user probably meant to call that. 858 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 859 PDiag(diag::warn_pass_class_arg_to_vararg) 860 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 861 } 862 break; 863 864 case VAK_Undefined: 865 case VAK_MSVCUndefined: 866 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 867 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 868 << getLangOpts().CPlusPlus11 << Ty << CT); 869 break; 870 871 case VAK_Invalid: 872 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 873 Diag(E->getBeginLoc(), 874 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 875 << Ty << CT; 876 else if (Ty->isObjCObjectType()) 877 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 878 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 879 << Ty << CT); 880 else 881 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 882 << isa<InitListExpr>(E) << Ty << CT; 883 break; 884 } 885 } 886 887 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 888 /// will create a trap if the resulting type is not a POD type. 889 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 890 FunctionDecl *FDecl) { 891 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 892 // Strip the unbridged-cast placeholder expression off, if applicable. 893 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 894 (CT == VariadicMethod || 895 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 896 E = stripARCUnbridgedCast(E); 897 898 // Otherwise, do normal placeholder checking. 899 } else { 900 ExprResult ExprRes = CheckPlaceholderExpr(E); 901 if (ExprRes.isInvalid()) 902 return ExprError(); 903 E = ExprRes.get(); 904 } 905 } 906 907 ExprResult ExprRes = DefaultArgumentPromotion(E); 908 if (ExprRes.isInvalid()) 909 return ExprError(); 910 E = ExprRes.get(); 911 912 // Diagnostics regarding non-POD argument types are 913 // emitted along with format string checking in Sema::CheckFunctionCall(). 914 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 915 // Turn this into a trap. 916 CXXScopeSpec SS; 917 SourceLocation TemplateKWLoc; 918 UnqualifiedId Name; 919 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 920 E->getBeginLoc()); 921 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 922 /*HasTrailingLParen=*/true, 923 /*IsAddressOfOperand=*/false); 924 if (TrapFn.isInvalid()) 925 return ExprError(); 926 927 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 928 None, E->getEndLoc()); 929 if (Call.isInvalid()) 930 return ExprError(); 931 932 ExprResult Comma = 933 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 934 if (Comma.isInvalid()) 935 return ExprError(); 936 return Comma.get(); 937 } 938 939 if (!getLangOpts().CPlusPlus && 940 RequireCompleteType(E->getExprLoc(), E->getType(), 941 diag::err_call_incomplete_argument)) 942 return ExprError(); 943 944 return E; 945 } 946 947 /// Converts an integer to complex float type. Helper function of 948 /// UsualArithmeticConversions() 949 /// 950 /// \return false if the integer expression is an integer type and is 951 /// successfully converted to the complex type. 952 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 953 ExprResult &ComplexExpr, 954 QualType IntTy, 955 QualType ComplexTy, 956 bool SkipCast) { 957 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 958 if (SkipCast) return false; 959 if (IntTy->isIntegerType()) { 960 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 961 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 962 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 963 CK_FloatingRealToComplex); 964 } else { 965 assert(IntTy->isComplexIntegerType()); 966 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 967 CK_IntegralComplexToFloatingComplex); 968 } 969 return false; 970 } 971 972 /// Handle arithmetic conversion with complex types. Helper function of 973 /// UsualArithmeticConversions() 974 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 975 ExprResult &RHS, QualType LHSType, 976 QualType RHSType, 977 bool IsCompAssign) { 978 // if we have an integer operand, the result is the complex type. 979 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 980 /*skipCast*/false)) 981 return LHSType; 982 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 983 /*skipCast*/IsCompAssign)) 984 return RHSType; 985 986 // This handles complex/complex, complex/float, or float/complex. 987 // When both operands are complex, the shorter operand is converted to the 988 // type of the longer, and that is the type of the result. This corresponds 989 // to what is done when combining two real floating-point operands. 990 // The fun begins when size promotion occur across type domains. 991 // From H&S 6.3.4: When one operand is complex and the other is a real 992 // floating-point type, the less precise type is converted, within it's 993 // real or complex domain, to the precision of the other type. For example, 994 // when combining a "long double" with a "double _Complex", the 995 // "double _Complex" is promoted to "long double _Complex". 996 997 // Compute the rank of the two types, regardless of whether they are complex. 998 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 999 1000 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1001 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1002 QualType LHSElementType = 1003 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1004 QualType RHSElementType = 1005 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1006 1007 QualType ResultType = S.Context.getComplexType(LHSElementType); 1008 if (Order < 0) { 1009 // Promote the precision of the LHS if not an assignment. 1010 ResultType = S.Context.getComplexType(RHSElementType); 1011 if (!IsCompAssign) { 1012 if (LHSComplexType) 1013 LHS = 1014 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1015 else 1016 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1017 } 1018 } else if (Order > 0) { 1019 // Promote the precision of the RHS. 1020 if (RHSComplexType) 1021 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1022 else 1023 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1024 } 1025 return ResultType; 1026 } 1027 1028 /// Handle arithmetic conversion from integer to float. Helper function 1029 /// of UsualArithmeticConversions() 1030 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1031 ExprResult &IntExpr, 1032 QualType FloatTy, QualType IntTy, 1033 bool ConvertFloat, bool ConvertInt) { 1034 if (IntTy->isIntegerType()) { 1035 if (ConvertInt) 1036 // Convert intExpr to the lhs floating point type. 1037 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1038 CK_IntegralToFloating); 1039 return FloatTy; 1040 } 1041 1042 // Convert both sides to the appropriate complex float. 1043 assert(IntTy->isComplexIntegerType()); 1044 QualType result = S.Context.getComplexType(FloatTy); 1045 1046 // _Complex int -> _Complex float 1047 if (ConvertInt) 1048 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1049 CK_IntegralComplexToFloatingComplex); 1050 1051 // float -> _Complex float 1052 if (ConvertFloat) 1053 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1054 CK_FloatingRealToComplex); 1055 1056 return result; 1057 } 1058 1059 /// Handle arithmethic conversion with floating point types. Helper 1060 /// function of UsualArithmeticConversions() 1061 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1062 ExprResult &RHS, QualType LHSType, 1063 QualType RHSType, bool IsCompAssign) { 1064 bool LHSFloat = LHSType->isRealFloatingType(); 1065 bool RHSFloat = RHSType->isRealFloatingType(); 1066 1067 // If we have two real floating types, convert the smaller operand 1068 // to the bigger result. 1069 if (LHSFloat && RHSFloat) { 1070 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1071 if (order > 0) { 1072 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1073 return LHSType; 1074 } 1075 1076 assert(order < 0 && "illegal float comparison"); 1077 if (!IsCompAssign) 1078 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1079 return RHSType; 1080 } 1081 1082 if (LHSFloat) { 1083 // Half FP has to be promoted to float unless it is natively supported 1084 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1085 LHSType = S.Context.FloatTy; 1086 1087 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1088 /*ConvertFloat=*/!IsCompAssign, 1089 /*ConvertInt=*/ true); 1090 } 1091 assert(RHSFloat); 1092 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1093 /*convertInt=*/ true, 1094 /*convertFloat=*/!IsCompAssign); 1095 } 1096 1097 /// Diagnose attempts to convert between __float128 and long double if 1098 /// there is no support for such conversion. Helper function of 1099 /// UsualArithmeticConversions(). 1100 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1101 QualType RHSType) { 1102 /* No issue converting if at least one of the types is not a floating point 1103 type or the two types have the same rank. 1104 */ 1105 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1106 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1107 return false; 1108 1109 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1110 "The remaining types must be floating point types."); 1111 1112 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1113 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1114 1115 QualType LHSElemType = LHSComplex ? 1116 LHSComplex->getElementType() : LHSType; 1117 QualType RHSElemType = RHSComplex ? 1118 RHSComplex->getElementType() : RHSType; 1119 1120 // No issue if the two types have the same representation 1121 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1122 &S.Context.getFloatTypeSemantics(RHSElemType)) 1123 return false; 1124 1125 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1126 RHSElemType == S.Context.LongDoubleTy); 1127 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1128 RHSElemType == S.Context.Float128Ty); 1129 1130 // We've handled the situation where __float128 and long double have the same 1131 // representation. We allow all conversions for all possible long double types 1132 // except PPC's double double. 1133 return Float128AndLongDouble && 1134 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1135 &llvm::APFloat::PPCDoubleDouble()); 1136 } 1137 1138 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1139 1140 namespace { 1141 /// These helper callbacks are placed in an anonymous namespace to 1142 /// permit their use as function template parameters. 1143 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1144 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1145 } 1146 1147 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1148 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1149 CK_IntegralComplexCast); 1150 } 1151 } 1152 1153 /// Handle integer arithmetic conversions. Helper function of 1154 /// UsualArithmeticConversions() 1155 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1156 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1157 ExprResult &RHS, QualType LHSType, 1158 QualType RHSType, bool IsCompAssign) { 1159 // The rules for this case are in C99 6.3.1.8 1160 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1161 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1162 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1163 if (LHSSigned == RHSSigned) { 1164 // Same signedness; use the higher-ranked type 1165 if (order >= 0) { 1166 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1167 return LHSType; 1168 } else if (!IsCompAssign) 1169 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1170 return RHSType; 1171 } else if (order != (LHSSigned ? 1 : -1)) { 1172 // The unsigned type has greater than or equal rank to the 1173 // signed type, so use the unsigned type 1174 if (RHSSigned) { 1175 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1176 return LHSType; 1177 } else if (!IsCompAssign) 1178 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1179 return RHSType; 1180 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1181 // The two types are different widths; if we are here, that 1182 // means the signed type is larger than the unsigned type, so 1183 // use the signed type. 1184 if (LHSSigned) { 1185 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1186 return LHSType; 1187 } else if (!IsCompAssign) 1188 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1189 return RHSType; 1190 } else { 1191 // The signed type is higher-ranked than the unsigned type, 1192 // but isn't actually any bigger (like unsigned int and long 1193 // on most 32-bit systems). Use the unsigned type corresponding 1194 // to the signed type. 1195 QualType result = 1196 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1197 RHS = (*doRHSCast)(S, RHS.get(), result); 1198 if (!IsCompAssign) 1199 LHS = (*doLHSCast)(S, LHS.get(), result); 1200 return result; 1201 } 1202 } 1203 1204 /// Handle conversions with GCC complex int extension. Helper function 1205 /// of UsualArithmeticConversions() 1206 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1207 ExprResult &RHS, QualType LHSType, 1208 QualType RHSType, 1209 bool IsCompAssign) { 1210 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1211 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1212 1213 if (LHSComplexInt && RHSComplexInt) { 1214 QualType LHSEltType = LHSComplexInt->getElementType(); 1215 QualType RHSEltType = RHSComplexInt->getElementType(); 1216 QualType ScalarType = 1217 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1218 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1219 1220 return S.Context.getComplexType(ScalarType); 1221 } 1222 1223 if (LHSComplexInt) { 1224 QualType LHSEltType = LHSComplexInt->getElementType(); 1225 QualType ScalarType = 1226 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1227 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1228 QualType ComplexType = S.Context.getComplexType(ScalarType); 1229 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1230 CK_IntegralRealToComplex); 1231 1232 return ComplexType; 1233 } 1234 1235 assert(RHSComplexInt); 1236 1237 QualType RHSEltType = RHSComplexInt->getElementType(); 1238 QualType ScalarType = 1239 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1240 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1241 QualType ComplexType = S.Context.getComplexType(ScalarType); 1242 1243 if (!IsCompAssign) 1244 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1245 CK_IntegralRealToComplex); 1246 return ComplexType; 1247 } 1248 1249 /// Return the rank of a given fixed point or integer type. The value itself 1250 /// doesn't matter, but the values must be increasing with proper increasing 1251 /// rank as described in N1169 4.1.1. 1252 static unsigned GetFixedPointRank(QualType Ty) { 1253 const auto *BTy = Ty->getAs<BuiltinType>(); 1254 assert(BTy && "Expected a builtin type."); 1255 1256 switch (BTy->getKind()) { 1257 case BuiltinType::ShortFract: 1258 case BuiltinType::UShortFract: 1259 case BuiltinType::SatShortFract: 1260 case BuiltinType::SatUShortFract: 1261 return 1; 1262 case BuiltinType::Fract: 1263 case BuiltinType::UFract: 1264 case BuiltinType::SatFract: 1265 case BuiltinType::SatUFract: 1266 return 2; 1267 case BuiltinType::LongFract: 1268 case BuiltinType::ULongFract: 1269 case BuiltinType::SatLongFract: 1270 case BuiltinType::SatULongFract: 1271 return 3; 1272 case BuiltinType::ShortAccum: 1273 case BuiltinType::UShortAccum: 1274 case BuiltinType::SatShortAccum: 1275 case BuiltinType::SatUShortAccum: 1276 return 4; 1277 case BuiltinType::Accum: 1278 case BuiltinType::UAccum: 1279 case BuiltinType::SatAccum: 1280 case BuiltinType::SatUAccum: 1281 return 5; 1282 case BuiltinType::LongAccum: 1283 case BuiltinType::ULongAccum: 1284 case BuiltinType::SatLongAccum: 1285 case BuiltinType::SatULongAccum: 1286 return 6; 1287 default: 1288 if (BTy->isInteger()) 1289 return 0; 1290 llvm_unreachable("Unexpected fixed point or integer type"); 1291 } 1292 } 1293 1294 /// handleFixedPointConversion - Fixed point operations between fixed 1295 /// point types and integers or other fixed point types do not fall under 1296 /// usual arithmetic conversion since these conversions could result in loss 1297 /// of precsision (N1169 4.1.4). These operations should be calculated with 1298 /// the full precision of their result type (N1169 4.1.6.2.1). 1299 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1300 QualType RHSTy) { 1301 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1302 "Expected at least one of the operands to be a fixed point type"); 1303 assert((LHSTy->isFixedPointOrIntegerType() || 1304 RHSTy->isFixedPointOrIntegerType()) && 1305 "Special fixed point arithmetic operation conversions are only " 1306 "applied to ints or other fixed point types"); 1307 1308 // If one operand has signed fixed-point type and the other operand has 1309 // unsigned fixed-point type, then the unsigned fixed-point operand is 1310 // converted to its corresponding signed fixed-point type and the resulting 1311 // type is the type of the converted operand. 1312 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1313 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1314 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1315 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1316 1317 // The result type is the type with the highest rank, whereby a fixed-point 1318 // conversion rank is always greater than an integer conversion rank; if the 1319 // type of either of the operands is a saturating fixedpoint type, the result 1320 // type shall be the saturating fixed-point type corresponding to the type 1321 // with the highest rank; the resulting value is converted (taking into 1322 // account rounding and overflow) to the precision of the resulting type. 1323 // Same ranks between signed and unsigned types are resolved earlier, so both 1324 // types are either signed or both unsigned at this point. 1325 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1326 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1327 1328 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1329 1330 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1331 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1332 1333 return ResultTy; 1334 } 1335 1336 /// UsualArithmeticConversions - Performs various conversions that are common to 1337 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1338 /// routine returns the first non-arithmetic type found. The client is 1339 /// responsible for emitting appropriate error diagnostics. 1340 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1341 bool IsCompAssign) { 1342 if (!IsCompAssign) { 1343 LHS = UsualUnaryConversions(LHS.get()); 1344 if (LHS.isInvalid()) 1345 return QualType(); 1346 } 1347 1348 RHS = UsualUnaryConversions(RHS.get()); 1349 if (RHS.isInvalid()) 1350 return QualType(); 1351 1352 // For conversion purposes, we ignore any qualifiers. 1353 // For example, "const float" and "float" are equivalent. 1354 QualType LHSType = 1355 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1356 QualType RHSType = 1357 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1358 1359 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1360 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1361 LHSType = AtomicLHS->getValueType(); 1362 1363 // If both types are identical, no conversion is needed. 1364 if (LHSType == RHSType) 1365 return LHSType; 1366 1367 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1368 // The caller can deal with this (e.g. pointer + int). 1369 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1370 return QualType(); 1371 1372 // Apply unary and bitfield promotions to the LHS's type. 1373 QualType LHSUnpromotedType = LHSType; 1374 if (LHSType->isPromotableIntegerType()) 1375 LHSType = Context.getPromotedIntegerType(LHSType); 1376 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1377 if (!LHSBitfieldPromoteTy.isNull()) 1378 LHSType = LHSBitfieldPromoteTy; 1379 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1380 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1381 1382 // If both types are identical, no conversion is needed. 1383 if (LHSType == RHSType) 1384 return LHSType; 1385 1386 // At this point, we have two different arithmetic types. 1387 1388 // Diagnose attempts to convert between __float128 and long double where 1389 // such conversions currently can't be handled. 1390 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1391 return QualType(); 1392 1393 // Handle complex types first (C99 6.3.1.8p1). 1394 if (LHSType->isComplexType() || RHSType->isComplexType()) 1395 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1396 IsCompAssign); 1397 1398 // Now handle "real" floating types (i.e. float, double, long double). 1399 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1400 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1401 IsCompAssign); 1402 1403 // Handle GCC complex int extension. 1404 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1405 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1406 IsCompAssign); 1407 1408 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1409 return handleFixedPointConversion(*this, LHSType, RHSType); 1410 1411 // Finally, we have two differing integer types. 1412 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1413 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1414 } 1415 1416 //===----------------------------------------------------------------------===// 1417 // Semantic Analysis for various Expression Types 1418 //===----------------------------------------------------------------------===// 1419 1420 1421 ExprResult 1422 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1423 SourceLocation DefaultLoc, 1424 SourceLocation RParenLoc, 1425 Expr *ControllingExpr, 1426 ArrayRef<ParsedType> ArgTypes, 1427 ArrayRef<Expr *> ArgExprs) { 1428 unsigned NumAssocs = ArgTypes.size(); 1429 assert(NumAssocs == ArgExprs.size()); 1430 1431 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1432 for (unsigned i = 0; i < NumAssocs; ++i) { 1433 if (ArgTypes[i]) 1434 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1435 else 1436 Types[i] = nullptr; 1437 } 1438 1439 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1440 ControllingExpr, 1441 llvm::makeArrayRef(Types, NumAssocs), 1442 ArgExprs); 1443 delete [] Types; 1444 return ER; 1445 } 1446 1447 ExprResult 1448 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1449 SourceLocation DefaultLoc, 1450 SourceLocation RParenLoc, 1451 Expr *ControllingExpr, 1452 ArrayRef<TypeSourceInfo *> Types, 1453 ArrayRef<Expr *> Exprs) { 1454 unsigned NumAssocs = Types.size(); 1455 assert(NumAssocs == Exprs.size()); 1456 1457 // Decay and strip qualifiers for the controlling expression type, and handle 1458 // placeholder type replacement. See committee discussion from WG14 DR423. 1459 { 1460 EnterExpressionEvaluationContext Unevaluated( 1461 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1462 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1463 if (R.isInvalid()) 1464 return ExprError(); 1465 ControllingExpr = R.get(); 1466 } 1467 1468 // The controlling expression is an unevaluated operand, so side effects are 1469 // likely unintended. 1470 if (!inTemplateInstantiation() && 1471 ControllingExpr->HasSideEffects(Context, false)) 1472 Diag(ControllingExpr->getExprLoc(), 1473 diag::warn_side_effects_unevaluated_context); 1474 1475 bool TypeErrorFound = false, 1476 IsResultDependent = ControllingExpr->isTypeDependent(), 1477 ContainsUnexpandedParameterPack 1478 = ControllingExpr->containsUnexpandedParameterPack(); 1479 1480 for (unsigned i = 0; i < NumAssocs; ++i) { 1481 if (Exprs[i]->containsUnexpandedParameterPack()) 1482 ContainsUnexpandedParameterPack = true; 1483 1484 if (Types[i]) { 1485 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1486 ContainsUnexpandedParameterPack = true; 1487 1488 if (Types[i]->getType()->isDependentType()) { 1489 IsResultDependent = true; 1490 } else { 1491 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1492 // complete object type other than a variably modified type." 1493 unsigned D = 0; 1494 if (Types[i]->getType()->isIncompleteType()) 1495 D = diag::err_assoc_type_incomplete; 1496 else if (!Types[i]->getType()->isObjectType()) 1497 D = diag::err_assoc_type_nonobject; 1498 else if (Types[i]->getType()->isVariablyModifiedType()) 1499 D = diag::err_assoc_type_variably_modified; 1500 1501 if (D != 0) { 1502 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1503 << Types[i]->getTypeLoc().getSourceRange() 1504 << Types[i]->getType(); 1505 TypeErrorFound = true; 1506 } 1507 1508 // C11 6.5.1.1p2 "No two generic associations in the same generic 1509 // selection shall specify compatible types." 1510 for (unsigned j = i+1; j < NumAssocs; ++j) 1511 if (Types[j] && !Types[j]->getType()->isDependentType() && 1512 Context.typesAreCompatible(Types[i]->getType(), 1513 Types[j]->getType())) { 1514 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1515 diag::err_assoc_compatible_types) 1516 << Types[j]->getTypeLoc().getSourceRange() 1517 << Types[j]->getType() 1518 << Types[i]->getType(); 1519 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1520 diag::note_compat_assoc) 1521 << Types[i]->getTypeLoc().getSourceRange() 1522 << Types[i]->getType(); 1523 TypeErrorFound = true; 1524 } 1525 } 1526 } 1527 } 1528 if (TypeErrorFound) 1529 return ExprError(); 1530 1531 // If we determined that the generic selection is result-dependent, don't 1532 // try to compute the result expression. 1533 if (IsResultDependent) 1534 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1535 Exprs, DefaultLoc, RParenLoc, 1536 ContainsUnexpandedParameterPack); 1537 1538 SmallVector<unsigned, 1> CompatIndices; 1539 unsigned DefaultIndex = -1U; 1540 for (unsigned i = 0; i < NumAssocs; ++i) { 1541 if (!Types[i]) 1542 DefaultIndex = i; 1543 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1544 Types[i]->getType())) 1545 CompatIndices.push_back(i); 1546 } 1547 1548 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1549 // type compatible with at most one of the types named in its generic 1550 // association list." 1551 if (CompatIndices.size() > 1) { 1552 // We strip parens here because the controlling expression is typically 1553 // parenthesized in macro definitions. 1554 ControllingExpr = ControllingExpr->IgnoreParens(); 1555 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1556 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1557 << (unsigned)CompatIndices.size(); 1558 for (unsigned I : CompatIndices) { 1559 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1560 diag::note_compat_assoc) 1561 << Types[I]->getTypeLoc().getSourceRange() 1562 << Types[I]->getType(); 1563 } 1564 return ExprError(); 1565 } 1566 1567 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1568 // its controlling expression shall have type compatible with exactly one of 1569 // the types named in its generic association list." 1570 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1571 // We strip parens here because the controlling expression is typically 1572 // parenthesized in macro definitions. 1573 ControllingExpr = ControllingExpr->IgnoreParens(); 1574 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1575 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1576 return ExprError(); 1577 } 1578 1579 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1580 // type name that is compatible with the type of the controlling expression, 1581 // then the result expression of the generic selection is the expression 1582 // in that generic association. Otherwise, the result expression of the 1583 // generic selection is the expression in the default generic association." 1584 unsigned ResultIndex = 1585 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1586 1587 return GenericSelectionExpr::Create( 1588 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1589 ContainsUnexpandedParameterPack, ResultIndex); 1590 } 1591 1592 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1593 /// location of the token and the offset of the ud-suffix within it. 1594 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1595 unsigned Offset) { 1596 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1597 S.getLangOpts()); 1598 } 1599 1600 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1601 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1602 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1603 IdentifierInfo *UDSuffix, 1604 SourceLocation UDSuffixLoc, 1605 ArrayRef<Expr*> Args, 1606 SourceLocation LitEndLoc) { 1607 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1608 1609 QualType ArgTy[2]; 1610 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1611 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1612 if (ArgTy[ArgIdx]->isArrayType()) 1613 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1614 } 1615 1616 DeclarationName OpName = 1617 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1618 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1619 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1620 1621 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1622 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1623 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1624 /*AllowStringTemplate*/ false, 1625 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1626 return ExprError(); 1627 1628 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1629 } 1630 1631 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1632 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1633 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1634 /// multiple tokens. However, the common case is that StringToks points to one 1635 /// string. 1636 /// 1637 ExprResult 1638 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1639 assert(!StringToks.empty() && "Must have at least one string!"); 1640 1641 StringLiteralParser Literal(StringToks, PP); 1642 if (Literal.hadError) 1643 return ExprError(); 1644 1645 SmallVector<SourceLocation, 4> StringTokLocs; 1646 for (const Token &Tok : StringToks) 1647 StringTokLocs.push_back(Tok.getLocation()); 1648 1649 QualType CharTy = Context.CharTy; 1650 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1651 if (Literal.isWide()) { 1652 CharTy = Context.getWideCharType(); 1653 Kind = StringLiteral::Wide; 1654 } else if (Literal.isUTF8()) { 1655 if (getLangOpts().Char8) 1656 CharTy = Context.Char8Ty; 1657 Kind = StringLiteral::UTF8; 1658 } else if (Literal.isUTF16()) { 1659 CharTy = Context.Char16Ty; 1660 Kind = StringLiteral::UTF16; 1661 } else if (Literal.isUTF32()) { 1662 CharTy = Context.Char32Ty; 1663 Kind = StringLiteral::UTF32; 1664 } else if (Literal.isPascal()) { 1665 CharTy = Context.UnsignedCharTy; 1666 } 1667 1668 // Warn on initializing an array of char from a u8 string literal; this 1669 // becomes ill-formed in C++2a. 1670 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus2a && 1671 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1672 Diag(StringTokLocs.front(), diag::warn_cxx2a_compat_utf8_string); 1673 1674 // Create removals for all 'u8' prefixes in the string literal(s). This 1675 // ensures C++2a compatibility (but may change the program behavior when 1676 // built by non-Clang compilers for which the execution character set is 1677 // not always UTF-8). 1678 auto RemovalDiag = PDiag(diag::note_cxx2a_compat_utf8_string_remove_u8); 1679 SourceLocation RemovalDiagLoc; 1680 for (const Token &Tok : StringToks) { 1681 if (Tok.getKind() == tok::utf8_string_literal) { 1682 if (RemovalDiagLoc.isInvalid()) 1683 RemovalDiagLoc = Tok.getLocation(); 1684 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1685 Tok.getLocation(), 1686 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1687 getSourceManager(), getLangOpts()))); 1688 } 1689 } 1690 Diag(RemovalDiagLoc, RemovalDiag); 1691 } 1692 1693 QualType StrTy = 1694 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); 1695 1696 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1697 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1698 Kind, Literal.Pascal, StrTy, 1699 &StringTokLocs[0], 1700 StringTokLocs.size()); 1701 if (Literal.getUDSuffix().empty()) 1702 return Lit; 1703 1704 // We're building a user-defined literal. 1705 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1706 SourceLocation UDSuffixLoc = 1707 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1708 Literal.getUDSuffixOffset()); 1709 1710 // Make sure we're allowed user-defined literals here. 1711 if (!UDLScope) 1712 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1713 1714 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1715 // operator "" X (str, len) 1716 QualType SizeType = Context.getSizeType(); 1717 1718 DeclarationName OpName = 1719 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1720 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1721 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1722 1723 QualType ArgTy[] = { 1724 Context.getArrayDecayedType(StrTy), SizeType 1725 }; 1726 1727 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1728 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1729 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1730 /*AllowStringTemplate*/ true, 1731 /*DiagnoseMissing*/ true)) { 1732 1733 case LOLR_Cooked: { 1734 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1735 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1736 StringTokLocs[0]); 1737 Expr *Args[] = { Lit, LenArg }; 1738 1739 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1740 } 1741 1742 case LOLR_StringTemplate: { 1743 TemplateArgumentListInfo ExplicitArgs; 1744 1745 unsigned CharBits = Context.getIntWidth(CharTy); 1746 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1747 llvm::APSInt Value(CharBits, CharIsUnsigned); 1748 1749 TemplateArgument TypeArg(CharTy); 1750 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1751 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1752 1753 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1754 Value = Lit->getCodeUnit(I); 1755 TemplateArgument Arg(Context, Value, CharTy); 1756 TemplateArgumentLocInfo ArgInfo; 1757 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1758 } 1759 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1760 &ExplicitArgs); 1761 } 1762 case LOLR_Raw: 1763 case LOLR_Template: 1764 case LOLR_ErrorNoDiagnostic: 1765 llvm_unreachable("unexpected literal operator lookup result"); 1766 case LOLR_Error: 1767 return ExprError(); 1768 } 1769 llvm_unreachable("unexpected literal operator lookup result"); 1770 } 1771 1772 DeclRefExpr * 1773 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1774 SourceLocation Loc, 1775 const CXXScopeSpec *SS) { 1776 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1777 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1778 } 1779 1780 DeclRefExpr * 1781 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1782 const DeclarationNameInfo &NameInfo, 1783 const CXXScopeSpec *SS, NamedDecl *FoundD, 1784 SourceLocation TemplateKWLoc, 1785 const TemplateArgumentListInfo *TemplateArgs) { 1786 NestedNameSpecifierLoc NNS = 1787 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); 1788 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, 1789 TemplateArgs); 1790 } 1791 1792 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { 1793 // A declaration named in an unevaluated operand never constitutes an odr-use. 1794 if (isUnevaluatedContext()) 1795 return NOUR_Unevaluated; 1796 1797 // C++2a [basic.def.odr]p4: 1798 // A variable x whose name appears as a potentially-evaluated expression e 1799 // is odr-used by e unless [...] x is a reference that is usable in 1800 // constant expressions. 1801 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 1802 if (VD->getType()->isReferenceType() && 1803 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && 1804 VD->isUsableInConstantExpressions(Context)) 1805 return NOUR_Constant; 1806 } 1807 1808 // All remaining non-variable cases constitute an odr-use. For variables, we 1809 // need to wait and see how the expression is used. 1810 return NOUR_None; 1811 } 1812 1813 /// BuildDeclRefExpr - Build an expression that references a 1814 /// declaration that does not require a closure capture. 1815 DeclRefExpr * 1816 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1817 const DeclarationNameInfo &NameInfo, 1818 NestedNameSpecifierLoc NNS, NamedDecl *FoundD, 1819 SourceLocation TemplateKWLoc, 1820 const TemplateArgumentListInfo *TemplateArgs) { 1821 bool RefersToCapturedVariable = 1822 isa<VarDecl>(D) && 1823 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1824 1825 DeclRefExpr *E = DeclRefExpr::Create( 1826 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, 1827 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); 1828 MarkDeclRefReferenced(E); 1829 1830 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1831 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 1832 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 1833 getCurFunction()->recordUseOfWeak(E); 1834 1835 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1836 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 1837 FD = IFD->getAnonField(); 1838 if (FD) { 1839 UnusedPrivateFields.remove(FD); 1840 // Just in case we're building an illegal pointer-to-member. 1841 if (FD->isBitField()) 1842 E->setObjectKind(OK_BitField); 1843 } 1844 1845 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1846 // designates a bit-field. 1847 if (auto *BD = dyn_cast<BindingDecl>(D)) 1848 if (auto *BE = BD->getBinding()) 1849 E->setObjectKind(BE->getObjectKind()); 1850 1851 return E; 1852 } 1853 1854 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1855 /// possibly a list of template arguments. 1856 /// 1857 /// If this produces template arguments, it is permitted to call 1858 /// DecomposeTemplateName. 1859 /// 1860 /// This actually loses a lot of source location information for 1861 /// non-standard name kinds; we should consider preserving that in 1862 /// some way. 1863 void 1864 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1865 TemplateArgumentListInfo &Buffer, 1866 DeclarationNameInfo &NameInfo, 1867 const TemplateArgumentListInfo *&TemplateArgs) { 1868 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 1869 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1870 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1871 1872 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1873 Id.TemplateId->NumArgs); 1874 translateTemplateArguments(TemplateArgsPtr, Buffer); 1875 1876 TemplateName TName = Id.TemplateId->Template.get(); 1877 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1878 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1879 TemplateArgs = &Buffer; 1880 } else { 1881 NameInfo = GetNameFromUnqualifiedId(Id); 1882 TemplateArgs = nullptr; 1883 } 1884 } 1885 1886 static void emitEmptyLookupTypoDiagnostic( 1887 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1888 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1889 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1890 DeclContext *Ctx = 1891 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1892 if (!TC) { 1893 // Emit a special diagnostic for failed member lookups. 1894 // FIXME: computing the declaration context might fail here (?) 1895 if (Ctx) 1896 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1897 << SS.getRange(); 1898 else 1899 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1900 return; 1901 } 1902 1903 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1904 bool DroppedSpecifier = 1905 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1906 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1907 ? diag::note_implicit_param_decl 1908 : diag::note_previous_decl; 1909 if (!Ctx) 1910 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1911 SemaRef.PDiag(NoteID)); 1912 else 1913 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1914 << Typo << Ctx << DroppedSpecifier 1915 << SS.getRange(), 1916 SemaRef.PDiag(NoteID)); 1917 } 1918 1919 /// Diagnose an empty lookup. 1920 /// 1921 /// \return false if new lookup candidates were found 1922 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1923 CorrectionCandidateCallback &CCC, 1924 TemplateArgumentListInfo *ExplicitTemplateArgs, 1925 ArrayRef<Expr *> Args, TypoExpr **Out) { 1926 DeclarationName Name = R.getLookupName(); 1927 1928 unsigned diagnostic = diag::err_undeclared_var_use; 1929 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1930 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1931 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1932 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1933 diagnostic = diag::err_undeclared_use; 1934 diagnostic_suggest = diag::err_undeclared_use_suggest; 1935 } 1936 1937 // If the original lookup was an unqualified lookup, fake an 1938 // unqualified lookup. This is useful when (for example) the 1939 // original lookup would not have found something because it was a 1940 // dependent name. 1941 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1942 while (DC) { 1943 if (isa<CXXRecordDecl>(DC)) { 1944 LookupQualifiedName(R, DC); 1945 1946 if (!R.empty()) { 1947 // Don't give errors about ambiguities in this lookup. 1948 R.suppressDiagnostics(); 1949 1950 // During a default argument instantiation the CurContext points 1951 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1952 // function parameter list, hence add an explicit check. 1953 bool isDefaultArgument = 1954 !CodeSynthesisContexts.empty() && 1955 CodeSynthesisContexts.back().Kind == 1956 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 1957 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1958 bool isInstance = CurMethod && 1959 CurMethod->isInstance() && 1960 DC == CurMethod->getParent() && !isDefaultArgument; 1961 1962 // Give a code modification hint to insert 'this->'. 1963 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1964 // Actually quite difficult! 1965 if (getLangOpts().MSVCCompat) 1966 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1967 if (isInstance) { 1968 Diag(R.getNameLoc(), diagnostic) << Name 1969 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1970 CheckCXXThisCapture(R.getNameLoc()); 1971 } else { 1972 Diag(R.getNameLoc(), diagnostic) << Name; 1973 } 1974 1975 // Do we really want to note all of these? 1976 for (NamedDecl *D : R) 1977 Diag(D->getLocation(), diag::note_dependent_var_use); 1978 1979 // Return true if we are inside a default argument instantiation 1980 // and the found name refers to an instance member function, otherwise 1981 // the function calling DiagnoseEmptyLookup will try to create an 1982 // implicit member call and this is wrong for default argument. 1983 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1984 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1985 return true; 1986 } 1987 1988 // Tell the callee to try to recover. 1989 return false; 1990 } 1991 1992 R.clear(); 1993 } 1994 1995 DC = DC->getLookupParent(); 1996 } 1997 1998 // We didn't find anything, so try to correct for a typo. 1999 TypoCorrection Corrected; 2000 if (S && Out) { 2001 SourceLocation TypoLoc = R.getNameLoc(); 2002 assert(!ExplicitTemplateArgs && 2003 "Diagnosing an empty lookup with explicit template args!"); 2004 *Out = CorrectTypoDelayed( 2005 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 2006 [=](const TypoCorrection &TC) { 2007 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2008 diagnostic, diagnostic_suggest); 2009 }, 2010 nullptr, CTK_ErrorRecovery); 2011 if (*Out) 2012 return true; 2013 } else if (S && 2014 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 2015 S, &SS, CCC, CTK_ErrorRecovery))) { 2016 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2017 bool DroppedSpecifier = 2018 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2019 R.setLookupName(Corrected.getCorrection()); 2020 2021 bool AcceptableWithRecovery = false; 2022 bool AcceptableWithoutRecovery = false; 2023 NamedDecl *ND = Corrected.getFoundDecl(); 2024 if (ND) { 2025 if (Corrected.isOverloaded()) { 2026 OverloadCandidateSet OCS(R.getNameLoc(), 2027 OverloadCandidateSet::CSK_Normal); 2028 OverloadCandidateSet::iterator Best; 2029 for (NamedDecl *CD : Corrected) { 2030 if (FunctionTemplateDecl *FTD = 2031 dyn_cast<FunctionTemplateDecl>(CD)) 2032 AddTemplateOverloadCandidate( 2033 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2034 Args, OCS); 2035 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2036 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2037 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2038 Args, OCS); 2039 } 2040 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2041 case OR_Success: 2042 ND = Best->FoundDecl; 2043 Corrected.setCorrectionDecl(ND); 2044 break; 2045 default: 2046 // FIXME: Arbitrarily pick the first declaration for the note. 2047 Corrected.setCorrectionDecl(ND); 2048 break; 2049 } 2050 } 2051 R.addDecl(ND); 2052 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2053 CXXRecordDecl *Record = nullptr; 2054 if (Corrected.getCorrectionSpecifier()) { 2055 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2056 Record = Ty->getAsCXXRecordDecl(); 2057 } 2058 if (!Record) 2059 Record = cast<CXXRecordDecl>( 2060 ND->getDeclContext()->getRedeclContext()); 2061 R.setNamingClass(Record); 2062 } 2063 2064 auto *UnderlyingND = ND->getUnderlyingDecl(); 2065 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2066 isa<FunctionTemplateDecl>(UnderlyingND); 2067 // FIXME: If we ended up with a typo for a type name or 2068 // Objective-C class name, we're in trouble because the parser 2069 // is in the wrong place to recover. Suggest the typo 2070 // correction, but don't make it a fix-it since we're not going 2071 // to recover well anyway. 2072 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || 2073 getAsTypeTemplateDecl(UnderlyingND) || 2074 isa<ObjCInterfaceDecl>(UnderlyingND); 2075 } else { 2076 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2077 // because we aren't able to recover. 2078 AcceptableWithoutRecovery = true; 2079 } 2080 2081 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2082 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2083 ? diag::note_implicit_param_decl 2084 : diag::note_previous_decl; 2085 if (SS.isEmpty()) 2086 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2087 PDiag(NoteID), AcceptableWithRecovery); 2088 else 2089 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2090 << Name << computeDeclContext(SS, false) 2091 << DroppedSpecifier << SS.getRange(), 2092 PDiag(NoteID), AcceptableWithRecovery); 2093 2094 // Tell the callee whether to try to recover. 2095 return !AcceptableWithRecovery; 2096 } 2097 } 2098 R.clear(); 2099 2100 // Emit a special diagnostic for failed member lookups. 2101 // FIXME: computing the declaration context might fail here (?) 2102 if (!SS.isEmpty()) { 2103 Diag(R.getNameLoc(), diag::err_no_member) 2104 << Name << computeDeclContext(SS, false) 2105 << SS.getRange(); 2106 return true; 2107 } 2108 2109 // Give up, we can't recover. 2110 Diag(R.getNameLoc(), diagnostic) << Name; 2111 return true; 2112 } 2113 2114 /// In Microsoft mode, if we are inside a template class whose parent class has 2115 /// dependent base classes, and we can't resolve an unqualified identifier, then 2116 /// assume the identifier is a member of a dependent base class. We can only 2117 /// recover successfully in static methods, instance methods, and other contexts 2118 /// where 'this' is available. This doesn't precisely match MSVC's 2119 /// instantiation model, but it's close enough. 2120 static Expr * 2121 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2122 DeclarationNameInfo &NameInfo, 2123 SourceLocation TemplateKWLoc, 2124 const TemplateArgumentListInfo *TemplateArgs) { 2125 // Only try to recover from lookup into dependent bases in static methods or 2126 // contexts where 'this' is available. 2127 QualType ThisType = S.getCurrentThisType(); 2128 const CXXRecordDecl *RD = nullptr; 2129 if (!ThisType.isNull()) 2130 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2131 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2132 RD = MD->getParent(); 2133 if (!RD || !RD->hasAnyDependentBases()) 2134 return nullptr; 2135 2136 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2137 // is available, suggest inserting 'this->' as a fixit. 2138 SourceLocation Loc = NameInfo.getLoc(); 2139 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2140 DB << NameInfo.getName() << RD; 2141 2142 if (!ThisType.isNull()) { 2143 DB << FixItHint::CreateInsertion(Loc, "this->"); 2144 return CXXDependentScopeMemberExpr::Create( 2145 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2146 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2147 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); 2148 } 2149 2150 // Synthesize a fake NNS that points to the derived class. This will 2151 // perform name lookup during template instantiation. 2152 CXXScopeSpec SS; 2153 auto *NNS = 2154 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2155 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2156 return DependentScopeDeclRefExpr::Create( 2157 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2158 TemplateArgs); 2159 } 2160 2161 ExprResult 2162 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2163 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2164 bool HasTrailingLParen, bool IsAddressOfOperand, 2165 CorrectionCandidateCallback *CCC, 2166 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2167 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2168 "cannot be direct & operand and have a trailing lparen"); 2169 if (SS.isInvalid()) 2170 return ExprError(); 2171 2172 TemplateArgumentListInfo TemplateArgsBuffer; 2173 2174 // Decompose the UnqualifiedId into the following data. 2175 DeclarationNameInfo NameInfo; 2176 const TemplateArgumentListInfo *TemplateArgs; 2177 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2178 2179 DeclarationName Name = NameInfo.getName(); 2180 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2181 SourceLocation NameLoc = NameInfo.getLoc(); 2182 2183 if (II && II->isEditorPlaceholder()) { 2184 // FIXME: When typed placeholders are supported we can create a typed 2185 // placeholder expression node. 2186 return ExprError(); 2187 } 2188 2189 // C++ [temp.dep.expr]p3: 2190 // An id-expression is type-dependent if it contains: 2191 // -- an identifier that was declared with a dependent type, 2192 // (note: handled after lookup) 2193 // -- a template-id that is dependent, 2194 // (note: handled in BuildTemplateIdExpr) 2195 // -- a conversion-function-id that specifies a dependent type, 2196 // -- a nested-name-specifier that contains a class-name that 2197 // names a dependent type. 2198 // Determine whether this is a member of an unknown specialization; 2199 // we need to handle these differently. 2200 bool DependentID = false; 2201 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2202 Name.getCXXNameType()->isDependentType()) { 2203 DependentID = true; 2204 } else if (SS.isSet()) { 2205 if (DeclContext *DC = computeDeclContext(SS, false)) { 2206 if (RequireCompleteDeclContext(SS, DC)) 2207 return ExprError(); 2208 } else { 2209 DependentID = true; 2210 } 2211 } 2212 2213 if (DependentID) 2214 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2215 IsAddressOfOperand, TemplateArgs); 2216 2217 // Perform the required lookup. 2218 LookupResult R(*this, NameInfo, 2219 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2220 ? LookupObjCImplicitSelfParam 2221 : LookupOrdinaryName); 2222 if (TemplateKWLoc.isValid() || TemplateArgs) { 2223 // Lookup the template name again to correctly establish the context in 2224 // which it was found. This is really unfortunate as we already did the 2225 // lookup to determine that it was a template name in the first place. If 2226 // this becomes a performance hit, we can work harder to preserve those 2227 // results until we get here but it's likely not worth it. 2228 bool MemberOfUnknownSpecialization; 2229 AssumedTemplateKind AssumedTemplate; 2230 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2231 MemberOfUnknownSpecialization, TemplateKWLoc, 2232 &AssumedTemplate)) 2233 return ExprError(); 2234 2235 if (MemberOfUnknownSpecialization || 2236 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2237 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2238 IsAddressOfOperand, TemplateArgs); 2239 } else { 2240 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2241 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2242 2243 // If the result might be in a dependent base class, this is a dependent 2244 // id-expression. 2245 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2246 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2247 IsAddressOfOperand, TemplateArgs); 2248 2249 // If this reference is in an Objective-C method, then we need to do 2250 // some special Objective-C lookup, too. 2251 if (IvarLookupFollowUp) { 2252 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2253 if (E.isInvalid()) 2254 return ExprError(); 2255 2256 if (Expr *Ex = E.getAs<Expr>()) 2257 return Ex; 2258 } 2259 } 2260 2261 if (R.isAmbiguous()) 2262 return ExprError(); 2263 2264 // This could be an implicitly declared function reference (legal in C90, 2265 // extension in C99, forbidden in C++). 2266 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2267 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2268 if (D) R.addDecl(D); 2269 } 2270 2271 // Determine whether this name might be a candidate for 2272 // argument-dependent lookup. 2273 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2274 2275 if (R.empty() && !ADL) { 2276 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2277 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2278 TemplateKWLoc, TemplateArgs)) 2279 return E; 2280 } 2281 2282 // Don't diagnose an empty lookup for inline assembly. 2283 if (IsInlineAsmIdentifier) 2284 return ExprError(); 2285 2286 // If this name wasn't predeclared and if this is not a function 2287 // call, diagnose the problem. 2288 TypoExpr *TE = nullptr; 2289 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2290 : nullptr); 2291 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2292 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2293 "Typo correction callback misconfigured"); 2294 if (CCC) { 2295 // Make sure the callback knows what the typo being diagnosed is. 2296 CCC->setTypoName(II); 2297 if (SS.isValid()) 2298 CCC->setTypoNNS(SS.getScopeRep()); 2299 } 2300 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2301 // a template name, but we happen to have always already looked up the name 2302 // before we get here if it must be a template name. 2303 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2304 None, &TE)) { 2305 if (TE && KeywordReplacement) { 2306 auto &State = getTypoExprState(TE); 2307 auto BestTC = State.Consumer->getNextCorrection(); 2308 if (BestTC.isKeyword()) { 2309 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2310 if (State.DiagHandler) 2311 State.DiagHandler(BestTC); 2312 KeywordReplacement->startToken(); 2313 KeywordReplacement->setKind(II->getTokenID()); 2314 KeywordReplacement->setIdentifierInfo(II); 2315 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2316 // Clean up the state associated with the TypoExpr, since it has 2317 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2318 clearDelayedTypo(TE); 2319 // Signal that a correction to a keyword was performed by returning a 2320 // valid-but-null ExprResult. 2321 return (Expr*)nullptr; 2322 } 2323 State.Consumer->resetCorrectionStream(); 2324 } 2325 return TE ? TE : ExprError(); 2326 } 2327 2328 assert(!R.empty() && 2329 "DiagnoseEmptyLookup returned false but added no results"); 2330 2331 // If we found an Objective-C instance variable, let 2332 // LookupInObjCMethod build the appropriate expression to 2333 // reference the ivar. 2334 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2335 R.clear(); 2336 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2337 // In a hopelessly buggy code, Objective-C instance variable 2338 // lookup fails and no expression will be built to reference it. 2339 if (!E.isInvalid() && !E.get()) 2340 return ExprError(); 2341 return E; 2342 } 2343 } 2344 2345 // This is guaranteed from this point on. 2346 assert(!R.empty() || ADL); 2347 2348 // Check whether this might be a C++ implicit instance member access. 2349 // C++ [class.mfct.non-static]p3: 2350 // When an id-expression that is not part of a class member access 2351 // syntax and not used to form a pointer to member is used in the 2352 // body of a non-static member function of class X, if name lookup 2353 // resolves the name in the id-expression to a non-static non-type 2354 // member of some class C, the id-expression is transformed into a 2355 // class member access expression using (*this) as the 2356 // postfix-expression to the left of the . operator. 2357 // 2358 // But we don't actually need to do this for '&' operands if R 2359 // resolved to a function or overloaded function set, because the 2360 // expression is ill-formed if it actually works out to be a 2361 // non-static member function: 2362 // 2363 // C++ [expr.ref]p4: 2364 // Otherwise, if E1.E2 refers to a non-static member function. . . 2365 // [t]he expression can be used only as the left-hand operand of a 2366 // member function call. 2367 // 2368 // There are other safeguards against such uses, but it's important 2369 // to get this right here so that we don't end up making a 2370 // spuriously dependent expression if we're inside a dependent 2371 // instance method. 2372 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2373 bool MightBeImplicitMember; 2374 if (!IsAddressOfOperand) 2375 MightBeImplicitMember = true; 2376 else if (!SS.isEmpty()) 2377 MightBeImplicitMember = false; 2378 else if (R.isOverloadedResult()) 2379 MightBeImplicitMember = false; 2380 else if (R.isUnresolvableResult()) 2381 MightBeImplicitMember = true; 2382 else 2383 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2384 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2385 isa<MSPropertyDecl>(R.getFoundDecl()); 2386 2387 if (MightBeImplicitMember) 2388 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2389 R, TemplateArgs, S); 2390 } 2391 2392 if (TemplateArgs || TemplateKWLoc.isValid()) { 2393 2394 // In C++1y, if this is a variable template id, then check it 2395 // in BuildTemplateIdExpr(). 2396 // The single lookup result must be a variable template declaration. 2397 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2398 Id.TemplateId->Kind == TNK_Var_template) { 2399 assert(R.getAsSingle<VarTemplateDecl>() && 2400 "There should only be one declaration found."); 2401 } 2402 2403 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2404 } 2405 2406 return BuildDeclarationNameExpr(SS, R, ADL); 2407 } 2408 2409 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2410 /// declaration name, generally during template instantiation. 2411 /// There's a large number of things which don't need to be done along 2412 /// this path. 2413 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2414 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2415 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2416 DeclContext *DC = computeDeclContext(SS, false); 2417 if (!DC) 2418 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2419 NameInfo, /*TemplateArgs=*/nullptr); 2420 2421 if (RequireCompleteDeclContext(SS, DC)) 2422 return ExprError(); 2423 2424 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2425 LookupQualifiedName(R, DC); 2426 2427 if (R.isAmbiguous()) 2428 return ExprError(); 2429 2430 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2431 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2432 NameInfo, /*TemplateArgs=*/nullptr); 2433 2434 if (R.empty()) { 2435 Diag(NameInfo.getLoc(), diag::err_no_member) 2436 << NameInfo.getName() << DC << SS.getRange(); 2437 return ExprError(); 2438 } 2439 2440 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2441 // Diagnose a missing typename if this resolved unambiguously to a type in 2442 // a dependent context. If we can recover with a type, downgrade this to 2443 // a warning in Microsoft compatibility mode. 2444 unsigned DiagID = diag::err_typename_missing; 2445 if (RecoveryTSI && getLangOpts().MSVCCompat) 2446 DiagID = diag::ext_typename_missing; 2447 SourceLocation Loc = SS.getBeginLoc(); 2448 auto D = Diag(Loc, DiagID); 2449 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2450 << SourceRange(Loc, NameInfo.getEndLoc()); 2451 2452 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2453 // context. 2454 if (!RecoveryTSI) 2455 return ExprError(); 2456 2457 // Only issue the fixit if we're prepared to recover. 2458 D << FixItHint::CreateInsertion(Loc, "typename "); 2459 2460 // Recover by pretending this was an elaborated type. 2461 QualType Ty = Context.getTypeDeclType(TD); 2462 TypeLocBuilder TLB; 2463 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2464 2465 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2466 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2467 QTL.setElaboratedKeywordLoc(SourceLocation()); 2468 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2469 2470 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2471 2472 return ExprEmpty(); 2473 } 2474 2475 // Defend against this resolving to an implicit member access. We usually 2476 // won't get here if this might be a legitimate a class member (we end up in 2477 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2478 // a pointer-to-member or in an unevaluated context in C++11. 2479 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2480 return BuildPossibleImplicitMemberExpr(SS, 2481 /*TemplateKWLoc=*/SourceLocation(), 2482 R, /*TemplateArgs=*/nullptr, S); 2483 2484 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2485 } 2486 2487 /// The parser has read a name in, and Sema has detected that we're currently 2488 /// inside an ObjC method. Perform some additional checks and determine if we 2489 /// should form a reference to an ivar. 2490 /// 2491 /// Ideally, most of this would be done by lookup, but there's 2492 /// actually quite a lot of extra work involved. 2493 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 2494 IdentifierInfo *II) { 2495 SourceLocation Loc = Lookup.getNameLoc(); 2496 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2497 2498 // Check for error condition which is already reported. 2499 if (!CurMethod) 2500 return DeclResult(true); 2501 2502 // There are two cases to handle here. 1) scoped lookup could have failed, 2503 // in which case we should look for an ivar. 2) scoped lookup could have 2504 // found a decl, but that decl is outside the current instance method (i.e. 2505 // a global variable). In these two cases, we do a lookup for an ivar with 2506 // this name, if the lookup sucedes, we replace it our current decl. 2507 2508 // If we're in a class method, we don't normally want to look for 2509 // ivars. But if we don't find anything else, and there's an 2510 // ivar, that's an error. 2511 bool IsClassMethod = CurMethod->isClassMethod(); 2512 2513 bool LookForIvars; 2514 if (Lookup.empty()) 2515 LookForIvars = true; 2516 else if (IsClassMethod) 2517 LookForIvars = false; 2518 else 2519 LookForIvars = (Lookup.isSingleResult() && 2520 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2521 ObjCInterfaceDecl *IFace = nullptr; 2522 if (LookForIvars) { 2523 IFace = CurMethod->getClassInterface(); 2524 ObjCInterfaceDecl *ClassDeclared; 2525 ObjCIvarDecl *IV = nullptr; 2526 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2527 // Diagnose using an ivar in a class method. 2528 if (IsClassMethod) { 2529 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2530 return DeclResult(true); 2531 } 2532 2533 // Diagnose the use of an ivar outside of the declaring class. 2534 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2535 !declaresSameEntity(ClassDeclared, IFace) && 2536 !getLangOpts().DebuggerSupport) 2537 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2538 2539 // Success. 2540 return IV; 2541 } 2542 } else if (CurMethod->isInstanceMethod()) { 2543 // We should warn if a local variable hides an ivar. 2544 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2545 ObjCInterfaceDecl *ClassDeclared; 2546 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2547 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2548 declaresSameEntity(IFace, ClassDeclared)) 2549 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2550 } 2551 } 2552 } else if (Lookup.isSingleResult() && 2553 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2554 // If accessing a stand-alone ivar in a class method, this is an error. 2555 if (const ObjCIvarDecl *IV = 2556 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { 2557 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2558 return DeclResult(true); 2559 } 2560 } 2561 2562 // Didn't encounter an error, didn't find an ivar. 2563 return DeclResult(false); 2564 } 2565 2566 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, 2567 ObjCIvarDecl *IV) { 2568 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2569 assert(CurMethod && CurMethod->isInstanceMethod() && 2570 "should not reference ivar from this context"); 2571 2572 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 2573 assert(IFace && "should not reference ivar from this context"); 2574 2575 // If we're referencing an invalid decl, just return this as a silent 2576 // error node. The error diagnostic was already emitted on the decl. 2577 if (IV->isInvalidDecl()) 2578 return ExprError(); 2579 2580 // Check if referencing a field with __attribute__((deprecated)). 2581 if (DiagnoseUseOfDecl(IV, Loc)) 2582 return ExprError(); 2583 2584 // FIXME: This should use a new expr for a direct reference, don't 2585 // turn this into Self->ivar, just return a BareIVarExpr or something. 2586 IdentifierInfo &II = Context.Idents.get("self"); 2587 UnqualifiedId SelfName; 2588 SelfName.setIdentifier(&II, SourceLocation()); 2589 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam); 2590 CXXScopeSpec SelfScopeSpec; 2591 SourceLocation TemplateKWLoc; 2592 ExprResult SelfExpr = 2593 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2594 /*HasTrailingLParen=*/false, 2595 /*IsAddressOfOperand=*/false); 2596 if (SelfExpr.isInvalid()) 2597 return ExprError(); 2598 2599 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2600 if (SelfExpr.isInvalid()) 2601 return ExprError(); 2602 2603 MarkAnyDeclReferenced(Loc, IV, true); 2604 2605 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2606 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2607 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2608 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2609 2610 ObjCIvarRefExpr *Result = new (Context) 2611 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2612 IV->getLocation(), SelfExpr.get(), true, true); 2613 2614 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2615 if (!isUnevaluatedContext() && 2616 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2617 getCurFunction()->recordUseOfWeak(Result); 2618 } 2619 if (getLangOpts().ObjCAutoRefCount) 2620 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2621 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2622 2623 return Result; 2624 } 2625 2626 /// The parser has read a name in, and Sema has detected that we're currently 2627 /// inside an ObjC method. Perform some additional checks and determine if we 2628 /// should form a reference to an ivar. If so, build an expression referencing 2629 /// that ivar. 2630 ExprResult 2631 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2632 IdentifierInfo *II, bool AllowBuiltinCreation) { 2633 // FIXME: Integrate this lookup step into LookupParsedName. 2634 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); 2635 if (Ivar.isInvalid()) 2636 return ExprError(); 2637 if (Ivar.isUsable()) 2638 return BuildIvarRefExpr(S, Lookup.getNameLoc(), 2639 cast<ObjCIvarDecl>(Ivar.get())); 2640 2641 if (Lookup.empty() && II && AllowBuiltinCreation) 2642 LookupBuiltin(Lookup); 2643 2644 // Sentinel value saying that we didn't do anything special. 2645 return ExprResult(false); 2646 } 2647 2648 /// Cast a base object to a member's actual type. 2649 /// 2650 /// Logically this happens in three phases: 2651 /// 2652 /// * First we cast from the base type to the naming class. 2653 /// The naming class is the class into which we were looking 2654 /// when we found the member; it's the qualifier type if a 2655 /// qualifier was provided, and otherwise it's the base type. 2656 /// 2657 /// * Next we cast from the naming class to the declaring class. 2658 /// If the member we found was brought into a class's scope by 2659 /// a using declaration, this is that class; otherwise it's 2660 /// the class declaring the member. 2661 /// 2662 /// * Finally we cast from the declaring class to the "true" 2663 /// declaring class of the member. This conversion does not 2664 /// obey access control. 2665 ExprResult 2666 Sema::PerformObjectMemberConversion(Expr *From, 2667 NestedNameSpecifier *Qualifier, 2668 NamedDecl *FoundDecl, 2669 NamedDecl *Member) { 2670 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2671 if (!RD) 2672 return From; 2673 2674 QualType DestRecordType; 2675 QualType DestType; 2676 QualType FromRecordType; 2677 QualType FromType = From->getType(); 2678 bool PointerConversions = false; 2679 if (isa<FieldDecl>(Member)) { 2680 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2681 auto FromPtrType = FromType->getAs<PointerType>(); 2682 DestRecordType = Context.getAddrSpaceQualType( 2683 DestRecordType, FromPtrType 2684 ? FromType->getPointeeType().getAddressSpace() 2685 : FromType.getAddressSpace()); 2686 2687 if (FromPtrType) { 2688 DestType = Context.getPointerType(DestRecordType); 2689 FromRecordType = FromPtrType->getPointeeType(); 2690 PointerConversions = true; 2691 } else { 2692 DestType = DestRecordType; 2693 FromRecordType = FromType; 2694 } 2695 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2696 if (Method->isStatic()) 2697 return From; 2698 2699 DestType = Method->getThisType(); 2700 DestRecordType = DestType->getPointeeType(); 2701 2702 if (FromType->getAs<PointerType>()) { 2703 FromRecordType = FromType->getPointeeType(); 2704 PointerConversions = true; 2705 } else { 2706 FromRecordType = FromType; 2707 DestType = DestRecordType; 2708 } 2709 2710 LangAS FromAS = FromRecordType.getAddressSpace(); 2711 LangAS DestAS = DestRecordType.getAddressSpace(); 2712 if (FromAS != DestAS) { 2713 QualType FromRecordTypeWithoutAS = 2714 Context.removeAddrSpaceQualType(FromRecordType); 2715 QualType FromTypeWithDestAS = 2716 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); 2717 if (PointerConversions) 2718 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); 2719 From = ImpCastExprToType(From, FromTypeWithDestAS, 2720 CK_AddressSpaceConversion, From->getValueKind()) 2721 .get(); 2722 } 2723 } else { 2724 // No conversion necessary. 2725 return From; 2726 } 2727 2728 if (DestType->isDependentType() || FromType->isDependentType()) 2729 return From; 2730 2731 // If the unqualified types are the same, no conversion is necessary. 2732 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2733 return From; 2734 2735 SourceRange FromRange = From->getSourceRange(); 2736 SourceLocation FromLoc = FromRange.getBegin(); 2737 2738 ExprValueKind VK = From->getValueKind(); 2739 2740 // C++ [class.member.lookup]p8: 2741 // [...] Ambiguities can often be resolved by qualifying a name with its 2742 // class name. 2743 // 2744 // If the member was a qualified name and the qualified referred to a 2745 // specific base subobject type, we'll cast to that intermediate type 2746 // first and then to the object in which the member is declared. That allows 2747 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2748 // 2749 // class Base { public: int x; }; 2750 // class Derived1 : public Base { }; 2751 // class Derived2 : public Base { }; 2752 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2753 // 2754 // void VeryDerived::f() { 2755 // x = 17; // error: ambiguous base subobjects 2756 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2757 // } 2758 if (Qualifier && Qualifier->getAsType()) { 2759 QualType QType = QualType(Qualifier->getAsType(), 0); 2760 assert(QType->isRecordType() && "lookup done with non-record type"); 2761 2762 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2763 2764 // In C++98, the qualifier type doesn't actually have to be a base 2765 // type of the object type, in which case we just ignore it. 2766 // Otherwise build the appropriate casts. 2767 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2768 CXXCastPath BasePath; 2769 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2770 FromLoc, FromRange, &BasePath)) 2771 return ExprError(); 2772 2773 if (PointerConversions) 2774 QType = Context.getPointerType(QType); 2775 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2776 VK, &BasePath).get(); 2777 2778 FromType = QType; 2779 FromRecordType = QRecordType; 2780 2781 // If the qualifier type was the same as the destination type, 2782 // we're done. 2783 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2784 return From; 2785 } 2786 } 2787 2788 bool IgnoreAccess = false; 2789 2790 // If we actually found the member through a using declaration, cast 2791 // down to the using declaration's type. 2792 // 2793 // Pointer equality is fine here because only one declaration of a 2794 // class ever has member declarations. 2795 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2796 assert(isa<UsingShadowDecl>(FoundDecl)); 2797 QualType URecordType = Context.getTypeDeclType( 2798 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2799 2800 // We only need to do this if the naming-class to declaring-class 2801 // conversion is non-trivial. 2802 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2803 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2804 CXXCastPath BasePath; 2805 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2806 FromLoc, FromRange, &BasePath)) 2807 return ExprError(); 2808 2809 QualType UType = URecordType; 2810 if (PointerConversions) 2811 UType = Context.getPointerType(UType); 2812 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2813 VK, &BasePath).get(); 2814 FromType = UType; 2815 FromRecordType = URecordType; 2816 } 2817 2818 // We don't do access control for the conversion from the 2819 // declaring class to the true declaring class. 2820 IgnoreAccess = true; 2821 } 2822 2823 CXXCastPath BasePath; 2824 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2825 FromLoc, FromRange, &BasePath, 2826 IgnoreAccess)) 2827 return ExprError(); 2828 2829 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2830 VK, &BasePath); 2831 } 2832 2833 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2834 const LookupResult &R, 2835 bool HasTrailingLParen) { 2836 // Only when used directly as the postfix-expression of a call. 2837 if (!HasTrailingLParen) 2838 return false; 2839 2840 // Never if a scope specifier was provided. 2841 if (SS.isSet()) 2842 return false; 2843 2844 // Only in C++ or ObjC++. 2845 if (!getLangOpts().CPlusPlus) 2846 return false; 2847 2848 // Turn off ADL when we find certain kinds of declarations during 2849 // normal lookup: 2850 for (NamedDecl *D : R) { 2851 // C++0x [basic.lookup.argdep]p3: 2852 // -- a declaration of a class member 2853 // Since using decls preserve this property, we check this on the 2854 // original decl. 2855 if (D->isCXXClassMember()) 2856 return false; 2857 2858 // C++0x [basic.lookup.argdep]p3: 2859 // -- a block-scope function declaration that is not a 2860 // using-declaration 2861 // NOTE: we also trigger this for function templates (in fact, we 2862 // don't check the decl type at all, since all other decl types 2863 // turn off ADL anyway). 2864 if (isa<UsingShadowDecl>(D)) 2865 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2866 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2867 return false; 2868 2869 // C++0x [basic.lookup.argdep]p3: 2870 // -- a declaration that is neither a function or a function 2871 // template 2872 // And also for builtin functions. 2873 if (isa<FunctionDecl>(D)) { 2874 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2875 2876 // But also builtin functions. 2877 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2878 return false; 2879 } else if (!isa<FunctionTemplateDecl>(D)) 2880 return false; 2881 } 2882 2883 return true; 2884 } 2885 2886 2887 /// Diagnoses obvious problems with the use of the given declaration 2888 /// as an expression. This is only actually called for lookups that 2889 /// were not overloaded, and it doesn't promise that the declaration 2890 /// will in fact be used. 2891 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2892 if (D->isInvalidDecl()) 2893 return true; 2894 2895 if (isa<TypedefNameDecl>(D)) { 2896 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2897 return true; 2898 } 2899 2900 if (isa<ObjCInterfaceDecl>(D)) { 2901 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2902 return true; 2903 } 2904 2905 if (isa<NamespaceDecl>(D)) { 2906 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2907 return true; 2908 } 2909 2910 return false; 2911 } 2912 2913 // Certain multiversion types should be treated as overloaded even when there is 2914 // only one result. 2915 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 2916 assert(R.isSingleResult() && "Expected only a single result"); 2917 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 2918 return FD && 2919 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 2920 } 2921 2922 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2923 LookupResult &R, bool NeedsADL, 2924 bool AcceptInvalidDecl) { 2925 // If this is a single, fully-resolved result and we don't need ADL, 2926 // just build an ordinary singleton decl ref. 2927 if (!NeedsADL && R.isSingleResult() && 2928 !R.getAsSingle<FunctionTemplateDecl>() && 2929 !ShouldLookupResultBeMultiVersionOverload(R)) 2930 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2931 R.getRepresentativeDecl(), nullptr, 2932 AcceptInvalidDecl); 2933 2934 // We only need to check the declaration if there's exactly one 2935 // result, because in the overloaded case the results can only be 2936 // functions and function templates. 2937 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 2938 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2939 return ExprError(); 2940 2941 // Otherwise, just build an unresolved lookup expression. Suppress 2942 // any lookup-related diagnostics; we'll hash these out later, when 2943 // we've picked a target. 2944 R.suppressDiagnostics(); 2945 2946 UnresolvedLookupExpr *ULE 2947 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2948 SS.getWithLocInContext(Context), 2949 R.getLookupNameInfo(), 2950 NeedsADL, R.isOverloadedResult(), 2951 R.begin(), R.end()); 2952 2953 return ULE; 2954 } 2955 2956 static void 2957 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 2958 ValueDecl *var, DeclContext *DC); 2959 2960 /// Complete semantic analysis for a reference to the given declaration. 2961 ExprResult Sema::BuildDeclarationNameExpr( 2962 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2963 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2964 bool AcceptInvalidDecl) { 2965 assert(D && "Cannot refer to a NULL declaration"); 2966 assert(!isa<FunctionTemplateDecl>(D) && 2967 "Cannot refer unambiguously to a function template"); 2968 2969 SourceLocation Loc = NameInfo.getLoc(); 2970 if (CheckDeclInExpr(*this, Loc, D)) 2971 return ExprError(); 2972 2973 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2974 // Specifically diagnose references to class templates that are missing 2975 // a template argument list. 2976 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 2977 return ExprError(); 2978 } 2979 2980 // Make sure that we're referring to a value. 2981 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2982 if (!VD) { 2983 Diag(Loc, diag::err_ref_non_value) 2984 << D << SS.getRange(); 2985 Diag(D->getLocation(), diag::note_declared_at); 2986 return ExprError(); 2987 } 2988 2989 // Check whether this declaration can be used. Note that we suppress 2990 // this check when we're going to perform argument-dependent lookup 2991 // on this function name, because this might not be the function 2992 // that overload resolution actually selects. 2993 if (DiagnoseUseOfDecl(VD, Loc)) 2994 return ExprError(); 2995 2996 // Only create DeclRefExpr's for valid Decl's. 2997 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2998 return ExprError(); 2999 3000 // Handle members of anonymous structs and unions. If we got here, 3001 // and the reference is to a class member indirect field, then this 3002 // must be the subject of a pointer-to-member expression. 3003 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 3004 if (!indirectField->isCXXClassMember()) 3005 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 3006 indirectField); 3007 3008 { 3009 QualType type = VD->getType(); 3010 if (type.isNull()) 3011 return ExprError(); 3012 if (auto *FPT = type->getAs<FunctionProtoType>()) { 3013 // C++ [except.spec]p17: 3014 // An exception-specification is considered to be needed when: 3015 // - in an expression, the function is the unique lookup result or 3016 // the selected member of a set of overloaded functions. 3017 ResolveExceptionSpec(Loc, FPT); 3018 type = VD->getType(); 3019 } 3020 ExprValueKind valueKind = VK_RValue; 3021 3022 switch (D->getKind()) { 3023 // Ignore all the non-ValueDecl kinds. 3024 #define ABSTRACT_DECL(kind) 3025 #define VALUE(type, base) 3026 #define DECL(type, base) \ 3027 case Decl::type: 3028 #include "clang/AST/DeclNodes.inc" 3029 llvm_unreachable("invalid value decl kind"); 3030 3031 // These shouldn't make it here. 3032 case Decl::ObjCAtDefsField: 3033 llvm_unreachable("forming non-member reference to ivar?"); 3034 3035 // Enum constants are always r-values and never references. 3036 // Unresolved using declarations are dependent. 3037 case Decl::EnumConstant: 3038 case Decl::UnresolvedUsingValue: 3039 case Decl::OMPDeclareReduction: 3040 case Decl::OMPDeclareMapper: 3041 valueKind = VK_RValue; 3042 break; 3043 3044 // Fields and indirect fields that got here must be for 3045 // pointer-to-member expressions; we just call them l-values for 3046 // internal consistency, because this subexpression doesn't really 3047 // exist in the high-level semantics. 3048 case Decl::Field: 3049 case Decl::IndirectField: 3050 case Decl::ObjCIvar: 3051 assert(getLangOpts().CPlusPlus && 3052 "building reference to field in C?"); 3053 3054 // These can't have reference type in well-formed programs, but 3055 // for internal consistency we do this anyway. 3056 type = type.getNonReferenceType(); 3057 valueKind = VK_LValue; 3058 break; 3059 3060 // Non-type template parameters are either l-values or r-values 3061 // depending on the type. 3062 case Decl::NonTypeTemplateParm: { 3063 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3064 type = reftype->getPointeeType(); 3065 valueKind = VK_LValue; // even if the parameter is an r-value reference 3066 break; 3067 } 3068 3069 // For non-references, we need to strip qualifiers just in case 3070 // the template parameter was declared as 'const int' or whatever. 3071 valueKind = VK_RValue; 3072 type = type.getUnqualifiedType(); 3073 break; 3074 } 3075 3076 case Decl::Var: 3077 case Decl::VarTemplateSpecialization: 3078 case Decl::VarTemplatePartialSpecialization: 3079 case Decl::Decomposition: 3080 case Decl::OMPCapturedExpr: 3081 // In C, "extern void blah;" is valid and is an r-value. 3082 if (!getLangOpts().CPlusPlus && 3083 !type.hasQualifiers() && 3084 type->isVoidType()) { 3085 valueKind = VK_RValue; 3086 break; 3087 } 3088 LLVM_FALLTHROUGH; 3089 3090 case Decl::ImplicitParam: 3091 case Decl::ParmVar: { 3092 // These are always l-values. 3093 valueKind = VK_LValue; 3094 type = type.getNonReferenceType(); 3095 3096 // FIXME: Does the addition of const really only apply in 3097 // potentially-evaluated contexts? Since the variable isn't actually 3098 // captured in an unevaluated context, it seems that the answer is no. 3099 if (!isUnevaluatedContext()) { 3100 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3101 if (!CapturedType.isNull()) 3102 type = CapturedType; 3103 } 3104 3105 break; 3106 } 3107 3108 case Decl::Binding: { 3109 // These are always lvalues. 3110 valueKind = VK_LValue; 3111 type = type.getNonReferenceType(); 3112 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3113 // decides how that's supposed to work. 3114 auto *BD = cast<BindingDecl>(VD); 3115 if (BD->getDeclContext() != CurContext) { 3116 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); 3117 if (DD && DD->hasLocalStorage()) 3118 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 3119 } 3120 break; 3121 } 3122 3123 case Decl::Function: { 3124 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3125 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3126 type = Context.BuiltinFnTy; 3127 valueKind = VK_RValue; 3128 break; 3129 } 3130 } 3131 3132 const FunctionType *fty = type->castAs<FunctionType>(); 3133 3134 // If we're referring to a function with an __unknown_anytype 3135 // result type, make the entire expression __unknown_anytype. 3136 if (fty->getReturnType() == Context.UnknownAnyTy) { 3137 type = Context.UnknownAnyTy; 3138 valueKind = VK_RValue; 3139 break; 3140 } 3141 3142 // Functions are l-values in C++. 3143 if (getLangOpts().CPlusPlus) { 3144 valueKind = VK_LValue; 3145 break; 3146 } 3147 3148 // C99 DR 316 says that, if a function type comes from a 3149 // function definition (without a prototype), that type is only 3150 // used for checking compatibility. Therefore, when referencing 3151 // the function, we pretend that we don't have the full function 3152 // type. 3153 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3154 isa<FunctionProtoType>(fty)) 3155 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3156 fty->getExtInfo()); 3157 3158 // Functions are r-values in C. 3159 valueKind = VK_RValue; 3160 break; 3161 } 3162 3163 case Decl::CXXDeductionGuide: 3164 llvm_unreachable("building reference to deduction guide"); 3165 3166 case Decl::MSProperty: 3167 valueKind = VK_LValue; 3168 break; 3169 3170 case Decl::CXXMethod: 3171 // If we're referring to a method with an __unknown_anytype 3172 // result type, make the entire expression __unknown_anytype. 3173 // This should only be possible with a type written directly. 3174 if (const FunctionProtoType *proto 3175 = dyn_cast<FunctionProtoType>(VD->getType())) 3176 if (proto->getReturnType() == Context.UnknownAnyTy) { 3177 type = Context.UnknownAnyTy; 3178 valueKind = VK_RValue; 3179 break; 3180 } 3181 3182 // C++ methods are l-values if static, r-values if non-static. 3183 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3184 valueKind = VK_LValue; 3185 break; 3186 } 3187 LLVM_FALLTHROUGH; 3188 3189 case Decl::CXXConversion: 3190 case Decl::CXXDestructor: 3191 case Decl::CXXConstructor: 3192 valueKind = VK_RValue; 3193 break; 3194 } 3195 3196 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3197 /*FIXME: TemplateKWLoc*/ SourceLocation(), 3198 TemplateArgs); 3199 } 3200 } 3201 3202 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3203 SmallString<32> &Target) { 3204 Target.resize(CharByteWidth * (Source.size() + 1)); 3205 char *ResultPtr = &Target[0]; 3206 const llvm::UTF8 *ErrorPtr; 3207 bool success = 3208 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3209 (void)success; 3210 assert(success); 3211 Target.resize(ResultPtr - &Target[0]); 3212 } 3213 3214 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3215 PredefinedExpr::IdentKind IK) { 3216 // Pick the current block, lambda, captured statement or function. 3217 Decl *currentDecl = nullptr; 3218 if (const BlockScopeInfo *BSI = getCurBlock()) 3219 currentDecl = BSI->TheDecl; 3220 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3221 currentDecl = LSI->CallOperator; 3222 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3223 currentDecl = CSI->TheCapturedDecl; 3224 else 3225 currentDecl = getCurFunctionOrMethodDecl(); 3226 3227 if (!currentDecl) { 3228 Diag(Loc, diag::ext_predef_outside_function); 3229 currentDecl = Context.getTranslationUnitDecl(); 3230 } 3231 3232 QualType ResTy; 3233 StringLiteral *SL = nullptr; 3234 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3235 ResTy = Context.DependentTy; 3236 else { 3237 // Pre-defined identifiers are of type char[x], where x is the length of 3238 // the string. 3239 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3240 unsigned Length = Str.length(); 3241 3242 llvm::APInt LengthI(32, Length + 1); 3243 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3244 ResTy = 3245 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3246 SmallString<32> RawChars; 3247 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3248 Str, RawChars); 3249 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3250 ArrayType::Normal, 3251 /*IndexTypeQuals*/ 0); 3252 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3253 /*Pascal*/ false, ResTy, Loc); 3254 } else { 3255 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3256 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3257 ArrayType::Normal, 3258 /*IndexTypeQuals*/ 0); 3259 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3260 /*Pascal*/ false, ResTy, Loc); 3261 } 3262 } 3263 3264 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3265 } 3266 3267 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3268 PredefinedExpr::IdentKind IK; 3269 3270 switch (Kind) { 3271 default: llvm_unreachable("Unknown simple primary expr!"); 3272 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3273 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3274 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3275 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3276 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3277 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3278 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3279 } 3280 3281 return BuildPredefinedExpr(Loc, IK); 3282 } 3283 3284 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3285 SmallString<16> CharBuffer; 3286 bool Invalid = false; 3287 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3288 if (Invalid) 3289 return ExprError(); 3290 3291 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3292 PP, Tok.getKind()); 3293 if (Literal.hadError()) 3294 return ExprError(); 3295 3296 QualType Ty; 3297 if (Literal.isWide()) 3298 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3299 else if (Literal.isUTF8() && getLangOpts().Char8) 3300 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3301 else if (Literal.isUTF16()) 3302 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3303 else if (Literal.isUTF32()) 3304 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3305 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3306 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3307 else 3308 Ty = Context.CharTy; // 'x' -> char in C++ 3309 3310 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3311 if (Literal.isWide()) 3312 Kind = CharacterLiteral::Wide; 3313 else if (Literal.isUTF16()) 3314 Kind = CharacterLiteral::UTF16; 3315 else if (Literal.isUTF32()) 3316 Kind = CharacterLiteral::UTF32; 3317 else if (Literal.isUTF8()) 3318 Kind = CharacterLiteral::UTF8; 3319 3320 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3321 Tok.getLocation()); 3322 3323 if (Literal.getUDSuffix().empty()) 3324 return Lit; 3325 3326 // We're building a user-defined literal. 3327 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3328 SourceLocation UDSuffixLoc = 3329 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3330 3331 // Make sure we're allowed user-defined literals here. 3332 if (!UDLScope) 3333 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3334 3335 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3336 // operator "" X (ch) 3337 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3338 Lit, Tok.getLocation()); 3339 } 3340 3341 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3342 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3343 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3344 Context.IntTy, Loc); 3345 } 3346 3347 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3348 QualType Ty, SourceLocation Loc) { 3349 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3350 3351 using llvm::APFloat; 3352 APFloat Val(Format); 3353 3354 APFloat::opStatus result = Literal.GetFloatValue(Val); 3355 3356 // Overflow is always an error, but underflow is only an error if 3357 // we underflowed to zero (APFloat reports denormals as underflow). 3358 if ((result & APFloat::opOverflow) || 3359 ((result & APFloat::opUnderflow) && Val.isZero())) { 3360 unsigned diagnostic; 3361 SmallString<20> buffer; 3362 if (result & APFloat::opOverflow) { 3363 diagnostic = diag::warn_float_overflow; 3364 APFloat::getLargest(Format).toString(buffer); 3365 } else { 3366 diagnostic = diag::warn_float_underflow; 3367 APFloat::getSmallest(Format).toString(buffer); 3368 } 3369 3370 S.Diag(Loc, diagnostic) 3371 << Ty 3372 << StringRef(buffer.data(), buffer.size()); 3373 } 3374 3375 bool isExact = (result == APFloat::opOK); 3376 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3377 } 3378 3379 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3380 assert(E && "Invalid expression"); 3381 3382 if (E->isValueDependent()) 3383 return false; 3384 3385 QualType QT = E->getType(); 3386 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3387 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3388 return true; 3389 } 3390 3391 llvm::APSInt ValueAPS; 3392 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3393 3394 if (R.isInvalid()) 3395 return true; 3396 3397 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3398 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3399 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3400 << ValueAPS.toString(10) << ValueIsPositive; 3401 return true; 3402 } 3403 3404 return false; 3405 } 3406 3407 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3408 // Fast path for a single digit (which is quite common). A single digit 3409 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3410 if (Tok.getLength() == 1) { 3411 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3412 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3413 } 3414 3415 SmallString<128> SpellingBuffer; 3416 // NumericLiteralParser wants to overread by one character. Add padding to 3417 // the buffer in case the token is copied to the buffer. If getSpelling() 3418 // returns a StringRef to the memory buffer, it should have a null char at 3419 // the EOF, so it is also safe. 3420 SpellingBuffer.resize(Tok.getLength() + 1); 3421 3422 // Get the spelling of the token, which eliminates trigraphs, etc. 3423 bool Invalid = false; 3424 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3425 if (Invalid) 3426 return ExprError(); 3427 3428 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3429 if (Literal.hadError) 3430 return ExprError(); 3431 3432 if (Literal.hasUDSuffix()) { 3433 // We're building a user-defined literal. 3434 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3435 SourceLocation UDSuffixLoc = 3436 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3437 3438 // Make sure we're allowed user-defined literals here. 3439 if (!UDLScope) 3440 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3441 3442 QualType CookedTy; 3443 if (Literal.isFloatingLiteral()) { 3444 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3445 // long double, the literal is treated as a call of the form 3446 // operator "" X (f L) 3447 CookedTy = Context.LongDoubleTy; 3448 } else { 3449 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3450 // unsigned long long, the literal is treated as a call of the form 3451 // operator "" X (n ULL) 3452 CookedTy = Context.UnsignedLongLongTy; 3453 } 3454 3455 DeclarationName OpName = 3456 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3457 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3458 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3459 3460 SourceLocation TokLoc = Tok.getLocation(); 3461 3462 // Perform literal operator lookup to determine if we're building a raw 3463 // literal or a cooked one. 3464 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3465 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3466 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3467 /*AllowStringTemplate*/ false, 3468 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3469 case LOLR_ErrorNoDiagnostic: 3470 // Lookup failure for imaginary constants isn't fatal, there's still the 3471 // GNU extension producing _Complex types. 3472 break; 3473 case LOLR_Error: 3474 return ExprError(); 3475 case LOLR_Cooked: { 3476 Expr *Lit; 3477 if (Literal.isFloatingLiteral()) { 3478 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3479 } else { 3480 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3481 if (Literal.GetIntegerValue(ResultVal)) 3482 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3483 << /* Unsigned */ 1; 3484 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3485 Tok.getLocation()); 3486 } 3487 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3488 } 3489 3490 case LOLR_Raw: { 3491 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3492 // literal is treated as a call of the form 3493 // operator "" X ("n") 3494 unsigned Length = Literal.getUDSuffixOffset(); 3495 QualType StrTy = Context.getConstantArrayType( 3496 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3497 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); 3498 Expr *Lit = StringLiteral::Create( 3499 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3500 /*Pascal*/false, StrTy, &TokLoc, 1); 3501 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3502 } 3503 3504 case LOLR_Template: { 3505 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3506 // template), L is treated as a call fo the form 3507 // operator "" X <'c1', 'c2', ... 'ck'>() 3508 // where n is the source character sequence c1 c2 ... ck. 3509 TemplateArgumentListInfo ExplicitArgs; 3510 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3511 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3512 llvm::APSInt Value(CharBits, CharIsUnsigned); 3513 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3514 Value = TokSpelling[I]; 3515 TemplateArgument Arg(Context, Value, Context.CharTy); 3516 TemplateArgumentLocInfo ArgInfo; 3517 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3518 } 3519 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3520 &ExplicitArgs); 3521 } 3522 case LOLR_StringTemplate: 3523 llvm_unreachable("unexpected literal operator lookup result"); 3524 } 3525 } 3526 3527 Expr *Res; 3528 3529 if (Literal.isFixedPointLiteral()) { 3530 QualType Ty; 3531 3532 if (Literal.isAccum) { 3533 if (Literal.isHalf) { 3534 Ty = Context.ShortAccumTy; 3535 } else if (Literal.isLong) { 3536 Ty = Context.LongAccumTy; 3537 } else { 3538 Ty = Context.AccumTy; 3539 } 3540 } else if (Literal.isFract) { 3541 if (Literal.isHalf) { 3542 Ty = Context.ShortFractTy; 3543 } else if (Literal.isLong) { 3544 Ty = Context.LongFractTy; 3545 } else { 3546 Ty = Context.FractTy; 3547 } 3548 } 3549 3550 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3551 3552 bool isSigned = !Literal.isUnsigned; 3553 unsigned scale = Context.getFixedPointScale(Ty); 3554 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3555 3556 llvm::APInt Val(bit_width, 0, isSigned); 3557 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3558 bool ValIsZero = Val.isNullValue() && !Overflowed; 3559 3560 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3561 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3562 // Clause 6.4.4 - The value of a constant shall be in the range of 3563 // representable values for its type, with exception for constants of a 3564 // fract type with a value of exactly 1; such a constant shall denote 3565 // the maximal value for the type. 3566 --Val; 3567 else if (Val.ugt(MaxVal) || Overflowed) 3568 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3569 3570 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3571 Tok.getLocation(), scale); 3572 } else if (Literal.isFloatingLiteral()) { 3573 QualType Ty; 3574 if (Literal.isHalf){ 3575 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3576 Ty = Context.HalfTy; 3577 else { 3578 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3579 return ExprError(); 3580 } 3581 } else if (Literal.isFloat) 3582 Ty = Context.FloatTy; 3583 else if (Literal.isLong) 3584 Ty = Context.LongDoubleTy; 3585 else if (Literal.isFloat16) 3586 Ty = Context.Float16Ty; 3587 else if (Literal.isFloat128) 3588 Ty = Context.Float128Ty; 3589 else 3590 Ty = Context.DoubleTy; 3591 3592 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3593 3594 if (Ty == Context.DoubleTy) { 3595 if (getLangOpts().SinglePrecisionConstants) { 3596 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3597 if (BTy->getKind() != BuiltinType::Float) { 3598 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3599 } 3600 } else if (getLangOpts().OpenCL && 3601 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3602 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3603 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3604 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3605 } 3606 } 3607 } else if (!Literal.isIntegerLiteral()) { 3608 return ExprError(); 3609 } else { 3610 QualType Ty; 3611 3612 // 'long long' is a C99 or C++11 feature. 3613 if (!getLangOpts().C99 && Literal.isLongLong) { 3614 if (getLangOpts().CPlusPlus) 3615 Diag(Tok.getLocation(), 3616 getLangOpts().CPlusPlus11 ? 3617 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3618 else 3619 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3620 } 3621 3622 // Get the value in the widest-possible width. 3623 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3624 llvm::APInt ResultVal(MaxWidth, 0); 3625 3626 if (Literal.GetIntegerValue(ResultVal)) { 3627 // If this value didn't fit into uintmax_t, error and force to ull. 3628 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3629 << /* Unsigned */ 1; 3630 Ty = Context.UnsignedLongLongTy; 3631 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3632 "long long is not intmax_t?"); 3633 } else { 3634 // If this value fits into a ULL, try to figure out what else it fits into 3635 // according to the rules of C99 6.4.4.1p5. 3636 3637 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3638 // be an unsigned int. 3639 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3640 3641 // Check from smallest to largest, picking the smallest type we can. 3642 unsigned Width = 0; 3643 3644 // Microsoft specific integer suffixes are explicitly sized. 3645 if (Literal.MicrosoftInteger) { 3646 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3647 Width = 8; 3648 Ty = Context.CharTy; 3649 } else { 3650 Width = Literal.MicrosoftInteger; 3651 Ty = Context.getIntTypeForBitwidth(Width, 3652 /*Signed=*/!Literal.isUnsigned); 3653 } 3654 } 3655 3656 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3657 // Are int/unsigned possibilities? 3658 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3659 3660 // Does it fit in a unsigned int? 3661 if (ResultVal.isIntN(IntSize)) { 3662 // Does it fit in a signed int? 3663 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3664 Ty = Context.IntTy; 3665 else if (AllowUnsigned) 3666 Ty = Context.UnsignedIntTy; 3667 Width = IntSize; 3668 } 3669 } 3670 3671 // Are long/unsigned long possibilities? 3672 if (Ty.isNull() && !Literal.isLongLong) { 3673 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3674 3675 // Does it fit in a unsigned long? 3676 if (ResultVal.isIntN(LongSize)) { 3677 // Does it fit in a signed long? 3678 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3679 Ty = Context.LongTy; 3680 else if (AllowUnsigned) 3681 Ty = Context.UnsignedLongTy; 3682 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3683 // is compatible. 3684 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3685 const unsigned LongLongSize = 3686 Context.getTargetInfo().getLongLongWidth(); 3687 Diag(Tok.getLocation(), 3688 getLangOpts().CPlusPlus 3689 ? Literal.isLong 3690 ? diag::warn_old_implicitly_unsigned_long_cxx 3691 : /*C++98 UB*/ diag:: 3692 ext_old_implicitly_unsigned_long_cxx 3693 : diag::warn_old_implicitly_unsigned_long) 3694 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3695 : /*will be ill-formed*/ 1); 3696 Ty = Context.UnsignedLongTy; 3697 } 3698 Width = LongSize; 3699 } 3700 } 3701 3702 // Check long long if needed. 3703 if (Ty.isNull()) { 3704 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3705 3706 // Does it fit in a unsigned long long? 3707 if (ResultVal.isIntN(LongLongSize)) { 3708 // Does it fit in a signed long long? 3709 // To be compatible with MSVC, hex integer literals ending with the 3710 // LL or i64 suffix are always signed in Microsoft mode. 3711 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3712 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3713 Ty = Context.LongLongTy; 3714 else if (AllowUnsigned) 3715 Ty = Context.UnsignedLongLongTy; 3716 Width = LongLongSize; 3717 } 3718 } 3719 3720 // If we still couldn't decide a type, we probably have something that 3721 // does not fit in a signed long long, but has no U suffix. 3722 if (Ty.isNull()) { 3723 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3724 Ty = Context.UnsignedLongLongTy; 3725 Width = Context.getTargetInfo().getLongLongWidth(); 3726 } 3727 3728 if (ResultVal.getBitWidth() != Width) 3729 ResultVal = ResultVal.trunc(Width); 3730 } 3731 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3732 } 3733 3734 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3735 if (Literal.isImaginary) { 3736 Res = new (Context) ImaginaryLiteral(Res, 3737 Context.getComplexType(Res->getType())); 3738 3739 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3740 } 3741 return Res; 3742 } 3743 3744 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3745 assert(E && "ActOnParenExpr() missing expr"); 3746 return new (Context) ParenExpr(L, R, E); 3747 } 3748 3749 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3750 SourceLocation Loc, 3751 SourceRange ArgRange) { 3752 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3753 // scalar or vector data type argument..." 3754 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3755 // type (C99 6.2.5p18) or void. 3756 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3757 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3758 << T << ArgRange; 3759 return true; 3760 } 3761 3762 assert((T->isVoidType() || !T->isIncompleteType()) && 3763 "Scalar types should always be complete"); 3764 return false; 3765 } 3766 3767 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3768 SourceLocation Loc, 3769 SourceRange ArgRange, 3770 UnaryExprOrTypeTrait TraitKind) { 3771 // Invalid types must be hard errors for SFINAE in C++. 3772 if (S.LangOpts.CPlusPlus) 3773 return true; 3774 3775 // C99 6.5.3.4p1: 3776 if (T->isFunctionType() && 3777 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 3778 TraitKind == UETT_PreferredAlignOf)) { 3779 // sizeof(function)/alignof(function) is allowed as an extension. 3780 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3781 << TraitKind << ArgRange; 3782 return false; 3783 } 3784 3785 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3786 // this is an error (OpenCL v1.1 s6.3.k) 3787 if (T->isVoidType()) { 3788 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3789 : diag::ext_sizeof_alignof_void_type; 3790 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3791 return false; 3792 } 3793 3794 return true; 3795 } 3796 3797 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3798 SourceLocation Loc, 3799 SourceRange ArgRange, 3800 UnaryExprOrTypeTrait TraitKind) { 3801 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3802 // runtime doesn't allow it. 3803 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3804 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3805 << T << (TraitKind == UETT_SizeOf) 3806 << ArgRange; 3807 return true; 3808 } 3809 3810 return false; 3811 } 3812 3813 /// Check whether E is a pointer from a decayed array type (the decayed 3814 /// pointer type is equal to T) and emit a warning if it is. 3815 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3816 Expr *E) { 3817 // Don't warn if the operation changed the type. 3818 if (T != E->getType()) 3819 return; 3820 3821 // Now look for array decays. 3822 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3823 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3824 return; 3825 3826 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3827 << ICE->getType() 3828 << ICE->getSubExpr()->getType(); 3829 } 3830 3831 /// Check the constraints on expression operands to unary type expression 3832 /// and type traits. 3833 /// 3834 /// Completes any types necessary and validates the constraints on the operand 3835 /// expression. The logic mostly mirrors the type-based overload, but may modify 3836 /// the expression as it completes the type for that expression through template 3837 /// instantiation, etc. 3838 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3839 UnaryExprOrTypeTrait ExprKind) { 3840 QualType ExprTy = E->getType(); 3841 assert(!ExprTy->isReferenceType()); 3842 3843 bool IsUnevaluatedOperand = 3844 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 3845 ExprKind == UETT_PreferredAlignOf); 3846 if (IsUnevaluatedOperand) { 3847 ExprResult Result = CheckUnevaluatedOperand(E); 3848 if (Result.isInvalid()) 3849 return true; 3850 E = Result.get(); 3851 } 3852 3853 if (ExprKind == UETT_VecStep) 3854 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3855 E->getSourceRange()); 3856 3857 // Whitelist some types as extensions 3858 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3859 E->getSourceRange(), ExprKind)) 3860 return false; 3861 3862 // 'alignof' applied to an expression only requires the base element type of 3863 // the expression to be complete. 'sizeof' requires the expression's type to 3864 // be complete (and will attempt to complete it if it's an array of unknown 3865 // bound). 3866 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 3867 if (RequireCompleteType(E->getExprLoc(), 3868 Context.getBaseElementType(E->getType()), 3869 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3870 E->getSourceRange())) 3871 return true; 3872 } else { 3873 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3874 ExprKind, E->getSourceRange())) 3875 return true; 3876 } 3877 3878 // Completing the expression's type may have changed it. 3879 ExprTy = E->getType(); 3880 assert(!ExprTy->isReferenceType()); 3881 3882 if (ExprTy->isFunctionType()) { 3883 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3884 << ExprKind << E->getSourceRange(); 3885 return true; 3886 } 3887 3888 // The operand for sizeof and alignof is in an unevaluated expression context, 3889 // so side effects could result in unintended consequences. 3890 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 3891 E->HasSideEffects(Context, false)) 3892 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3893 3894 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3895 E->getSourceRange(), ExprKind)) 3896 return true; 3897 3898 if (ExprKind == UETT_SizeOf) { 3899 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3900 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3901 QualType OType = PVD->getOriginalType(); 3902 QualType Type = PVD->getType(); 3903 if (Type->isPointerType() && OType->isArrayType()) { 3904 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3905 << Type << OType; 3906 Diag(PVD->getLocation(), diag::note_declared_at); 3907 } 3908 } 3909 } 3910 3911 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3912 // decays into a pointer and returns an unintended result. This is most 3913 // likely a typo for "sizeof(array) op x". 3914 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3915 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3916 BO->getLHS()); 3917 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3918 BO->getRHS()); 3919 } 3920 } 3921 3922 return false; 3923 } 3924 3925 /// Check the constraints on operands to unary expression and type 3926 /// traits. 3927 /// 3928 /// This will complete any types necessary, and validate the various constraints 3929 /// on those operands. 3930 /// 3931 /// The UsualUnaryConversions() function is *not* called by this routine. 3932 /// C99 6.3.2.1p[2-4] all state: 3933 /// Except when it is the operand of the sizeof operator ... 3934 /// 3935 /// C++ [expr.sizeof]p4 3936 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3937 /// standard conversions are not applied to the operand of sizeof. 3938 /// 3939 /// This policy is followed for all of the unary trait expressions. 3940 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3941 SourceLocation OpLoc, 3942 SourceRange ExprRange, 3943 UnaryExprOrTypeTrait ExprKind) { 3944 if (ExprType->isDependentType()) 3945 return false; 3946 3947 // C++ [expr.sizeof]p2: 3948 // When applied to a reference or a reference type, the result 3949 // is the size of the referenced type. 3950 // C++11 [expr.alignof]p3: 3951 // When alignof is applied to a reference type, the result 3952 // shall be the alignment of the referenced type. 3953 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3954 ExprType = Ref->getPointeeType(); 3955 3956 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3957 // When alignof or _Alignof is applied to an array type, the result 3958 // is the alignment of the element type. 3959 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 3960 ExprKind == UETT_OpenMPRequiredSimdAlign) 3961 ExprType = Context.getBaseElementType(ExprType); 3962 3963 if (ExprKind == UETT_VecStep) 3964 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3965 3966 // Whitelist some types as extensions 3967 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3968 ExprKind)) 3969 return false; 3970 3971 if (RequireCompleteType(OpLoc, ExprType, 3972 diag::err_sizeof_alignof_incomplete_type, 3973 ExprKind, ExprRange)) 3974 return true; 3975 3976 if (ExprType->isFunctionType()) { 3977 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3978 << ExprKind << ExprRange; 3979 return true; 3980 } 3981 3982 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3983 ExprKind)) 3984 return true; 3985 3986 return false; 3987 } 3988 3989 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 3990 // Cannot know anything else if the expression is dependent. 3991 if (E->isTypeDependent()) 3992 return false; 3993 3994 if (E->getObjectKind() == OK_BitField) { 3995 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3996 << 1 << E->getSourceRange(); 3997 return true; 3998 } 3999 4000 ValueDecl *D = nullptr; 4001 Expr *Inner = E->IgnoreParens(); 4002 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 4003 D = DRE->getDecl(); 4004 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 4005 D = ME->getMemberDecl(); 4006 } 4007 4008 // If it's a field, require the containing struct to have a 4009 // complete definition so that we can compute the layout. 4010 // 4011 // This can happen in C++11 onwards, either by naming the member 4012 // in a way that is not transformed into a member access expression 4013 // (in an unevaluated operand, for instance), or by naming the member 4014 // in a trailing-return-type. 4015 // 4016 // For the record, since __alignof__ on expressions is a GCC 4017 // extension, GCC seems to permit this but always gives the 4018 // nonsensical answer 0. 4019 // 4020 // We don't really need the layout here --- we could instead just 4021 // directly check for all the appropriate alignment-lowing 4022 // attributes --- but that would require duplicating a lot of 4023 // logic that just isn't worth duplicating for such a marginal 4024 // use-case. 4025 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4026 // Fast path this check, since we at least know the record has a 4027 // definition if we can find a member of it. 4028 if (!FD->getParent()->isCompleteDefinition()) { 4029 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4030 << E->getSourceRange(); 4031 return true; 4032 } 4033 4034 // Otherwise, if it's a field, and the field doesn't have 4035 // reference type, then it must have a complete type (or be a 4036 // flexible array member, which we explicitly want to 4037 // white-list anyway), which makes the following checks trivial. 4038 if (!FD->getType()->isReferenceType()) 4039 return false; 4040 } 4041 4042 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4043 } 4044 4045 bool Sema::CheckVecStepExpr(Expr *E) { 4046 E = E->IgnoreParens(); 4047 4048 // Cannot know anything else if the expression is dependent. 4049 if (E->isTypeDependent()) 4050 return false; 4051 4052 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4053 } 4054 4055 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4056 CapturingScopeInfo *CSI) { 4057 assert(T->isVariablyModifiedType()); 4058 assert(CSI != nullptr); 4059 4060 // We're going to walk down into the type and look for VLA expressions. 4061 do { 4062 const Type *Ty = T.getTypePtr(); 4063 switch (Ty->getTypeClass()) { 4064 #define TYPE(Class, Base) 4065 #define ABSTRACT_TYPE(Class, Base) 4066 #define NON_CANONICAL_TYPE(Class, Base) 4067 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4068 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4069 #include "clang/AST/TypeNodes.inc" 4070 T = QualType(); 4071 break; 4072 // These types are never variably-modified. 4073 case Type::Builtin: 4074 case Type::Complex: 4075 case Type::Vector: 4076 case Type::ExtVector: 4077 case Type::Record: 4078 case Type::Enum: 4079 case Type::Elaborated: 4080 case Type::TemplateSpecialization: 4081 case Type::ObjCObject: 4082 case Type::ObjCInterface: 4083 case Type::ObjCObjectPointer: 4084 case Type::ObjCTypeParam: 4085 case Type::Pipe: 4086 llvm_unreachable("type class is never variably-modified!"); 4087 case Type::Adjusted: 4088 T = cast<AdjustedType>(Ty)->getOriginalType(); 4089 break; 4090 case Type::Decayed: 4091 T = cast<DecayedType>(Ty)->getPointeeType(); 4092 break; 4093 case Type::Pointer: 4094 T = cast<PointerType>(Ty)->getPointeeType(); 4095 break; 4096 case Type::BlockPointer: 4097 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4098 break; 4099 case Type::LValueReference: 4100 case Type::RValueReference: 4101 T = cast<ReferenceType>(Ty)->getPointeeType(); 4102 break; 4103 case Type::MemberPointer: 4104 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4105 break; 4106 case Type::ConstantArray: 4107 case Type::IncompleteArray: 4108 // Losing element qualification here is fine. 4109 T = cast<ArrayType>(Ty)->getElementType(); 4110 break; 4111 case Type::VariableArray: { 4112 // Losing element qualification here is fine. 4113 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4114 4115 // Unknown size indication requires no size computation. 4116 // Otherwise, evaluate and record it. 4117 auto Size = VAT->getSizeExpr(); 4118 if (Size && !CSI->isVLATypeCaptured(VAT) && 4119 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4120 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4121 4122 T = VAT->getElementType(); 4123 break; 4124 } 4125 case Type::FunctionProto: 4126 case Type::FunctionNoProto: 4127 T = cast<FunctionType>(Ty)->getReturnType(); 4128 break; 4129 case Type::Paren: 4130 case Type::TypeOf: 4131 case Type::UnaryTransform: 4132 case Type::Attributed: 4133 case Type::SubstTemplateTypeParm: 4134 case Type::PackExpansion: 4135 case Type::MacroQualified: 4136 // Keep walking after single level desugaring. 4137 T = T.getSingleStepDesugaredType(Context); 4138 break; 4139 case Type::Typedef: 4140 T = cast<TypedefType>(Ty)->desugar(); 4141 break; 4142 case Type::Decltype: 4143 T = cast<DecltypeType>(Ty)->desugar(); 4144 break; 4145 case Type::Auto: 4146 case Type::DeducedTemplateSpecialization: 4147 T = cast<DeducedType>(Ty)->getDeducedType(); 4148 break; 4149 case Type::TypeOfExpr: 4150 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4151 break; 4152 case Type::Atomic: 4153 T = cast<AtomicType>(Ty)->getValueType(); 4154 break; 4155 } 4156 } while (!T.isNull() && T->isVariablyModifiedType()); 4157 } 4158 4159 /// Build a sizeof or alignof expression given a type operand. 4160 ExprResult 4161 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4162 SourceLocation OpLoc, 4163 UnaryExprOrTypeTrait ExprKind, 4164 SourceRange R) { 4165 if (!TInfo) 4166 return ExprError(); 4167 4168 QualType T = TInfo->getType(); 4169 4170 if (!T->isDependentType() && 4171 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4172 return ExprError(); 4173 4174 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4175 if (auto *TT = T->getAs<TypedefType>()) { 4176 for (auto I = FunctionScopes.rbegin(), 4177 E = std::prev(FunctionScopes.rend()); 4178 I != E; ++I) { 4179 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4180 if (CSI == nullptr) 4181 break; 4182 DeclContext *DC = nullptr; 4183 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4184 DC = LSI->CallOperator; 4185 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4186 DC = CRSI->TheCapturedDecl; 4187 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4188 DC = BSI->TheDecl; 4189 if (DC) { 4190 if (DC->containsDecl(TT->getDecl())) 4191 break; 4192 captureVariablyModifiedType(Context, T, CSI); 4193 } 4194 } 4195 } 4196 } 4197 4198 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4199 return new (Context) UnaryExprOrTypeTraitExpr( 4200 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4201 } 4202 4203 /// Build a sizeof or alignof expression given an expression 4204 /// operand. 4205 ExprResult 4206 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4207 UnaryExprOrTypeTrait ExprKind) { 4208 ExprResult PE = CheckPlaceholderExpr(E); 4209 if (PE.isInvalid()) 4210 return ExprError(); 4211 4212 E = PE.get(); 4213 4214 // Verify that the operand is valid. 4215 bool isInvalid = false; 4216 if (E->isTypeDependent()) { 4217 // Delay type-checking for type-dependent expressions. 4218 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4219 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4220 } else if (ExprKind == UETT_VecStep) { 4221 isInvalid = CheckVecStepExpr(E); 4222 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4223 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4224 isInvalid = true; 4225 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4226 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4227 isInvalid = true; 4228 } else { 4229 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4230 } 4231 4232 if (isInvalid) 4233 return ExprError(); 4234 4235 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4236 PE = TransformToPotentiallyEvaluated(E); 4237 if (PE.isInvalid()) return ExprError(); 4238 E = PE.get(); 4239 } 4240 4241 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4242 return new (Context) UnaryExprOrTypeTraitExpr( 4243 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4244 } 4245 4246 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4247 /// expr and the same for @c alignof and @c __alignof 4248 /// Note that the ArgRange is invalid if isType is false. 4249 ExprResult 4250 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4251 UnaryExprOrTypeTrait ExprKind, bool IsType, 4252 void *TyOrEx, SourceRange ArgRange) { 4253 // If error parsing type, ignore. 4254 if (!TyOrEx) return ExprError(); 4255 4256 if (IsType) { 4257 TypeSourceInfo *TInfo; 4258 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4259 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4260 } 4261 4262 Expr *ArgEx = (Expr *)TyOrEx; 4263 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4264 return Result; 4265 } 4266 4267 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4268 bool IsReal) { 4269 if (V.get()->isTypeDependent()) 4270 return S.Context.DependentTy; 4271 4272 // _Real and _Imag are only l-values for normal l-values. 4273 if (V.get()->getObjectKind() != OK_Ordinary) { 4274 V = S.DefaultLvalueConversion(V.get()); 4275 if (V.isInvalid()) 4276 return QualType(); 4277 } 4278 4279 // These operators return the element type of a complex type. 4280 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4281 return CT->getElementType(); 4282 4283 // Otherwise they pass through real integer and floating point types here. 4284 if (V.get()->getType()->isArithmeticType()) 4285 return V.get()->getType(); 4286 4287 // Test for placeholders. 4288 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4289 if (PR.isInvalid()) return QualType(); 4290 if (PR.get() != V.get()) { 4291 V = PR; 4292 return CheckRealImagOperand(S, V, Loc, IsReal); 4293 } 4294 4295 // Reject anything else. 4296 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4297 << (IsReal ? "__real" : "__imag"); 4298 return QualType(); 4299 } 4300 4301 4302 4303 ExprResult 4304 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4305 tok::TokenKind Kind, Expr *Input) { 4306 UnaryOperatorKind Opc; 4307 switch (Kind) { 4308 default: llvm_unreachable("Unknown unary op!"); 4309 case tok::plusplus: Opc = UO_PostInc; break; 4310 case tok::minusminus: Opc = UO_PostDec; break; 4311 } 4312 4313 // Since this might is a postfix expression, get rid of ParenListExprs. 4314 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4315 if (Result.isInvalid()) return ExprError(); 4316 Input = Result.get(); 4317 4318 return BuildUnaryOp(S, OpLoc, Opc, Input); 4319 } 4320 4321 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4322 /// 4323 /// \return true on error 4324 static bool checkArithmeticOnObjCPointer(Sema &S, 4325 SourceLocation opLoc, 4326 Expr *op) { 4327 assert(op->getType()->isObjCObjectPointerType()); 4328 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4329 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4330 return false; 4331 4332 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4333 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4334 << op->getSourceRange(); 4335 return true; 4336 } 4337 4338 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4339 auto *BaseNoParens = Base->IgnoreParens(); 4340 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4341 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4342 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4343 } 4344 4345 ExprResult 4346 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4347 Expr *idx, SourceLocation rbLoc) { 4348 if (base && !base->getType().isNull() && 4349 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4350 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4351 /*Length=*/nullptr, rbLoc); 4352 4353 // Since this might be a postfix expression, get rid of ParenListExprs. 4354 if (isa<ParenListExpr>(base)) { 4355 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4356 if (result.isInvalid()) return ExprError(); 4357 base = result.get(); 4358 } 4359 4360 // A comma-expression as the index is deprecated in C++2a onwards. 4361 if (getLangOpts().CPlusPlus2a && 4362 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4363 (isa<CXXOperatorCallExpr>(idx) && 4364 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { 4365 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4366 << SourceRange(base->getBeginLoc(), rbLoc); 4367 } 4368 4369 // Handle any non-overload placeholder types in the base and index 4370 // expressions. We can't handle overloads here because the other 4371 // operand might be an overloadable type, in which case the overload 4372 // resolution for the operator overload should get the first crack 4373 // at the overload. 4374 bool IsMSPropertySubscript = false; 4375 if (base->getType()->isNonOverloadPlaceholderType()) { 4376 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4377 if (!IsMSPropertySubscript) { 4378 ExprResult result = CheckPlaceholderExpr(base); 4379 if (result.isInvalid()) 4380 return ExprError(); 4381 base = result.get(); 4382 } 4383 } 4384 if (idx->getType()->isNonOverloadPlaceholderType()) { 4385 ExprResult result = CheckPlaceholderExpr(idx); 4386 if (result.isInvalid()) return ExprError(); 4387 idx = result.get(); 4388 } 4389 4390 // Build an unanalyzed expression if either operand is type-dependent. 4391 if (getLangOpts().CPlusPlus && 4392 (base->isTypeDependent() || idx->isTypeDependent())) { 4393 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4394 VK_LValue, OK_Ordinary, rbLoc); 4395 } 4396 4397 // MSDN, property (C++) 4398 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4399 // This attribute can also be used in the declaration of an empty array in a 4400 // class or structure definition. For example: 4401 // __declspec(property(get=GetX, put=PutX)) int x[]; 4402 // The above statement indicates that x[] can be used with one or more array 4403 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4404 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4405 if (IsMSPropertySubscript) { 4406 // Build MS property subscript expression if base is MS property reference 4407 // or MS property subscript. 4408 return new (Context) MSPropertySubscriptExpr( 4409 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4410 } 4411 4412 // Use C++ overloaded-operator rules if either operand has record 4413 // type. The spec says to do this if either type is *overloadable*, 4414 // but enum types can't declare subscript operators or conversion 4415 // operators, so there's nothing interesting for overload resolution 4416 // to do if there aren't any record types involved. 4417 // 4418 // ObjC pointers have their own subscripting logic that is not tied 4419 // to overload resolution and so should not take this path. 4420 if (getLangOpts().CPlusPlus && 4421 (base->getType()->isRecordType() || 4422 (!base->getType()->isObjCObjectPointerType() && 4423 idx->getType()->isRecordType()))) { 4424 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4425 } 4426 4427 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4428 4429 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4430 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4431 4432 return Res; 4433 } 4434 4435 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4436 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4437 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4438 4439 // For expressions like `&(*s).b`, the base is recorded and what should be 4440 // checked. 4441 const MemberExpr *Member = nullptr; 4442 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4443 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4444 4445 LastRecord.PossibleDerefs.erase(StrippedExpr); 4446 } 4447 4448 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4449 QualType ResultTy = E->getType(); 4450 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4451 4452 // Bail if the element is an array since it is not memory access. 4453 if (isa<ArrayType>(ResultTy)) 4454 return; 4455 4456 if (ResultTy->hasAttr(attr::NoDeref)) { 4457 LastRecord.PossibleDerefs.insert(E); 4458 return; 4459 } 4460 4461 // Check if the base type is a pointer to a member access of a struct 4462 // marked with noderef. 4463 const Expr *Base = E->getBase(); 4464 QualType BaseTy = Base->getType(); 4465 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4466 // Not a pointer access 4467 return; 4468 4469 const MemberExpr *Member = nullptr; 4470 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4471 Member->isArrow()) 4472 Base = Member->getBase(); 4473 4474 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4475 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4476 LastRecord.PossibleDerefs.insert(E); 4477 } 4478 } 4479 4480 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4481 Expr *LowerBound, 4482 SourceLocation ColonLoc, Expr *Length, 4483 SourceLocation RBLoc) { 4484 if (Base->getType()->isPlaceholderType() && 4485 !Base->getType()->isSpecificPlaceholderType( 4486 BuiltinType::OMPArraySection)) { 4487 ExprResult Result = CheckPlaceholderExpr(Base); 4488 if (Result.isInvalid()) 4489 return ExprError(); 4490 Base = Result.get(); 4491 } 4492 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4493 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4494 if (Result.isInvalid()) 4495 return ExprError(); 4496 Result = DefaultLvalueConversion(Result.get()); 4497 if (Result.isInvalid()) 4498 return ExprError(); 4499 LowerBound = Result.get(); 4500 } 4501 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4502 ExprResult Result = CheckPlaceholderExpr(Length); 4503 if (Result.isInvalid()) 4504 return ExprError(); 4505 Result = DefaultLvalueConversion(Result.get()); 4506 if (Result.isInvalid()) 4507 return ExprError(); 4508 Length = Result.get(); 4509 } 4510 4511 // Build an unanalyzed expression if either operand is type-dependent. 4512 if (Base->isTypeDependent() || 4513 (LowerBound && 4514 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4515 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4516 return new (Context) 4517 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4518 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4519 } 4520 4521 // Perform default conversions. 4522 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4523 QualType ResultTy; 4524 if (OriginalTy->isAnyPointerType()) { 4525 ResultTy = OriginalTy->getPointeeType(); 4526 } else if (OriginalTy->isArrayType()) { 4527 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4528 } else { 4529 return ExprError( 4530 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4531 << Base->getSourceRange()); 4532 } 4533 // C99 6.5.2.1p1 4534 if (LowerBound) { 4535 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4536 LowerBound); 4537 if (Res.isInvalid()) 4538 return ExprError(Diag(LowerBound->getExprLoc(), 4539 diag::err_omp_typecheck_section_not_integer) 4540 << 0 << LowerBound->getSourceRange()); 4541 LowerBound = Res.get(); 4542 4543 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4544 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4545 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4546 << 0 << LowerBound->getSourceRange(); 4547 } 4548 if (Length) { 4549 auto Res = 4550 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4551 if (Res.isInvalid()) 4552 return ExprError(Diag(Length->getExprLoc(), 4553 diag::err_omp_typecheck_section_not_integer) 4554 << 1 << Length->getSourceRange()); 4555 Length = Res.get(); 4556 4557 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4558 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4559 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4560 << 1 << Length->getSourceRange(); 4561 } 4562 4563 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4564 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4565 // type. Note that functions are not objects, and that (in C99 parlance) 4566 // incomplete types are not object types. 4567 if (ResultTy->isFunctionType()) { 4568 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4569 << ResultTy << Base->getSourceRange(); 4570 return ExprError(); 4571 } 4572 4573 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4574 diag::err_omp_section_incomplete_type, Base)) 4575 return ExprError(); 4576 4577 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4578 Expr::EvalResult Result; 4579 if (LowerBound->EvaluateAsInt(Result, Context)) { 4580 // OpenMP 4.5, [2.4 Array Sections] 4581 // The array section must be a subset of the original array. 4582 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 4583 if (LowerBoundValue.isNegative()) { 4584 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4585 << LowerBound->getSourceRange(); 4586 return ExprError(); 4587 } 4588 } 4589 } 4590 4591 if (Length) { 4592 Expr::EvalResult Result; 4593 if (Length->EvaluateAsInt(Result, Context)) { 4594 // OpenMP 4.5, [2.4 Array Sections] 4595 // The length must evaluate to non-negative integers. 4596 llvm::APSInt LengthValue = Result.Val.getInt(); 4597 if (LengthValue.isNegative()) { 4598 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4599 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4600 << Length->getSourceRange(); 4601 return ExprError(); 4602 } 4603 } 4604 } else if (ColonLoc.isValid() && 4605 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4606 !OriginalTy->isVariableArrayType()))) { 4607 // OpenMP 4.5, [2.4 Array Sections] 4608 // When the size of the array dimension is not known, the length must be 4609 // specified explicitly. 4610 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4611 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4612 return ExprError(); 4613 } 4614 4615 if (!Base->getType()->isSpecificPlaceholderType( 4616 BuiltinType::OMPArraySection)) { 4617 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4618 if (Result.isInvalid()) 4619 return ExprError(); 4620 Base = Result.get(); 4621 } 4622 return new (Context) 4623 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4624 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4625 } 4626 4627 ExprResult 4628 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4629 Expr *Idx, SourceLocation RLoc) { 4630 Expr *LHSExp = Base; 4631 Expr *RHSExp = Idx; 4632 4633 ExprValueKind VK = VK_LValue; 4634 ExprObjectKind OK = OK_Ordinary; 4635 4636 // Per C++ core issue 1213, the result is an xvalue if either operand is 4637 // a non-lvalue array, and an lvalue otherwise. 4638 if (getLangOpts().CPlusPlus11) { 4639 for (auto *Op : {LHSExp, RHSExp}) { 4640 Op = Op->IgnoreImplicit(); 4641 if (Op->getType()->isArrayType() && !Op->isLValue()) 4642 VK = VK_XValue; 4643 } 4644 } 4645 4646 // Perform default conversions. 4647 if (!LHSExp->getType()->getAs<VectorType>()) { 4648 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4649 if (Result.isInvalid()) 4650 return ExprError(); 4651 LHSExp = Result.get(); 4652 } 4653 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4654 if (Result.isInvalid()) 4655 return ExprError(); 4656 RHSExp = Result.get(); 4657 4658 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4659 4660 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4661 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4662 // in the subscript position. As a result, we need to derive the array base 4663 // and index from the expression types. 4664 Expr *BaseExpr, *IndexExpr; 4665 QualType ResultType; 4666 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4667 BaseExpr = LHSExp; 4668 IndexExpr = RHSExp; 4669 ResultType = Context.DependentTy; 4670 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4671 BaseExpr = LHSExp; 4672 IndexExpr = RHSExp; 4673 ResultType = PTy->getPointeeType(); 4674 } else if (const ObjCObjectPointerType *PTy = 4675 LHSTy->getAs<ObjCObjectPointerType>()) { 4676 BaseExpr = LHSExp; 4677 IndexExpr = RHSExp; 4678 4679 // Use custom logic if this should be the pseudo-object subscript 4680 // expression. 4681 if (!LangOpts.isSubscriptPointerArithmetic()) 4682 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4683 nullptr); 4684 4685 ResultType = PTy->getPointeeType(); 4686 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4687 // Handle the uncommon case of "123[Ptr]". 4688 BaseExpr = RHSExp; 4689 IndexExpr = LHSExp; 4690 ResultType = PTy->getPointeeType(); 4691 } else if (const ObjCObjectPointerType *PTy = 4692 RHSTy->getAs<ObjCObjectPointerType>()) { 4693 // Handle the uncommon case of "123[Ptr]". 4694 BaseExpr = RHSExp; 4695 IndexExpr = LHSExp; 4696 ResultType = PTy->getPointeeType(); 4697 if (!LangOpts.isSubscriptPointerArithmetic()) { 4698 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4699 << ResultType << BaseExpr->getSourceRange(); 4700 return ExprError(); 4701 } 4702 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4703 BaseExpr = LHSExp; // vectors: V[123] 4704 IndexExpr = RHSExp; 4705 // We apply C++ DR1213 to vector subscripting too. 4706 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { 4707 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 4708 if (Materialized.isInvalid()) 4709 return ExprError(); 4710 LHSExp = Materialized.get(); 4711 } 4712 VK = LHSExp->getValueKind(); 4713 if (VK != VK_RValue) 4714 OK = OK_VectorComponent; 4715 4716 ResultType = VTy->getElementType(); 4717 QualType BaseType = BaseExpr->getType(); 4718 Qualifiers BaseQuals = BaseType.getQualifiers(); 4719 Qualifiers MemberQuals = ResultType.getQualifiers(); 4720 Qualifiers Combined = BaseQuals + MemberQuals; 4721 if (Combined != MemberQuals) 4722 ResultType = Context.getQualifiedType(ResultType, Combined); 4723 } else if (LHSTy->isArrayType()) { 4724 // If we see an array that wasn't promoted by 4725 // DefaultFunctionArrayLvalueConversion, it must be an array that 4726 // wasn't promoted because of the C90 rule that doesn't 4727 // allow promoting non-lvalue arrays. Warn, then 4728 // force the promotion here. 4729 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 4730 << LHSExp->getSourceRange(); 4731 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4732 CK_ArrayToPointerDecay).get(); 4733 LHSTy = LHSExp->getType(); 4734 4735 BaseExpr = LHSExp; 4736 IndexExpr = RHSExp; 4737 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4738 } else if (RHSTy->isArrayType()) { 4739 // Same as previous, except for 123[f().a] case 4740 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 4741 << RHSExp->getSourceRange(); 4742 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4743 CK_ArrayToPointerDecay).get(); 4744 RHSTy = RHSExp->getType(); 4745 4746 BaseExpr = RHSExp; 4747 IndexExpr = LHSExp; 4748 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4749 } else { 4750 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4751 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4752 } 4753 // C99 6.5.2.1p1 4754 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4755 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4756 << IndexExpr->getSourceRange()); 4757 4758 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4759 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4760 && !IndexExpr->isTypeDependent()) 4761 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4762 4763 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4764 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4765 // type. Note that Functions are not objects, and that (in C99 parlance) 4766 // incomplete types are not object types. 4767 if (ResultType->isFunctionType()) { 4768 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 4769 << ResultType << BaseExpr->getSourceRange(); 4770 return ExprError(); 4771 } 4772 4773 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4774 // GNU extension: subscripting on pointer to void 4775 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4776 << BaseExpr->getSourceRange(); 4777 4778 // C forbids expressions of unqualified void type from being l-values. 4779 // See IsCForbiddenLValueType. 4780 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4781 } else if (!ResultType->isDependentType() && 4782 RequireCompleteType(LLoc, ResultType, 4783 diag::err_subscript_incomplete_type, BaseExpr)) 4784 return ExprError(); 4785 4786 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4787 !ResultType.isCForbiddenLValueType()); 4788 4789 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 4790 FunctionScopes.size() > 1) { 4791 if (auto *TT = 4792 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 4793 for (auto I = FunctionScopes.rbegin(), 4794 E = std::prev(FunctionScopes.rend()); 4795 I != E; ++I) { 4796 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4797 if (CSI == nullptr) 4798 break; 4799 DeclContext *DC = nullptr; 4800 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4801 DC = LSI->CallOperator; 4802 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4803 DC = CRSI->TheCapturedDecl; 4804 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4805 DC = BSI->TheDecl; 4806 if (DC) { 4807 if (DC->containsDecl(TT->getDecl())) 4808 break; 4809 captureVariablyModifiedType( 4810 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 4811 } 4812 } 4813 } 4814 } 4815 4816 return new (Context) 4817 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4818 } 4819 4820 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 4821 ParmVarDecl *Param) { 4822 if (Param->hasUnparsedDefaultArg()) { 4823 Diag(CallLoc, 4824 diag::err_use_of_default_argument_to_function_declared_later) << 4825 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4826 Diag(UnparsedDefaultArgLocs[Param], 4827 diag::note_default_argument_declared_here); 4828 return true; 4829 } 4830 4831 if (Param->hasUninstantiatedDefaultArg()) { 4832 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4833 4834 EnterExpressionEvaluationContext EvalContext( 4835 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 4836 4837 // Instantiate the expression. 4838 // 4839 // FIXME: Pass in a correct Pattern argument, otherwise 4840 // getTemplateInstantiationArgs uses the lexical context of FD, e.g. 4841 // 4842 // template<typename T> 4843 // struct A { 4844 // static int FooImpl(); 4845 // 4846 // template<typename Tp> 4847 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level 4848 // // template argument list [[T], [Tp]], should be [[Tp]]. 4849 // friend A<Tp> Foo(int a); 4850 // }; 4851 // 4852 // template<typename T> 4853 // A<T> Foo(int a = A<T>::FooImpl()); 4854 MultiLevelTemplateArgumentList MutiLevelArgList 4855 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4856 4857 InstantiatingTemplate Inst(*this, CallLoc, Param, 4858 MutiLevelArgList.getInnermost()); 4859 if (Inst.isInvalid()) 4860 return true; 4861 if (Inst.isAlreadyInstantiating()) { 4862 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 4863 Param->setInvalidDecl(); 4864 return true; 4865 } 4866 4867 ExprResult Result; 4868 { 4869 // C++ [dcl.fct.default]p5: 4870 // The names in the [default argument] expression are bound, and 4871 // the semantic constraints are checked, at the point where the 4872 // default argument expression appears. 4873 ContextRAII SavedContext(*this, FD); 4874 LocalInstantiationScope Local(*this); 4875 runWithSufficientStackSpace(CallLoc, [&] { 4876 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 4877 /*DirectInit*/false); 4878 }); 4879 } 4880 if (Result.isInvalid()) 4881 return true; 4882 4883 // Check the expression as an initializer for the parameter. 4884 InitializedEntity Entity 4885 = InitializedEntity::InitializeParameter(Context, Param); 4886 InitializationKind Kind = InitializationKind::CreateCopy( 4887 Param->getLocation(), 4888 /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc()); 4889 Expr *ResultE = Result.getAs<Expr>(); 4890 4891 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4892 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4893 if (Result.isInvalid()) 4894 return true; 4895 4896 Result = 4897 ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(), 4898 /*DiscardedValue*/ false); 4899 if (Result.isInvalid()) 4900 return true; 4901 4902 // Remember the instantiated default argument. 4903 Param->setDefaultArg(Result.getAs<Expr>()); 4904 if (ASTMutationListener *L = getASTMutationListener()) { 4905 L->DefaultArgumentInstantiated(Param); 4906 } 4907 } 4908 4909 // If the default argument expression is not set yet, we are building it now. 4910 if (!Param->hasInit()) { 4911 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 4912 Param->setInvalidDecl(); 4913 return true; 4914 } 4915 4916 // If the default expression creates temporaries, we need to 4917 // push them to the current stack of expression temporaries so they'll 4918 // be properly destroyed. 4919 // FIXME: We should really be rebuilding the default argument with new 4920 // bound temporaries; see the comment in PR5810. 4921 // We don't need to do that with block decls, though, because 4922 // blocks in default argument expression can never capture anything. 4923 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 4924 // Set the "needs cleanups" bit regardless of whether there are 4925 // any explicit objects. 4926 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 4927 4928 // Append all the objects to the cleanup list. Right now, this 4929 // should always be a no-op, because blocks in default argument 4930 // expressions should never be able to capture anything. 4931 assert(!Init->getNumObjects() && 4932 "default argument expression has capturing blocks?"); 4933 } 4934 4935 // We already type-checked the argument, so we know it works. 4936 // Just mark all of the declarations in this potentially-evaluated expression 4937 // as being "referenced". 4938 EnterExpressionEvaluationContext EvalContext( 4939 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 4940 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4941 /*SkipLocalVariables=*/true); 4942 return false; 4943 } 4944 4945 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4946 FunctionDecl *FD, ParmVarDecl *Param) { 4947 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 4948 return ExprError(); 4949 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 4950 } 4951 4952 Sema::VariadicCallType 4953 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4954 Expr *Fn) { 4955 if (Proto && Proto->isVariadic()) { 4956 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4957 return VariadicConstructor; 4958 else if (Fn && Fn->getType()->isBlockPointerType()) 4959 return VariadicBlock; 4960 else if (FDecl) { 4961 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4962 if (Method->isInstance()) 4963 return VariadicMethod; 4964 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4965 return VariadicMethod; 4966 return VariadicFunction; 4967 } 4968 return VariadicDoesNotApply; 4969 } 4970 4971 namespace { 4972 class FunctionCallCCC final : public FunctionCallFilterCCC { 4973 public: 4974 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4975 unsigned NumArgs, MemberExpr *ME) 4976 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4977 FunctionName(FuncName) {} 4978 4979 bool ValidateCandidate(const TypoCorrection &candidate) override { 4980 if (!candidate.getCorrectionSpecifier() || 4981 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4982 return false; 4983 } 4984 4985 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4986 } 4987 4988 std::unique_ptr<CorrectionCandidateCallback> clone() override { 4989 return std::make_unique<FunctionCallCCC>(*this); 4990 } 4991 4992 private: 4993 const IdentifierInfo *const FunctionName; 4994 }; 4995 } 4996 4997 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4998 FunctionDecl *FDecl, 4999 ArrayRef<Expr *> Args) { 5000 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 5001 DeclarationName FuncName = FDecl->getDeclName(); 5002 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 5003 5004 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 5005 if (TypoCorrection Corrected = S.CorrectTypo( 5006 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 5007 S.getScopeForContext(S.CurContext), nullptr, CCC, 5008 Sema::CTK_ErrorRecovery)) { 5009 if (NamedDecl *ND = Corrected.getFoundDecl()) { 5010 if (Corrected.isOverloaded()) { 5011 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 5012 OverloadCandidateSet::iterator Best; 5013 for (NamedDecl *CD : Corrected) { 5014 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 5015 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 5016 OCS); 5017 } 5018 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 5019 case OR_Success: 5020 ND = Best->FoundDecl; 5021 Corrected.setCorrectionDecl(ND); 5022 break; 5023 default: 5024 break; 5025 } 5026 } 5027 ND = ND->getUnderlyingDecl(); 5028 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 5029 return Corrected; 5030 } 5031 } 5032 return TypoCorrection(); 5033 } 5034 5035 /// ConvertArgumentsForCall - Converts the arguments specified in 5036 /// Args/NumArgs to the parameter types of the function FDecl with 5037 /// function prototype Proto. Call is the call expression itself, and 5038 /// Fn is the function expression. For a C++ member function, this 5039 /// routine does not attempt to convert the object argument. Returns 5040 /// true if the call is ill-formed. 5041 bool 5042 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5043 FunctionDecl *FDecl, 5044 const FunctionProtoType *Proto, 5045 ArrayRef<Expr *> Args, 5046 SourceLocation RParenLoc, 5047 bool IsExecConfig) { 5048 // Bail out early if calling a builtin with custom typechecking. 5049 if (FDecl) 5050 if (unsigned ID = FDecl->getBuiltinID()) 5051 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 5052 return false; 5053 5054 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 5055 // assignment, to the types of the corresponding parameter, ... 5056 unsigned NumParams = Proto->getNumParams(); 5057 bool Invalid = false; 5058 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 5059 unsigned FnKind = Fn->getType()->isBlockPointerType() 5060 ? 1 /* block */ 5061 : (IsExecConfig ? 3 /* kernel function (exec config) */ 5062 : 0 /* function */); 5063 5064 // If too few arguments are available (and we don't have default 5065 // arguments for the remaining parameters), don't make the call. 5066 if (Args.size() < NumParams) { 5067 if (Args.size() < MinArgs) { 5068 TypoCorrection TC; 5069 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5070 unsigned diag_id = 5071 MinArgs == NumParams && !Proto->isVariadic() 5072 ? diag::err_typecheck_call_too_few_args_suggest 5073 : diag::err_typecheck_call_too_few_args_at_least_suggest; 5074 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 5075 << static_cast<unsigned>(Args.size()) 5076 << TC.getCorrectionRange()); 5077 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 5078 Diag(RParenLoc, 5079 MinArgs == NumParams && !Proto->isVariadic() 5080 ? diag::err_typecheck_call_too_few_args_one 5081 : diag::err_typecheck_call_too_few_args_at_least_one) 5082 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 5083 else 5084 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 5085 ? diag::err_typecheck_call_too_few_args 5086 : diag::err_typecheck_call_too_few_args_at_least) 5087 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 5088 << Fn->getSourceRange(); 5089 5090 // Emit the location of the prototype. 5091 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5092 Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl; 5093 5094 return true; 5095 } 5096 // We reserve space for the default arguments when we create 5097 // the call expression, before calling ConvertArgumentsForCall. 5098 assert((Call->getNumArgs() == NumParams) && 5099 "We should have reserved space for the default arguments before!"); 5100 } 5101 5102 // If too many are passed and not variadic, error on the extras and drop 5103 // them. 5104 if (Args.size() > NumParams) { 5105 if (!Proto->isVariadic()) { 5106 TypoCorrection TC; 5107 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5108 unsigned diag_id = 5109 MinArgs == NumParams && !Proto->isVariadic() 5110 ? diag::err_typecheck_call_too_many_args_suggest 5111 : diag::err_typecheck_call_too_many_args_at_most_suggest; 5112 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 5113 << static_cast<unsigned>(Args.size()) 5114 << TC.getCorrectionRange()); 5115 } else if (NumParams == 1 && FDecl && 5116 FDecl->getParamDecl(0)->getDeclName()) 5117 Diag(Args[NumParams]->getBeginLoc(), 5118 MinArgs == NumParams 5119 ? diag::err_typecheck_call_too_many_args_one 5120 : diag::err_typecheck_call_too_many_args_at_most_one) 5121 << FnKind << FDecl->getParamDecl(0) 5122 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 5123 << SourceRange(Args[NumParams]->getBeginLoc(), 5124 Args.back()->getEndLoc()); 5125 else 5126 Diag(Args[NumParams]->getBeginLoc(), 5127 MinArgs == NumParams 5128 ? diag::err_typecheck_call_too_many_args 5129 : diag::err_typecheck_call_too_many_args_at_most) 5130 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 5131 << Fn->getSourceRange() 5132 << SourceRange(Args[NumParams]->getBeginLoc(), 5133 Args.back()->getEndLoc()); 5134 5135 // Emit the location of the prototype. 5136 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5137 Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl; 5138 5139 // This deletes the extra arguments. 5140 Call->shrinkNumArgs(NumParams); 5141 return true; 5142 } 5143 } 5144 SmallVector<Expr *, 8> AllArgs; 5145 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 5146 5147 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 5148 AllArgs, CallType); 5149 if (Invalid) 5150 return true; 5151 unsigned TotalNumArgs = AllArgs.size(); 5152 for (unsigned i = 0; i < TotalNumArgs; ++i) 5153 Call->setArg(i, AllArgs[i]); 5154 5155 return false; 5156 } 5157 5158 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 5159 const FunctionProtoType *Proto, 5160 unsigned FirstParam, ArrayRef<Expr *> Args, 5161 SmallVectorImpl<Expr *> &AllArgs, 5162 VariadicCallType CallType, bool AllowExplicit, 5163 bool IsListInitialization) { 5164 unsigned NumParams = Proto->getNumParams(); 5165 bool Invalid = false; 5166 size_t ArgIx = 0; 5167 // Continue to check argument types (even if we have too few/many args). 5168 for (unsigned i = FirstParam; i < NumParams; i++) { 5169 QualType ProtoArgType = Proto->getParamType(i); 5170 5171 Expr *Arg; 5172 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 5173 if (ArgIx < Args.size()) { 5174 Arg = Args[ArgIx++]; 5175 5176 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5177 diag::err_call_incomplete_argument, Arg)) 5178 return true; 5179 5180 // Strip the unbridged-cast placeholder expression off, if applicable. 5181 bool CFAudited = false; 5182 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5183 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5184 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5185 Arg = stripARCUnbridgedCast(Arg); 5186 else if (getLangOpts().ObjCAutoRefCount && 5187 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5188 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5189 CFAudited = true; 5190 5191 if (Proto->getExtParameterInfo(i).isNoEscape()) 5192 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 5193 BE->getBlockDecl()->setDoesNotEscape(); 5194 5195 InitializedEntity Entity = 5196 Param ? InitializedEntity::InitializeParameter(Context, Param, 5197 ProtoArgType) 5198 : InitializedEntity::InitializeParameter( 5199 Context, ProtoArgType, Proto->isParamConsumed(i)); 5200 5201 // Remember that parameter belongs to a CF audited API. 5202 if (CFAudited) 5203 Entity.setParameterCFAudited(); 5204 5205 ExprResult ArgE = PerformCopyInitialization( 5206 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 5207 if (ArgE.isInvalid()) 5208 return true; 5209 5210 Arg = ArgE.getAs<Expr>(); 5211 } else { 5212 assert(Param && "can't use default arguments without a known callee"); 5213 5214 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 5215 if (ArgExpr.isInvalid()) 5216 return true; 5217 5218 Arg = ArgExpr.getAs<Expr>(); 5219 } 5220 5221 // Check for array bounds violations for each argument to the call. This 5222 // check only triggers warnings when the argument isn't a more complex Expr 5223 // with its own checking, such as a BinaryOperator. 5224 CheckArrayAccess(Arg); 5225 5226 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 5227 CheckStaticArrayArgument(CallLoc, Param, Arg); 5228 5229 AllArgs.push_back(Arg); 5230 } 5231 5232 // If this is a variadic call, handle args passed through "...". 5233 if (CallType != VariadicDoesNotApply) { 5234 // Assume that extern "C" functions with variadic arguments that 5235 // return __unknown_anytype aren't *really* variadic. 5236 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 5237 FDecl->isExternC()) { 5238 for (Expr *A : Args.slice(ArgIx)) { 5239 QualType paramType; // ignored 5240 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 5241 Invalid |= arg.isInvalid(); 5242 AllArgs.push_back(arg.get()); 5243 } 5244 5245 // Otherwise do argument promotion, (C99 6.5.2.2p7). 5246 } else { 5247 for (Expr *A : Args.slice(ArgIx)) { 5248 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 5249 Invalid |= Arg.isInvalid(); 5250 AllArgs.push_back(Arg.get()); 5251 } 5252 } 5253 5254 // Check for array bounds violations. 5255 for (Expr *A : Args.slice(ArgIx)) 5256 CheckArrayAccess(A); 5257 } 5258 return Invalid; 5259 } 5260 5261 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 5262 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 5263 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 5264 TL = DTL.getOriginalLoc(); 5265 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 5266 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 5267 << ATL.getLocalSourceRange(); 5268 } 5269 5270 /// CheckStaticArrayArgument - If the given argument corresponds to a static 5271 /// array parameter, check that it is non-null, and that if it is formed by 5272 /// array-to-pointer decay, the underlying array is sufficiently large. 5273 /// 5274 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 5275 /// array type derivation, then for each call to the function, the value of the 5276 /// corresponding actual argument shall provide access to the first element of 5277 /// an array with at least as many elements as specified by the size expression. 5278 void 5279 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 5280 ParmVarDecl *Param, 5281 const Expr *ArgExpr) { 5282 // Static array parameters are not supported in C++. 5283 if (!Param || getLangOpts().CPlusPlus) 5284 return; 5285 5286 QualType OrigTy = Param->getOriginalType(); 5287 5288 const ArrayType *AT = Context.getAsArrayType(OrigTy); 5289 if (!AT || AT->getSizeModifier() != ArrayType::Static) 5290 return; 5291 5292 if (ArgExpr->isNullPointerConstant(Context, 5293 Expr::NPC_NeverValueDependent)) { 5294 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 5295 DiagnoseCalleeStaticArrayParam(*this, Param); 5296 return; 5297 } 5298 5299 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 5300 if (!CAT) 5301 return; 5302 5303 const ConstantArrayType *ArgCAT = 5304 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 5305 if (!ArgCAT) 5306 return; 5307 5308 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 5309 ArgCAT->getElementType())) { 5310 if (ArgCAT->getSize().ult(CAT->getSize())) { 5311 Diag(CallLoc, diag::warn_static_array_too_small) 5312 << ArgExpr->getSourceRange() 5313 << (unsigned)ArgCAT->getSize().getZExtValue() 5314 << (unsigned)CAT->getSize().getZExtValue() << 0; 5315 DiagnoseCalleeStaticArrayParam(*this, Param); 5316 } 5317 return; 5318 } 5319 5320 Optional<CharUnits> ArgSize = 5321 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 5322 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 5323 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 5324 Diag(CallLoc, diag::warn_static_array_too_small) 5325 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 5326 << (unsigned)ParmSize->getQuantity() << 1; 5327 DiagnoseCalleeStaticArrayParam(*this, Param); 5328 } 5329 } 5330 5331 /// Given a function expression of unknown-any type, try to rebuild it 5332 /// to have a function type. 5333 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 5334 5335 /// Is the given type a placeholder that we need to lower out 5336 /// immediately during argument processing? 5337 static bool isPlaceholderToRemoveAsArg(QualType type) { 5338 // Placeholders are never sugared. 5339 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 5340 if (!placeholder) return false; 5341 5342 switch (placeholder->getKind()) { 5343 // Ignore all the non-placeholder types. 5344 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 5345 case BuiltinType::Id: 5346 #include "clang/Basic/OpenCLImageTypes.def" 5347 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 5348 case BuiltinType::Id: 5349 #include "clang/Basic/OpenCLExtensionTypes.def" 5350 // In practice we'll never use this, since all SVE types are sugared 5351 // via TypedefTypes rather than exposed directly as BuiltinTypes. 5352 #define SVE_TYPE(Name, Id, SingletonId) \ 5353 case BuiltinType::Id: 5354 #include "clang/Basic/AArch64SVEACLETypes.def" 5355 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 5356 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 5357 #include "clang/AST/BuiltinTypes.def" 5358 return false; 5359 5360 // We cannot lower out overload sets; they might validly be resolved 5361 // by the call machinery. 5362 case BuiltinType::Overload: 5363 return false; 5364 5365 // Unbridged casts in ARC can be handled in some call positions and 5366 // should be left in place. 5367 case BuiltinType::ARCUnbridgedCast: 5368 return false; 5369 5370 // Pseudo-objects should be converted as soon as possible. 5371 case BuiltinType::PseudoObject: 5372 return true; 5373 5374 // The debugger mode could theoretically but currently does not try 5375 // to resolve unknown-typed arguments based on known parameter types. 5376 case BuiltinType::UnknownAny: 5377 return true; 5378 5379 // These are always invalid as call arguments and should be reported. 5380 case BuiltinType::BoundMember: 5381 case BuiltinType::BuiltinFn: 5382 case BuiltinType::OMPArraySection: 5383 return true; 5384 5385 } 5386 llvm_unreachable("bad builtin type kind"); 5387 } 5388 5389 /// Check an argument list for placeholders that we won't try to 5390 /// handle later. 5391 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5392 // Apply this processing to all the arguments at once instead of 5393 // dying at the first failure. 5394 bool hasInvalid = false; 5395 for (size_t i = 0, e = args.size(); i != e; i++) { 5396 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5397 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5398 if (result.isInvalid()) hasInvalid = true; 5399 else args[i] = result.get(); 5400 } else if (hasInvalid) { 5401 (void)S.CorrectDelayedTyposInExpr(args[i]); 5402 } 5403 } 5404 return hasInvalid; 5405 } 5406 5407 /// If a builtin function has a pointer argument with no explicit address 5408 /// space, then it should be able to accept a pointer to any address 5409 /// space as input. In order to do this, we need to replace the 5410 /// standard builtin declaration with one that uses the same address space 5411 /// as the call. 5412 /// 5413 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5414 /// it does not contain any pointer arguments without 5415 /// an address space qualifer. Otherwise the rewritten 5416 /// FunctionDecl is returned. 5417 /// TODO: Handle pointer return types. 5418 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5419 FunctionDecl *FDecl, 5420 MultiExprArg ArgExprs) { 5421 5422 QualType DeclType = FDecl->getType(); 5423 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5424 5425 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 5426 ArgExprs.size() < FT->getNumParams()) 5427 return nullptr; 5428 5429 bool NeedsNewDecl = false; 5430 unsigned i = 0; 5431 SmallVector<QualType, 8> OverloadParams; 5432 5433 for (QualType ParamType : FT->param_types()) { 5434 5435 // Convert array arguments to pointer to simplify type lookup. 5436 ExprResult ArgRes = 5437 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5438 if (ArgRes.isInvalid()) 5439 return nullptr; 5440 Expr *Arg = ArgRes.get(); 5441 QualType ArgType = Arg->getType(); 5442 if (!ParamType->isPointerType() || 5443 ParamType.hasAddressSpace() || 5444 !ArgType->isPointerType() || 5445 !ArgType->getPointeeType().hasAddressSpace()) { 5446 OverloadParams.push_back(ParamType); 5447 continue; 5448 } 5449 5450 QualType PointeeType = ParamType->getPointeeType(); 5451 if (PointeeType.hasAddressSpace()) 5452 continue; 5453 5454 NeedsNewDecl = true; 5455 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 5456 5457 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5458 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5459 } 5460 5461 if (!NeedsNewDecl) 5462 return nullptr; 5463 5464 FunctionProtoType::ExtProtoInfo EPI; 5465 EPI.Variadic = FT->isVariadic(); 5466 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5467 OverloadParams, EPI); 5468 DeclContext *Parent = FDecl->getParent(); 5469 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5470 FDecl->getLocation(), 5471 FDecl->getLocation(), 5472 FDecl->getIdentifier(), 5473 OverloadTy, 5474 /*TInfo=*/nullptr, 5475 SC_Extern, false, 5476 /*hasPrototype=*/true); 5477 SmallVector<ParmVarDecl*, 16> Params; 5478 FT = cast<FunctionProtoType>(OverloadTy); 5479 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5480 QualType ParamType = FT->getParamType(i); 5481 ParmVarDecl *Parm = 5482 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5483 SourceLocation(), nullptr, ParamType, 5484 /*TInfo=*/nullptr, SC_None, nullptr); 5485 Parm->setScopeInfo(0, i); 5486 Params.push_back(Parm); 5487 } 5488 OverloadDecl->setParams(Params); 5489 return OverloadDecl; 5490 } 5491 5492 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 5493 FunctionDecl *Callee, 5494 MultiExprArg ArgExprs) { 5495 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 5496 // similar attributes) really don't like it when functions are called with an 5497 // invalid number of args. 5498 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 5499 /*PartialOverloading=*/false) && 5500 !Callee->isVariadic()) 5501 return; 5502 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 5503 return; 5504 5505 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) { 5506 S.Diag(Fn->getBeginLoc(), 5507 isa<CXXMethodDecl>(Callee) 5508 ? diag::err_ovl_no_viable_member_function_in_call 5509 : diag::err_ovl_no_viable_function_in_call) 5510 << Callee << Callee->getSourceRange(); 5511 S.Diag(Callee->getLocation(), 5512 diag::note_ovl_candidate_disabled_by_function_cond_attr) 5513 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5514 return; 5515 } 5516 } 5517 5518 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 5519 const UnresolvedMemberExpr *const UME, Sema &S) { 5520 5521 const auto GetFunctionLevelDCIfCXXClass = 5522 [](Sema &S) -> const CXXRecordDecl * { 5523 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 5524 if (!DC || !DC->getParent()) 5525 return nullptr; 5526 5527 // If the call to some member function was made from within a member 5528 // function body 'M' return return 'M's parent. 5529 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 5530 return MD->getParent()->getCanonicalDecl(); 5531 // else the call was made from within a default member initializer of a 5532 // class, so return the class. 5533 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 5534 return RD->getCanonicalDecl(); 5535 return nullptr; 5536 }; 5537 // If our DeclContext is neither a member function nor a class (in the 5538 // case of a lambda in a default member initializer), we can't have an 5539 // enclosing 'this'. 5540 5541 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 5542 if (!CurParentClass) 5543 return false; 5544 5545 // The naming class for implicit member functions call is the class in which 5546 // name lookup starts. 5547 const CXXRecordDecl *const NamingClass = 5548 UME->getNamingClass()->getCanonicalDecl(); 5549 assert(NamingClass && "Must have naming class even for implicit access"); 5550 5551 // If the unresolved member functions were found in a 'naming class' that is 5552 // related (either the same or derived from) to the class that contains the 5553 // member function that itself contained the implicit member access. 5554 5555 return CurParentClass == NamingClass || 5556 CurParentClass->isDerivedFrom(NamingClass); 5557 } 5558 5559 static void 5560 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5561 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 5562 5563 if (!UME) 5564 return; 5565 5566 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 5567 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 5568 // already been captured, or if this is an implicit member function call (if 5569 // it isn't, an attempt to capture 'this' should already have been made). 5570 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 5571 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 5572 return; 5573 5574 // Check if the naming class in which the unresolved members were found is 5575 // related (same as or is a base of) to the enclosing class. 5576 5577 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 5578 return; 5579 5580 5581 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 5582 // If the enclosing function is not dependent, then this lambda is 5583 // capture ready, so if we can capture this, do so. 5584 if (!EnclosingFunctionCtx->isDependentContext()) { 5585 // If the current lambda and all enclosing lambdas can capture 'this' - 5586 // then go ahead and capture 'this' (since our unresolved overload set 5587 // contains at least one non-static member function). 5588 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 5589 S.CheckCXXThisCapture(CallLoc); 5590 } else if (S.CurContext->isDependentContext()) { 5591 // ... since this is an implicit member reference, that might potentially 5592 // involve a 'this' capture, mark 'this' for potential capture in 5593 // enclosing lambdas. 5594 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 5595 CurLSI->addPotentialThisCapture(CallLoc); 5596 } 5597 } 5598 5599 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5600 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5601 Expr *ExecConfig) { 5602 ExprResult Call = 5603 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig); 5604 if (Call.isInvalid()) 5605 return Call; 5606 5607 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 5608 // language modes. 5609 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 5610 if (ULE->hasExplicitTemplateArgs() && 5611 ULE->decls_begin() == ULE->decls_end()) { 5612 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus2a 5613 ? diag::warn_cxx17_compat_adl_only_template_id 5614 : diag::ext_adl_only_template_id) 5615 << ULE->getName(); 5616 } 5617 } 5618 5619 return Call; 5620 } 5621 5622 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 5623 /// This provides the location of the left/right parens and a list of comma 5624 /// locations. 5625 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5626 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5627 Expr *ExecConfig, bool IsExecConfig) { 5628 // Since this might be a postfix expression, get rid of ParenListExprs. 5629 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 5630 if (Result.isInvalid()) return ExprError(); 5631 Fn = Result.get(); 5632 5633 if (checkArgsForPlaceholders(*this, ArgExprs)) 5634 return ExprError(); 5635 5636 if (getLangOpts().CPlusPlus) { 5637 // If this is a pseudo-destructor expression, build the call immediately. 5638 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5639 if (!ArgExprs.empty()) { 5640 // Pseudo-destructor calls should not have any arguments. 5641 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 5642 << FixItHint::CreateRemoval( 5643 SourceRange(ArgExprs.front()->getBeginLoc(), 5644 ArgExprs.back()->getEndLoc())); 5645 } 5646 5647 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 5648 VK_RValue, RParenLoc); 5649 } 5650 if (Fn->getType() == Context.PseudoObjectTy) { 5651 ExprResult result = CheckPlaceholderExpr(Fn); 5652 if (result.isInvalid()) return ExprError(); 5653 Fn = result.get(); 5654 } 5655 5656 // Determine whether this is a dependent call inside a C++ template, 5657 // in which case we won't do any semantic analysis now. 5658 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 5659 if (ExecConfig) { 5660 return CUDAKernelCallExpr::Create( 5661 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5662 Context.DependentTy, VK_RValue, RParenLoc); 5663 } else { 5664 5665 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5666 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 5667 Fn->getBeginLoc()); 5668 5669 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 5670 VK_RValue, RParenLoc); 5671 } 5672 } 5673 5674 // Determine whether this is a call to an object (C++ [over.call.object]). 5675 if (Fn->getType()->isRecordType()) 5676 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 5677 RParenLoc); 5678 5679 if (Fn->getType() == Context.UnknownAnyTy) { 5680 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5681 if (result.isInvalid()) return ExprError(); 5682 Fn = result.get(); 5683 } 5684 5685 if (Fn->getType() == Context.BoundMemberTy) { 5686 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5687 RParenLoc); 5688 } 5689 } 5690 5691 // Check for overloaded calls. This can happen even in C due to extensions. 5692 if (Fn->getType() == Context.OverloadTy) { 5693 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5694 5695 // We aren't supposed to apply this logic if there's an '&' involved. 5696 if (!find.HasFormOfMemberPointer) { 5697 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5698 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 5699 VK_RValue, RParenLoc); 5700 OverloadExpr *ovl = find.Expression; 5701 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5702 return BuildOverloadedCallExpr( 5703 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 5704 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 5705 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5706 RParenLoc); 5707 } 5708 } 5709 5710 // If we're directly calling a function, get the appropriate declaration. 5711 if (Fn->getType() == Context.UnknownAnyTy) { 5712 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5713 if (result.isInvalid()) return ExprError(); 5714 Fn = result.get(); 5715 } 5716 5717 Expr *NakedFn = Fn->IgnoreParens(); 5718 5719 bool CallingNDeclIndirectly = false; 5720 NamedDecl *NDecl = nullptr; 5721 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5722 if (UnOp->getOpcode() == UO_AddrOf) { 5723 CallingNDeclIndirectly = true; 5724 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5725 } 5726 } 5727 5728 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 5729 NDecl = DRE->getDecl(); 5730 5731 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5732 if (FDecl && FDecl->getBuiltinID()) { 5733 // Rewrite the function decl for this builtin by replacing parameters 5734 // with no explicit address space with the address space of the arguments 5735 // in ArgExprs. 5736 if ((FDecl = 5737 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5738 NDecl = FDecl; 5739 Fn = DeclRefExpr::Create( 5740 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 5741 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 5742 nullptr, DRE->isNonOdrUse()); 5743 } 5744 } 5745 } else if (isa<MemberExpr>(NakedFn)) 5746 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5747 5748 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5749 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 5750 FD, /*Complain=*/true, Fn->getBeginLoc())) 5751 return ExprError(); 5752 5753 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 5754 return ExprError(); 5755 5756 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 5757 } 5758 5759 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5760 ExecConfig, IsExecConfig); 5761 } 5762 5763 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5764 /// 5765 /// __builtin_astype( value, dst type ) 5766 /// 5767 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5768 SourceLocation BuiltinLoc, 5769 SourceLocation RParenLoc) { 5770 ExprValueKind VK = VK_RValue; 5771 ExprObjectKind OK = OK_Ordinary; 5772 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5773 QualType SrcTy = E->getType(); 5774 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5775 return ExprError(Diag(BuiltinLoc, 5776 diag::err_invalid_astype_of_different_size) 5777 << DstTy 5778 << SrcTy 5779 << E->getSourceRange()); 5780 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5781 } 5782 5783 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5784 /// provided arguments. 5785 /// 5786 /// __builtin_convertvector( value, dst type ) 5787 /// 5788 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5789 SourceLocation BuiltinLoc, 5790 SourceLocation RParenLoc) { 5791 TypeSourceInfo *TInfo; 5792 GetTypeFromParser(ParsedDestTy, &TInfo); 5793 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5794 } 5795 5796 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5797 /// i.e. an expression not of \p OverloadTy. The expression should 5798 /// unary-convert to an expression of function-pointer or 5799 /// block-pointer type. 5800 /// 5801 /// \param NDecl the declaration being called, if available 5802 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5803 SourceLocation LParenLoc, 5804 ArrayRef<Expr *> Args, 5805 SourceLocation RParenLoc, Expr *Config, 5806 bool IsExecConfig, ADLCallKind UsesADL) { 5807 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5808 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5809 5810 // Functions with 'interrupt' attribute cannot be called directly. 5811 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5812 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5813 return ExprError(); 5814 } 5815 5816 // Interrupt handlers don't save off the VFP regs automatically on ARM, 5817 // so there's some risk when calling out to non-interrupt handler functions 5818 // that the callee might not preserve them. This is easy to diagnose here, 5819 // but can be very challenging to debug. 5820 if (auto *Caller = getCurFunctionDecl()) 5821 if (Caller->hasAttr<ARMInterruptAttr>()) { 5822 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 5823 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) 5824 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 5825 } 5826 5827 // Promote the function operand. 5828 // We special-case function promotion here because we only allow promoting 5829 // builtin functions to function pointers in the callee of a call. 5830 ExprResult Result; 5831 QualType ResultTy; 5832 if (BuiltinID && 5833 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5834 // Extract the return type from the (builtin) function pointer type. 5835 // FIXME Several builtins still have setType in 5836 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 5837 // Builtins.def to ensure they are correct before removing setType calls. 5838 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 5839 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 5840 ResultTy = FDecl->getCallResultType(); 5841 } else { 5842 Result = CallExprUnaryConversions(Fn); 5843 ResultTy = Context.BoolTy; 5844 } 5845 if (Result.isInvalid()) 5846 return ExprError(); 5847 Fn = Result.get(); 5848 5849 // Check for a valid function type, but only if it is not a builtin which 5850 // requires custom type checking. These will be handled by 5851 // CheckBuiltinFunctionCall below just after creation of the call expression. 5852 const FunctionType *FuncT = nullptr; 5853 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 5854 retry: 5855 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5856 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5857 // have type pointer to function". 5858 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5859 if (!FuncT) 5860 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5861 << Fn->getType() << Fn->getSourceRange()); 5862 } else if (const BlockPointerType *BPT = 5863 Fn->getType()->getAs<BlockPointerType>()) { 5864 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5865 } else { 5866 // Handle calls to expressions of unknown-any type. 5867 if (Fn->getType() == Context.UnknownAnyTy) { 5868 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5869 if (rewrite.isInvalid()) 5870 return ExprError(); 5871 Fn = rewrite.get(); 5872 goto retry; 5873 } 5874 5875 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5876 << Fn->getType() << Fn->getSourceRange()); 5877 } 5878 } 5879 5880 // Get the number of parameters in the function prototype, if any. 5881 // We will allocate space for max(Args.size(), NumParams) arguments 5882 // in the call expression. 5883 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 5884 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 5885 5886 CallExpr *TheCall; 5887 if (Config) { 5888 assert(UsesADL == ADLCallKind::NotADL && 5889 "CUDAKernelCallExpr should not use ADL"); 5890 TheCall = 5891 CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args, 5892 ResultTy, VK_RValue, RParenLoc, NumParams); 5893 } else { 5894 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, 5895 RParenLoc, NumParams, UsesADL); 5896 } 5897 5898 if (!getLangOpts().CPlusPlus) { 5899 // Forget about the nulled arguments since typo correction 5900 // do not handle them well. 5901 TheCall->shrinkNumArgs(Args.size()); 5902 // C cannot always handle TypoExpr nodes in builtin calls and direct 5903 // function calls as their argument checking don't necessarily handle 5904 // dependent types properly, so make sure any TypoExprs have been 5905 // dealt with. 5906 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5907 if (!Result.isUsable()) return ExprError(); 5908 CallExpr *TheOldCall = TheCall; 5909 TheCall = dyn_cast<CallExpr>(Result.get()); 5910 bool CorrectedTypos = TheCall != TheOldCall; 5911 if (!TheCall) return Result; 5912 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5913 5914 // A new call expression node was created if some typos were corrected. 5915 // However it may not have been constructed with enough storage. In this 5916 // case, rebuild the node with enough storage. The waste of space is 5917 // immaterial since this only happens when some typos were corrected. 5918 if (CorrectedTypos && Args.size() < NumParams) { 5919 if (Config) 5920 TheCall = CUDAKernelCallExpr::Create( 5921 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue, 5922 RParenLoc, NumParams); 5923 else 5924 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, 5925 RParenLoc, NumParams, UsesADL); 5926 } 5927 // We can now handle the nulled arguments for the default arguments. 5928 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 5929 } 5930 5931 // Bail out early if calling a builtin with custom type checking. 5932 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5933 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5934 5935 if (getLangOpts().CUDA) { 5936 if (Config) { 5937 // CUDA: Kernel calls must be to global functions 5938 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5939 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5940 << FDecl << Fn->getSourceRange()); 5941 5942 // CUDA: Kernel function must have 'void' return type 5943 if (!FuncT->getReturnType()->isVoidType() && 5944 !FuncT->getReturnType()->getAs<AutoType>() && 5945 !FuncT->getReturnType()->isInstantiationDependentType()) 5946 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5947 << Fn->getType() << Fn->getSourceRange()); 5948 } else { 5949 // CUDA: Calls to global functions must be configured 5950 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5951 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5952 << FDecl << Fn->getSourceRange()); 5953 } 5954 } 5955 5956 // Check for a valid return type 5957 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 5958 FDecl)) 5959 return ExprError(); 5960 5961 // We know the result type of the call, set it. 5962 TheCall->setType(FuncT->getCallResultType(Context)); 5963 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5964 5965 if (Proto) { 5966 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5967 IsExecConfig)) 5968 return ExprError(); 5969 } else { 5970 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5971 5972 if (FDecl) { 5973 // Check if we have too few/too many template arguments, based 5974 // on our knowledge of the function definition. 5975 const FunctionDecl *Def = nullptr; 5976 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5977 Proto = Def->getType()->getAs<FunctionProtoType>(); 5978 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5979 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5980 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5981 } 5982 5983 // If the function we're calling isn't a function prototype, but we have 5984 // a function prototype from a prior declaratiom, use that prototype. 5985 if (!FDecl->hasPrototype()) 5986 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5987 } 5988 5989 // Promote the arguments (C99 6.5.2.2p6). 5990 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5991 Expr *Arg = Args[i]; 5992 5993 if (Proto && i < Proto->getNumParams()) { 5994 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5995 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5996 ExprResult ArgE = 5997 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5998 if (ArgE.isInvalid()) 5999 return true; 6000 6001 Arg = ArgE.getAs<Expr>(); 6002 6003 } else { 6004 ExprResult ArgE = DefaultArgumentPromotion(Arg); 6005 6006 if (ArgE.isInvalid()) 6007 return true; 6008 6009 Arg = ArgE.getAs<Expr>(); 6010 } 6011 6012 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 6013 diag::err_call_incomplete_argument, Arg)) 6014 return ExprError(); 6015 6016 TheCall->setArg(i, Arg); 6017 } 6018 } 6019 6020 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 6021 if (!Method->isStatic()) 6022 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 6023 << Fn->getSourceRange()); 6024 6025 // Check for sentinels 6026 if (NDecl) 6027 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 6028 6029 // Do special checking on direct calls to functions. 6030 if (FDecl) { 6031 if (CheckFunctionCall(FDecl, TheCall, Proto)) 6032 return ExprError(); 6033 6034 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 6035 6036 if (BuiltinID) 6037 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6038 } else if (NDecl) { 6039 if (CheckPointerCall(NDecl, TheCall, Proto)) 6040 return ExprError(); 6041 } else { 6042 if (CheckOtherCall(TheCall, Proto)) 6043 return ExprError(); 6044 } 6045 6046 return MaybeBindToTemporary(TheCall); 6047 } 6048 6049 ExprResult 6050 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 6051 SourceLocation RParenLoc, Expr *InitExpr) { 6052 assert(Ty && "ActOnCompoundLiteral(): missing type"); 6053 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 6054 6055 TypeSourceInfo *TInfo; 6056 QualType literalType = GetTypeFromParser(Ty, &TInfo); 6057 if (!TInfo) 6058 TInfo = Context.getTrivialTypeSourceInfo(literalType); 6059 6060 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 6061 } 6062 6063 ExprResult 6064 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 6065 SourceLocation RParenLoc, Expr *LiteralExpr) { 6066 QualType literalType = TInfo->getType(); 6067 6068 if (literalType->isArrayType()) { 6069 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 6070 diag::err_illegal_decl_array_incomplete_type, 6071 SourceRange(LParenLoc, 6072 LiteralExpr->getSourceRange().getEnd()))) 6073 return ExprError(); 6074 if (literalType->isVariableArrayType()) 6075 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 6076 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 6077 } else if (!literalType->isDependentType() && 6078 RequireCompleteType(LParenLoc, literalType, 6079 diag::err_typecheck_decl_incomplete_type, 6080 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6081 return ExprError(); 6082 6083 InitializedEntity Entity 6084 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 6085 InitializationKind Kind 6086 = InitializationKind::CreateCStyleCast(LParenLoc, 6087 SourceRange(LParenLoc, RParenLoc), 6088 /*InitList=*/true); 6089 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 6090 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 6091 &literalType); 6092 if (Result.isInvalid()) 6093 return ExprError(); 6094 LiteralExpr = Result.get(); 6095 6096 bool isFileScope = !CurContext->isFunctionOrMethod(); 6097 6098 // In C, compound literals are l-values for some reason. 6099 // For GCC compatibility, in C++, file-scope array compound literals with 6100 // constant initializers are also l-values, and compound literals are 6101 // otherwise prvalues. 6102 // 6103 // (GCC also treats C++ list-initialized file-scope array prvalues with 6104 // constant initializers as l-values, but that's non-conforming, so we don't 6105 // follow it there.) 6106 // 6107 // FIXME: It would be better to handle the lvalue cases as materializing and 6108 // lifetime-extending a temporary object, but our materialized temporaries 6109 // representation only supports lifetime extension from a variable, not "out 6110 // of thin air". 6111 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 6112 // is bound to the result of applying array-to-pointer decay to the compound 6113 // literal. 6114 // FIXME: GCC supports compound literals of reference type, which should 6115 // obviously have a value kind derived from the kind of reference involved. 6116 ExprValueKind VK = 6117 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 6118 ? VK_RValue 6119 : VK_LValue; 6120 6121 if (isFileScope) 6122 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 6123 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 6124 Expr *Init = ILE->getInit(i); 6125 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 6126 } 6127 6128 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 6129 VK, LiteralExpr, isFileScope); 6130 if (isFileScope) { 6131 if (!LiteralExpr->isTypeDependent() && 6132 !LiteralExpr->isValueDependent() && 6133 !literalType->isDependentType()) // C99 6.5.2.5p3 6134 if (CheckForConstantInitializer(LiteralExpr, literalType)) 6135 return ExprError(); 6136 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 6137 literalType.getAddressSpace() != LangAS::Default) { 6138 // Embedded-C extensions to C99 6.5.2.5: 6139 // "If the compound literal occurs inside the body of a function, the 6140 // type name shall not be qualified by an address-space qualifier." 6141 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 6142 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 6143 return ExprError(); 6144 } 6145 6146 // Compound literals that have automatic storage duration are destroyed at 6147 // the end of the scope. Emit diagnostics if it is or contains a C union type 6148 // that is non-trivial to destruct. 6149 if (!isFileScope) 6150 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 6151 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 6152 NTCUC_CompoundLiteral, NTCUK_Destruct); 6153 6154 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 6155 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 6156 checkNonTrivialCUnionInInitializer(E->getInitializer(), 6157 E->getInitializer()->getExprLoc()); 6158 6159 return MaybeBindToTemporary(E); 6160 } 6161 6162 ExprResult 6163 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6164 SourceLocation RBraceLoc) { 6165 // Only produce each kind of designated initialization diagnostic once. 6166 SourceLocation FirstDesignator; 6167 bool DiagnosedArrayDesignator = false; 6168 bool DiagnosedNestedDesignator = false; 6169 bool DiagnosedMixedDesignator = false; 6170 6171 // Check that any designated initializers are syntactically valid in the 6172 // current language mode. 6173 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6174 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 6175 if (FirstDesignator.isInvalid()) 6176 FirstDesignator = DIE->getBeginLoc(); 6177 6178 if (!getLangOpts().CPlusPlus) 6179 break; 6180 6181 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 6182 DiagnosedNestedDesignator = true; 6183 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 6184 << DIE->getDesignatorsSourceRange(); 6185 } 6186 6187 for (auto &Desig : DIE->designators()) { 6188 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 6189 DiagnosedArrayDesignator = true; 6190 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 6191 << Desig.getSourceRange(); 6192 } 6193 } 6194 6195 if (!DiagnosedMixedDesignator && 6196 !isa<DesignatedInitExpr>(InitArgList[0])) { 6197 DiagnosedMixedDesignator = true; 6198 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6199 << DIE->getSourceRange(); 6200 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 6201 << InitArgList[0]->getSourceRange(); 6202 } 6203 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 6204 isa<DesignatedInitExpr>(InitArgList[0])) { 6205 DiagnosedMixedDesignator = true; 6206 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 6207 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6208 << DIE->getSourceRange(); 6209 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 6210 << InitArgList[I]->getSourceRange(); 6211 } 6212 } 6213 6214 if (FirstDesignator.isValid()) { 6215 // Only diagnose designated initiaization as a C++20 extension if we didn't 6216 // already diagnose use of (non-C++20) C99 designator syntax. 6217 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 6218 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 6219 Diag(FirstDesignator, getLangOpts().CPlusPlus2a 6220 ? diag::warn_cxx17_compat_designated_init 6221 : diag::ext_cxx_designated_init); 6222 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 6223 Diag(FirstDesignator, diag::ext_designated_init); 6224 } 6225 } 6226 6227 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 6228 } 6229 6230 ExprResult 6231 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6232 SourceLocation RBraceLoc) { 6233 // Semantic analysis for initializers is done by ActOnDeclarator() and 6234 // CheckInitializer() - it requires knowledge of the object being initialized. 6235 6236 // Immediately handle non-overload placeholders. Overloads can be 6237 // resolved contextually, but everything else here can't. 6238 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6239 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 6240 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 6241 6242 // Ignore failures; dropping the entire initializer list because 6243 // of one failure would be terrible for indexing/etc. 6244 if (result.isInvalid()) continue; 6245 6246 InitArgList[I] = result.get(); 6247 } 6248 } 6249 6250 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 6251 RBraceLoc); 6252 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 6253 return E; 6254 } 6255 6256 /// Do an explicit extend of the given block pointer if we're in ARC. 6257 void Sema::maybeExtendBlockObject(ExprResult &E) { 6258 assert(E.get()->getType()->isBlockPointerType()); 6259 assert(E.get()->isRValue()); 6260 6261 // Only do this in an r-value context. 6262 if (!getLangOpts().ObjCAutoRefCount) return; 6263 6264 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 6265 CK_ARCExtendBlockObject, E.get(), 6266 /*base path*/ nullptr, VK_RValue); 6267 Cleanup.setExprNeedsCleanups(true); 6268 } 6269 6270 /// Prepare a conversion of the given expression to an ObjC object 6271 /// pointer type. 6272 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 6273 QualType type = E.get()->getType(); 6274 if (type->isObjCObjectPointerType()) { 6275 return CK_BitCast; 6276 } else if (type->isBlockPointerType()) { 6277 maybeExtendBlockObject(E); 6278 return CK_BlockPointerToObjCPointerCast; 6279 } else { 6280 assert(type->isPointerType()); 6281 return CK_CPointerToObjCPointerCast; 6282 } 6283 } 6284 6285 /// Prepares for a scalar cast, performing all the necessary stages 6286 /// except the final cast and returning the kind required. 6287 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 6288 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 6289 // Also, callers should have filtered out the invalid cases with 6290 // pointers. Everything else should be possible. 6291 6292 QualType SrcTy = Src.get()->getType(); 6293 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 6294 return CK_NoOp; 6295 6296 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 6297 case Type::STK_MemberPointer: 6298 llvm_unreachable("member pointer type in C"); 6299 6300 case Type::STK_CPointer: 6301 case Type::STK_BlockPointer: 6302 case Type::STK_ObjCObjectPointer: 6303 switch (DestTy->getScalarTypeKind()) { 6304 case Type::STK_CPointer: { 6305 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 6306 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 6307 if (SrcAS != DestAS) 6308 return CK_AddressSpaceConversion; 6309 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 6310 return CK_NoOp; 6311 return CK_BitCast; 6312 } 6313 case Type::STK_BlockPointer: 6314 return (SrcKind == Type::STK_BlockPointer 6315 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 6316 case Type::STK_ObjCObjectPointer: 6317 if (SrcKind == Type::STK_ObjCObjectPointer) 6318 return CK_BitCast; 6319 if (SrcKind == Type::STK_CPointer) 6320 return CK_CPointerToObjCPointerCast; 6321 maybeExtendBlockObject(Src); 6322 return CK_BlockPointerToObjCPointerCast; 6323 case Type::STK_Bool: 6324 return CK_PointerToBoolean; 6325 case Type::STK_Integral: 6326 return CK_PointerToIntegral; 6327 case Type::STK_Floating: 6328 case Type::STK_FloatingComplex: 6329 case Type::STK_IntegralComplex: 6330 case Type::STK_MemberPointer: 6331 case Type::STK_FixedPoint: 6332 llvm_unreachable("illegal cast from pointer"); 6333 } 6334 llvm_unreachable("Should have returned before this"); 6335 6336 case Type::STK_FixedPoint: 6337 switch (DestTy->getScalarTypeKind()) { 6338 case Type::STK_FixedPoint: 6339 return CK_FixedPointCast; 6340 case Type::STK_Bool: 6341 return CK_FixedPointToBoolean; 6342 case Type::STK_Integral: 6343 return CK_FixedPointToIntegral; 6344 case Type::STK_Floating: 6345 case Type::STK_IntegralComplex: 6346 case Type::STK_FloatingComplex: 6347 Diag(Src.get()->getExprLoc(), 6348 diag::err_unimplemented_conversion_with_fixed_point_type) 6349 << DestTy; 6350 return CK_IntegralCast; 6351 case Type::STK_CPointer: 6352 case Type::STK_ObjCObjectPointer: 6353 case Type::STK_BlockPointer: 6354 case Type::STK_MemberPointer: 6355 llvm_unreachable("illegal cast to pointer type"); 6356 } 6357 llvm_unreachable("Should have returned before this"); 6358 6359 case Type::STK_Bool: // casting from bool is like casting from an integer 6360 case Type::STK_Integral: 6361 switch (DestTy->getScalarTypeKind()) { 6362 case Type::STK_CPointer: 6363 case Type::STK_ObjCObjectPointer: 6364 case Type::STK_BlockPointer: 6365 if (Src.get()->isNullPointerConstant(Context, 6366 Expr::NPC_ValueDependentIsNull)) 6367 return CK_NullToPointer; 6368 return CK_IntegralToPointer; 6369 case Type::STK_Bool: 6370 return CK_IntegralToBoolean; 6371 case Type::STK_Integral: 6372 return CK_IntegralCast; 6373 case Type::STK_Floating: 6374 return CK_IntegralToFloating; 6375 case Type::STK_IntegralComplex: 6376 Src = ImpCastExprToType(Src.get(), 6377 DestTy->castAs<ComplexType>()->getElementType(), 6378 CK_IntegralCast); 6379 return CK_IntegralRealToComplex; 6380 case Type::STK_FloatingComplex: 6381 Src = ImpCastExprToType(Src.get(), 6382 DestTy->castAs<ComplexType>()->getElementType(), 6383 CK_IntegralToFloating); 6384 return CK_FloatingRealToComplex; 6385 case Type::STK_MemberPointer: 6386 llvm_unreachable("member pointer type in C"); 6387 case Type::STK_FixedPoint: 6388 return CK_IntegralToFixedPoint; 6389 } 6390 llvm_unreachable("Should have returned before this"); 6391 6392 case Type::STK_Floating: 6393 switch (DestTy->getScalarTypeKind()) { 6394 case Type::STK_Floating: 6395 return CK_FloatingCast; 6396 case Type::STK_Bool: 6397 return CK_FloatingToBoolean; 6398 case Type::STK_Integral: 6399 return CK_FloatingToIntegral; 6400 case Type::STK_FloatingComplex: 6401 Src = ImpCastExprToType(Src.get(), 6402 DestTy->castAs<ComplexType>()->getElementType(), 6403 CK_FloatingCast); 6404 return CK_FloatingRealToComplex; 6405 case Type::STK_IntegralComplex: 6406 Src = ImpCastExprToType(Src.get(), 6407 DestTy->castAs<ComplexType>()->getElementType(), 6408 CK_FloatingToIntegral); 6409 return CK_IntegralRealToComplex; 6410 case Type::STK_CPointer: 6411 case Type::STK_ObjCObjectPointer: 6412 case Type::STK_BlockPointer: 6413 llvm_unreachable("valid float->pointer cast?"); 6414 case Type::STK_MemberPointer: 6415 llvm_unreachable("member pointer type in C"); 6416 case Type::STK_FixedPoint: 6417 Diag(Src.get()->getExprLoc(), 6418 diag::err_unimplemented_conversion_with_fixed_point_type) 6419 << SrcTy; 6420 return CK_IntegralCast; 6421 } 6422 llvm_unreachable("Should have returned before this"); 6423 6424 case Type::STK_FloatingComplex: 6425 switch (DestTy->getScalarTypeKind()) { 6426 case Type::STK_FloatingComplex: 6427 return CK_FloatingComplexCast; 6428 case Type::STK_IntegralComplex: 6429 return CK_FloatingComplexToIntegralComplex; 6430 case Type::STK_Floating: { 6431 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 6432 if (Context.hasSameType(ET, DestTy)) 6433 return CK_FloatingComplexToReal; 6434 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 6435 return CK_FloatingCast; 6436 } 6437 case Type::STK_Bool: 6438 return CK_FloatingComplexToBoolean; 6439 case Type::STK_Integral: 6440 Src = ImpCastExprToType(Src.get(), 6441 SrcTy->castAs<ComplexType>()->getElementType(), 6442 CK_FloatingComplexToReal); 6443 return CK_FloatingToIntegral; 6444 case Type::STK_CPointer: 6445 case Type::STK_ObjCObjectPointer: 6446 case Type::STK_BlockPointer: 6447 llvm_unreachable("valid complex float->pointer cast?"); 6448 case Type::STK_MemberPointer: 6449 llvm_unreachable("member pointer type in C"); 6450 case Type::STK_FixedPoint: 6451 Diag(Src.get()->getExprLoc(), 6452 diag::err_unimplemented_conversion_with_fixed_point_type) 6453 << SrcTy; 6454 return CK_IntegralCast; 6455 } 6456 llvm_unreachable("Should have returned before this"); 6457 6458 case Type::STK_IntegralComplex: 6459 switch (DestTy->getScalarTypeKind()) { 6460 case Type::STK_FloatingComplex: 6461 return CK_IntegralComplexToFloatingComplex; 6462 case Type::STK_IntegralComplex: 6463 return CK_IntegralComplexCast; 6464 case Type::STK_Integral: { 6465 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 6466 if (Context.hasSameType(ET, DestTy)) 6467 return CK_IntegralComplexToReal; 6468 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 6469 return CK_IntegralCast; 6470 } 6471 case Type::STK_Bool: 6472 return CK_IntegralComplexToBoolean; 6473 case Type::STK_Floating: 6474 Src = ImpCastExprToType(Src.get(), 6475 SrcTy->castAs<ComplexType>()->getElementType(), 6476 CK_IntegralComplexToReal); 6477 return CK_IntegralToFloating; 6478 case Type::STK_CPointer: 6479 case Type::STK_ObjCObjectPointer: 6480 case Type::STK_BlockPointer: 6481 llvm_unreachable("valid complex int->pointer cast?"); 6482 case Type::STK_MemberPointer: 6483 llvm_unreachable("member pointer type in C"); 6484 case Type::STK_FixedPoint: 6485 Diag(Src.get()->getExprLoc(), 6486 diag::err_unimplemented_conversion_with_fixed_point_type) 6487 << SrcTy; 6488 return CK_IntegralCast; 6489 } 6490 llvm_unreachable("Should have returned before this"); 6491 } 6492 6493 llvm_unreachable("Unhandled scalar cast"); 6494 } 6495 6496 static bool breakDownVectorType(QualType type, uint64_t &len, 6497 QualType &eltType) { 6498 // Vectors are simple. 6499 if (const VectorType *vecType = type->getAs<VectorType>()) { 6500 len = vecType->getNumElements(); 6501 eltType = vecType->getElementType(); 6502 assert(eltType->isScalarType()); 6503 return true; 6504 } 6505 6506 // We allow lax conversion to and from non-vector types, but only if 6507 // they're real types (i.e. non-complex, non-pointer scalar types). 6508 if (!type->isRealType()) return false; 6509 6510 len = 1; 6511 eltType = type; 6512 return true; 6513 } 6514 6515 /// Are the two types lax-compatible vector types? That is, given 6516 /// that one of them is a vector, do they have equal storage sizes, 6517 /// where the storage size is the number of elements times the element 6518 /// size? 6519 /// 6520 /// This will also return false if either of the types is neither a 6521 /// vector nor a real type. 6522 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 6523 assert(destTy->isVectorType() || srcTy->isVectorType()); 6524 6525 // Disallow lax conversions between scalars and ExtVectors (these 6526 // conversions are allowed for other vector types because common headers 6527 // depend on them). Most scalar OP ExtVector cases are handled by the 6528 // splat path anyway, which does what we want (convert, not bitcast). 6529 // What this rules out for ExtVectors is crazy things like char4*float. 6530 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 6531 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 6532 6533 uint64_t srcLen, destLen; 6534 QualType srcEltTy, destEltTy; 6535 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 6536 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 6537 6538 // ASTContext::getTypeSize will return the size rounded up to a 6539 // power of 2, so instead of using that, we need to use the raw 6540 // element size multiplied by the element count. 6541 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 6542 uint64_t destEltSize = Context.getTypeSize(destEltTy); 6543 6544 return (srcLen * srcEltSize == destLen * destEltSize); 6545 } 6546 6547 /// Is this a legal conversion between two types, one of which is 6548 /// known to be a vector type? 6549 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 6550 assert(destTy->isVectorType() || srcTy->isVectorType()); 6551 6552 switch (Context.getLangOpts().getLaxVectorConversions()) { 6553 case LangOptions::LaxVectorConversionKind::None: 6554 return false; 6555 6556 case LangOptions::LaxVectorConversionKind::Integer: 6557 if (!srcTy->isIntegralOrEnumerationType()) { 6558 auto *Vec = srcTy->getAs<VectorType>(); 6559 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 6560 return false; 6561 } 6562 if (!destTy->isIntegralOrEnumerationType()) { 6563 auto *Vec = destTy->getAs<VectorType>(); 6564 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 6565 return false; 6566 } 6567 // OK, integer (vector) -> integer (vector) bitcast. 6568 break; 6569 6570 case LangOptions::LaxVectorConversionKind::All: 6571 break; 6572 } 6573 6574 return areLaxCompatibleVectorTypes(srcTy, destTy); 6575 } 6576 6577 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 6578 CastKind &Kind) { 6579 assert(VectorTy->isVectorType() && "Not a vector type!"); 6580 6581 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 6582 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 6583 return Diag(R.getBegin(), 6584 Ty->isVectorType() ? 6585 diag::err_invalid_conversion_between_vectors : 6586 diag::err_invalid_conversion_between_vector_and_integer) 6587 << VectorTy << Ty << R; 6588 } else 6589 return Diag(R.getBegin(), 6590 diag::err_invalid_conversion_between_vector_and_scalar) 6591 << VectorTy << Ty << R; 6592 6593 Kind = CK_BitCast; 6594 return false; 6595 } 6596 6597 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 6598 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 6599 6600 if (DestElemTy == SplattedExpr->getType()) 6601 return SplattedExpr; 6602 6603 assert(DestElemTy->isFloatingType() || 6604 DestElemTy->isIntegralOrEnumerationType()); 6605 6606 CastKind CK; 6607 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 6608 // OpenCL requires that we convert `true` boolean expressions to -1, but 6609 // only when splatting vectors. 6610 if (DestElemTy->isFloatingType()) { 6611 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 6612 // in two steps: boolean to signed integral, then to floating. 6613 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 6614 CK_BooleanToSignedIntegral); 6615 SplattedExpr = CastExprRes.get(); 6616 CK = CK_IntegralToFloating; 6617 } else { 6618 CK = CK_BooleanToSignedIntegral; 6619 } 6620 } else { 6621 ExprResult CastExprRes = SplattedExpr; 6622 CK = PrepareScalarCast(CastExprRes, DestElemTy); 6623 if (CastExprRes.isInvalid()) 6624 return ExprError(); 6625 SplattedExpr = CastExprRes.get(); 6626 } 6627 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 6628 } 6629 6630 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 6631 Expr *CastExpr, CastKind &Kind) { 6632 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 6633 6634 QualType SrcTy = CastExpr->getType(); 6635 6636 // If SrcTy is a VectorType, the total size must match to explicitly cast to 6637 // an ExtVectorType. 6638 // In OpenCL, casts between vectors of different types are not allowed. 6639 // (See OpenCL 6.2). 6640 if (SrcTy->isVectorType()) { 6641 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 6642 (getLangOpts().OpenCL && 6643 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 6644 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 6645 << DestTy << SrcTy << R; 6646 return ExprError(); 6647 } 6648 Kind = CK_BitCast; 6649 return CastExpr; 6650 } 6651 6652 // All non-pointer scalars can be cast to ExtVector type. The appropriate 6653 // conversion will take place first from scalar to elt type, and then 6654 // splat from elt type to vector. 6655 if (SrcTy->isPointerType()) 6656 return Diag(R.getBegin(), 6657 diag::err_invalid_conversion_between_vector_and_scalar) 6658 << DestTy << SrcTy << R; 6659 6660 Kind = CK_VectorSplat; 6661 return prepareVectorSplat(DestTy, CastExpr); 6662 } 6663 6664 ExprResult 6665 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 6666 Declarator &D, ParsedType &Ty, 6667 SourceLocation RParenLoc, Expr *CastExpr) { 6668 assert(!D.isInvalidType() && (CastExpr != nullptr) && 6669 "ActOnCastExpr(): missing type or expr"); 6670 6671 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 6672 if (D.isInvalidType()) 6673 return ExprError(); 6674 6675 if (getLangOpts().CPlusPlus) { 6676 // Check that there are no default arguments (C++ only). 6677 CheckExtraCXXDefaultArguments(D); 6678 } else { 6679 // Make sure any TypoExprs have been dealt with. 6680 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 6681 if (!Res.isUsable()) 6682 return ExprError(); 6683 CastExpr = Res.get(); 6684 } 6685 6686 checkUnusedDeclAttributes(D); 6687 6688 QualType castType = castTInfo->getType(); 6689 Ty = CreateParsedType(castType, castTInfo); 6690 6691 bool isVectorLiteral = false; 6692 6693 // Check for an altivec or OpenCL literal, 6694 // i.e. all the elements are integer constants. 6695 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 6696 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 6697 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 6698 && castType->isVectorType() && (PE || PLE)) { 6699 if (PLE && PLE->getNumExprs() == 0) { 6700 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 6701 return ExprError(); 6702 } 6703 if (PE || PLE->getNumExprs() == 1) { 6704 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 6705 if (!E->getType()->isVectorType()) 6706 isVectorLiteral = true; 6707 } 6708 else 6709 isVectorLiteral = true; 6710 } 6711 6712 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 6713 // then handle it as such. 6714 if (isVectorLiteral) 6715 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 6716 6717 // If the Expr being casted is a ParenListExpr, handle it specially. 6718 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 6719 // sequence of BinOp comma operators. 6720 if (isa<ParenListExpr>(CastExpr)) { 6721 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 6722 if (Result.isInvalid()) return ExprError(); 6723 CastExpr = Result.get(); 6724 } 6725 6726 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6727 !getSourceManager().isInSystemMacro(LParenLoc)) 6728 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6729 6730 CheckTollFreeBridgeCast(castType, CastExpr); 6731 6732 CheckObjCBridgeRelatedCast(castType, CastExpr); 6733 6734 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 6735 6736 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6737 } 6738 6739 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6740 SourceLocation RParenLoc, Expr *E, 6741 TypeSourceInfo *TInfo) { 6742 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6743 "Expected paren or paren list expression"); 6744 6745 Expr **exprs; 6746 unsigned numExprs; 6747 Expr *subExpr; 6748 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6749 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6750 LiteralLParenLoc = PE->getLParenLoc(); 6751 LiteralRParenLoc = PE->getRParenLoc(); 6752 exprs = PE->getExprs(); 6753 numExprs = PE->getNumExprs(); 6754 } else { // isa<ParenExpr> by assertion at function entrance 6755 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6756 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6757 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6758 exprs = &subExpr; 6759 numExprs = 1; 6760 } 6761 6762 QualType Ty = TInfo->getType(); 6763 assert(Ty->isVectorType() && "Expected vector type"); 6764 6765 SmallVector<Expr *, 8> initExprs; 6766 const VectorType *VTy = Ty->castAs<VectorType>(); 6767 unsigned numElems = VTy->getNumElements(); 6768 6769 // '(...)' form of vector initialization in AltiVec: the number of 6770 // initializers must be one or must match the size of the vector. 6771 // If a single value is specified in the initializer then it will be 6772 // replicated to all the components of the vector 6773 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6774 // The number of initializers must be one or must match the size of the 6775 // vector. If a single value is specified in the initializer then it will 6776 // be replicated to all the components of the vector 6777 if (numExprs == 1) { 6778 QualType ElemTy = VTy->getElementType(); 6779 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6780 if (Literal.isInvalid()) 6781 return ExprError(); 6782 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6783 PrepareScalarCast(Literal, ElemTy)); 6784 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6785 } 6786 else if (numExprs < numElems) { 6787 Diag(E->getExprLoc(), 6788 diag::err_incorrect_number_of_vector_initializers); 6789 return ExprError(); 6790 } 6791 else 6792 initExprs.append(exprs, exprs + numExprs); 6793 } 6794 else { 6795 // For OpenCL, when the number of initializers is a single value, 6796 // it will be replicated to all components of the vector. 6797 if (getLangOpts().OpenCL && 6798 VTy->getVectorKind() == VectorType::GenericVector && 6799 numExprs == 1) { 6800 QualType ElemTy = VTy->getElementType(); 6801 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6802 if (Literal.isInvalid()) 6803 return ExprError(); 6804 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6805 PrepareScalarCast(Literal, ElemTy)); 6806 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6807 } 6808 6809 initExprs.append(exprs, exprs + numExprs); 6810 } 6811 // FIXME: This means that pretty-printing the final AST will produce curly 6812 // braces instead of the original commas. 6813 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6814 initExprs, LiteralRParenLoc); 6815 initE->setType(Ty); 6816 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6817 } 6818 6819 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6820 /// the ParenListExpr into a sequence of comma binary operators. 6821 ExprResult 6822 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6823 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6824 if (!E) 6825 return OrigExpr; 6826 6827 ExprResult Result(E->getExpr(0)); 6828 6829 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6830 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6831 E->getExpr(i)); 6832 6833 if (Result.isInvalid()) return ExprError(); 6834 6835 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6836 } 6837 6838 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6839 SourceLocation R, 6840 MultiExprArg Val) { 6841 return ParenListExpr::Create(Context, L, Val, R); 6842 } 6843 6844 /// Emit a specialized diagnostic when one expression is a null pointer 6845 /// constant and the other is not a pointer. Returns true if a diagnostic is 6846 /// emitted. 6847 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6848 SourceLocation QuestionLoc) { 6849 Expr *NullExpr = LHSExpr; 6850 Expr *NonPointerExpr = RHSExpr; 6851 Expr::NullPointerConstantKind NullKind = 6852 NullExpr->isNullPointerConstant(Context, 6853 Expr::NPC_ValueDependentIsNotNull); 6854 6855 if (NullKind == Expr::NPCK_NotNull) { 6856 NullExpr = RHSExpr; 6857 NonPointerExpr = LHSExpr; 6858 NullKind = 6859 NullExpr->isNullPointerConstant(Context, 6860 Expr::NPC_ValueDependentIsNotNull); 6861 } 6862 6863 if (NullKind == Expr::NPCK_NotNull) 6864 return false; 6865 6866 if (NullKind == Expr::NPCK_ZeroExpression) 6867 return false; 6868 6869 if (NullKind == Expr::NPCK_ZeroLiteral) { 6870 // In this case, check to make sure that we got here from a "NULL" 6871 // string in the source code. 6872 NullExpr = NullExpr->IgnoreParenImpCasts(); 6873 SourceLocation loc = NullExpr->getExprLoc(); 6874 if (!findMacroSpelling(loc, "NULL")) 6875 return false; 6876 } 6877 6878 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6879 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6880 << NonPointerExpr->getType() << DiagType 6881 << NonPointerExpr->getSourceRange(); 6882 return true; 6883 } 6884 6885 /// Return false if the condition expression is valid, true otherwise. 6886 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6887 QualType CondTy = Cond->getType(); 6888 6889 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6890 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6891 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6892 << CondTy << Cond->getSourceRange(); 6893 return true; 6894 } 6895 6896 // C99 6.5.15p2 6897 if (CondTy->isScalarType()) return false; 6898 6899 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6900 << CondTy << Cond->getSourceRange(); 6901 return true; 6902 } 6903 6904 /// Handle when one or both operands are void type. 6905 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6906 ExprResult &RHS) { 6907 Expr *LHSExpr = LHS.get(); 6908 Expr *RHSExpr = RHS.get(); 6909 6910 if (!LHSExpr->getType()->isVoidType()) 6911 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 6912 << RHSExpr->getSourceRange(); 6913 if (!RHSExpr->getType()->isVoidType()) 6914 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 6915 << LHSExpr->getSourceRange(); 6916 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6917 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6918 return S.Context.VoidTy; 6919 } 6920 6921 /// Return false if the NullExpr can be promoted to PointerTy, 6922 /// true otherwise. 6923 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6924 QualType PointerTy) { 6925 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6926 !NullExpr.get()->isNullPointerConstant(S.Context, 6927 Expr::NPC_ValueDependentIsNull)) 6928 return true; 6929 6930 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6931 return false; 6932 } 6933 6934 /// Checks compatibility between two pointers and return the resulting 6935 /// type. 6936 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6937 ExprResult &RHS, 6938 SourceLocation Loc) { 6939 QualType LHSTy = LHS.get()->getType(); 6940 QualType RHSTy = RHS.get()->getType(); 6941 6942 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6943 // Two identical pointers types are always compatible. 6944 return LHSTy; 6945 } 6946 6947 QualType lhptee, rhptee; 6948 6949 // Get the pointee types. 6950 bool IsBlockPointer = false; 6951 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6952 lhptee = LHSBTy->getPointeeType(); 6953 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6954 IsBlockPointer = true; 6955 } else { 6956 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6957 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6958 } 6959 6960 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6961 // differently qualified versions of compatible types, the result type is 6962 // a pointer to an appropriately qualified version of the composite 6963 // type. 6964 6965 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6966 // clause doesn't make sense for our extensions. E.g. address space 2 should 6967 // be incompatible with address space 3: they may live on different devices or 6968 // anything. 6969 Qualifiers lhQual = lhptee.getQualifiers(); 6970 Qualifiers rhQual = rhptee.getQualifiers(); 6971 6972 LangAS ResultAddrSpace = LangAS::Default; 6973 LangAS LAddrSpace = lhQual.getAddressSpace(); 6974 LangAS RAddrSpace = rhQual.getAddressSpace(); 6975 6976 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 6977 // spaces is disallowed. 6978 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 6979 ResultAddrSpace = LAddrSpace; 6980 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 6981 ResultAddrSpace = RAddrSpace; 6982 else { 6983 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 6984 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 6985 << RHS.get()->getSourceRange(); 6986 return QualType(); 6987 } 6988 6989 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6990 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 6991 lhQual.removeCVRQualifiers(); 6992 rhQual.removeCVRQualifiers(); 6993 6994 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 6995 // (C99 6.7.3) for address spaces. We assume that the check should behave in 6996 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 6997 // qual types are compatible iff 6998 // * corresponded types are compatible 6999 // * CVR qualifiers are equal 7000 // * address spaces are equal 7001 // Thus for conditional operator we merge CVR and address space unqualified 7002 // pointees and if there is a composite type we return a pointer to it with 7003 // merged qualifiers. 7004 LHSCastKind = 7005 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7006 RHSCastKind = 7007 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7008 lhQual.removeAddressSpace(); 7009 rhQual.removeAddressSpace(); 7010 7011 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 7012 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 7013 7014 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 7015 7016 if (CompositeTy.isNull()) { 7017 // In this situation, we assume void* type. No especially good 7018 // reason, but this is what gcc does, and we do have to pick 7019 // to get a consistent AST. 7020 QualType incompatTy; 7021 incompatTy = S.Context.getPointerType( 7022 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 7023 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 7024 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 7025 7026 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 7027 // for casts between types with incompatible address space qualifiers. 7028 // For the following code the compiler produces casts between global and 7029 // local address spaces of the corresponded innermost pointees: 7030 // local int *global *a; 7031 // global int *global *b; 7032 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 7033 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 7034 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7035 << RHS.get()->getSourceRange(); 7036 7037 return incompatTy; 7038 } 7039 7040 // The pointer types are compatible. 7041 // In case of OpenCL ResultTy should have the address space qualifier 7042 // which is a superset of address spaces of both the 2nd and the 3rd 7043 // operands of the conditional operator. 7044 QualType ResultTy = [&, ResultAddrSpace]() { 7045 if (S.getLangOpts().OpenCL) { 7046 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 7047 CompositeQuals.setAddressSpace(ResultAddrSpace); 7048 return S.Context 7049 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 7050 .withCVRQualifiers(MergedCVRQual); 7051 } 7052 return CompositeTy.withCVRQualifiers(MergedCVRQual); 7053 }(); 7054 if (IsBlockPointer) 7055 ResultTy = S.Context.getBlockPointerType(ResultTy); 7056 else 7057 ResultTy = S.Context.getPointerType(ResultTy); 7058 7059 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 7060 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 7061 return ResultTy; 7062 } 7063 7064 /// Return the resulting type when the operands are both block pointers. 7065 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 7066 ExprResult &LHS, 7067 ExprResult &RHS, 7068 SourceLocation Loc) { 7069 QualType LHSTy = LHS.get()->getType(); 7070 QualType RHSTy = RHS.get()->getType(); 7071 7072 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 7073 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 7074 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 7075 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7076 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7077 return destType; 7078 } 7079 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 7080 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7081 << RHS.get()->getSourceRange(); 7082 return QualType(); 7083 } 7084 7085 // We have 2 block pointer types. 7086 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7087 } 7088 7089 /// Return the resulting type when the operands are both pointers. 7090 static QualType 7091 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 7092 ExprResult &RHS, 7093 SourceLocation Loc) { 7094 // get the pointer types 7095 QualType LHSTy = LHS.get()->getType(); 7096 QualType RHSTy = RHS.get()->getType(); 7097 7098 // get the "pointed to" types 7099 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7100 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7101 7102 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 7103 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 7104 // Figure out necessary qualifiers (C99 6.5.15p6) 7105 QualType destPointee 7106 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7107 QualType destType = S.Context.getPointerType(destPointee); 7108 // Add qualifiers if necessary. 7109 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7110 // Promote to void*. 7111 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7112 return destType; 7113 } 7114 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 7115 QualType destPointee 7116 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7117 QualType destType = S.Context.getPointerType(destPointee); 7118 // Add qualifiers if necessary. 7119 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7120 // Promote to void*. 7121 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7122 return destType; 7123 } 7124 7125 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7126 } 7127 7128 /// Return false if the first expression is not an integer and the second 7129 /// expression is not a pointer, true otherwise. 7130 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 7131 Expr* PointerExpr, SourceLocation Loc, 7132 bool IsIntFirstExpr) { 7133 if (!PointerExpr->getType()->isPointerType() || 7134 !Int.get()->getType()->isIntegerType()) 7135 return false; 7136 7137 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 7138 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 7139 7140 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 7141 << Expr1->getType() << Expr2->getType() 7142 << Expr1->getSourceRange() << Expr2->getSourceRange(); 7143 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 7144 CK_IntegralToPointer); 7145 return true; 7146 } 7147 7148 /// Simple conversion between integer and floating point types. 7149 /// 7150 /// Used when handling the OpenCL conditional operator where the 7151 /// condition is a vector while the other operands are scalar. 7152 /// 7153 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 7154 /// types are either integer or floating type. Between the two 7155 /// operands, the type with the higher rank is defined as the "result 7156 /// type". The other operand needs to be promoted to the same type. No 7157 /// other type promotion is allowed. We cannot use 7158 /// UsualArithmeticConversions() for this purpose, since it always 7159 /// promotes promotable types. 7160 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 7161 ExprResult &RHS, 7162 SourceLocation QuestionLoc) { 7163 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 7164 if (LHS.isInvalid()) 7165 return QualType(); 7166 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 7167 if (RHS.isInvalid()) 7168 return QualType(); 7169 7170 // For conversion purposes, we ignore any qualifiers. 7171 // For example, "const float" and "float" are equivalent. 7172 QualType LHSType = 7173 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 7174 QualType RHSType = 7175 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 7176 7177 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 7178 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7179 << LHSType << LHS.get()->getSourceRange(); 7180 return QualType(); 7181 } 7182 7183 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 7184 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7185 << RHSType << RHS.get()->getSourceRange(); 7186 return QualType(); 7187 } 7188 7189 // If both types are identical, no conversion is needed. 7190 if (LHSType == RHSType) 7191 return LHSType; 7192 7193 // Now handle "real" floating types (i.e. float, double, long double). 7194 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 7195 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 7196 /*IsCompAssign = */ false); 7197 7198 // Finally, we have two differing integer types. 7199 return handleIntegerConversion<doIntegralCast, doIntegralCast> 7200 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 7201 } 7202 7203 /// Convert scalar operands to a vector that matches the 7204 /// condition in length. 7205 /// 7206 /// Used when handling the OpenCL conditional operator where the 7207 /// condition is a vector while the other operands are scalar. 7208 /// 7209 /// We first compute the "result type" for the scalar operands 7210 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 7211 /// into a vector of that type where the length matches the condition 7212 /// vector type. s6.11.6 requires that the element types of the result 7213 /// and the condition must have the same number of bits. 7214 static QualType 7215 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 7216 QualType CondTy, SourceLocation QuestionLoc) { 7217 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 7218 if (ResTy.isNull()) return QualType(); 7219 7220 const VectorType *CV = CondTy->getAs<VectorType>(); 7221 assert(CV); 7222 7223 // Determine the vector result type 7224 unsigned NumElements = CV->getNumElements(); 7225 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 7226 7227 // Ensure that all types have the same number of bits 7228 if (S.Context.getTypeSize(CV->getElementType()) 7229 != S.Context.getTypeSize(ResTy)) { 7230 // Since VectorTy is created internally, it does not pretty print 7231 // with an OpenCL name. Instead, we just print a description. 7232 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 7233 SmallString<64> Str; 7234 llvm::raw_svector_ostream OS(Str); 7235 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 7236 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 7237 << CondTy << OS.str(); 7238 return QualType(); 7239 } 7240 7241 // Convert operands to the vector result type 7242 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 7243 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 7244 7245 return VectorTy; 7246 } 7247 7248 /// Return false if this is a valid OpenCL condition vector 7249 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 7250 SourceLocation QuestionLoc) { 7251 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 7252 // integral type. 7253 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 7254 assert(CondTy); 7255 QualType EleTy = CondTy->getElementType(); 7256 if (EleTy->isIntegerType()) return false; 7257 7258 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7259 << Cond->getType() << Cond->getSourceRange(); 7260 return true; 7261 } 7262 7263 /// Return false if the vector condition type and the vector 7264 /// result type are compatible. 7265 /// 7266 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 7267 /// number of elements, and their element types have the same number 7268 /// of bits. 7269 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 7270 SourceLocation QuestionLoc) { 7271 const VectorType *CV = CondTy->getAs<VectorType>(); 7272 const VectorType *RV = VecResTy->getAs<VectorType>(); 7273 assert(CV && RV); 7274 7275 if (CV->getNumElements() != RV->getNumElements()) { 7276 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 7277 << CondTy << VecResTy; 7278 return true; 7279 } 7280 7281 QualType CVE = CV->getElementType(); 7282 QualType RVE = RV->getElementType(); 7283 7284 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 7285 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 7286 << CondTy << VecResTy; 7287 return true; 7288 } 7289 7290 return false; 7291 } 7292 7293 /// Return the resulting type for the conditional operator in 7294 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 7295 /// s6.3.i) when the condition is a vector type. 7296 static QualType 7297 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 7298 ExprResult &LHS, ExprResult &RHS, 7299 SourceLocation QuestionLoc) { 7300 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 7301 if (Cond.isInvalid()) 7302 return QualType(); 7303 QualType CondTy = Cond.get()->getType(); 7304 7305 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 7306 return QualType(); 7307 7308 // If either operand is a vector then find the vector type of the 7309 // result as specified in OpenCL v1.1 s6.3.i. 7310 if (LHS.get()->getType()->isVectorType() || 7311 RHS.get()->getType()->isVectorType()) { 7312 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 7313 /*isCompAssign*/false, 7314 /*AllowBothBool*/true, 7315 /*AllowBoolConversions*/false); 7316 if (VecResTy.isNull()) return QualType(); 7317 // The result type must match the condition type as specified in 7318 // OpenCL v1.1 s6.11.6. 7319 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 7320 return QualType(); 7321 return VecResTy; 7322 } 7323 7324 // Both operands are scalar. 7325 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 7326 } 7327 7328 /// Return true if the Expr is block type 7329 static bool checkBlockType(Sema &S, const Expr *E) { 7330 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 7331 QualType Ty = CE->getCallee()->getType(); 7332 if (Ty->isBlockPointerType()) { 7333 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 7334 return true; 7335 } 7336 } 7337 return false; 7338 } 7339 7340 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 7341 /// In that case, LHS = cond. 7342 /// C99 6.5.15 7343 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 7344 ExprResult &RHS, ExprValueKind &VK, 7345 ExprObjectKind &OK, 7346 SourceLocation QuestionLoc) { 7347 7348 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 7349 if (!LHSResult.isUsable()) return QualType(); 7350 LHS = LHSResult; 7351 7352 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 7353 if (!RHSResult.isUsable()) return QualType(); 7354 RHS = RHSResult; 7355 7356 // C++ is sufficiently different to merit its own checker. 7357 if (getLangOpts().CPlusPlus) 7358 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 7359 7360 VK = VK_RValue; 7361 OK = OK_Ordinary; 7362 7363 // The OpenCL operator with a vector condition is sufficiently 7364 // different to merit its own checker. 7365 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 7366 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 7367 7368 // First, check the condition. 7369 Cond = UsualUnaryConversions(Cond.get()); 7370 if (Cond.isInvalid()) 7371 return QualType(); 7372 if (checkCondition(*this, Cond.get(), QuestionLoc)) 7373 return QualType(); 7374 7375 // Now check the two expressions. 7376 if (LHS.get()->getType()->isVectorType() || 7377 RHS.get()->getType()->isVectorType()) 7378 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 7379 /*AllowBothBool*/true, 7380 /*AllowBoolConversions*/false); 7381 7382 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 7383 if (LHS.isInvalid() || RHS.isInvalid()) 7384 return QualType(); 7385 7386 QualType LHSTy = LHS.get()->getType(); 7387 QualType RHSTy = RHS.get()->getType(); 7388 7389 // Diagnose attempts to convert between __float128 and long double where 7390 // such conversions currently can't be handled. 7391 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 7392 Diag(QuestionLoc, 7393 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 7394 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7395 return QualType(); 7396 } 7397 7398 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 7399 // selection operator (?:). 7400 if (getLangOpts().OpenCL && 7401 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 7402 return QualType(); 7403 } 7404 7405 // If both operands have arithmetic type, do the usual arithmetic conversions 7406 // to find a common type: C99 6.5.15p3,5. 7407 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 7408 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 7409 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 7410 7411 return ResTy; 7412 } 7413 7414 // If both operands are the same structure or union type, the result is that 7415 // type. 7416 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 7417 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 7418 if (LHSRT->getDecl() == RHSRT->getDecl()) 7419 // "If both the operands have structure or union type, the result has 7420 // that type." This implies that CV qualifiers are dropped. 7421 return LHSTy.getUnqualifiedType(); 7422 // FIXME: Type of conditional expression must be complete in C mode. 7423 } 7424 7425 // C99 6.5.15p5: "If both operands have void type, the result has void type." 7426 // The following || allows only one side to be void (a GCC-ism). 7427 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 7428 return checkConditionalVoidType(*this, LHS, RHS); 7429 } 7430 7431 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 7432 // the type of the other operand." 7433 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 7434 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 7435 7436 // All objective-c pointer type analysis is done here. 7437 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 7438 QuestionLoc); 7439 if (LHS.isInvalid() || RHS.isInvalid()) 7440 return QualType(); 7441 if (!compositeType.isNull()) 7442 return compositeType; 7443 7444 7445 // Handle block pointer types. 7446 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 7447 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 7448 QuestionLoc); 7449 7450 // Check constraints for C object pointers types (C99 6.5.15p3,6). 7451 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 7452 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 7453 QuestionLoc); 7454 7455 // GCC compatibility: soften pointer/integer mismatch. Note that 7456 // null pointers have been filtered out by this point. 7457 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 7458 /*IsIntFirstExpr=*/true)) 7459 return RHSTy; 7460 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 7461 /*IsIntFirstExpr=*/false)) 7462 return LHSTy; 7463 7464 // Emit a better diagnostic if one of the expressions is a null pointer 7465 // constant and the other is not a pointer type. In this case, the user most 7466 // likely forgot to take the address of the other expression. 7467 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 7468 return QualType(); 7469 7470 // Otherwise, the operands are not compatible. 7471 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 7472 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7473 << RHS.get()->getSourceRange(); 7474 return QualType(); 7475 } 7476 7477 /// FindCompositeObjCPointerType - Helper method to find composite type of 7478 /// two objective-c pointer types of the two input expressions. 7479 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 7480 SourceLocation QuestionLoc) { 7481 QualType LHSTy = LHS.get()->getType(); 7482 QualType RHSTy = RHS.get()->getType(); 7483 7484 // Handle things like Class and struct objc_class*. Here we case the result 7485 // to the pseudo-builtin, because that will be implicitly cast back to the 7486 // redefinition type if an attempt is made to access its fields. 7487 if (LHSTy->isObjCClassType() && 7488 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 7489 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 7490 return LHSTy; 7491 } 7492 if (RHSTy->isObjCClassType() && 7493 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 7494 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 7495 return RHSTy; 7496 } 7497 // And the same for struct objc_object* / id 7498 if (LHSTy->isObjCIdType() && 7499 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 7500 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 7501 return LHSTy; 7502 } 7503 if (RHSTy->isObjCIdType() && 7504 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 7505 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 7506 return RHSTy; 7507 } 7508 // And the same for struct objc_selector* / SEL 7509 if (Context.isObjCSelType(LHSTy) && 7510 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 7511 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 7512 return LHSTy; 7513 } 7514 if (Context.isObjCSelType(RHSTy) && 7515 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 7516 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 7517 return RHSTy; 7518 } 7519 // Check constraints for Objective-C object pointers types. 7520 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 7521 7522 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 7523 // Two identical object pointer types are always compatible. 7524 return LHSTy; 7525 } 7526 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 7527 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 7528 QualType compositeType = LHSTy; 7529 7530 // If both operands are interfaces and either operand can be 7531 // assigned to the other, use that type as the composite 7532 // type. This allows 7533 // xxx ? (A*) a : (B*) b 7534 // where B is a subclass of A. 7535 // 7536 // Additionally, as for assignment, if either type is 'id' 7537 // allow silent coercion. Finally, if the types are 7538 // incompatible then make sure to use 'id' as the composite 7539 // type so the result is acceptable for sending messages to. 7540 7541 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 7542 // It could return the composite type. 7543 if (!(compositeType = 7544 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 7545 // Nothing more to do. 7546 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 7547 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 7548 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 7549 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 7550 } else if ((LHSOPT->isObjCQualifiedIdType() || 7551 RHSOPT->isObjCQualifiedIdType()) && 7552 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 7553 true)) { 7554 // Need to handle "id<xx>" explicitly. 7555 // GCC allows qualified id and any Objective-C type to devolve to 7556 // id. Currently localizing to here until clear this should be 7557 // part of ObjCQualifiedIdTypesAreCompatible. 7558 compositeType = Context.getObjCIdType(); 7559 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 7560 compositeType = Context.getObjCIdType(); 7561 } else { 7562 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 7563 << LHSTy << RHSTy 7564 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7565 QualType incompatTy = Context.getObjCIdType(); 7566 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 7567 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 7568 return incompatTy; 7569 } 7570 // The object pointer types are compatible. 7571 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 7572 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 7573 return compositeType; 7574 } 7575 // Check Objective-C object pointer types and 'void *' 7576 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 7577 if (getLangOpts().ObjCAutoRefCount) { 7578 // ARC forbids the implicit conversion of object pointers to 'void *', 7579 // so these types are not compatible. 7580 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7581 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7582 LHS = RHS = true; 7583 return QualType(); 7584 } 7585 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7586 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 7587 QualType destPointee 7588 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7589 QualType destType = Context.getPointerType(destPointee); 7590 // Add qualifiers if necessary. 7591 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7592 // Promote to void*. 7593 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7594 return destType; 7595 } 7596 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 7597 if (getLangOpts().ObjCAutoRefCount) { 7598 // ARC forbids the implicit conversion of object pointers to 'void *', 7599 // so these types are not compatible. 7600 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7601 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7602 LHS = RHS = true; 7603 return QualType(); 7604 } 7605 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 7606 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7607 QualType destPointee 7608 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7609 QualType destType = Context.getPointerType(destPointee); 7610 // Add qualifiers if necessary. 7611 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7612 // Promote to void*. 7613 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7614 return destType; 7615 } 7616 return QualType(); 7617 } 7618 7619 /// SuggestParentheses - Emit a note with a fixit hint that wraps 7620 /// ParenRange in parentheses. 7621 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 7622 const PartialDiagnostic &Note, 7623 SourceRange ParenRange) { 7624 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 7625 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 7626 EndLoc.isValid()) { 7627 Self.Diag(Loc, Note) 7628 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 7629 << FixItHint::CreateInsertion(EndLoc, ")"); 7630 } else { 7631 // We can't display the parentheses, so just show the bare note. 7632 Self.Diag(Loc, Note) << ParenRange; 7633 } 7634 } 7635 7636 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 7637 return BinaryOperator::isAdditiveOp(Opc) || 7638 BinaryOperator::isMultiplicativeOp(Opc) || 7639 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 7640 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 7641 // not any of the logical operators. Bitwise-xor is commonly used as a 7642 // logical-xor because there is no logical-xor operator. The logical 7643 // operators, including uses of xor, have a high false positive rate for 7644 // precedence warnings. 7645 } 7646 7647 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 7648 /// expression, either using a built-in or overloaded operator, 7649 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 7650 /// expression. 7651 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 7652 Expr **RHSExprs) { 7653 // Don't strip parenthesis: we should not warn if E is in parenthesis. 7654 E = E->IgnoreImpCasts(); 7655 E = E->IgnoreConversionOperator(); 7656 E = E->IgnoreImpCasts(); 7657 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 7658 E = MTE->getSubExpr(); 7659 E = E->IgnoreImpCasts(); 7660 } 7661 7662 // Built-in binary operator. 7663 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 7664 if (IsArithmeticOp(OP->getOpcode())) { 7665 *Opcode = OP->getOpcode(); 7666 *RHSExprs = OP->getRHS(); 7667 return true; 7668 } 7669 } 7670 7671 // Overloaded operator. 7672 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 7673 if (Call->getNumArgs() != 2) 7674 return false; 7675 7676 // Make sure this is really a binary operator that is safe to pass into 7677 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 7678 OverloadedOperatorKind OO = Call->getOperator(); 7679 if (OO < OO_Plus || OO > OO_Arrow || 7680 OO == OO_PlusPlus || OO == OO_MinusMinus) 7681 return false; 7682 7683 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 7684 if (IsArithmeticOp(OpKind)) { 7685 *Opcode = OpKind; 7686 *RHSExprs = Call->getArg(1); 7687 return true; 7688 } 7689 } 7690 7691 return false; 7692 } 7693 7694 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 7695 /// or is a logical expression such as (x==y) which has int type, but is 7696 /// commonly interpreted as boolean. 7697 static bool ExprLooksBoolean(Expr *E) { 7698 E = E->IgnoreParenImpCasts(); 7699 7700 if (E->getType()->isBooleanType()) 7701 return true; 7702 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 7703 return OP->isComparisonOp() || OP->isLogicalOp(); 7704 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 7705 return OP->getOpcode() == UO_LNot; 7706 if (E->getType()->isPointerType()) 7707 return true; 7708 // FIXME: What about overloaded operator calls returning "unspecified boolean 7709 // type"s (commonly pointer-to-members)? 7710 7711 return false; 7712 } 7713 7714 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 7715 /// and binary operator are mixed in a way that suggests the programmer assumed 7716 /// the conditional operator has higher precedence, for example: 7717 /// "int x = a + someBinaryCondition ? 1 : 2". 7718 static void DiagnoseConditionalPrecedence(Sema &Self, 7719 SourceLocation OpLoc, 7720 Expr *Condition, 7721 Expr *LHSExpr, 7722 Expr *RHSExpr) { 7723 BinaryOperatorKind CondOpcode; 7724 Expr *CondRHS; 7725 7726 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 7727 return; 7728 if (!ExprLooksBoolean(CondRHS)) 7729 return; 7730 7731 // The condition is an arithmetic binary expression, with a right- 7732 // hand side that looks boolean, so warn. 7733 7734 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 7735 ? diag::warn_precedence_bitwise_conditional 7736 : diag::warn_precedence_conditional; 7737 7738 Self.Diag(OpLoc, DiagID) 7739 << Condition->getSourceRange() 7740 << BinaryOperator::getOpcodeStr(CondOpcode); 7741 7742 SuggestParentheses( 7743 Self, OpLoc, 7744 Self.PDiag(diag::note_precedence_silence) 7745 << BinaryOperator::getOpcodeStr(CondOpcode), 7746 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 7747 7748 SuggestParentheses(Self, OpLoc, 7749 Self.PDiag(diag::note_precedence_conditional_first), 7750 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 7751 } 7752 7753 /// Compute the nullability of a conditional expression. 7754 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 7755 QualType LHSTy, QualType RHSTy, 7756 ASTContext &Ctx) { 7757 if (!ResTy->isAnyPointerType()) 7758 return ResTy; 7759 7760 auto GetNullability = [&Ctx](QualType Ty) { 7761 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 7762 if (Kind) 7763 return *Kind; 7764 return NullabilityKind::Unspecified; 7765 }; 7766 7767 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 7768 NullabilityKind MergedKind; 7769 7770 // Compute nullability of a binary conditional expression. 7771 if (IsBin) { 7772 if (LHSKind == NullabilityKind::NonNull) 7773 MergedKind = NullabilityKind::NonNull; 7774 else 7775 MergedKind = RHSKind; 7776 // Compute nullability of a normal conditional expression. 7777 } else { 7778 if (LHSKind == NullabilityKind::Nullable || 7779 RHSKind == NullabilityKind::Nullable) 7780 MergedKind = NullabilityKind::Nullable; 7781 else if (LHSKind == NullabilityKind::NonNull) 7782 MergedKind = RHSKind; 7783 else if (RHSKind == NullabilityKind::NonNull) 7784 MergedKind = LHSKind; 7785 else 7786 MergedKind = NullabilityKind::Unspecified; 7787 } 7788 7789 // Return if ResTy already has the correct nullability. 7790 if (GetNullability(ResTy) == MergedKind) 7791 return ResTy; 7792 7793 // Strip all nullability from ResTy. 7794 while (ResTy->getNullability(Ctx)) 7795 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 7796 7797 // Create a new AttributedType with the new nullability kind. 7798 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 7799 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 7800 } 7801 7802 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7803 /// in the case of a the GNU conditional expr extension. 7804 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7805 SourceLocation ColonLoc, 7806 Expr *CondExpr, Expr *LHSExpr, 7807 Expr *RHSExpr) { 7808 if (!getLangOpts().CPlusPlus) { 7809 // C cannot handle TypoExpr nodes in the condition because it 7810 // doesn't handle dependent types properly, so make sure any TypoExprs have 7811 // been dealt with before checking the operands. 7812 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7813 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7814 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7815 7816 if (!CondResult.isUsable()) 7817 return ExprError(); 7818 7819 if (LHSExpr) { 7820 if (!LHSResult.isUsable()) 7821 return ExprError(); 7822 } 7823 7824 if (!RHSResult.isUsable()) 7825 return ExprError(); 7826 7827 CondExpr = CondResult.get(); 7828 LHSExpr = LHSResult.get(); 7829 RHSExpr = RHSResult.get(); 7830 } 7831 7832 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7833 // was the condition. 7834 OpaqueValueExpr *opaqueValue = nullptr; 7835 Expr *commonExpr = nullptr; 7836 if (!LHSExpr) { 7837 commonExpr = CondExpr; 7838 // Lower out placeholder types first. This is important so that we don't 7839 // try to capture a placeholder. This happens in few cases in C++; such 7840 // as Objective-C++'s dictionary subscripting syntax. 7841 if (commonExpr->hasPlaceholderType()) { 7842 ExprResult result = CheckPlaceholderExpr(commonExpr); 7843 if (!result.isUsable()) return ExprError(); 7844 commonExpr = result.get(); 7845 } 7846 // We usually want to apply unary conversions *before* saving, except 7847 // in the special case of a C++ l-value conditional. 7848 if (!(getLangOpts().CPlusPlus 7849 && !commonExpr->isTypeDependent() 7850 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7851 && commonExpr->isGLValue() 7852 && commonExpr->isOrdinaryOrBitFieldObject() 7853 && RHSExpr->isOrdinaryOrBitFieldObject() 7854 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7855 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7856 if (commonRes.isInvalid()) 7857 return ExprError(); 7858 commonExpr = commonRes.get(); 7859 } 7860 7861 // If the common expression is a class or array prvalue, materialize it 7862 // so that we can safely refer to it multiple times. 7863 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 7864 commonExpr->getType()->isArrayType())) { 7865 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 7866 if (MatExpr.isInvalid()) 7867 return ExprError(); 7868 commonExpr = MatExpr.get(); 7869 } 7870 7871 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7872 commonExpr->getType(), 7873 commonExpr->getValueKind(), 7874 commonExpr->getObjectKind(), 7875 commonExpr); 7876 LHSExpr = CondExpr = opaqueValue; 7877 } 7878 7879 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 7880 ExprValueKind VK = VK_RValue; 7881 ExprObjectKind OK = OK_Ordinary; 7882 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7883 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7884 VK, OK, QuestionLoc); 7885 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7886 RHS.isInvalid()) 7887 return ExprError(); 7888 7889 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7890 RHS.get()); 7891 7892 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 7893 7894 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 7895 Context); 7896 7897 if (!commonExpr) 7898 return new (Context) 7899 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 7900 RHS.get(), result, VK, OK); 7901 7902 return new (Context) BinaryConditionalOperator( 7903 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 7904 ColonLoc, result, VK, OK); 7905 } 7906 7907 // checkPointerTypesForAssignment - This is a very tricky routine (despite 7908 // being closely modeled after the C99 spec:-). The odd characteristic of this 7909 // routine is it effectively iqnores the qualifiers on the top level pointee. 7910 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 7911 // FIXME: add a couple examples in this comment. 7912 static Sema::AssignConvertType 7913 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 7914 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7915 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7916 7917 // get the "pointed to" type (ignoring qualifiers at the top level) 7918 const Type *lhptee, *rhptee; 7919 Qualifiers lhq, rhq; 7920 std::tie(lhptee, lhq) = 7921 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 7922 std::tie(rhptee, rhq) = 7923 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 7924 7925 Sema::AssignConvertType ConvTy = Sema::Compatible; 7926 7927 // C99 6.5.16.1p1: This following citation is common to constraints 7928 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 7929 // qualifiers of the type *pointed to* by the right; 7930 7931 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 7932 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 7933 lhq.compatiblyIncludesObjCLifetime(rhq)) { 7934 // Ignore lifetime for further calculation. 7935 lhq.removeObjCLifetime(); 7936 rhq.removeObjCLifetime(); 7937 } 7938 7939 if (!lhq.compatiblyIncludes(rhq)) { 7940 // Treat address-space mismatches as fatal. 7941 if (!lhq.isAddressSpaceSupersetOf(rhq)) 7942 return Sema::IncompatiblePointerDiscardsQualifiers; 7943 7944 // It's okay to add or remove GC or lifetime qualifiers when converting to 7945 // and from void*. 7946 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 7947 .compatiblyIncludes( 7948 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 7949 && (lhptee->isVoidType() || rhptee->isVoidType())) 7950 ; // keep old 7951 7952 // Treat lifetime mismatches as fatal. 7953 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 7954 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7955 7956 // For GCC/MS compatibility, other qualifier mismatches are treated 7957 // as still compatible in C. 7958 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7959 } 7960 7961 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 7962 // incomplete type and the other is a pointer to a qualified or unqualified 7963 // version of void... 7964 if (lhptee->isVoidType()) { 7965 if (rhptee->isIncompleteOrObjectType()) 7966 return ConvTy; 7967 7968 // As an extension, we allow cast to/from void* to function pointer. 7969 assert(rhptee->isFunctionType()); 7970 return Sema::FunctionVoidPointer; 7971 } 7972 7973 if (rhptee->isVoidType()) { 7974 if (lhptee->isIncompleteOrObjectType()) 7975 return ConvTy; 7976 7977 // As an extension, we allow cast to/from void* to function pointer. 7978 assert(lhptee->isFunctionType()); 7979 return Sema::FunctionVoidPointer; 7980 } 7981 7982 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7983 // unqualified versions of compatible types, ... 7984 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7985 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7986 // Check if the pointee types are compatible ignoring the sign. 7987 // We explicitly check for char so that we catch "char" vs 7988 // "unsigned char" on systems where "char" is unsigned. 7989 if (lhptee->isCharType()) 7990 ltrans = S.Context.UnsignedCharTy; 7991 else if (lhptee->hasSignedIntegerRepresentation()) 7992 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7993 7994 if (rhptee->isCharType()) 7995 rtrans = S.Context.UnsignedCharTy; 7996 else if (rhptee->hasSignedIntegerRepresentation()) 7997 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 7998 7999 if (ltrans == rtrans) { 8000 // Types are compatible ignoring the sign. Qualifier incompatibility 8001 // takes priority over sign incompatibility because the sign 8002 // warning can be disabled. 8003 if (ConvTy != Sema::Compatible) 8004 return ConvTy; 8005 8006 return Sema::IncompatiblePointerSign; 8007 } 8008 8009 // If we are a multi-level pointer, it's possible that our issue is simply 8010 // one of qualification - e.g. char ** -> const char ** is not allowed. If 8011 // the eventual target type is the same and the pointers have the same 8012 // level of indirection, this must be the issue. 8013 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 8014 do { 8015 std::tie(lhptee, lhq) = 8016 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 8017 std::tie(rhptee, rhq) = 8018 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 8019 8020 // Inconsistent address spaces at this point is invalid, even if the 8021 // address spaces would be compatible. 8022 // FIXME: This doesn't catch address space mismatches for pointers of 8023 // different nesting levels, like: 8024 // __local int *** a; 8025 // int ** b = a; 8026 // It's not clear how to actually determine when such pointers are 8027 // invalidly incompatible. 8028 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 8029 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 8030 8031 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 8032 8033 if (lhptee == rhptee) 8034 return Sema::IncompatibleNestedPointerQualifiers; 8035 } 8036 8037 // General pointer incompatibility takes priority over qualifiers. 8038 return Sema::IncompatiblePointer; 8039 } 8040 if (!S.getLangOpts().CPlusPlus && 8041 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 8042 return Sema::IncompatiblePointer; 8043 return ConvTy; 8044 } 8045 8046 /// checkBlockPointerTypesForAssignment - This routine determines whether two 8047 /// block pointer types are compatible or whether a block and normal pointer 8048 /// are compatible. It is more restrict than comparing two function pointer 8049 // types. 8050 static Sema::AssignConvertType 8051 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 8052 QualType RHSType) { 8053 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8054 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8055 8056 QualType lhptee, rhptee; 8057 8058 // get the "pointed to" type (ignoring qualifiers at the top level) 8059 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 8060 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 8061 8062 // In C++, the types have to match exactly. 8063 if (S.getLangOpts().CPlusPlus) 8064 return Sema::IncompatibleBlockPointer; 8065 8066 Sema::AssignConvertType ConvTy = Sema::Compatible; 8067 8068 // For blocks we enforce that qualifiers are identical. 8069 Qualifiers LQuals = lhptee.getLocalQualifiers(); 8070 Qualifiers RQuals = rhptee.getLocalQualifiers(); 8071 if (S.getLangOpts().OpenCL) { 8072 LQuals.removeAddressSpace(); 8073 RQuals.removeAddressSpace(); 8074 } 8075 if (LQuals != RQuals) 8076 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8077 8078 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 8079 // assignment. 8080 // The current behavior is similar to C++ lambdas. A block might be 8081 // assigned to a variable iff its return type and parameters are compatible 8082 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 8083 // an assignment. Presumably it should behave in way that a function pointer 8084 // assignment does in C, so for each parameter and return type: 8085 // * CVR and address space of LHS should be a superset of CVR and address 8086 // space of RHS. 8087 // * unqualified types should be compatible. 8088 if (S.getLangOpts().OpenCL) { 8089 if (!S.Context.typesAreBlockPointerCompatible( 8090 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 8091 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 8092 return Sema::IncompatibleBlockPointer; 8093 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 8094 return Sema::IncompatibleBlockPointer; 8095 8096 return ConvTy; 8097 } 8098 8099 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 8100 /// for assignment compatibility. 8101 static Sema::AssignConvertType 8102 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 8103 QualType RHSType) { 8104 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 8105 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 8106 8107 if (LHSType->isObjCBuiltinType()) { 8108 // Class is not compatible with ObjC object pointers. 8109 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 8110 !RHSType->isObjCQualifiedClassType()) 8111 return Sema::IncompatiblePointer; 8112 return Sema::Compatible; 8113 } 8114 if (RHSType->isObjCBuiltinType()) { 8115 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 8116 !LHSType->isObjCQualifiedClassType()) 8117 return Sema::IncompatiblePointer; 8118 return Sema::Compatible; 8119 } 8120 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8121 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8122 8123 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 8124 // make an exception for id<P> 8125 !LHSType->isObjCQualifiedIdType()) 8126 return Sema::CompatiblePointerDiscardsQualifiers; 8127 8128 if (S.Context.typesAreCompatible(LHSType, RHSType)) 8129 return Sema::Compatible; 8130 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 8131 return Sema::IncompatibleObjCQualifiedId; 8132 return Sema::IncompatiblePointer; 8133 } 8134 8135 Sema::AssignConvertType 8136 Sema::CheckAssignmentConstraints(SourceLocation Loc, 8137 QualType LHSType, QualType RHSType) { 8138 // Fake up an opaque expression. We don't actually care about what 8139 // cast operations are required, so if CheckAssignmentConstraints 8140 // adds casts to this they'll be wasted, but fortunately that doesn't 8141 // usually happen on valid code. 8142 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 8143 ExprResult RHSPtr = &RHSExpr; 8144 CastKind K; 8145 8146 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 8147 } 8148 8149 /// This helper function returns true if QT is a vector type that has element 8150 /// type ElementType. 8151 static bool isVector(QualType QT, QualType ElementType) { 8152 if (const VectorType *VT = QT->getAs<VectorType>()) 8153 return VT->getElementType() == ElementType; 8154 return false; 8155 } 8156 8157 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 8158 /// has code to accommodate several GCC extensions when type checking 8159 /// pointers. Here are some objectionable examples that GCC considers warnings: 8160 /// 8161 /// int a, *pint; 8162 /// short *pshort; 8163 /// struct foo *pfoo; 8164 /// 8165 /// pint = pshort; // warning: assignment from incompatible pointer type 8166 /// a = pint; // warning: assignment makes integer from pointer without a cast 8167 /// pint = a; // warning: assignment makes pointer from integer without a cast 8168 /// pint = pfoo; // warning: assignment from incompatible pointer type 8169 /// 8170 /// As a result, the code for dealing with pointers is more complex than the 8171 /// C99 spec dictates. 8172 /// 8173 /// Sets 'Kind' for any result kind except Incompatible. 8174 Sema::AssignConvertType 8175 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 8176 CastKind &Kind, bool ConvertRHS) { 8177 QualType RHSType = RHS.get()->getType(); 8178 QualType OrigLHSType = LHSType; 8179 8180 // Get canonical types. We're not formatting these types, just comparing 8181 // them. 8182 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 8183 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 8184 8185 // Common case: no conversion required. 8186 if (LHSType == RHSType) { 8187 Kind = CK_NoOp; 8188 return Compatible; 8189 } 8190 8191 // If we have an atomic type, try a non-atomic assignment, then just add an 8192 // atomic qualification step. 8193 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 8194 Sema::AssignConvertType result = 8195 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 8196 if (result != Compatible) 8197 return result; 8198 if (Kind != CK_NoOp && ConvertRHS) 8199 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 8200 Kind = CK_NonAtomicToAtomic; 8201 return Compatible; 8202 } 8203 8204 // If the left-hand side is a reference type, then we are in a 8205 // (rare!) case where we've allowed the use of references in C, 8206 // e.g., as a parameter type in a built-in function. In this case, 8207 // just make sure that the type referenced is compatible with the 8208 // right-hand side type. The caller is responsible for adjusting 8209 // LHSType so that the resulting expression does not have reference 8210 // type. 8211 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 8212 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 8213 Kind = CK_LValueBitCast; 8214 return Compatible; 8215 } 8216 return Incompatible; 8217 } 8218 8219 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 8220 // to the same ExtVector type. 8221 if (LHSType->isExtVectorType()) { 8222 if (RHSType->isExtVectorType()) 8223 return Incompatible; 8224 if (RHSType->isArithmeticType()) { 8225 // CK_VectorSplat does T -> vector T, so first cast to the element type. 8226 if (ConvertRHS) 8227 RHS = prepareVectorSplat(LHSType, RHS.get()); 8228 Kind = CK_VectorSplat; 8229 return Compatible; 8230 } 8231 } 8232 8233 // Conversions to or from vector type. 8234 if (LHSType->isVectorType() || RHSType->isVectorType()) { 8235 if (LHSType->isVectorType() && RHSType->isVectorType()) { 8236 // Allow assignments of an AltiVec vector type to an equivalent GCC 8237 // vector type and vice versa 8238 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8239 Kind = CK_BitCast; 8240 return Compatible; 8241 } 8242 8243 // If we are allowing lax vector conversions, and LHS and RHS are both 8244 // vectors, the total size only needs to be the same. This is a bitcast; 8245 // no bits are changed but the result type is different. 8246 if (isLaxVectorConversion(RHSType, LHSType)) { 8247 Kind = CK_BitCast; 8248 return IncompatibleVectors; 8249 } 8250 } 8251 8252 // When the RHS comes from another lax conversion (e.g. binops between 8253 // scalars and vectors) the result is canonicalized as a vector. When the 8254 // LHS is also a vector, the lax is allowed by the condition above. Handle 8255 // the case where LHS is a scalar. 8256 if (LHSType->isScalarType()) { 8257 const VectorType *VecType = RHSType->getAs<VectorType>(); 8258 if (VecType && VecType->getNumElements() == 1 && 8259 isLaxVectorConversion(RHSType, LHSType)) { 8260 ExprResult *VecExpr = &RHS; 8261 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 8262 Kind = CK_BitCast; 8263 return Compatible; 8264 } 8265 } 8266 8267 return Incompatible; 8268 } 8269 8270 // Diagnose attempts to convert between __float128 and long double where 8271 // such conversions currently can't be handled. 8272 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 8273 return Incompatible; 8274 8275 // Disallow assigning a _Complex to a real type in C++ mode since it simply 8276 // discards the imaginary part. 8277 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 8278 !LHSType->getAs<ComplexType>()) 8279 return Incompatible; 8280 8281 // Arithmetic conversions. 8282 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 8283 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 8284 if (ConvertRHS) 8285 Kind = PrepareScalarCast(RHS, LHSType); 8286 return Compatible; 8287 } 8288 8289 // Conversions to normal pointers. 8290 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 8291 // U* -> T* 8292 if (isa<PointerType>(RHSType)) { 8293 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 8294 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 8295 if (AddrSpaceL != AddrSpaceR) 8296 Kind = CK_AddressSpaceConversion; 8297 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 8298 Kind = CK_NoOp; 8299 else 8300 Kind = CK_BitCast; 8301 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 8302 } 8303 8304 // int -> T* 8305 if (RHSType->isIntegerType()) { 8306 Kind = CK_IntegralToPointer; // FIXME: null? 8307 return IntToPointer; 8308 } 8309 8310 // C pointers are not compatible with ObjC object pointers, 8311 // with two exceptions: 8312 if (isa<ObjCObjectPointerType>(RHSType)) { 8313 // - conversions to void* 8314 if (LHSPointer->getPointeeType()->isVoidType()) { 8315 Kind = CK_BitCast; 8316 return Compatible; 8317 } 8318 8319 // - conversions from 'Class' to the redefinition type 8320 if (RHSType->isObjCClassType() && 8321 Context.hasSameType(LHSType, 8322 Context.getObjCClassRedefinitionType())) { 8323 Kind = CK_BitCast; 8324 return Compatible; 8325 } 8326 8327 Kind = CK_BitCast; 8328 return IncompatiblePointer; 8329 } 8330 8331 // U^ -> void* 8332 if (RHSType->getAs<BlockPointerType>()) { 8333 if (LHSPointer->getPointeeType()->isVoidType()) { 8334 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 8335 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 8336 ->getPointeeType() 8337 .getAddressSpace(); 8338 Kind = 8339 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 8340 return Compatible; 8341 } 8342 } 8343 8344 return Incompatible; 8345 } 8346 8347 // Conversions to block pointers. 8348 if (isa<BlockPointerType>(LHSType)) { 8349 // U^ -> T^ 8350 if (RHSType->isBlockPointerType()) { 8351 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 8352 ->getPointeeType() 8353 .getAddressSpace(); 8354 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 8355 ->getPointeeType() 8356 .getAddressSpace(); 8357 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 8358 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 8359 } 8360 8361 // int or null -> T^ 8362 if (RHSType->isIntegerType()) { 8363 Kind = CK_IntegralToPointer; // FIXME: null 8364 return IntToBlockPointer; 8365 } 8366 8367 // id -> T^ 8368 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 8369 Kind = CK_AnyPointerToBlockPointerCast; 8370 return Compatible; 8371 } 8372 8373 // void* -> T^ 8374 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 8375 if (RHSPT->getPointeeType()->isVoidType()) { 8376 Kind = CK_AnyPointerToBlockPointerCast; 8377 return Compatible; 8378 } 8379 8380 return Incompatible; 8381 } 8382 8383 // Conversions to Objective-C pointers. 8384 if (isa<ObjCObjectPointerType>(LHSType)) { 8385 // A* -> B* 8386 if (RHSType->isObjCObjectPointerType()) { 8387 Kind = CK_BitCast; 8388 Sema::AssignConvertType result = 8389 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 8390 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8391 result == Compatible && 8392 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 8393 result = IncompatibleObjCWeakRef; 8394 return result; 8395 } 8396 8397 // int or null -> A* 8398 if (RHSType->isIntegerType()) { 8399 Kind = CK_IntegralToPointer; // FIXME: null 8400 return IntToPointer; 8401 } 8402 8403 // In general, C pointers are not compatible with ObjC object pointers, 8404 // with two exceptions: 8405 if (isa<PointerType>(RHSType)) { 8406 Kind = CK_CPointerToObjCPointerCast; 8407 8408 // - conversions from 'void*' 8409 if (RHSType->isVoidPointerType()) { 8410 return Compatible; 8411 } 8412 8413 // - conversions to 'Class' from its redefinition type 8414 if (LHSType->isObjCClassType() && 8415 Context.hasSameType(RHSType, 8416 Context.getObjCClassRedefinitionType())) { 8417 return Compatible; 8418 } 8419 8420 return IncompatiblePointer; 8421 } 8422 8423 // Only under strict condition T^ is compatible with an Objective-C pointer. 8424 if (RHSType->isBlockPointerType() && 8425 LHSType->isBlockCompatibleObjCPointerType(Context)) { 8426 if (ConvertRHS) 8427 maybeExtendBlockObject(RHS); 8428 Kind = CK_BlockPointerToObjCPointerCast; 8429 return Compatible; 8430 } 8431 8432 return Incompatible; 8433 } 8434 8435 // Conversions from pointers that are not covered by the above. 8436 if (isa<PointerType>(RHSType)) { 8437 // T* -> _Bool 8438 if (LHSType == Context.BoolTy) { 8439 Kind = CK_PointerToBoolean; 8440 return Compatible; 8441 } 8442 8443 // T* -> int 8444 if (LHSType->isIntegerType()) { 8445 Kind = CK_PointerToIntegral; 8446 return PointerToInt; 8447 } 8448 8449 return Incompatible; 8450 } 8451 8452 // Conversions from Objective-C pointers that are not covered by the above. 8453 if (isa<ObjCObjectPointerType>(RHSType)) { 8454 // T* -> _Bool 8455 if (LHSType == Context.BoolTy) { 8456 Kind = CK_PointerToBoolean; 8457 return Compatible; 8458 } 8459 8460 // T* -> int 8461 if (LHSType->isIntegerType()) { 8462 Kind = CK_PointerToIntegral; 8463 return PointerToInt; 8464 } 8465 8466 return Incompatible; 8467 } 8468 8469 // struct A -> struct B 8470 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 8471 if (Context.typesAreCompatible(LHSType, RHSType)) { 8472 Kind = CK_NoOp; 8473 return Compatible; 8474 } 8475 } 8476 8477 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 8478 Kind = CK_IntToOCLSampler; 8479 return Compatible; 8480 } 8481 8482 return Incompatible; 8483 } 8484 8485 /// Constructs a transparent union from an expression that is 8486 /// used to initialize the transparent union. 8487 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 8488 ExprResult &EResult, QualType UnionType, 8489 FieldDecl *Field) { 8490 // Build an initializer list that designates the appropriate member 8491 // of the transparent union. 8492 Expr *E = EResult.get(); 8493 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 8494 E, SourceLocation()); 8495 Initializer->setType(UnionType); 8496 Initializer->setInitializedFieldInUnion(Field); 8497 8498 // Build a compound literal constructing a value of the transparent 8499 // union type from this initializer list. 8500 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 8501 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 8502 VK_RValue, Initializer, false); 8503 } 8504 8505 Sema::AssignConvertType 8506 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 8507 ExprResult &RHS) { 8508 QualType RHSType = RHS.get()->getType(); 8509 8510 // If the ArgType is a Union type, we want to handle a potential 8511 // transparent_union GCC extension. 8512 const RecordType *UT = ArgType->getAsUnionType(); 8513 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 8514 return Incompatible; 8515 8516 // The field to initialize within the transparent union. 8517 RecordDecl *UD = UT->getDecl(); 8518 FieldDecl *InitField = nullptr; 8519 // It's compatible if the expression matches any of the fields. 8520 for (auto *it : UD->fields()) { 8521 if (it->getType()->isPointerType()) { 8522 // If the transparent union contains a pointer type, we allow: 8523 // 1) void pointer 8524 // 2) null pointer constant 8525 if (RHSType->isPointerType()) 8526 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 8527 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 8528 InitField = it; 8529 break; 8530 } 8531 8532 if (RHS.get()->isNullPointerConstant(Context, 8533 Expr::NPC_ValueDependentIsNull)) { 8534 RHS = ImpCastExprToType(RHS.get(), it->getType(), 8535 CK_NullToPointer); 8536 InitField = it; 8537 break; 8538 } 8539 } 8540 8541 CastKind Kind; 8542 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 8543 == Compatible) { 8544 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 8545 InitField = it; 8546 break; 8547 } 8548 } 8549 8550 if (!InitField) 8551 return Incompatible; 8552 8553 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 8554 return Compatible; 8555 } 8556 8557 Sema::AssignConvertType 8558 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 8559 bool Diagnose, 8560 bool DiagnoseCFAudited, 8561 bool ConvertRHS) { 8562 // We need to be able to tell the caller whether we diagnosed a problem, if 8563 // they ask us to issue diagnostics. 8564 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 8565 8566 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 8567 // we can't avoid *all* modifications at the moment, so we need some somewhere 8568 // to put the updated value. 8569 ExprResult LocalRHS = CallerRHS; 8570 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 8571 8572 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 8573 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 8574 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 8575 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 8576 Diag(RHS.get()->getExprLoc(), 8577 diag::warn_noderef_to_dereferenceable_pointer) 8578 << RHS.get()->getSourceRange(); 8579 } 8580 } 8581 } 8582 8583 if (getLangOpts().CPlusPlus) { 8584 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 8585 // C++ 5.17p3: If the left operand is not of class type, the 8586 // expression is implicitly converted (C++ 4) to the 8587 // cv-unqualified type of the left operand. 8588 QualType RHSType = RHS.get()->getType(); 8589 if (Diagnose) { 8590 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8591 AA_Assigning); 8592 } else { 8593 ImplicitConversionSequence ICS = 8594 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8595 /*SuppressUserConversions=*/false, 8596 /*AllowExplicit=*/false, 8597 /*InOverloadResolution=*/false, 8598 /*CStyle=*/false, 8599 /*AllowObjCWritebackConversion=*/false); 8600 if (ICS.isFailure()) 8601 return Incompatible; 8602 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8603 ICS, AA_Assigning); 8604 } 8605 if (RHS.isInvalid()) 8606 return Incompatible; 8607 Sema::AssignConvertType result = Compatible; 8608 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8609 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 8610 result = IncompatibleObjCWeakRef; 8611 return result; 8612 } 8613 8614 // FIXME: Currently, we fall through and treat C++ classes like C 8615 // structures. 8616 // FIXME: We also fall through for atomics; not sure what should 8617 // happen there, though. 8618 } else if (RHS.get()->getType() == Context.OverloadTy) { 8619 // As a set of extensions to C, we support overloading on functions. These 8620 // functions need to be resolved here. 8621 DeclAccessPair DAP; 8622 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 8623 RHS.get(), LHSType, /*Complain=*/false, DAP)) 8624 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 8625 else 8626 return Incompatible; 8627 } 8628 8629 // C99 6.5.16.1p1: the left operand is a pointer and the right is 8630 // a null pointer constant. 8631 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 8632 LHSType->isBlockPointerType()) && 8633 RHS.get()->isNullPointerConstant(Context, 8634 Expr::NPC_ValueDependentIsNull)) { 8635 if (Diagnose || ConvertRHS) { 8636 CastKind Kind; 8637 CXXCastPath Path; 8638 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 8639 /*IgnoreBaseAccess=*/false, Diagnose); 8640 if (ConvertRHS) 8641 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 8642 } 8643 return Compatible; 8644 } 8645 8646 // OpenCL queue_t type assignment. 8647 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 8648 Context, Expr::NPC_ValueDependentIsNull)) { 8649 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 8650 return Compatible; 8651 } 8652 8653 // This check seems unnatural, however it is necessary to ensure the proper 8654 // conversion of functions/arrays. If the conversion were done for all 8655 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 8656 // expressions that suppress this implicit conversion (&, sizeof). 8657 // 8658 // Suppress this for references: C++ 8.5.3p5. 8659 if (!LHSType->isReferenceType()) { 8660 // FIXME: We potentially allocate here even if ConvertRHS is false. 8661 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 8662 if (RHS.isInvalid()) 8663 return Incompatible; 8664 } 8665 CastKind Kind; 8666 Sema::AssignConvertType result = 8667 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 8668 8669 // C99 6.5.16.1p2: The value of the right operand is converted to the 8670 // type of the assignment expression. 8671 // CheckAssignmentConstraints allows the left-hand side to be a reference, 8672 // so that we can use references in built-in functions even in C. 8673 // The getNonReferenceType() call makes sure that the resulting expression 8674 // does not have reference type. 8675 if (result != Incompatible && RHS.get()->getType() != LHSType) { 8676 QualType Ty = LHSType.getNonLValueExprType(Context); 8677 Expr *E = RHS.get(); 8678 8679 // Check for various Objective-C errors. If we are not reporting 8680 // diagnostics and just checking for errors, e.g., during overload 8681 // resolution, return Incompatible to indicate the failure. 8682 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8683 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 8684 Diagnose, DiagnoseCFAudited) != ACR_okay) { 8685 if (!Diagnose) 8686 return Incompatible; 8687 } 8688 if (getLangOpts().ObjC && 8689 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 8690 E->getType(), E, Diagnose) || 8691 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 8692 if (!Diagnose) 8693 return Incompatible; 8694 // Replace the expression with a corrected version and continue so we 8695 // can find further errors. 8696 RHS = E; 8697 return Compatible; 8698 } 8699 8700 if (ConvertRHS) 8701 RHS = ImpCastExprToType(E, Ty, Kind); 8702 } 8703 8704 return result; 8705 } 8706 8707 namespace { 8708 /// The original operand to an operator, prior to the application of the usual 8709 /// arithmetic conversions and converting the arguments of a builtin operator 8710 /// candidate. 8711 struct OriginalOperand { 8712 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 8713 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 8714 Op = MTE->getSubExpr(); 8715 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 8716 Op = BTE->getSubExpr(); 8717 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 8718 Orig = ICE->getSubExprAsWritten(); 8719 Conversion = ICE->getConversionFunction(); 8720 } 8721 } 8722 8723 QualType getType() const { return Orig->getType(); } 8724 8725 Expr *Orig; 8726 NamedDecl *Conversion; 8727 }; 8728 } 8729 8730 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 8731 ExprResult &RHS) { 8732 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 8733 8734 Diag(Loc, diag::err_typecheck_invalid_operands) 8735 << OrigLHS.getType() << OrigRHS.getType() 8736 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8737 8738 // If a user-defined conversion was applied to either of the operands prior 8739 // to applying the built-in operator rules, tell the user about it. 8740 if (OrigLHS.Conversion) { 8741 Diag(OrigLHS.Conversion->getLocation(), 8742 diag::note_typecheck_invalid_operands_converted) 8743 << 0 << LHS.get()->getType(); 8744 } 8745 if (OrigRHS.Conversion) { 8746 Diag(OrigRHS.Conversion->getLocation(), 8747 diag::note_typecheck_invalid_operands_converted) 8748 << 1 << RHS.get()->getType(); 8749 } 8750 8751 return QualType(); 8752 } 8753 8754 // Diagnose cases where a scalar was implicitly converted to a vector and 8755 // diagnose the underlying types. Otherwise, diagnose the error 8756 // as invalid vector logical operands for non-C++ cases. 8757 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 8758 ExprResult &RHS) { 8759 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 8760 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 8761 8762 bool LHSNatVec = LHSType->isVectorType(); 8763 bool RHSNatVec = RHSType->isVectorType(); 8764 8765 if (!(LHSNatVec && RHSNatVec)) { 8766 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 8767 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 8768 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8769 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 8770 << Vector->getSourceRange(); 8771 return QualType(); 8772 } 8773 8774 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8775 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 8776 << RHS.get()->getSourceRange(); 8777 8778 return QualType(); 8779 } 8780 8781 /// Try to convert a value of non-vector type to a vector type by converting 8782 /// the type to the element type of the vector and then performing a splat. 8783 /// If the language is OpenCL, we only use conversions that promote scalar 8784 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 8785 /// for float->int. 8786 /// 8787 /// OpenCL V2.0 6.2.6.p2: 8788 /// An error shall occur if any scalar operand type has greater rank 8789 /// than the type of the vector element. 8790 /// 8791 /// \param scalar - if non-null, actually perform the conversions 8792 /// \return true if the operation fails (but without diagnosing the failure) 8793 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 8794 QualType scalarTy, 8795 QualType vectorEltTy, 8796 QualType vectorTy, 8797 unsigned &DiagID) { 8798 // The conversion to apply to the scalar before splatting it, 8799 // if necessary. 8800 CastKind scalarCast = CK_NoOp; 8801 8802 if (vectorEltTy->isIntegralType(S.Context)) { 8803 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 8804 (scalarTy->isIntegerType() && 8805 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 8806 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8807 return true; 8808 } 8809 if (!scalarTy->isIntegralType(S.Context)) 8810 return true; 8811 scalarCast = CK_IntegralCast; 8812 } else if (vectorEltTy->isRealFloatingType()) { 8813 if (scalarTy->isRealFloatingType()) { 8814 if (S.getLangOpts().OpenCL && 8815 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 8816 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8817 return true; 8818 } 8819 scalarCast = CK_FloatingCast; 8820 } 8821 else if (scalarTy->isIntegralType(S.Context)) 8822 scalarCast = CK_IntegralToFloating; 8823 else 8824 return true; 8825 } else { 8826 return true; 8827 } 8828 8829 // Adjust scalar if desired. 8830 if (scalar) { 8831 if (scalarCast != CK_NoOp) 8832 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 8833 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 8834 } 8835 return false; 8836 } 8837 8838 /// Convert vector E to a vector with the same number of elements but different 8839 /// element type. 8840 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 8841 const auto *VecTy = E->getType()->getAs<VectorType>(); 8842 assert(VecTy && "Expression E must be a vector"); 8843 QualType NewVecTy = S.Context.getVectorType(ElementType, 8844 VecTy->getNumElements(), 8845 VecTy->getVectorKind()); 8846 8847 // Look through the implicit cast. Return the subexpression if its type is 8848 // NewVecTy. 8849 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 8850 if (ICE->getSubExpr()->getType() == NewVecTy) 8851 return ICE->getSubExpr(); 8852 8853 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 8854 return S.ImpCastExprToType(E, NewVecTy, Cast); 8855 } 8856 8857 /// Test if a (constant) integer Int can be casted to another integer type 8858 /// IntTy without losing precision. 8859 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 8860 QualType OtherIntTy) { 8861 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8862 8863 // Reject cases where the value of the Int is unknown as that would 8864 // possibly cause truncation, but accept cases where the scalar can be 8865 // demoted without loss of precision. 8866 Expr::EvalResult EVResult; 8867 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 8868 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 8869 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 8870 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 8871 8872 if (CstInt) { 8873 // If the scalar is constant and is of a higher order and has more active 8874 // bits that the vector element type, reject it. 8875 llvm::APSInt Result = EVResult.Val.getInt(); 8876 unsigned NumBits = IntSigned 8877 ? (Result.isNegative() ? Result.getMinSignedBits() 8878 : Result.getActiveBits()) 8879 : Result.getActiveBits(); 8880 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 8881 return true; 8882 8883 // If the signedness of the scalar type and the vector element type 8884 // differs and the number of bits is greater than that of the vector 8885 // element reject it. 8886 return (IntSigned != OtherIntSigned && 8887 NumBits > S.Context.getIntWidth(OtherIntTy)); 8888 } 8889 8890 // Reject cases where the value of the scalar is not constant and it's 8891 // order is greater than that of the vector element type. 8892 return (Order < 0); 8893 } 8894 8895 /// Test if a (constant) integer Int can be casted to floating point type 8896 /// FloatTy without losing precision. 8897 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 8898 QualType FloatTy) { 8899 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8900 8901 // Determine if the integer constant can be expressed as a floating point 8902 // number of the appropriate type. 8903 Expr::EvalResult EVResult; 8904 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 8905 8906 uint64_t Bits = 0; 8907 if (CstInt) { 8908 // Reject constants that would be truncated if they were converted to 8909 // the floating point type. Test by simple to/from conversion. 8910 // FIXME: Ideally the conversion to an APFloat and from an APFloat 8911 // could be avoided if there was a convertFromAPInt method 8912 // which could signal back if implicit truncation occurred. 8913 llvm::APSInt Result = EVResult.Val.getInt(); 8914 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 8915 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 8916 llvm::APFloat::rmTowardZero); 8917 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 8918 !IntTy->hasSignedIntegerRepresentation()); 8919 bool Ignored = false; 8920 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 8921 &Ignored); 8922 if (Result != ConvertBack) 8923 return true; 8924 } else { 8925 // Reject types that cannot be fully encoded into the mantissa of 8926 // the float. 8927 Bits = S.Context.getTypeSize(IntTy); 8928 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 8929 S.Context.getFloatTypeSemantics(FloatTy)); 8930 if (Bits > FloatPrec) 8931 return true; 8932 } 8933 8934 return false; 8935 } 8936 8937 /// Attempt to convert and splat Scalar into a vector whose types matches 8938 /// Vector following GCC conversion rules. The rule is that implicit 8939 /// conversion can occur when Scalar can be casted to match Vector's element 8940 /// type without causing truncation of Scalar. 8941 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 8942 ExprResult *Vector) { 8943 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 8944 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 8945 const VectorType *VT = VectorTy->getAs<VectorType>(); 8946 8947 assert(!isa<ExtVectorType>(VT) && 8948 "ExtVectorTypes should not be handled here!"); 8949 8950 QualType VectorEltTy = VT->getElementType(); 8951 8952 // Reject cases where the vector element type or the scalar element type are 8953 // not integral or floating point types. 8954 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 8955 return true; 8956 8957 // The conversion to apply to the scalar before splatting it, 8958 // if necessary. 8959 CastKind ScalarCast = CK_NoOp; 8960 8961 // Accept cases where the vector elements are integers and the scalar is 8962 // an integer. 8963 // FIXME: Notionally if the scalar was a floating point value with a precise 8964 // integral representation, we could cast it to an appropriate integer 8965 // type and then perform the rest of the checks here. GCC will perform 8966 // this conversion in some cases as determined by the input language. 8967 // We should accept it on a language independent basis. 8968 if (VectorEltTy->isIntegralType(S.Context) && 8969 ScalarTy->isIntegralType(S.Context) && 8970 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 8971 8972 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 8973 return true; 8974 8975 ScalarCast = CK_IntegralCast; 8976 } else if (VectorEltTy->isRealFloatingType()) { 8977 if (ScalarTy->isRealFloatingType()) { 8978 8979 // Reject cases where the scalar type is not a constant and has a higher 8980 // Order than the vector element type. 8981 llvm::APFloat Result(0.0); 8982 bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context); 8983 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 8984 if (!CstScalar && Order < 0) 8985 return true; 8986 8987 // If the scalar cannot be safely casted to the vector element type, 8988 // reject it. 8989 if (CstScalar) { 8990 bool Truncated = false; 8991 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 8992 llvm::APFloat::rmNearestTiesToEven, &Truncated); 8993 if (Truncated) 8994 return true; 8995 } 8996 8997 ScalarCast = CK_FloatingCast; 8998 } else if (ScalarTy->isIntegralType(S.Context)) { 8999 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 9000 return true; 9001 9002 ScalarCast = CK_IntegralToFloating; 9003 } else 9004 return true; 9005 } 9006 9007 // Adjust scalar if desired. 9008 if (Scalar) { 9009 if (ScalarCast != CK_NoOp) 9010 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 9011 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 9012 } 9013 return false; 9014 } 9015 9016 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 9017 SourceLocation Loc, bool IsCompAssign, 9018 bool AllowBothBool, 9019 bool AllowBoolConversions) { 9020 if (!IsCompAssign) { 9021 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 9022 if (LHS.isInvalid()) 9023 return QualType(); 9024 } 9025 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 9026 if (RHS.isInvalid()) 9027 return QualType(); 9028 9029 // For conversion purposes, we ignore any qualifiers. 9030 // For example, "const float" and "float" are equivalent. 9031 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 9032 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 9033 9034 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 9035 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 9036 assert(LHSVecType || RHSVecType); 9037 9038 // AltiVec-style "vector bool op vector bool" combinations are allowed 9039 // for some operators but not others. 9040 if (!AllowBothBool && 9041 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9042 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9043 return InvalidOperands(Loc, LHS, RHS); 9044 9045 // If the vector types are identical, return. 9046 if (Context.hasSameType(LHSType, RHSType)) 9047 return LHSType; 9048 9049 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 9050 if (LHSVecType && RHSVecType && 9051 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9052 if (isa<ExtVectorType>(LHSVecType)) { 9053 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9054 return LHSType; 9055 } 9056 9057 if (!IsCompAssign) 9058 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9059 return RHSType; 9060 } 9061 9062 // AllowBoolConversions says that bool and non-bool AltiVec vectors 9063 // can be mixed, with the result being the non-bool type. The non-bool 9064 // operand must have integer element type. 9065 if (AllowBoolConversions && LHSVecType && RHSVecType && 9066 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 9067 (Context.getTypeSize(LHSVecType->getElementType()) == 9068 Context.getTypeSize(RHSVecType->getElementType()))) { 9069 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 9070 LHSVecType->getElementType()->isIntegerType() && 9071 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 9072 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9073 return LHSType; 9074 } 9075 if (!IsCompAssign && 9076 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9077 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 9078 RHSVecType->getElementType()->isIntegerType()) { 9079 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9080 return RHSType; 9081 } 9082 } 9083 9084 // If there's a vector type and a scalar, try to convert the scalar to 9085 // the vector element type and splat. 9086 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 9087 if (!RHSVecType) { 9088 if (isa<ExtVectorType>(LHSVecType)) { 9089 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 9090 LHSVecType->getElementType(), LHSType, 9091 DiagID)) 9092 return LHSType; 9093 } else { 9094 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 9095 return LHSType; 9096 } 9097 } 9098 if (!LHSVecType) { 9099 if (isa<ExtVectorType>(RHSVecType)) { 9100 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 9101 LHSType, RHSVecType->getElementType(), 9102 RHSType, DiagID)) 9103 return RHSType; 9104 } else { 9105 if (LHS.get()->getValueKind() == VK_LValue || 9106 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 9107 return RHSType; 9108 } 9109 } 9110 9111 // FIXME: The code below also handles conversion between vectors and 9112 // non-scalars, we should break this down into fine grained specific checks 9113 // and emit proper diagnostics. 9114 QualType VecType = LHSVecType ? LHSType : RHSType; 9115 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 9116 QualType OtherType = LHSVecType ? RHSType : LHSType; 9117 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 9118 if (isLaxVectorConversion(OtherType, VecType)) { 9119 // If we're allowing lax vector conversions, only the total (data) size 9120 // needs to be the same. For non compound assignment, if one of the types is 9121 // scalar, the result is always the vector type. 9122 if (!IsCompAssign) { 9123 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 9124 return VecType; 9125 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 9126 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 9127 // type. Note that this is already done by non-compound assignments in 9128 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 9129 // <1 x T> -> T. The result is also a vector type. 9130 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 9131 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 9132 ExprResult *RHSExpr = &RHS; 9133 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 9134 return VecType; 9135 } 9136 } 9137 9138 // Okay, the expression is invalid. 9139 9140 // If there's a non-vector, non-real operand, diagnose that. 9141 if ((!RHSVecType && !RHSType->isRealType()) || 9142 (!LHSVecType && !LHSType->isRealType())) { 9143 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 9144 << LHSType << RHSType 9145 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9146 return QualType(); 9147 } 9148 9149 // OpenCL V1.1 6.2.6.p1: 9150 // If the operands are of more than one vector type, then an error shall 9151 // occur. Implicit conversions between vector types are not permitted, per 9152 // section 6.2.1. 9153 if (getLangOpts().OpenCL && 9154 RHSVecType && isa<ExtVectorType>(RHSVecType) && 9155 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 9156 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 9157 << RHSType; 9158 return QualType(); 9159 } 9160 9161 9162 // If there is a vector type that is not a ExtVector and a scalar, we reach 9163 // this point if scalar could not be converted to the vector's element type 9164 // without truncation. 9165 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 9166 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 9167 QualType Scalar = LHSVecType ? RHSType : LHSType; 9168 QualType Vector = LHSVecType ? LHSType : RHSType; 9169 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 9170 Diag(Loc, 9171 diag::err_typecheck_vector_not_convertable_implict_truncation) 9172 << ScalarOrVector << Scalar << Vector; 9173 9174 return QualType(); 9175 } 9176 9177 // Otherwise, use the generic diagnostic. 9178 Diag(Loc, DiagID) 9179 << LHSType << RHSType 9180 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9181 return QualType(); 9182 } 9183 9184 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 9185 // expression. These are mainly cases where the null pointer is used as an 9186 // integer instead of a pointer. 9187 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 9188 SourceLocation Loc, bool IsCompare) { 9189 // The canonical way to check for a GNU null is with isNullPointerConstant, 9190 // but we use a bit of a hack here for speed; this is a relatively 9191 // hot path, and isNullPointerConstant is slow. 9192 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 9193 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 9194 9195 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 9196 9197 // Avoid analyzing cases where the result will either be invalid (and 9198 // diagnosed as such) or entirely valid and not something to warn about. 9199 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 9200 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 9201 return; 9202 9203 // Comparison operations would not make sense with a null pointer no matter 9204 // what the other expression is. 9205 if (!IsCompare) { 9206 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 9207 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 9208 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 9209 return; 9210 } 9211 9212 // The rest of the operations only make sense with a null pointer 9213 // if the other expression is a pointer. 9214 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 9215 NonNullType->canDecayToPointerType()) 9216 return; 9217 9218 S.Diag(Loc, diag::warn_null_in_comparison_operation) 9219 << LHSNull /* LHS is NULL */ << NonNullType 9220 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9221 } 9222 9223 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 9224 SourceLocation Loc) { 9225 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 9226 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 9227 if (!LUE || !RUE) 9228 return; 9229 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 9230 RUE->getKind() != UETT_SizeOf) 9231 return; 9232 9233 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 9234 QualType LHSTy = LHSArg->getType(); 9235 QualType RHSTy; 9236 9237 if (RUE->isArgumentType()) 9238 RHSTy = RUE->getArgumentType(); 9239 else 9240 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 9241 9242 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 9243 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 9244 return; 9245 9246 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 9247 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 9248 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 9249 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 9250 << LHSArgDecl; 9251 } 9252 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 9253 QualType ArrayElemTy = ArrayTy->getElementType(); 9254 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 9255 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 9256 ArrayElemTy->isCharType() || 9257 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 9258 return; 9259 S.Diag(Loc, diag::warn_division_sizeof_array) 9260 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 9261 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 9262 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 9263 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 9264 << LHSArgDecl; 9265 } 9266 9267 S.Diag(Loc, diag::note_precedence_silence) << RHS; 9268 } 9269 } 9270 9271 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 9272 ExprResult &RHS, 9273 SourceLocation Loc, bool IsDiv) { 9274 // Check for division/remainder by zero. 9275 Expr::EvalResult RHSValue; 9276 if (!RHS.get()->isValueDependent() && 9277 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 9278 RHSValue.Val.getInt() == 0) 9279 S.DiagRuntimeBehavior(Loc, RHS.get(), 9280 S.PDiag(diag::warn_remainder_division_by_zero) 9281 << IsDiv << RHS.get()->getSourceRange()); 9282 } 9283 9284 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 9285 SourceLocation Loc, 9286 bool IsCompAssign, bool IsDiv) { 9287 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9288 9289 if (LHS.get()->getType()->isVectorType() || 9290 RHS.get()->getType()->isVectorType()) 9291 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9292 /*AllowBothBool*/getLangOpts().AltiVec, 9293 /*AllowBoolConversions*/false); 9294 9295 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 9296 if (LHS.isInvalid() || RHS.isInvalid()) 9297 return QualType(); 9298 9299 9300 if (compType.isNull() || !compType->isArithmeticType()) 9301 return InvalidOperands(Loc, LHS, RHS); 9302 if (IsDiv) { 9303 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 9304 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 9305 } 9306 return compType; 9307 } 9308 9309 QualType Sema::CheckRemainderOperands( 9310 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 9311 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9312 9313 if (LHS.get()->getType()->isVectorType() || 9314 RHS.get()->getType()->isVectorType()) { 9315 if (LHS.get()->getType()->hasIntegerRepresentation() && 9316 RHS.get()->getType()->hasIntegerRepresentation()) 9317 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9318 /*AllowBothBool*/getLangOpts().AltiVec, 9319 /*AllowBoolConversions*/false); 9320 return InvalidOperands(Loc, LHS, RHS); 9321 } 9322 9323 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 9324 if (LHS.isInvalid() || RHS.isInvalid()) 9325 return QualType(); 9326 9327 if (compType.isNull() || !compType->isIntegerType()) 9328 return InvalidOperands(Loc, LHS, RHS); 9329 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 9330 return compType; 9331 } 9332 9333 /// Diagnose invalid arithmetic on two void pointers. 9334 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 9335 Expr *LHSExpr, Expr *RHSExpr) { 9336 S.Diag(Loc, S.getLangOpts().CPlusPlus 9337 ? diag::err_typecheck_pointer_arith_void_type 9338 : diag::ext_gnu_void_ptr) 9339 << 1 /* two pointers */ << LHSExpr->getSourceRange() 9340 << RHSExpr->getSourceRange(); 9341 } 9342 9343 /// Diagnose invalid arithmetic on a void pointer. 9344 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 9345 Expr *Pointer) { 9346 S.Diag(Loc, S.getLangOpts().CPlusPlus 9347 ? diag::err_typecheck_pointer_arith_void_type 9348 : diag::ext_gnu_void_ptr) 9349 << 0 /* one pointer */ << Pointer->getSourceRange(); 9350 } 9351 9352 /// Diagnose invalid arithmetic on a null pointer. 9353 /// 9354 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 9355 /// idiom, which we recognize as a GNU extension. 9356 /// 9357 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 9358 Expr *Pointer, bool IsGNUIdiom) { 9359 if (IsGNUIdiom) 9360 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 9361 << Pointer->getSourceRange(); 9362 else 9363 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 9364 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 9365 } 9366 9367 /// Diagnose invalid arithmetic on two function pointers. 9368 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 9369 Expr *LHS, Expr *RHS) { 9370 assert(LHS->getType()->isAnyPointerType()); 9371 assert(RHS->getType()->isAnyPointerType()); 9372 S.Diag(Loc, S.getLangOpts().CPlusPlus 9373 ? diag::err_typecheck_pointer_arith_function_type 9374 : diag::ext_gnu_ptr_func_arith) 9375 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 9376 // We only show the second type if it differs from the first. 9377 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 9378 RHS->getType()) 9379 << RHS->getType()->getPointeeType() 9380 << LHS->getSourceRange() << RHS->getSourceRange(); 9381 } 9382 9383 /// Diagnose invalid arithmetic on a function pointer. 9384 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 9385 Expr *Pointer) { 9386 assert(Pointer->getType()->isAnyPointerType()); 9387 S.Diag(Loc, S.getLangOpts().CPlusPlus 9388 ? diag::err_typecheck_pointer_arith_function_type 9389 : diag::ext_gnu_ptr_func_arith) 9390 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 9391 << 0 /* one pointer, so only one type */ 9392 << Pointer->getSourceRange(); 9393 } 9394 9395 /// Emit error if Operand is incomplete pointer type 9396 /// 9397 /// \returns True if pointer has incomplete type 9398 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 9399 Expr *Operand) { 9400 QualType ResType = Operand->getType(); 9401 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 9402 ResType = ResAtomicType->getValueType(); 9403 9404 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 9405 QualType PointeeTy = ResType->getPointeeType(); 9406 return S.RequireCompleteType(Loc, PointeeTy, 9407 diag::err_typecheck_arithmetic_incomplete_type, 9408 PointeeTy, Operand->getSourceRange()); 9409 } 9410 9411 /// Check the validity of an arithmetic pointer operand. 9412 /// 9413 /// If the operand has pointer type, this code will check for pointer types 9414 /// which are invalid in arithmetic operations. These will be diagnosed 9415 /// appropriately, including whether or not the use is supported as an 9416 /// extension. 9417 /// 9418 /// \returns True when the operand is valid to use (even if as an extension). 9419 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 9420 Expr *Operand) { 9421 QualType ResType = Operand->getType(); 9422 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 9423 ResType = ResAtomicType->getValueType(); 9424 9425 if (!ResType->isAnyPointerType()) return true; 9426 9427 QualType PointeeTy = ResType->getPointeeType(); 9428 if (PointeeTy->isVoidType()) { 9429 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 9430 return !S.getLangOpts().CPlusPlus; 9431 } 9432 if (PointeeTy->isFunctionType()) { 9433 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 9434 return !S.getLangOpts().CPlusPlus; 9435 } 9436 9437 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 9438 9439 return true; 9440 } 9441 9442 /// Check the validity of a binary arithmetic operation w.r.t. pointer 9443 /// operands. 9444 /// 9445 /// This routine will diagnose any invalid arithmetic on pointer operands much 9446 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 9447 /// for emitting a single diagnostic even for operations where both LHS and RHS 9448 /// are (potentially problematic) pointers. 9449 /// 9450 /// \returns True when the operand is valid to use (even if as an extension). 9451 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 9452 Expr *LHSExpr, Expr *RHSExpr) { 9453 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 9454 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 9455 if (!isLHSPointer && !isRHSPointer) return true; 9456 9457 QualType LHSPointeeTy, RHSPointeeTy; 9458 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 9459 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 9460 9461 // if both are pointers check if operation is valid wrt address spaces 9462 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 9463 const PointerType *lhsPtr = LHSExpr->getType()->castAs<PointerType>(); 9464 const PointerType *rhsPtr = RHSExpr->getType()->castAs<PointerType>(); 9465 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 9466 S.Diag(Loc, 9467 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 9468 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 9469 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 9470 return false; 9471 } 9472 } 9473 9474 // Check for arithmetic on pointers to incomplete types. 9475 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 9476 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 9477 if (isLHSVoidPtr || isRHSVoidPtr) { 9478 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 9479 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 9480 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 9481 9482 return !S.getLangOpts().CPlusPlus; 9483 } 9484 9485 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 9486 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 9487 if (isLHSFuncPtr || isRHSFuncPtr) { 9488 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 9489 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 9490 RHSExpr); 9491 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 9492 9493 return !S.getLangOpts().CPlusPlus; 9494 } 9495 9496 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 9497 return false; 9498 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 9499 return false; 9500 9501 return true; 9502 } 9503 9504 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 9505 /// literal. 9506 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 9507 Expr *LHSExpr, Expr *RHSExpr) { 9508 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 9509 Expr* IndexExpr = RHSExpr; 9510 if (!StrExpr) { 9511 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 9512 IndexExpr = LHSExpr; 9513 } 9514 9515 bool IsStringPlusInt = StrExpr && 9516 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 9517 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 9518 return; 9519 9520 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 9521 Self.Diag(OpLoc, diag::warn_string_plus_int) 9522 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 9523 9524 // Only print a fixit for "str" + int, not for int + "str". 9525 if (IndexExpr == RHSExpr) { 9526 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 9527 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 9528 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 9529 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 9530 << FixItHint::CreateInsertion(EndLoc, "]"); 9531 } else 9532 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 9533 } 9534 9535 /// Emit a warning when adding a char literal to a string. 9536 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 9537 Expr *LHSExpr, Expr *RHSExpr) { 9538 const Expr *StringRefExpr = LHSExpr; 9539 const CharacterLiteral *CharExpr = 9540 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 9541 9542 if (!CharExpr) { 9543 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 9544 StringRefExpr = RHSExpr; 9545 } 9546 9547 if (!CharExpr || !StringRefExpr) 9548 return; 9549 9550 const QualType StringType = StringRefExpr->getType(); 9551 9552 // Return if not a PointerType. 9553 if (!StringType->isAnyPointerType()) 9554 return; 9555 9556 // Return if not a CharacterType. 9557 if (!StringType->getPointeeType()->isAnyCharacterType()) 9558 return; 9559 9560 ASTContext &Ctx = Self.getASTContext(); 9561 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 9562 9563 const QualType CharType = CharExpr->getType(); 9564 if (!CharType->isAnyCharacterType() && 9565 CharType->isIntegerType() && 9566 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 9567 Self.Diag(OpLoc, diag::warn_string_plus_char) 9568 << DiagRange << Ctx.CharTy; 9569 } else { 9570 Self.Diag(OpLoc, diag::warn_string_plus_char) 9571 << DiagRange << CharExpr->getType(); 9572 } 9573 9574 // Only print a fixit for str + char, not for char + str. 9575 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 9576 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 9577 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 9578 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 9579 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 9580 << FixItHint::CreateInsertion(EndLoc, "]"); 9581 } else { 9582 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 9583 } 9584 } 9585 9586 /// Emit error when two pointers are incompatible. 9587 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 9588 Expr *LHSExpr, Expr *RHSExpr) { 9589 assert(LHSExpr->getType()->isAnyPointerType()); 9590 assert(RHSExpr->getType()->isAnyPointerType()); 9591 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 9592 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 9593 << RHSExpr->getSourceRange(); 9594 } 9595 9596 // C99 6.5.6 9597 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 9598 SourceLocation Loc, BinaryOperatorKind Opc, 9599 QualType* CompLHSTy) { 9600 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9601 9602 if (LHS.get()->getType()->isVectorType() || 9603 RHS.get()->getType()->isVectorType()) { 9604 QualType compType = CheckVectorOperands( 9605 LHS, RHS, Loc, CompLHSTy, 9606 /*AllowBothBool*/getLangOpts().AltiVec, 9607 /*AllowBoolConversions*/getLangOpts().ZVector); 9608 if (CompLHSTy) *CompLHSTy = compType; 9609 return compType; 9610 } 9611 9612 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 9613 if (LHS.isInvalid() || RHS.isInvalid()) 9614 return QualType(); 9615 9616 // Diagnose "string literal" '+' int and string '+' "char literal". 9617 if (Opc == BO_Add) { 9618 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 9619 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 9620 } 9621 9622 // handle the common case first (both operands are arithmetic). 9623 if (!compType.isNull() && compType->isArithmeticType()) { 9624 if (CompLHSTy) *CompLHSTy = compType; 9625 return compType; 9626 } 9627 9628 // Type-checking. Ultimately the pointer's going to be in PExp; 9629 // note that we bias towards the LHS being the pointer. 9630 Expr *PExp = LHS.get(), *IExp = RHS.get(); 9631 9632 bool isObjCPointer; 9633 if (PExp->getType()->isPointerType()) { 9634 isObjCPointer = false; 9635 } else if (PExp->getType()->isObjCObjectPointerType()) { 9636 isObjCPointer = true; 9637 } else { 9638 std::swap(PExp, IExp); 9639 if (PExp->getType()->isPointerType()) { 9640 isObjCPointer = false; 9641 } else if (PExp->getType()->isObjCObjectPointerType()) { 9642 isObjCPointer = true; 9643 } else { 9644 return InvalidOperands(Loc, LHS, RHS); 9645 } 9646 } 9647 assert(PExp->getType()->isAnyPointerType()); 9648 9649 if (!IExp->getType()->isIntegerType()) 9650 return InvalidOperands(Loc, LHS, RHS); 9651 9652 // Adding to a null pointer results in undefined behavior. 9653 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 9654 Context, Expr::NPC_ValueDependentIsNotNull)) { 9655 // In C++ adding zero to a null pointer is defined. 9656 Expr::EvalResult KnownVal; 9657 if (!getLangOpts().CPlusPlus || 9658 (!IExp->isValueDependent() && 9659 (!IExp->EvaluateAsInt(KnownVal, Context) || 9660 KnownVal.Val.getInt() != 0))) { 9661 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 9662 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 9663 Context, BO_Add, PExp, IExp); 9664 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 9665 } 9666 } 9667 9668 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 9669 return QualType(); 9670 9671 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 9672 return QualType(); 9673 9674 // Check array bounds for pointer arithemtic 9675 CheckArrayAccess(PExp, IExp); 9676 9677 if (CompLHSTy) { 9678 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 9679 if (LHSTy.isNull()) { 9680 LHSTy = LHS.get()->getType(); 9681 if (LHSTy->isPromotableIntegerType()) 9682 LHSTy = Context.getPromotedIntegerType(LHSTy); 9683 } 9684 *CompLHSTy = LHSTy; 9685 } 9686 9687 return PExp->getType(); 9688 } 9689 9690 // C99 6.5.6 9691 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 9692 SourceLocation Loc, 9693 QualType* CompLHSTy) { 9694 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9695 9696 if (LHS.get()->getType()->isVectorType() || 9697 RHS.get()->getType()->isVectorType()) { 9698 QualType compType = CheckVectorOperands( 9699 LHS, RHS, Loc, CompLHSTy, 9700 /*AllowBothBool*/getLangOpts().AltiVec, 9701 /*AllowBoolConversions*/getLangOpts().ZVector); 9702 if (CompLHSTy) *CompLHSTy = compType; 9703 return compType; 9704 } 9705 9706 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 9707 if (LHS.isInvalid() || RHS.isInvalid()) 9708 return QualType(); 9709 9710 // Enforce type constraints: C99 6.5.6p3. 9711 9712 // Handle the common case first (both operands are arithmetic). 9713 if (!compType.isNull() && compType->isArithmeticType()) { 9714 if (CompLHSTy) *CompLHSTy = compType; 9715 return compType; 9716 } 9717 9718 // Either ptr - int or ptr - ptr. 9719 if (LHS.get()->getType()->isAnyPointerType()) { 9720 QualType lpointee = LHS.get()->getType()->getPointeeType(); 9721 9722 // Diagnose bad cases where we step over interface counts. 9723 if (LHS.get()->getType()->isObjCObjectPointerType() && 9724 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 9725 return QualType(); 9726 9727 // The result type of a pointer-int computation is the pointer type. 9728 if (RHS.get()->getType()->isIntegerType()) { 9729 // Subtracting from a null pointer should produce a warning. 9730 // The last argument to the diagnose call says this doesn't match the 9731 // GNU int-to-pointer idiom. 9732 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 9733 Expr::NPC_ValueDependentIsNotNull)) { 9734 // In C++ adding zero to a null pointer is defined. 9735 Expr::EvalResult KnownVal; 9736 if (!getLangOpts().CPlusPlus || 9737 (!RHS.get()->isValueDependent() && 9738 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 9739 KnownVal.Val.getInt() != 0))) { 9740 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 9741 } 9742 } 9743 9744 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 9745 return QualType(); 9746 9747 // Check array bounds for pointer arithemtic 9748 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 9749 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 9750 9751 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9752 return LHS.get()->getType(); 9753 } 9754 9755 // Handle pointer-pointer subtractions. 9756 if (const PointerType *RHSPTy 9757 = RHS.get()->getType()->getAs<PointerType>()) { 9758 QualType rpointee = RHSPTy->getPointeeType(); 9759 9760 if (getLangOpts().CPlusPlus) { 9761 // Pointee types must be the same: C++ [expr.add] 9762 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 9763 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9764 } 9765 } else { 9766 // Pointee types must be compatible C99 6.5.6p3 9767 if (!Context.typesAreCompatible( 9768 Context.getCanonicalType(lpointee).getUnqualifiedType(), 9769 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 9770 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9771 return QualType(); 9772 } 9773 } 9774 9775 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 9776 LHS.get(), RHS.get())) 9777 return QualType(); 9778 9779 // FIXME: Add warnings for nullptr - ptr. 9780 9781 // The pointee type may have zero size. As an extension, a structure or 9782 // union may have zero size or an array may have zero length. In this 9783 // case subtraction does not make sense. 9784 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 9785 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 9786 if (ElementSize.isZero()) { 9787 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 9788 << rpointee.getUnqualifiedType() 9789 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9790 } 9791 } 9792 9793 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9794 return Context.getPointerDiffType(); 9795 } 9796 } 9797 9798 return InvalidOperands(Loc, LHS, RHS); 9799 } 9800 9801 static bool isScopedEnumerationType(QualType T) { 9802 if (const EnumType *ET = T->getAs<EnumType>()) 9803 return ET->getDecl()->isScoped(); 9804 return false; 9805 } 9806 9807 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 9808 SourceLocation Loc, BinaryOperatorKind Opc, 9809 QualType LHSType) { 9810 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 9811 // so skip remaining warnings as we don't want to modify values within Sema. 9812 if (S.getLangOpts().OpenCL) 9813 return; 9814 9815 // Check right/shifter operand 9816 Expr::EvalResult RHSResult; 9817 if (RHS.get()->isValueDependent() || 9818 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 9819 return; 9820 llvm::APSInt Right = RHSResult.Val.getInt(); 9821 9822 if (Right.isNegative()) { 9823 S.DiagRuntimeBehavior(Loc, RHS.get(), 9824 S.PDiag(diag::warn_shift_negative) 9825 << RHS.get()->getSourceRange()); 9826 return; 9827 } 9828 llvm::APInt LeftBits(Right.getBitWidth(), 9829 S.Context.getTypeSize(LHS.get()->getType())); 9830 if (Right.uge(LeftBits)) { 9831 S.DiagRuntimeBehavior(Loc, RHS.get(), 9832 S.PDiag(diag::warn_shift_gt_typewidth) 9833 << RHS.get()->getSourceRange()); 9834 return; 9835 } 9836 if (Opc != BO_Shl) 9837 return; 9838 9839 // When left shifting an ICE which is signed, we can check for overflow which 9840 // according to C++ standards prior to C++2a has undefined behavior 9841 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 9842 // more than the maximum value representable in the result type, so never 9843 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 9844 // expression is still probably a bug.) 9845 Expr::EvalResult LHSResult; 9846 if (LHS.get()->isValueDependent() || 9847 LHSType->hasUnsignedIntegerRepresentation() || 9848 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 9849 return; 9850 llvm::APSInt Left = LHSResult.Val.getInt(); 9851 9852 // If LHS does not have a signed type and non-negative value 9853 // then, the behavior is undefined before C++2a. Warn about it. 9854 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 9855 !S.getLangOpts().CPlusPlus2a) { 9856 S.DiagRuntimeBehavior(Loc, LHS.get(), 9857 S.PDiag(diag::warn_shift_lhs_negative) 9858 << LHS.get()->getSourceRange()); 9859 return; 9860 } 9861 9862 llvm::APInt ResultBits = 9863 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 9864 if (LeftBits.uge(ResultBits)) 9865 return; 9866 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 9867 Result = Result.shl(Right); 9868 9869 // Print the bit representation of the signed integer as an unsigned 9870 // hexadecimal number. 9871 SmallString<40> HexResult; 9872 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 9873 9874 // If we are only missing a sign bit, this is less likely to result in actual 9875 // bugs -- if the result is cast back to an unsigned type, it will have the 9876 // expected value. Thus we place this behind a different warning that can be 9877 // turned off separately if needed. 9878 if (LeftBits == ResultBits - 1) { 9879 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 9880 << HexResult << LHSType 9881 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9882 return; 9883 } 9884 9885 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 9886 << HexResult.str() << Result.getMinSignedBits() << LHSType 9887 << Left.getBitWidth() << LHS.get()->getSourceRange() 9888 << RHS.get()->getSourceRange(); 9889 } 9890 9891 /// Return the resulting type when a vector is shifted 9892 /// by a scalar or vector shift amount. 9893 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 9894 SourceLocation Loc, bool IsCompAssign) { 9895 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 9896 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 9897 !LHS.get()->getType()->isVectorType()) { 9898 S.Diag(Loc, diag::err_shift_rhs_only_vector) 9899 << RHS.get()->getType() << LHS.get()->getType() 9900 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9901 return QualType(); 9902 } 9903 9904 if (!IsCompAssign) { 9905 LHS = S.UsualUnaryConversions(LHS.get()); 9906 if (LHS.isInvalid()) return QualType(); 9907 } 9908 9909 RHS = S.UsualUnaryConversions(RHS.get()); 9910 if (RHS.isInvalid()) return QualType(); 9911 9912 QualType LHSType = LHS.get()->getType(); 9913 // Note that LHS might be a scalar because the routine calls not only in 9914 // OpenCL case. 9915 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 9916 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 9917 9918 // Note that RHS might not be a vector. 9919 QualType RHSType = RHS.get()->getType(); 9920 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 9921 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 9922 9923 // The operands need to be integers. 9924 if (!LHSEleType->isIntegerType()) { 9925 S.Diag(Loc, diag::err_typecheck_expect_int) 9926 << LHS.get()->getType() << LHS.get()->getSourceRange(); 9927 return QualType(); 9928 } 9929 9930 if (!RHSEleType->isIntegerType()) { 9931 S.Diag(Loc, diag::err_typecheck_expect_int) 9932 << RHS.get()->getType() << RHS.get()->getSourceRange(); 9933 return QualType(); 9934 } 9935 9936 if (!LHSVecTy) { 9937 assert(RHSVecTy); 9938 if (IsCompAssign) 9939 return RHSType; 9940 if (LHSEleType != RHSEleType) { 9941 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 9942 LHSEleType = RHSEleType; 9943 } 9944 QualType VecTy = 9945 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 9946 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 9947 LHSType = VecTy; 9948 } else if (RHSVecTy) { 9949 // OpenCL v1.1 s6.3.j says that for vector types, the operators 9950 // are applied component-wise. So if RHS is a vector, then ensure 9951 // that the number of elements is the same as LHS... 9952 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 9953 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 9954 << LHS.get()->getType() << RHS.get()->getType() 9955 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9956 return QualType(); 9957 } 9958 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 9959 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 9960 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 9961 if (LHSBT != RHSBT && 9962 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 9963 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 9964 << LHS.get()->getType() << RHS.get()->getType() 9965 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9966 } 9967 } 9968 } else { 9969 // ...else expand RHS to match the number of elements in LHS. 9970 QualType VecTy = 9971 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 9972 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 9973 } 9974 9975 return LHSType; 9976 } 9977 9978 // C99 6.5.7 9979 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 9980 SourceLocation Loc, BinaryOperatorKind Opc, 9981 bool IsCompAssign) { 9982 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9983 9984 // Vector shifts promote their scalar inputs to vector type. 9985 if (LHS.get()->getType()->isVectorType() || 9986 RHS.get()->getType()->isVectorType()) { 9987 if (LangOpts.ZVector) { 9988 // The shift operators for the z vector extensions work basically 9989 // like general shifts, except that neither the LHS nor the RHS is 9990 // allowed to be a "vector bool". 9991 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 9992 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 9993 return InvalidOperands(Loc, LHS, RHS); 9994 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 9995 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9996 return InvalidOperands(Loc, LHS, RHS); 9997 } 9998 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 9999 } 10000 10001 // Shifts don't perform usual arithmetic conversions, they just do integer 10002 // promotions on each operand. C99 6.5.7p3 10003 10004 // For the LHS, do usual unary conversions, but then reset them away 10005 // if this is a compound assignment. 10006 ExprResult OldLHS = LHS; 10007 LHS = UsualUnaryConversions(LHS.get()); 10008 if (LHS.isInvalid()) 10009 return QualType(); 10010 QualType LHSType = LHS.get()->getType(); 10011 if (IsCompAssign) LHS = OldLHS; 10012 10013 // The RHS is simpler. 10014 RHS = UsualUnaryConversions(RHS.get()); 10015 if (RHS.isInvalid()) 10016 return QualType(); 10017 QualType RHSType = RHS.get()->getType(); 10018 10019 // C99 6.5.7p2: Each of the operands shall have integer type. 10020 if (!LHSType->hasIntegerRepresentation() || 10021 !RHSType->hasIntegerRepresentation()) 10022 return InvalidOperands(Loc, LHS, RHS); 10023 10024 // C++0x: Don't allow scoped enums. FIXME: Use something better than 10025 // hasIntegerRepresentation() above instead of this. 10026 if (isScopedEnumerationType(LHSType) || 10027 isScopedEnumerationType(RHSType)) { 10028 return InvalidOperands(Loc, LHS, RHS); 10029 } 10030 // Sanity-check shift operands 10031 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 10032 10033 // "The type of the result is that of the promoted left operand." 10034 return LHSType; 10035 } 10036 10037 /// If two different enums are compared, raise a warning. 10038 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 10039 Expr *RHS) { 10040 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 10041 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 10042 10043 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 10044 if (!LHSEnumType) 10045 return; 10046 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 10047 if (!RHSEnumType) 10048 return; 10049 10050 // Ignore anonymous enums. 10051 if (!LHSEnumType->getDecl()->getIdentifier() && 10052 !LHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 10053 return; 10054 if (!RHSEnumType->getDecl()->getIdentifier() && 10055 !RHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 10056 return; 10057 10058 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 10059 return; 10060 10061 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 10062 << LHSStrippedType << RHSStrippedType 10063 << LHS->getSourceRange() << RHS->getSourceRange(); 10064 } 10065 10066 /// Diagnose bad pointer comparisons. 10067 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 10068 ExprResult &LHS, ExprResult &RHS, 10069 bool IsError) { 10070 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 10071 : diag::ext_typecheck_comparison_of_distinct_pointers) 10072 << LHS.get()->getType() << RHS.get()->getType() 10073 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10074 } 10075 10076 /// Returns false if the pointers are converted to a composite type, 10077 /// true otherwise. 10078 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 10079 ExprResult &LHS, ExprResult &RHS) { 10080 // C++ [expr.rel]p2: 10081 // [...] Pointer conversions (4.10) and qualification 10082 // conversions (4.4) are performed on pointer operands (or on 10083 // a pointer operand and a null pointer constant) to bring 10084 // them to their composite pointer type. [...] 10085 // 10086 // C++ [expr.eq]p1 uses the same notion for (in)equality 10087 // comparisons of pointers. 10088 10089 QualType LHSType = LHS.get()->getType(); 10090 QualType RHSType = RHS.get()->getType(); 10091 assert(LHSType->isPointerType() || RHSType->isPointerType() || 10092 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 10093 10094 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 10095 if (T.isNull()) { 10096 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 10097 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 10098 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 10099 else 10100 S.InvalidOperands(Loc, LHS, RHS); 10101 return true; 10102 } 10103 10104 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 10105 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 10106 return false; 10107 } 10108 10109 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 10110 ExprResult &LHS, 10111 ExprResult &RHS, 10112 bool IsError) { 10113 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 10114 : diag::ext_typecheck_comparison_of_fptr_to_void) 10115 << LHS.get()->getType() << RHS.get()->getType() 10116 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10117 } 10118 10119 static bool isObjCObjectLiteral(ExprResult &E) { 10120 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 10121 case Stmt::ObjCArrayLiteralClass: 10122 case Stmt::ObjCDictionaryLiteralClass: 10123 case Stmt::ObjCStringLiteralClass: 10124 case Stmt::ObjCBoxedExprClass: 10125 return true; 10126 default: 10127 // Note that ObjCBoolLiteral is NOT an object literal! 10128 return false; 10129 } 10130 } 10131 10132 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 10133 const ObjCObjectPointerType *Type = 10134 LHS->getType()->getAs<ObjCObjectPointerType>(); 10135 10136 // If this is not actually an Objective-C object, bail out. 10137 if (!Type) 10138 return false; 10139 10140 // Get the LHS object's interface type. 10141 QualType InterfaceType = Type->getPointeeType(); 10142 10143 // If the RHS isn't an Objective-C object, bail out. 10144 if (!RHS->getType()->isObjCObjectPointerType()) 10145 return false; 10146 10147 // Try to find the -isEqual: method. 10148 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 10149 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 10150 InterfaceType, 10151 /*IsInstance=*/true); 10152 if (!Method) { 10153 if (Type->isObjCIdType()) { 10154 // For 'id', just check the global pool. 10155 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 10156 /*receiverId=*/true); 10157 } else { 10158 // Check protocols. 10159 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 10160 /*IsInstance=*/true); 10161 } 10162 } 10163 10164 if (!Method) 10165 return false; 10166 10167 QualType T = Method->parameters()[0]->getType(); 10168 if (!T->isObjCObjectPointerType()) 10169 return false; 10170 10171 QualType R = Method->getReturnType(); 10172 if (!R->isScalarType()) 10173 return false; 10174 10175 return true; 10176 } 10177 10178 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 10179 FromE = FromE->IgnoreParenImpCasts(); 10180 switch (FromE->getStmtClass()) { 10181 default: 10182 break; 10183 case Stmt::ObjCStringLiteralClass: 10184 // "string literal" 10185 return LK_String; 10186 case Stmt::ObjCArrayLiteralClass: 10187 // "array literal" 10188 return LK_Array; 10189 case Stmt::ObjCDictionaryLiteralClass: 10190 // "dictionary literal" 10191 return LK_Dictionary; 10192 case Stmt::BlockExprClass: 10193 return LK_Block; 10194 case Stmt::ObjCBoxedExprClass: { 10195 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 10196 switch (Inner->getStmtClass()) { 10197 case Stmt::IntegerLiteralClass: 10198 case Stmt::FloatingLiteralClass: 10199 case Stmt::CharacterLiteralClass: 10200 case Stmt::ObjCBoolLiteralExprClass: 10201 case Stmt::CXXBoolLiteralExprClass: 10202 // "numeric literal" 10203 return LK_Numeric; 10204 case Stmt::ImplicitCastExprClass: { 10205 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 10206 // Boolean literals can be represented by implicit casts. 10207 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 10208 return LK_Numeric; 10209 break; 10210 } 10211 default: 10212 break; 10213 } 10214 return LK_Boxed; 10215 } 10216 } 10217 return LK_None; 10218 } 10219 10220 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 10221 ExprResult &LHS, ExprResult &RHS, 10222 BinaryOperator::Opcode Opc){ 10223 Expr *Literal; 10224 Expr *Other; 10225 if (isObjCObjectLiteral(LHS)) { 10226 Literal = LHS.get(); 10227 Other = RHS.get(); 10228 } else { 10229 Literal = RHS.get(); 10230 Other = LHS.get(); 10231 } 10232 10233 // Don't warn on comparisons against nil. 10234 Other = Other->IgnoreParenCasts(); 10235 if (Other->isNullPointerConstant(S.getASTContext(), 10236 Expr::NPC_ValueDependentIsNotNull)) 10237 return; 10238 10239 // This should be kept in sync with warn_objc_literal_comparison. 10240 // LK_String should always be after the other literals, since it has its own 10241 // warning flag. 10242 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 10243 assert(LiteralKind != Sema::LK_Block); 10244 if (LiteralKind == Sema::LK_None) { 10245 llvm_unreachable("Unknown Objective-C object literal kind"); 10246 } 10247 10248 if (LiteralKind == Sema::LK_String) 10249 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 10250 << Literal->getSourceRange(); 10251 else 10252 S.Diag(Loc, diag::warn_objc_literal_comparison) 10253 << LiteralKind << Literal->getSourceRange(); 10254 10255 if (BinaryOperator::isEqualityOp(Opc) && 10256 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 10257 SourceLocation Start = LHS.get()->getBeginLoc(); 10258 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 10259 CharSourceRange OpRange = 10260 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 10261 10262 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 10263 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 10264 << FixItHint::CreateReplacement(OpRange, " isEqual:") 10265 << FixItHint::CreateInsertion(End, "]"); 10266 } 10267 } 10268 10269 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 10270 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 10271 ExprResult &RHS, SourceLocation Loc, 10272 BinaryOperatorKind Opc) { 10273 // Check that left hand side is !something. 10274 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 10275 if (!UO || UO->getOpcode() != UO_LNot) return; 10276 10277 // Only check if the right hand side is non-bool arithmetic type. 10278 if (RHS.get()->isKnownToHaveBooleanValue()) return; 10279 10280 // Make sure that the something in !something is not bool. 10281 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 10282 if (SubExpr->isKnownToHaveBooleanValue()) return; 10283 10284 // Emit warning. 10285 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 10286 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 10287 << Loc << IsBitwiseOp; 10288 10289 // First note suggest !(x < y) 10290 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 10291 SourceLocation FirstClose = RHS.get()->getEndLoc(); 10292 FirstClose = S.getLocForEndOfToken(FirstClose); 10293 if (FirstClose.isInvalid()) 10294 FirstOpen = SourceLocation(); 10295 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 10296 << IsBitwiseOp 10297 << FixItHint::CreateInsertion(FirstOpen, "(") 10298 << FixItHint::CreateInsertion(FirstClose, ")"); 10299 10300 // Second note suggests (!x) < y 10301 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 10302 SourceLocation SecondClose = LHS.get()->getEndLoc(); 10303 SecondClose = S.getLocForEndOfToken(SecondClose); 10304 if (SecondClose.isInvalid()) 10305 SecondOpen = SourceLocation(); 10306 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 10307 << FixItHint::CreateInsertion(SecondOpen, "(") 10308 << FixItHint::CreateInsertion(SecondClose, ")"); 10309 } 10310 10311 // Returns true if E refers to a non-weak array. 10312 static bool checkForArray(const Expr *E) { 10313 const ValueDecl *D = nullptr; 10314 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 10315 D = DR->getDecl(); 10316 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 10317 if (Mem->isImplicitAccess()) 10318 D = Mem->getMemberDecl(); 10319 } 10320 if (!D) 10321 return false; 10322 return D->getType()->isArrayType() && !D->isWeak(); 10323 } 10324 10325 /// Diagnose some forms of syntactically-obvious tautological comparison. 10326 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 10327 Expr *LHS, Expr *RHS, 10328 BinaryOperatorKind Opc) { 10329 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 10330 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 10331 10332 QualType LHSType = LHS->getType(); 10333 QualType RHSType = RHS->getType(); 10334 if (LHSType->hasFloatingRepresentation() || 10335 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 10336 S.inTemplateInstantiation()) 10337 return; 10338 10339 // Comparisons between two array types are ill-formed for operator<=>, so 10340 // we shouldn't emit any additional warnings about it. 10341 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 10342 return; 10343 10344 // For non-floating point types, check for self-comparisons of the form 10345 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 10346 // often indicate logic errors in the program. 10347 // 10348 // NOTE: Don't warn about comparison expressions resulting from macro 10349 // expansion. Also don't warn about comparisons which are only self 10350 // comparisons within a template instantiation. The warnings should catch 10351 // obvious cases in the definition of the template anyways. The idea is to 10352 // warn when the typed comparison operator will always evaluate to the same 10353 // result. 10354 10355 // Used for indexing into %select in warn_comparison_always 10356 enum { 10357 AlwaysConstant, 10358 AlwaysTrue, 10359 AlwaysFalse, 10360 AlwaysEqual, // std::strong_ordering::equal from operator<=> 10361 }; 10362 10363 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 10364 if (Expr::isSameComparisonOperand(LHS, RHS)) { 10365 unsigned Result; 10366 switch (Opc) { 10367 case BO_EQ: 10368 case BO_LE: 10369 case BO_GE: 10370 Result = AlwaysTrue; 10371 break; 10372 case BO_NE: 10373 case BO_LT: 10374 case BO_GT: 10375 Result = AlwaysFalse; 10376 break; 10377 case BO_Cmp: 10378 Result = AlwaysEqual; 10379 break; 10380 default: 10381 Result = AlwaysConstant; 10382 break; 10383 } 10384 S.DiagRuntimeBehavior(Loc, nullptr, 10385 S.PDiag(diag::warn_comparison_always) 10386 << 0 /*self-comparison*/ 10387 << Result); 10388 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 10389 // What is it always going to evaluate to? 10390 unsigned Result; 10391 switch (Opc) { 10392 case BO_EQ: // e.g. array1 == array2 10393 Result = AlwaysFalse; 10394 break; 10395 case BO_NE: // e.g. array1 != array2 10396 Result = AlwaysTrue; 10397 break; 10398 default: // e.g. array1 <= array2 10399 // The best we can say is 'a constant' 10400 Result = AlwaysConstant; 10401 break; 10402 } 10403 S.DiagRuntimeBehavior(Loc, nullptr, 10404 S.PDiag(diag::warn_comparison_always) 10405 << 1 /*array comparison*/ 10406 << Result); 10407 } 10408 } 10409 10410 if (isa<CastExpr>(LHSStripped)) 10411 LHSStripped = LHSStripped->IgnoreParenCasts(); 10412 if (isa<CastExpr>(RHSStripped)) 10413 RHSStripped = RHSStripped->IgnoreParenCasts(); 10414 10415 // Warn about comparisons against a string constant (unless the other 10416 // operand is null); the user probably wants string comparison function. 10417 Expr *LiteralString = nullptr; 10418 Expr *LiteralStringStripped = nullptr; 10419 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 10420 !RHSStripped->isNullPointerConstant(S.Context, 10421 Expr::NPC_ValueDependentIsNull)) { 10422 LiteralString = LHS; 10423 LiteralStringStripped = LHSStripped; 10424 } else if ((isa<StringLiteral>(RHSStripped) || 10425 isa<ObjCEncodeExpr>(RHSStripped)) && 10426 !LHSStripped->isNullPointerConstant(S.Context, 10427 Expr::NPC_ValueDependentIsNull)) { 10428 LiteralString = RHS; 10429 LiteralStringStripped = RHSStripped; 10430 } 10431 10432 if (LiteralString) { 10433 S.DiagRuntimeBehavior(Loc, nullptr, 10434 S.PDiag(diag::warn_stringcompare) 10435 << isa<ObjCEncodeExpr>(LiteralStringStripped) 10436 << LiteralString->getSourceRange()); 10437 } 10438 } 10439 10440 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 10441 switch (CK) { 10442 default: { 10443 #ifndef NDEBUG 10444 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 10445 << "\n"; 10446 #endif 10447 llvm_unreachable("unhandled cast kind"); 10448 } 10449 case CK_UserDefinedConversion: 10450 return ICK_Identity; 10451 case CK_LValueToRValue: 10452 return ICK_Lvalue_To_Rvalue; 10453 case CK_ArrayToPointerDecay: 10454 return ICK_Array_To_Pointer; 10455 case CK_FunctionToPointerDecay: 10456 return ICK_Function_To_Pointer; 10457 case CK_IntegralCast: 10458 return ICK_Integral_Conversion; 10459 case CK_FloatingCast: 10460 return ICK_Floating_Conversion; 10461 case CK_IntegralToFloating: 10462 case CK_FloatingToIntegral: 10463 return ICK_Floating_Integral; 10464 case CK_IntegralComplexCast: 10465 case CK_FloatingComplexCast: 10466 case CK_FloatingComplexToIntegralComplex: 10467 case CK_IntegralComplexToFloatingComplex: 10468 return ICK_Complex_Conversion; 10469 case CK_FloatingComplexToReal: 10470 case CK_FloatingRealToComplex: 10471 case CK_IntegralComplexToReal: 10472 case CK_IntegralRealToComplex: 10473 return ICK_Complex_Real; 10474 } 10475 } 10476 10477 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 10478 QualType FromType, 10479 SourceLocation Loc) { 10480 // Check for a narrowing implicit conversion. 10481 StandardConversionSequence SCS; 10482 SCS.setAsIdentityConversion(); 10483 SCS.setToType(0, FromType); 10484 SCS.setToType(1, ToType); 10485 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 10486 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 10487 10488 APValue PreNarrowingValue; 10489 QualType PreNarrowingType; 10490 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 10491 PreNarrowingType, 10492 /*IgnoreFloatToIntegralConversion*/ true)) { 10493 case NK_Dependent_Narrowing: 10494 // Implicit conversion to a narrower type, but the expression is 10495 // value-dependent so we can't tell whether it's actually narrowing. 10496 case NK_Not_Narrowing: 10497 return false; 10498 10499 case NK_Constant_Narrowing: 10500 // Implicit conversion to a narrower type, and the value is not a constant 10501 // expression. 10502 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 10503 << /*Constant*/ 1 10504 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 10505 return true; 10506 10507 case NK_Variable_Narrowing: 10508 // Implicit conversion to a narrower type, and the value is not a constant 10509 // expression. 10510 case NK_Type_Narrowing: 10511 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 10512 << /*Constant*/ 0 << FromType << ToType; 10513 // TODO: It's not a constant expression, but what if the user intended it 10514 // to be? Can we produce notes to help them figure out why it isn't? 10515 return true; 10516 } 10517 llvm_unreachable("unhandled case in switch"); 10518 } 10519 10520 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 10521 ExprResult &LHS, 10522 ExprResult &RHS, 10523 SourceLocation Loc) { 10524 using CCT = ComparisonCategoryType; 10525 10526 QualType LHSType = LHS.get()->getType(); 10527 QualType RHSType = RHS.get()->getType(); 10528 // Dig out the original argument type and expression before implicit casts 10529 // were applied. These are the types/expressions we need to check the 10530 // [expr.spaceship] requirements against. 10531 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 10532 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 10533 QualType LHSStrippedType = LHSStripped.get()->getType(); 10534 QualType RHSStrippedType = RHSStripped.get()->getType(); 10535 10536 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 10537 // other is not, the program is ill-formed. 10538 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 10539 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 10540 return QualType(); 10541 } 10542 10543 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 10544 RHSStrippedType->isEnumeralType(); 10545 if (NumEnumArgs == 1) { 10546 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 10547 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 10548 if (OtherTy->hasFloatingRepresentation()) { 10549 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 10550 return QualType(); 10551 } 10552 } 10553 if (NumEnumArgs == 2) { 10554 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 10555 // type E, the operator yields the result of converting the operands 10556 // to the underlying type of E and applying <=> to the converted operands. 10557 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 10558 S.InvalidOperands(Loc, LHS, RHS); 10559 return QualType(); 10560 } 10561 QualType IntType = 10562 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 10563 assert(IntType->isArithmeticType()); 10564 10565 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 10566 // promote the boolean type, and all other promotable integer types, to 10567 // avoid this. 10568 if (IntType->isPromotableIntegerType()) 10569 IntType = S.Context.getPromotedIntegerType(IntType); 10570 10571 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 10572 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 10573 LHSType = RHSType = IntType; 10574 } 10575 10576 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 10577 // usual arithmetic conversions are applied to the operands. 10578 QualType Type = S.UsualArithmeticConversions(LHS, RHS); 10579 if (LHS.isInvalid() || RHS.isInvalid()) 10580 return QualType(); 10581 if (Type.isNull()) 10582 return S.InvalidOperands(Loc, LHS, RHS); 10583 assert(Type->isArithmeticType() || Type->isEnumeralType()); 10584 10585 bool HasNarrowing = checkThreeWayNarrowingConversion( 10586 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 10587 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 10588 RHS.get()->getBeginLoc()); 10589 if (HasNarrowing) 10590 return QualType(); 10591 10592 assert(!Type.isNull() && "composite type for <=> has not been set"); 10593 10594 auto TypeKind = [&]() { 10595 if (const ComplexType *CT = Type->getAs<ComplexType>()) { 10596 if (CT->getElementType()->hasFloatingRepresentation()) 10597 return CCT::WeakEquality; 10598 return CCT::StrongEquality; 10599 } 10600 if (Type->isIntegralOrEnumerationType()) 10601 return CCT::StrongOrdering; 10602 if (Type->hasFloatingRepresentation()) 10603 return CCT::PartialOrdering; 10604 llvm_unreachable("other types are unimplemented"); 10605 }(); 10606 10607 return S.CheckComparisonCategoryType(TypeKind, Loc); 10608 } 10609 10610 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 10611 ExprResult &RHS, 10612 SourceLocation Loc, 10613 BinaryOperatorKind Opc) { 10614 if (Opc == BO_Cmp) 10615 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 10616 10617 // C99 6.5.8p3 / C99 6.5.9p4 10618 QualType Type = S.UsualArithmeticConversions(LHS, RHS); 10619 if (LHS.isInvalid() || RHS.isInvalid()) 10620 return QualType(); 10621 if (Type.isNull()) 10622 return S.InvalidOperands(Loc, LHS, RHS); 10623 assert(Type->isArithmeticType() || Type->isEnumeralType()); 10624 10625 checkEnumComparison(S, Loc, LHS.get(), RHS.get()); 10626 10627 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 10628 return S.InvalidOperands(Loc, LHS, RHS); 10629 10630 // Check for comparisons of floating point operands using != and ==. 10631 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 10632 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 10633 10634 // The result of comparisons is 'bool' in C++, 'int' in C. 10635 return S.Context.getLogicalOperationType(); 10636 } 10637 10638 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 10639 if (!NullE.get()->getType()->isAnyPointerType()) 10640 return; 10641 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 10642 if (!E.get()->getType()->isAnyPointerType() && 10643 E.get()->isNullPointerConstant(Context, 10644 Expr::NPC_ValueDependentIsNotNull) == 10645 Expr::NPCK_ZeroExpression) { 10646 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 10647 if (CL->getValue() == 0) 10648 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 10649 << NullValue 10650 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 10651 NullValue ? "NULL" : "(void *)0"); 10652 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 10653 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 10654 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 10655 if (T == Context.CharTy) 10656 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 10657 << NullValue 10658 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 10659 NullValue ? "NULL" : "(void *)0"); 10660 } 10661 } 10662 } 10663 10664 // C99 6.5.8, C++ [expr.rel] 10665 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 10666 SourceLocation Loc, 10667 BinaryOperatorKind Opc) { 10668 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 10669 bool IsThreeWay = Opc == BO_Cmp; 10670 auto IsAnyPointerType = [](ExprResult E) { 10671 QualType Ty = E.get()->getType(); 10672 return Ty->isPointerType() || Ty->isMemberPointerType(); 10673 }; 10674 10675 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 10676 // type, array-to-pointer, ..., conversions are performed on both operands to 10677 // bring them to their composite type. 10678 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 10679 // any type-related checks. 10680 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 10681 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10682 if (LHS.isInvalid()) 10683 return QualType(); 10684 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10685 if (RHS.isInvalid()) 10686 return QualType(); 10687 } else { 10688 LHS = DefaultLvalueConversion(LHS.get()); 10689 if (LHS.isInvalid()) 10690 return QualType(); 10691 RHS = DefaultLvalueConversion(RHS.get()); 10692 if (RHS.isInvalid()) 10693 return QualType(); 10694 } 10695 10696 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 10697 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 10698 CheckPtrComparisonWithNullChar(LHS, RHS); 10699 CheckPtrComparisonWithNullChar(RHS, LHS); 10700 } 10701 10702 // Handle vector comparisons separately. 10703 if (LHS.get()->getType()->isVectorType() || 10704 RHS.get()->getType()->isVectorType()) 10705 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 10706 10707 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 10708 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 10709 10710 QualType LHSType = LHS.get()->getType(); 10711 QualType RHSType = RHS.get()->getType(); 10712 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 10713 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 10714 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 10715 10716 const Expr::NullPointerConstantKind LHSNullKind = 10717 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 10718 const Expr::NullPointerConstantKind RHSNullKind = 10719 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 10720 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 10721 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 10722 10723 auto computeResultTy = [&]() { 10724 if (Opc != BO_Cmp) 10725 return Context.getLogicalOperationType(); 10726 assert(getLangOpts().CPlusPlus); 10727 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 10728 10729 QualType CompositeTy = LHS.get()->getType(); 10730 assert(!CompositeTy->isReferenceType()); 10731 10732 auto buildResultTy = [&](ComparisonCategoryType Kind) { 10733 return CheckComparisonCategoryType(Kind, Loc); 10734 }; 10735 10736 // C++2a [expr.spaceship]p7: If the composite pointer type is a function 10737 // pointer type, a pointer-to-member type, or std::nullptr_t, the 10738 // result is of type std::strong_equality 10739 if (CompositeTy->isFunctionPointerType() || 10740 CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType()) 10741 // FIXME: consider making the function pointer case produce 10742 // strong_ordering not strong_equality, per P0946R0-Jax18 discussion 10743 // and direction polls 10744 return buildResultTy(ComparisonCategoryType::StrongEquality); 10745 10746 // C++2a [expr.spaceship]p8: If the composite pointer type is an object 10747 // pointer type, p <=> q is of type std::strong_ordering. 10748 if (CompositeTy->isPointerType()) { 10749 // P0946R0: Comparisons between a null pointer constant and an object 10750 // pointer result in std::strong_equality 10751 if (LHSIsNull != RHSIsNull) 10752 return buildResultTy(ComparisonCategoryType::StrongEquality); 10753 return buildResultTy(ComparisonCategoryType::StrongOrdering); 10754 } 10755 // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed. 10756 // TODO: Extend support for operator<=> to ObjC types. 10757 return InvalidOperands(Loc, LHS, RHS); 10758 }; 10759 10760 10761 if (!IsRelational && LHSIsNull != RHSIsNull) { 10762 bool IsEquality = Opc == BO_EQ; 10763 if (RHSIsNull) 10764 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 10765 RHS.get()->getSourceRange()); 10766 else 10767 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 10768 LHS.get()->getSourceRange()); 10769 } 10770 10771 if ((LHSType->isIntegerType() && !LHSIsNull) || 10772 (RHSType->isIntegerType() && !RHSIsNull)) { 10773 // Skip normal pointer conversion checks in this case; we have better 10774 // diagnostics for this below. 10775 } else if (getLangOpts().CPlusPlus) { 10776 // Equality comparison of a function pointer to a void pointer is invalid, 10777 // but we allow it as an extension. 10778 // FIXME: If we really want to allow this, should it be part of composite 10779 // pointer type computation so it works in conditionals too? 10780 if (!IsRelational && 10781 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 10782 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 10783 // This is a gcc extension compatibility comparison. 10784 // In a SFINAE context, we treat this as a hard error to maintain 10785 // conformance with the C++ standard. 10786 diagnoseFunctionPointerToVoidComparison( 10787 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 10788 10789 if (isSFINAEContext()) 10790 return QualType(); 10791 10792 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10793 return computeResultTy(); 10794 } 10795 10796 // C++ [expr.eq]p2: 10797 // If at least one operand is a pointer [...] bring them to their 10798 // composite pointer type. 10799 // C++ [expr.spaceship]p6 10800 // If at least one of the operands is of pointer type, [...] bring them 10801 // to their composite pointer type. 10802 // C++ [expr.rel]p2: 10803 // If both operands are pointers, [...] bring them to their composite 10804 // pointer type. 10805 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 10806 (IsRelational ? 2 : 1) && 10807 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 10808 RHSType->isObjCObjectPointerType()))) { 10809 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 10810 return QualType(); 10811 return computeResultTy(); 10812 } 10813 } else if (LHSType->isPointerType() && 10814 RHSType->isPointerType()) { // C99 6.5.8p2 10815 // All of the following pointer-related warnings are GCC extensions, except 10816 // when handling null pointer constants. 10817 QualType LCanPointeeTy = 10818 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 10819 QualType RCanPointeeTy = 10820 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 10821 10822 // C99 6.5.9p2 and C99 6.5.8p2 10823 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 10824 RCanPointeeTy.getUnqualifiedType())) { 10825 // Valid unless a relational comparison of function pointers 10826 if (IsRelational && LCanPointeeTy->isFunctionType()) { 10827 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 10828 << LHSType << RHSType << LHS.get()->getSourceRange() 10829 << RHS.get()->getSourceRange(); 10830 } 10831 } else if (!IsRelational && 10832 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 10833 // Valid unless comparison between non-null pointer and function pointer 10834 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 10835 && !LHSIsNull && !RHSIsNull) 10836 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 10837 /*isError*/false); 10838 } else { 10839 // Invalid 10840 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 10841 } 10842 if (LCanPointeeTy != RCanPointeeTy) { 10843 // Treat NULL constant as a special case in OpenCL. 10844 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 10845 const PointerType *LHSPtr = LHSType->castAs<PointerType>(); 10846 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->castAs<PointerType>())) { 10847 Diag(Loc, 10848 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10849 << LHSType << RHSType << 0 /* comparison */ 10850 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10851 } 10852 } 10853 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 10854 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 10855 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 10856 : CK_BitCast; 10857 if (LHSIsNull && !RHSIsNull) 10858 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 10859 else 10860 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 10861 } 10862 return computeResultTy(); 10863 } 10864 10865 if (getLangOpts().CPlusPlus) { 10866 // C++ [expr.eq]p4: 10867 // Two operands of type std::nullptr_t or one operand of type 10868 // std::nullptr_t and the other a null pointer constant compare equal. 10869 if (!IsRelational && LHSIsNull && RHSIsNull) { 10870 if (LHSType->isNullPtrType()) { 10871 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10872 return computeResultTy(); 10873 } 10874 if (RHSType->isNullPtrType()) { 10875 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10876 return computeResultTy(); 10877 } 10878 } 10879 10880 // Comparison of Objective-C pointers and block pointers against nullptr_t. 10881 // These aren't covered by the composite pointer type rules. 10882 if (!IsRelational && RHSType->isNullPtrType() && 10883 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 10884 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10885 return computeResultTy(); 10886 } 10887 if (!IsRelational && LHSType->isNullPtrType() && 10888 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 10889 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10890 return computeResultTy(); 10891 } 10892 10893 if (IsRelational && 10894 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 10895 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 10896 // HACK: Relational comparison of nullptr_t against a pointer type is 10897 // invalid per DR583, but we allow it within std::less<> and friends, 10898 // since otherwise common uses of it break. 10899 // FIXME: Consider removing this hack once LWG fixes std::less<> and 10900 // friends to have std::nullptr_t overload candidates. 10901 DeclContext *DC = CurContext; 10902 if (isa<FunctionDecl>(DC)) 10903 DC = DC->getParent(); 10904 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 10905 if (CTSD->isInStdNamespace() && 10906 llvm::StringSwitch<bool>(CTSD->getName()) 10907 .Cases("less", "less_equal", "greater", "greater_equal", true) 10908 .Default(false)) { 10909 if (RHSType->isNullPtrType()) 10910 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10911 else 10912 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10913 return computeResultTy(); 10914 } 10915 } 10916 } 10917 10918 // C++ [expr.eq]p2: 10919 // If at least one operand is a pointer to member, [...] bring them to 10920 // their composite pointer type. 10921 if (!IsRelational && 10922 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 10923 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 10924 return QualType(); 10925 else 10926 return computeResultTy(); 10927 } 10928 } 10929 10930 // Handle block pointer types. 10931 if (!IsRelational && LHSType->isBlockPointerType() && 10932 RHSType->isBlockPointerType()) { 10933 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 10934 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 10935 10936 if (!LHSIsNull && !RHSIsNull && 10937 !Context.typesAreCompatible(lpointee, rpointee)) { 10938 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 10939 << LHSType << RHSType << LHS.get()->getSourceRange() 10940 << RHS.get()->getSourceRange(); 10941 } 10942 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10943 return computeResultTy(); 10944 } 10945 10946 // Allow block pointers to be compared with null pointer constants. 10947 if (!IsRelational 10948 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 10949 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 10950 if (!LHSIsNull && !RHSIsNull) { 10951 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 10952 ->getPointeeType()->isVoidType()) 10953 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 10954 ->getPointeeType()->isVoidType()))) 10955 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 10956 << LHSType << RHSType << LHS.get()->getSourceRange() 10957 << RHS.get()->getSourceRange(); 10958 } 10959 if (LHSIsNull && !RHSIsNull) 10960 LHS = ImpCastExprToType(LHS.get(), RHSType, 10961 RHSType->isPointerType() ? CK_BitCast 10962 : CK_AnyPointerToBlockPointerCast); 10963 else 10964 RHS = ImpCastExprToType(RHS.get(), LHSType, 10965 LHSType->isPointerType() ? CK_BitCast 10966 : CK_AnyPointerToBlockPointerCast); 10967 return computeResultTy(); 10968 } 10969 10970 if (LHSType->isObjCObjectPointerType() || 10971 RHSType->isObjCObjectPointerType()) { 10972 const PointerType *LPT = LHSType->getAs<PointerType>(); 10973 const PointerType *RPT = RHSType->getAs<PointerType>(); 10974 if (LPT || RPT) { 10975 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 10976 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 10977 10978 if (!LPtrToVoid && !RPtrToVoid && 10979 !Context.typesAreCompatible(LHSType, RHSType)) { 10980 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 10981 /*isError*/false); 10982 } 10983 if (LHSIsNull && !RHSIsNull) { 10984 Expr *E = LHS.get(); 10985 if (getLangOpts().ObjCAutoRefCount) 10986 CheckObjCConversion(SourceRange(), RHSType, E, 10987 CCK_ImplicitConversion); 10988 LHS = ImpCastExprToType(E, RHSType, 10989 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 10990 } 10991 else { 10992 Expr *E = RHS.get(); 10993 if (getLangOpts().ObjCAutoRefCount) 10994 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 10995 /*Diagnose=*/true, 10996 /*DiagnoseCFAudited=*/false, Opc); 10997 RHS = ImpCastExprToType(E, LHSType, 10998 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 10999 } 11000 return computeResultTy(); 11001 } 11002 if (LHSType->isObjCObjectPointerType() && 11003 RHSType->isObjCObjectPointerType()) { 11004 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 11005 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 11006 /*isError*/false); 11007 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 11008 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 11009 11010 if (LHSIsNull && !RHSIsNull) 11011 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 11012 else 11013 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11014 return computeResultTy(); 11015 } 11016 11017 if (!IsRelational && LHSType->isBlockPointerType() && 11018 RHSType->isBlockCompatibleObjCPointerType(Context)) { 11019 LHS = ImpCastExprToType(LHS.get(), RHSType, 11020 CK_BlockPointerToObjCPointerCast); 11021 return computeResultTy(); 11022 } else if (!IsRelational && 11023 LHSType->isBlockCompatibleObjCPointerType(Context) && 11024 RHSType->isBlockPointerType()) { 11025 RHS = ImpCastExprToType(RHS.get(), LHSType, 11026 CK_BlockPointerToObjCPointerCast); 11027 return computeResultTy(); 11028 } 11029 } 11030 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 11031 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 11032 unsigned DiagID = 0; 11033 bool isError = false; 11034 if (LangOpts.DebuggerSupport) { 11035 // Under a debugger, allow the comparison of pointers to integers, 11036 // since users tend to want to compare addresses. 11037 } else if ((LHSIsNull && LHSType->isIntegerType()) || 11038 (RHSIsNull && RHSType->isIntegerType())) { 11039 if (IsRelational) { 11040 isError = getLangOpts().CPlusPlus; 11041 DiagID = 11042 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 11043 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 11044 } 11045 } else if (getLangOpts().CPlusPlus) { 11046 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 11047 isError = true; 11048 } else if (IsRelational) 11049 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 11050 else 11051 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 11052 11053 if (DiagID) { 11054 Diag(Loc, DiagID) 11055 << LHSType << RHSType << LHS.get()->getSourceRange() 11056 << RHS.get()->getSourceRange(); 11057 if (isError) 11058 return QualType(); 11059 } 11060 11061 if (LHSType->isIntegerType()) 11062 LHS = ImpCastExprToType(LHS.get(), RHSType, 11063 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11064 else 11065 RHS = ImpCastExprToType(RHS.get(), LHSType, 11066 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11067 return computeResultTy(); 11068 } 11069 11070 // Handle block pointers. 11071 if (!IsRelational && RHSIsNull 11072 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 11073 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11074 return computeResultTy(); 11075 } 11076 if (!IsRelational && LHSIsNull 11077 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 11078 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11079 return computeResultTy(); 11080 } 11081 11082 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 11083 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 11084 return computeResultTy(); 11085 } 11086 11087 if (LHSType->isQueueT() && RHSType->isQueueT()) { 11088 return computeResultTy(); 11089 } 11090 11091 if (LHSIsNull && RHSType->isQueueT()) { 11092 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11093 return computeResultTy(); 11094 } 11095 11096 if (LHSType->isQueueT() && RHSIsNull) { 11097 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11098 return computeResultTy(); 11099 } 11100 } 11101 11102 return InvalidOperands(Loc, LHS, RHS); 11103 } 11104 11105 // Return a signed ext_vector_type that is of identical size and number of 11106 // elements. For floating point vectors, return an integer type of identical 11107 // size and number of elements. In the non ext_vector_type case, search from 11108 // the largest type to the smallest type to avoid cases where long long == long, 11109 // where long gets picked over long long. 11110 QualType Sema::GetSignedVectorType(QualType V) { 11111 const VectorType *VTy = V->castAs<VectorType>(); 11112 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 11113 11114 if (isa<ExtVectorType>(VTy)) { 11115 if (TypeSize == Context.getTypeSize(Context.CharTy)) 11116 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 11117 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 11118 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 11119 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 11120 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 11121 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 11122 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 11123 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 11124 "Unhandled vector element size in vector compare"); 11125 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 11126 } 11127 11128 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 11129 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 11130 VectorType::GenericVector); 11131 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 11132 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 11133 VectorType::GenericVector); 11134 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 11135 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 11136 VectorType::GenericVector); 11137 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 11138 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 11139 VectorType::GenericVector); 11140 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 11141 "Unhandled vector element size in vector compare"); 11142 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 11143 VectorType::GenericVector); 11144 } 11145 11146 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 11147 /// operates on extended vector types. Instead of producing an IntTy result, 11148 /// like a scalar comparison, a vector comparison produces a vector of integer 11149 /// types. 11150 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 11151 SourceLocation Loc, 11152 BinaryOperatorKind Opc) { 11153 // Check to make sure we're operating on vectors of the same type and width, 11154 // Allowing one side to be a scalar of element type. 11155 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 11156 /*AllowBothBool*/true, 11157 /*AllowBoolConversions*/getLangOpts().ZVector); 11158 if (vType.isNull()) 11159 return vType; 11160 11161 QualType LHSType = LHS.get()->getType(); 11162 11163 // If AltiVec, the comparison results in a numeric type, i.e. 11164 // bool for C++, int for C 11165 if (getLangOpts().AltiVec && 11166 vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 11167 return Context.getLogicalOperationType(); 11168 11169 // For non-floating point types, check for self-comparisons of the form 11170 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11171 // often indicate logic errors in the program. 11172 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11173 11174 // Check for comparisons of floating point operands using != and ==. 11175 if (BinaryOperator::isEqualityOp(Opc) && 11176 LHSType->hasFloatingRepresentation()) { 11177 assert(RHS.get()->getType()->hasFloatingRepresentation()); 11178 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11179 } 11180 11181 // Return a signed type for the vector. 11182 return GetSignedVectorType(vType); 11183 } 11184 11185 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 11186 const ExprResult &XorRHS, 11187 const SourceLocation Loc) { 11188 // Do not diagnose macros. 11189 if (Loc.isMacroID()) 11190 return; 11191 11192 bool Negative = false; 11193 bool ExplicitPlus = false; 11194 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 11195 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 11196 11197 if (!LHSInt) 11198 return; 11199 if (!RHSInt) { 11200 // Check negative literals. 11201 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 11202 UnaryOperatorKind Opc = UO->getOpcode(); 11203 if (Opc != UO_Minus && Opc != UO_Plus) 11204 return; 11205 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 11206 if (!RHSInt) 11207 return; 11208 Negative = (Opc == UO_Minus); 11209 ExplicitPlus = !Negative; 11210 } else { 11211 return; 11212 } 11213 } 11214 11215 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 11216 llvm::APInt RightSideValue = RHSInt->getValue(); 11217 if (LeftSideValue != 2 && LeftSideValue != 10) 11218 return; 11219 11220 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 11221 return; 11222 11223 CharSourceRange ExprRange = CharSourceRange::getCharRange( 11224 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 11225 llvm::StringRef ExprStr = 11226 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 11227 11228 CharSourceRange XorRange = 11229 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11230 llvm::StringRef XorStr = 11231 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 11232 // Do not diagnose if xor keyword/macro is used. 11233 if (XorStr == "xor") 11234 return; 11235 11236 std::string LHSStr = Lexer::getSourceText( 11237 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 11238 S.getSourceManager(), S.getLangOpts()); 11239 std::string RHSStr = Lexer::getSourceText( 11240 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 11241 S.getSourceManager(), S.getLangOpts()); 11242 11243 if (Negative) { 11244 RightSideValue = -RightSideValue; 11245 RHSStr = "-" + RHSStr; 11246 } else if (ExplicitPlus) { 11247 RHSStr = "+" + RHSStr; 11248 } 11249 11250 StringRef LHSStrRef = LHSStr; 11251 StringRef RHSStrRef = RHSStr; 11252 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 11253 // literals. 11254 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 11255 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 11256 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 11257 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 11258 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 11259 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 11260 LHSStrRef.find('\'') != StringRef::npos || 11261 RHSStrRef.find('\'') != StringRef::npos) 11262 return; 11263 11264 bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 11265 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 11266 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 11267 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 11268 std::string SuggestedExpr = "1 << " + RHSStr; 11269 bool Overflow = false; 11270 llvm::APInt One = (LeftSideValue - 1); 11271 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 11272 if (Overflow) { 11273 if (RightSideIntValue < 64) 11274 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 11275 << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr) 11276 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 11277 else if (RightSideIntValue == 64) 11278 S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true); 11279 else 11280 return; 11281 } else { 11282 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 11283 << ExprStr << XorValue.toString(10, true) << SuggestedExpr 11284 << PowValue.toString(10, true) 11285 << FixItHint::CreateReplacement( 11286 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 11287 } 11288 11289 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor; 11290 } else if (LeftSideValue == 10) { 11291 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 11292 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 11293 << ExprStr << XorValue.toString(10, true) << SuggestedValue 11294 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 11295 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor; 11296 } 11297 } 11298 11299 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 11300 SourceLocation Loc) { 11301 // Ensure that either both operands are of the same vector type, or 11302 // one operand is of a vector type and the other is of its element type. 11303 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 11304 /*AllowBothBool*/true, 11305 /*AllowBoolConversions*/false); 11306 if (vType.isNull()) 11307 return InvalidOperands(Loc, LHS, RHS); 11308 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 11309 !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation()) 11310 return InvalidOperands(Loc, LHS, RHS); 11311 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 11312 // usage of the logical operators && and || with vectors in C. This 11313 // check could be notionally dropped. 11314 if (!getLangOpts().CPlusPlus && 11315 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 11316 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 11317 11318 return GetSignedVectorType(LHS.get()->getType()); 11319 } 11320 11321 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 11322 SourceLocation Loc, 11323 BinaryOperatorKind Opc) { 11324 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11325 11326 bool IsCompAssign = 11327 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 11328 11329 if (LHS.get()->getType()->isVectorType() || 11330 RHS.get()->getType()->isVectorType()) { 11331 if (LHS.get()->getType()->hasIntegerRepresentation() && 11332 RHS.get()->getType()->hasIntegerRepresentation()) 11333 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 11334 /*AllowBothBool*/true, 11335 /*AllowBoolConversions*/getLangOpts().ZVector); 11336 return InvalidOperands(Loc, LHS, RHS); 11337 } 11338 11339 if (Opc == BO_And) 11340 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11341 11342 ExprResult LHSResult = LHS, RHSResult = RHS; 11343 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 11344 IsCompAssign); 11345 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 11346 return QualType(); 11347 LHS = LHSResult.get(); 11348 RHS = RHSResult.get(); 11349 11350 if (Opc == BO_Xor) 11351 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 11352 11353 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 11354 return compType; 11355 return InvalidOperands(Loc, LHS, RHS); 11356 } 11357 11358 // C99 6.5.[13,14] 11359 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 11360 SourceLocation Loc, 11361 BinaryOperatorKind Opc) { 11362 // Check vector operands differently. 11363 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 11364 return CheckVectorLogicalOperands(LHS, RHS, Loc); 11365 11366 bool EnumConstantInBoolContext = false; 11367 for (const ExprResult &HS : {LHS, RHS}) { 11368 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 11369 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 11370 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 11371 EnumConstantInBoolContext = true; 11372 } 11373 } 11374 11375 if (EnumConstantInBoolContext) 11376 Diag(Loc, diag::warn_enum_constant_in_bool_context); 11377 11378 // Diagnose cases where the user write a logical and/or but probably meant a 11379 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 11380 // is a constant. 11381 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 11382 !LHS.get()->getType()->isBooleanType() && 11383 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 11384 // Don't warn in macros or template instantiations. 11385 !Loc.isMacroID() && !inTemplateInstantiation()) { 11386 // If the RHS can be constant folded, and if it constant folds to something 11387 // that isn't 0 or 1 (which indicate a potential logical operation that 11388 // happened to fold to true/false) then warn. 11389 // Parens on the RHS are ignored. 11390 Expr::EvalResult EVResult; 11391 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 11392 llvm::APSInt Result = EVResult.Val.getInt(); 11393 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 11394 !RHS.get()->getExprLoc().isMacroID()) || 11395 (Result != 0 && Result != 1)) { 11396 Diag(Loc, diag::warn_logical_instead_of_bitwise) 11397 << RHS.get()->getSourceRange() 11398 << (Opc == BO_LAnd ? "&&" : "||"); 11399 // Suggest replacing the logical operator with the bitwise version 11400 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 11401 << (Opc == BO_LAnd ? "&" : "|") 11402 << FixItHint::CreateReplacement(SourceRange( 11403 Loc, getLocForEndOfToken(Loc)), 11404 Opc == BO_LAnd ? "&" : "|"); 11405 if (Opc == BO_LAnd) 11406 // Suggest replacing "Foo() && kNonZero" with "Foo()" 11407 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 11408 << FixItHint::CreateRemoval( 11409 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 11410 RHS.get()->getEndLoc())); 11411 } 11412 } 11413 } 11414 11415 if (!Context.getLangOpts().CPlusPlus) { 11416 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 11417 // not operate on the built-in scalar and vector float types. 11418 if (Context.getLangOpts().OpenCL && 11419 Context.getLangOpts().OpenCLVersion < 120) { 11420 if (LHS.get()->getType()->isFloatingType() || 11421 RHS.get()->getType()->isFloatingType()) 11422 return InvalidOperands(Loc, LHS, RHS); 11423 } 11424 11425 LHS = UsualUnaryConversions(LHS.get()); 11426 if (LHS.isInvalid()) 11427 return QualType(); 11428 11429 RHS = UsualUnaryConversions(RHS.get()); 11430 if (RHS.isInvalid()) 11431 return QualType(); 11432 11433 if (!LHS.get()->getType()->isScalarType() || 11434 !RHS.get()->getType()->isScalarType()) 11435 return InvalidOperands(Loc, LHS, RHS); 11436 11437 return Context.IntTy; 11438 } 11439 11440 // The following is safe because we only use this method for 11441 // non-overloadable operands. 11442 11443 // C++ [expr.log.and]p1 11444 // C++ [expr.log.or]p1 11445 // The operands are both contextually converted to type bool. 11446 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 11447 if (LHSRes.isInvalid()) 11448 return InvalidOperands(Loc, LHS, RHS); 11449 LHS = LHSRes; 11450 11451 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 11452 if (RHSRes.isInvalid()) 11453 return InvalidOperands(Loc, LHS, RHS); 11454 RHS = RHSRes; 11455 11456 // C++ [expr.log.and]p2 11457 // C++ [expr.log.or]p2 11458 // The result is a bool. 11459 return Context.BoolTy; 11460 } 11461 11462 static bool IsReadonlyMessage(Expr *E, Sema &S) { 11463 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 11464 if (!ME) return false; 11465 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 11466 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 11467 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 11468 if (!Base) return false; 11469 return Base->getMethodDecl() != nullptr; 11470 } 11471 11472 /// Is the given expression (which must be 'const') a reference to a 11473 /// variable which was originally non-const, but which has become 11474 /// 'const' due to being captured within a block? 11475 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 11476 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 11477 assert(E->isLValue() && E->getType().isConstQualified()); 11478 E = E->IgnoreParens(); 11479 11480 // Must be a reference to a declaration from an enclosing scope. 11481 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 11482 if (!DRE) return NCCK_None; 11483 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 11484 11485 // The declaration must be a variable which is not declared 'const'. 11486 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 11487 if (!var) return NCCK_None; 11488 if (var->getType().isConstQualified()) return NCCK_None; 11489 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 11490 11491 // Decide whether the first capture was for a block or a lambda. 11492 DeclContext *DC = S.CurContext, *Prev = nullptr; 11493 // Decide whether the first capture was for a block or a lambda. 11494 while (DC) { 11495 // For init-capture, it is possible that the variable belongs to the 11496 // template pattern of the current context. 11497 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 11498 if (var->isInitCapture() && 11499 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 11500 break; 11501 if (DC == var->getDeclContext()) 11502 break; 11503 Prev = DC; 11504 DC = DC->getParent(); 11505 } 11506 // Unless we have an init-capture, we've gone one step too far. 11507 if (!var->isInitCapture()) 11508 DC = Prev; 11509 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 11510 } 11511 11512 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 11513 Ty = Ty.getNonReferenceType(); 11514 if (IsDereference && Ty->isPointerType()) 11515 Ty = Ty->getPointeeType(); 11516 return !Ty.isConstQualified(); 11517 } 11518 11519 // Update err_typecheck_assign_const and note_typecheck_assign_const 11520 // when this enum is changed. 11521 enum { 11522 ConstFunction, 11523 ConstVariable, 11524 ConstMember, 11525 ConstMethod, 11526 NestedConstMember, 11527 ConstUnknown, // Keep as last element 11528 }; 11529 11530 /// Emit the "read-only variable not assignable" error and print notes to give 11531 /// more information about why the variable is not assignable, such as pointing 11532 /// to the declaration of a const variable, showing that a method is const, or 11533 /// that the function is returning a const reference. 11534 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 11535 SourceLocation Loc) { 11536 SourceRange ExprRange = E->getSourceRange(); 11537 11538 // Only emit one error on the first const found. All other consts will emit 11539 // a note to the error. 11540 bool DiagnosticEmitted = false; 11541 11542 // Track if the current expression is the result of a dereference, and if the 11543 // next checked expression is the result of a dereference. 11544 bool IsDereference = false; 11545 bool NextIsDereference = false; 11546 11547 // Loop to process MemberExpr chains. 11548 while (true) { 11549 IsDereference = NextIsDereference; 11550 11551 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 11552 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 11553 NextIsDereference = ME->isArrow(); 11554 const ValueDecl *VD = ME->getMemberDecl(); 11555 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 11556 // Mutable fields can be modified even if the class is const. 11557 if (Field->isMutable()) { 11558 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 11559 break; 11560 } 11561 11562 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 11563 if (!DiagnosticEmitted) { 11564 S.Diag(Loc, diag::err_typecheck_assign_const) 11565 << ExprRange << ConstMember << false /*static*/ << Field 11566 << Field->getType(); 11567 DiagnosticEmitted = true; 11568 } 11569 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11570 << ConstMember << false /*static*/ << Field << Field->getType() 11571 << Field->getSourceRange(); 11572 } 11573 E = ME->getBase(); 11574 continue; 11575 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 11576 if (VDecl->getType().isConstQualified()) { 11577 if (!DiagnosticEmitted) { 11578 S.Diag(Loc, diag::err_typecheck_assign_const) 11579 << ExprRange << ConstMember << true /*static*/ << VDecl 11580 << VDecl->getType(); 11581 DiagnosticEmitted = true; 11582 } 11583 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11584 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 11585 << VDecl->getSourceRange(); 11586 } 11587 // Static fields do not inherit constness from parents. 11588 break; 11589 } 11590 break; // End MemberExpr 11591 } else if (const ArraySubscriptExpr *ASE = 11592 dyn_cast<ArraySubscriptExpr>(E)) { 11593 E = ASE->getBase()->IgnoreParenImpCasts(); 11594 continue; 11595 } else if (const ExtVectorElementExpr *EVE = 11596 dyn_cast<ExtVectorElementExpr>(E)) { 11597 E = EVE->getBase()->IgnoreParenImpCasts(); 11598 continue; 11599 } 11600 break; 11601 } 11602 11603 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 11604 // Function calls 11605 const FunctionDecl *FD = CE->getDirectCallee(); 11606 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 11607 if (!DiagnosticEmitted) { 11608 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 11609 << ConstFunction << FD; 11610 DiagnosticEmitted = true; 11611 } 11612 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 11613 diag::note_typecheck_assign_const) 11614 << ConstFunction << FD << FD->getReturnType() 11615 << FD->getReturnTypeSourceRange(); 11616 } 11617 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11618 // Point to variable declaration. 11619 if (const ValueDecl *VD = DRE->getDecl()) { 11620 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 11621 if (!DiagnosticEmitted) { 11622 S.Diag(Loc, diag::err_typecheck_assign_const) 11623 << ExprRange << ConstVariable << VD << VD->getType(); 11624 DiagnosticEmitted = true; 11625 } 11626 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11627 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 11628 } 11629 } 11630 } else if (isa<CXXThisExpr>(E)) { 11631 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 11632 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 11633 if (MD->isConst()) { 11634 if (!DiagnosticEmitted) { 11635 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 11636 << ConstMethod << MD; 11637 DiagnosticEmitted = true; 11638 } 11639 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 11640 << ConstMethod << MD << MD->getSourceRange(); 11641 } 11642 } 11643 } 11644 } 11645 11646 if (DiagnosticEmitted) 11647 return; 11648 11649 // Can't determine a more specific message, so display the generic error. 11650 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 11651 } 11652 11653 enum OriginalExprKind { 11654 OEK_Variable, 11655 OEK_Member, 11656 OEK_LValue 11657 }; 11658 11659 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 11660 const RecordType *Ty, 11661 SourceLocation Loc, SourceRange Range, 11662 OriginalExprKind OEK, 11663 bool &DiagnosticEmitted) { 11664 std::vector<const RecordType *> RecordTypeList; 11665 RecordTypeList.push_back(Ty); 11666 unsigned NextToCheckIndex = 0; 11667 // We walk the record hierarchy breadth-first to ensure that we print 11668 // diagnostics in field nesting order. 11669 while (RecordTypeList.size() > NextToCheckIndex) { 11670 bool IsNested = NextToCheckIndex > 0; 11671 for (const FieldDecl *Field : 11672 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 11673 // First, check every field for constness. 11674 QualType FieldTy = Field->getType(); 11675 if (FieldTy.isConstQualified()) { 11676 if (!DiagnosticEmitted) { 11677 S.Diag(Loc, diag::err_typecheck_assign_const) 11678 << Range << NestedConstMember << OEK << VD 11679 << IsNested << Field; 11680 DiagnosticEmitted = true; 11681 } 11682 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 11683 << NestedConstMember << IsNested << Field 11684 << FieldTy << Field->getSourceRange(); 11685 } 11686 11687 // Then we append it to the list to check next in order. 11688 FieldTy = FieldTy.getCanonicalType(); 11689 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 11690 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) 11691 RecordTypeList.push_back(FieldRecTy); 11692 } 11693 } 11694 ++NextToCheckIndex; 11695 } 11696 } 11697 11698 /// Emit an error for the case where a record we are trying to assign to has a 11699 /// const-qualified field somewhere in its hierarchy. 11700 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 11701 SourceLocation Loc) { 11702 QualType Ty = E->getType(); 11703 assert(Ty->isRecordType() && "lvalue was not record?"); 11704 SourceRange Range = E->getSourceRange(); 11705 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 11706 bool DiagEmitted = false; 11707 11708 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 11709 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 11710 Range, OEK_Member, DiagEmitted); 11711 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11712 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 11713 Range, OEK_Variable, DiagEmitted); 11714 else 11715 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 11716 Range, OEK_LValue, DiagEmitted); 11717 if (!DiagEmitted) 11718 DiagnoseConstAssignment(S, E, Loc); 11719 } 11720 11721 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 11722 /// emit an error and return true. If so, return false. 11723 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 11724 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 11725 11726 S.CheckShadowingDeclModification(E, Loc); 11727 11728 SourceLocation OrigLoc = Loc; 11729 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 11730 &Loc); 11731 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 11732 IsLV = Expr::MLV_InvalidMessageExpression; 11733 if (IsLV == Expr::MLV_Valid) 11734 return false; 11735 11736 unsigned DiagID = 0; 11737 bool NeedType = false; 11738 switch (IsLV) { // C99 6.5.16p2 11739 case Expr::MLV_ConstQualified: 11740 // Use a specialized diagnostic when we're assigning to an object 11741 // from an enclosing function or block. 11742 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 11743 if (NCCK == NCCK_Block) 11744 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 11745 else 11746 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 11747 break; 11748 } 11749 11750 // In ARC, use some specialized diagnostics for occasions where we 11751 // infer 'const'. These are always pseudo-strong variables. 11752 if (S.getLangOpts().ObjCAutoRefCount) { 11753 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 11754 if (declRef && isa<VarDecl>(declRef->getDecl())) { 11755 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 11756 11757 // Use the normal diagnostic if it's pseudo-__strong but the 11758 // user actually wrote 'const'. 11759 if (var->isARCPseudoStrong() && 11760 (!var->getTypeSourceInfo() || 11761 !var->getTypeSourceInfo()->getType().isConstQualified())) { 11762 // There are three pseudo-strong cases: 11763 // - self 11764 ObjCMethodDecl *method = S.getCurMethodDecl(); 11765 if (method && var == method->getSelfDecl()) { 11766 DiagID = method->isClassMethod() 11767 ? diag::err_typecheck_arc_assign_self_class_method 11768 : diag::err_typecheck_arc_assign_self; 11769 11770 // - Objective-C externally_retained attribute. 11771 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 11772 isa<ParmVarDecl>(var)) { 11773 DiagID = diag::err_typecheck_arc_assign_externally_retained; 11774 11775 // - fast enumeration variables 11776 } else { 11777 DiagID = diag::err_typecheck_arr_assign_enumeration; 11778 } 11779 11780 SourceRange Assign; 11781 if (Loc != OrigLoc) 11782 Assign = SourceRange(OrigLoc, OrigLoc); 11783 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 11784 // We need to preserve the AST regardless, so migration tool 11785 // can do its job. 11786 return false; 11787 } 11788 } 11789 } 11790 11791 // If none of the special cases above are triggered, then this is a 11792 // simple const assignment. 11793 if (DiagID == 0) { 11794 DiagnoseConstAssignment(S, E, Loc); 11795 return true; 11796 } 11797 11798 break; 11799 case Expr::MLV_ConstAddrSpace: 11800 DiagnoseConstAssignment(S, E, Loc); 11801 return true; 11802 case Expr::MLV_ConstQualifiedField: 11803 DiagnoseRecursiveConstFields(S, E, Loc); 11804 return true; 11805 case Expr::MLV_ArrayType: 11806 case Expr::MLV_ArrayTemporary: 11807 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 11808 NeedType = true; 11809 break; 11810 case Expr::MLV_NotObjectType: 11811 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 11812 NeedType = true; 11813 break; 11814 case Expr::MLV_LValueCast: 11815 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 11816 break; 11817 case Expr::MLV_Valid: 11818 llvm_unreachable("did not take early return for MLV_Valid"); 11819 case Expr::MLV_InvalidExpression: 11820 case Expr::MLV_MemberFunction: 11821 case Expr::MLV_ClassTemporary: 11822 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 11823 break; 11824 case Expr::MLV_IncompleteType: 11825 case Expr::MLV_IncompleteVoidType: 11826 return S.RequireCompleteType(Loc, E->getType(), 11827 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 11828 case Expr::MLV_DuplicateVectorComponents: 11829 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 11830 break; 11831 case Expr::MLV_NoSetterProperty: 11832 llvm_unreachable("readonly properties should be processed differently"); 11833 case Expr::MLV_InvalidMessageExpression: 11834 DiagID = diag::err_readonly_message_assignment; 11835 break; 11836 case Expr::MLV_SubObjCPropertySetting: 11837 DiagID = diag::err_no_subobject_property_setting; 11838 break; 11839 } 11840 11841 SourceRange Assign; 11842 if (Loc != OrigLoc) 11843 Assign = SourceRange(OrigLoc, OrigLoc); 11844 if (NeedType) 11845 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 11846 else 11847 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 11848 return true; 11849 } 11850 11851 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 11852 SourceLocation Loc, 11853 Sema &Sema) { 11854 if (Sema.inTemplateInstantiation()) 11855 return; 11856 if (Sema.isUnevaluatedContext()) 11857 return; 11858 if (Loc.isInvalid() || Loc.isMacroID()) 11859 return; 11860 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 11861 return; 11862 11863 // C / C++ fields 11864 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 11865 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 11866 if (ML && MR) { 11867 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 11868 return; 11869 const ValueDecl *LHSDecl = 11870 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 11871 const ValueDecl *RHSDecl = 11872 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 11873 if (LHSDecl != RHSDecl) 11874 return; 11875 if (LHSDecl->getType().isVolatileQualified()) 11876 return; 11877 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 11878 if (RefTy->getPointeeType().isVolatileQualified()) 11879 return; 11880 11881 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 11882 } 11883 11884 // Objective-C instance variables 11885 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 11886 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 11887 if (OL && OR && OL->getDecl() == OR->getDecl()) { 11888 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 11889 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 11890 if (RL && RR && RL->getDecl() == RR->getDecl()) 11891 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 11892 } 11893 } 11894 11895 // C99 6.5.16.1 11896 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 11897 SourceLocation Loc, 11898 QualType CompoundType) { 11899 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 11900 11901 // Verify that LHS is a modifiable lvalue, and emit error if not. 11902 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 11903 return QualType(); 11904 11905 QualType LHSType = LHSExpr->getType(); 11906 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 11907 CompoundType; 11908 // OpenCL v1.2 s6.1.1.1 p2: 11909 // The half data type can only be used to declare a pointer to a buffer that 11910 // contains half values 11911 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 11912 LHSType->isHalfType()) { 11913 Diag(Loc, diag::err_opencl_half_load_store) << 1 11914 << LHSType.getUnqualifiedType(); 11915 return QualType(); 11916 } 11917 11918 AssignConvertType ConvTy; 11919 if (CompoundType.isNull()) { 11920 Expr *RHSCheck = RHS.get(); 11921 11922 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 11923 11924 QualType LHSTy(LHSType); 11925 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 11926 if (RHS.isInvalid()) 11927 return QualType(); 11928 // Special case of NSObject attributes on c-style pointer types. 11929 if (ConvTy == IncompatiblePointer && 11930 ((Context.isObjCNSObjectType(LHSType) && 11931 RHSType->isObjCObjectPointerType()) || 11932 (Context.isObjCNSObjectType(RHSType) && 11933 LHSType->isObjCObjectPointerType()))) 11934 ConvTy = Compatible; 11935 11936 if (ConvTy == Compatible && 11937 LHSType->isObjCObjectType()) 11938 Diag(Loc, diag::err_objc_object_assignment) 11939 << LHSType; 11940 11941 // If the RHS is a unary plus or minus, check to see if they = and + are 11942 // right next to each other. If so, the user may have typo'd "x =+ 4" 11943 // instead of "x += 4". 11944 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 11945 RHSCheck = ICE->getSubExpr(); 11946 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 11947 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 11948 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 11949 // Only if the two operators are exactly adjacent. 11950 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 11951 // And there is a space or other character before the subexpr of the 11952 // unary +/-. We don't want to warn on "x=-1". 11953 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 11954 UO->getSubExpr()->getBeginLoc().isFileID()) { 11955 Diag(Loc, diag::warn_not_compound_assign) 11956 << (UO->getOpcode() == UO_Plus ? "+" : "-") 11957 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 11958 } 11959 } 11960 11961 if (ConvTy == Compatible) { 11962 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 11963 // Warn about retain cycles where a block captures the LHS, but 11964 // not if the LHS is a simple variable into which the block is 11965 // being stored...unless that variable can be captured by reference! 11966 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 11967 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 11968 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 11969 checkRetainCycles(LHSExpr, RHS.get()); 11970 } 11971 11972 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 11973 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 11974 // It is safe to assign a weak reference into a strong variable. 11975 // Although this code can still have problems: 11976 // id x = self.weakProp; 11977 // id y = self.weakProp; 11978 // we do not warn to warn spuriously when 'x' and 'y' are on separate 11979 // paths through the function. This should be revisited if 11980 // -Wrepeated-use-of-weak is made flow-sensitive. 11981 // For ObjCWeak only, we do not warn if the assign is to a non-weak 11982 // variable, which will be valid for the current autorelease scope. 11983 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 11984 RHS.get()->getBeginLoc())) 11985 getCurFunction()->markSafeWeakUse(RHS.get()); 11986 11987 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 11988 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 11989 } 11990 } 11991 } else { 11992 // Compound assignment "x += y" 11993 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 11994 } 11995 11996 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 11997 RHS.get(), AA_Assigning)) 11998 return QualType(); 11999 12000 CheckForNullPointerDereference(*this, LHSExpr); 12001 12002 if (getLangOpts().CPlusPlus2a && LHSType.isVolatileQualified()) { 12003 if (CompoundType.isNull()) { 12004 // C++2a [expr.ass]p5: 12005 // A simple-assignment whose left operand is of a volatile-qualified 12006 // type is deprecated unless the assignment is either a discarded-value 12007 // expression or an unevaluated operand 12008 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 12009 } else { 12010 // C++2a [expr.ass]p6: 12011 // [Compound-assignment] expressions are deprecated if E1 has 12012 // volatile-qualified type 12013 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 12014 } 12015 } 12016 12017 // C99 6.5.16p3: The type of an assignment expression is the type of the 12018 // left operand unless the left operand has qualified type, in which case 12019 // it is the unqualified version of the type of the left operand. 12020 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 12021 // is converted to the type of the assignment expression (above). 12022 // C++ 5.17p1: the type of the assignment expression is that of its left 12023 // operand. 12024 return (getLangOpts().CPlusPlus 12025 ? LHSType : LHSType.getUnqualifiedType()); 12026 } 12027 12028 // Only ignore explicit casts to void. 12029 static bool IgnoreCommaOperand(const Expr *E) { 12030 E = E->IgnoreParens(); 12031 12032 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 12033 if (CE->getCastKind() == CK_ToVoid) { 12034 return true; 12035 } 12036 12037 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 12038 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 12039 CE->getSubExpr()->getType()->isDependentType()) { 12040 return true; 12041 } 12042 } 12043 12044 return false; 12045 } 12046 12047 // Look for instances where it is likely the comma operator is confused with 12048 // another operator. There is a whitelist of acceptable expressions for the 12049 // left hand side of the comma operator, otherwise emit a warning. 12050 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 12051 // No warnings in macros 12052 if (Loc.isMacroID()) 12053 return; 12054 12055 // Don't warn in template instantiations. 12056 if (inTemplateInstantiation()) 12057 return; 12058 12059 // Scope isn't fine-grained enough to whitelist the specific cases, so 12060 // instead, skip more than needed, then call back into here with the 12061 // CommaVisitor in SemaStmt.cpp. 12062 // The whitelisted locations are the initialization and increment portions 12063 // of a for loop. The additional checks are on the condition of 12064 // if statements, do/while loops, and for loops. 12065 // Differences in scope flags for C89 mode requires the extra logic. 12066 const unsigned ForIncrementFlags = 12067 getLangOpts().C99 || getLangOpts().CPlusPlus 12068 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 12069 : Scope::ContinueScope | Scope::BreakScope; 12070 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 12071 const unsigned ScopeFlags = getCurScope()->getFlags(); 12072 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 12073 (ScopeFlags & ForInitFlags) == ForInitFlags) 12074 return; 12075 12076 // If there are multiple comma operators used together, get the RHS of the 12077 // of the comma operator as the LHS. 12078 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 12079 if (BO->getOpcode() != BO_Comma) 12080 break; 12081 LHS = BO->getRHS(); 12082 } 12083 12084 // Only allow some expressions on LHS to not warn. 12085 if (IgnoreCommaOperand(LHS)) 12086 return; 12087 12088 Diag(Loc, diag::warn_comma_operator); 12089 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 12090 << LHS->getSourceRange() 12091 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 12092 LangOpts.CPlusPlus ? "static_cast<void>(" 12093 : "(void)(") 12094 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 12095 ")"); 12096 } 12097 12098 // C99 6.5.17 12099 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 12100 SourceLocation Loc) { 12101 LHS = S.CheckPlaceholderExpr(LHS.get()); 12102 RHS = S.CheckPlaceholderExpr(RHS.get()); 12103 if (LHS.isInvalid() || RHS.isInvalid()) 12104 return QualType(); 12105 12106 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 12107 // operands, but not unary promotions. 12108 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 12109 12110 // So we treat the LHS as a ignored value, and in C++ we allow the 12111 // containing site to determine what should be done with the RHS. 12112 LHS = S.IgnoredValueConversions(LHS.get()); 12113 if (LHS.isInvalid()) 12114 return QualType(); 12115 12116 S.DiagnoseUnusedExprResult(LHS.get()); 12117 12118 if (!S.getLangOpts().CPlusPlus) { 12119 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 12120 if (RHS.isInvalid()) 12121 return QualType(); 12122 if (!RHS.get()->getType()->isVoidType()) 12123 S.RequireCompleteType(Loc, RHS.get()->getType(), 12124 diag::err_incomplete_type); 12125 } 12126 12127 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 12128 S.DiagnoseCommaOperator(LHS.get(), Loc); 12129 12130 return RHS.get()->getType(); 12131 } 12132 12133 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 12134 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 12135 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 12136 ExprValueKind &VK, 12137 ExprObjectKind &OK, 12138 SourceLocation OpLoc, 12139 bool IsInc, bool IsPrefix) { 12140 if (Op->isTypeDependent()) 12141 return S.Context.DependentTy; 12142 12143 QualType ResType = Op->getType(); 12144 // Atomic types can be used for increment / decrement where the non-atomic 12145 // versions can, so ignore the _Atomic() specifier for the purpose of 12146 // checking. 12147 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 12148 ResType = ResAtomicType->getValueType(); 12149 12150 assert(!ResType.isNull() && "no type for increment/decrement expression"); 12151 12152 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 12153 // Decrement of bool is not allowed. 12154 if (!IsInc) { 12155 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 12156 return QualType(); 12157 } 12158 // Increment of bool sets it to true, but is deprecated. 12159 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 12160 : diag::warn_increment_bool) 12161 << Op->getSourceRange(); 12162 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 12163 // Error on enum increments and decrements in C++ mode 12164 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 12165 return QualType(); 12166 } else if (ResType->isRealType()) { 12167 // OK! 12168 } else if (ResType->isPointerType()) { 12169 // C99 6.5.2.4p2, 6.5.6p2 12170 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 12171 return QualType(); 12172 } else if (ResType->isObjCObjectPointerType()) { 12173 // On modern runtimes, ObjC pointer arithmetic is forbidden. 12174 // Otherwise, we just need a complete type. 12175 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 12176 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 12177 return QualType(); 12178 } else if (ResType->isAnyComplexType()) { 12179 // C99 does not support ++/-- on complex types, we allow as an extension. 12180 S.Diag(OpLoc, diag::ext_integer_increment_complex) 12181 << ResType << Op->getSourceRange(); 12182 } else if (ResType->isPlaceholderType()) { 12183 ExprResult PR = S.CheckPlaceholderExpr(Op); 12184 if (PR.isInvalid()) return QualType(); 12185 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 12186 IsInc, IsPrefix); 12187 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 12188 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 12189 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 12190 (ResType->castAs<VectorType>()->getVectorKind() != 12191 VectorType::AltiVecBool)) { 12192 // The z vector extensions allow ++ and -- for non-bool vectors. 12193 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 12194 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 12195 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 12196 } else { 12197 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 12198 << ResType << int(IsInc) << Op->getSourceRange(); 12199 return QualType(); 12200 } 12201 // At this point, we know we have a real, complex or pointer type. 12202 // Now make sure the operand is a modifiable lvalue. 12203 if (CheckForModifiableLvalue(Op, OpLoc, S)) 12204 return QualType(); 12205 if (S.getLangOpts().CPlusPlus2a && ResType.isVolatileQualified()) { 12206 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 12207 // An operand with volatile-qualified type is deprecated 12208 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 12209 << IsInc << ResType; 12210 } 12211 // In C++, a prefix increment is the same type as the operand. Otherwise 12212 // (in C or with postfix), the increment is the unqualified type of the 12213 // operand. 12214 if (IsPrefix && S.getLangOpts().CPlusPlus) { 12215 VK = VK_LValue; 12216 OK = Op->getObjectKind(); 12217 return ResType; 12218 } else { 12219 VK = VK_RValue; 12220 return ResType.getUnqualifiedType(); 12221 } 12222 } 12223 12224 12225 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 12226 /// This routine allows us to typecheck complex/recursive expressions 12227 /// where the declaration is needed for type checking. We only need to 12228 /// handle cases when the expression references a function designator 12229 /// or is an lvalue. Here are some examples: 12230 /// - &(x) => x 12231 /// - &*****f => f for f a function designator. 12232 /// - &s.xx => s 12233 /// - &s.zz[1].yy -> s, if zz is an array 12234 /// - *(x + 1) -> x, if x is an array 12235 /// - &"123"[2] -> 0 12236 /// - & __real__ x -> x 12237 static ValueDecl *getPrimaryDecl(Expr *E) { 12238 switch (E->getStmtClass()) { 12239 case Stmt::DeclRefExprClass: 12240 return cast<DeclRefExpr>(E)->getDecl(); 12241 case Stmt::MemberExprClass: 12242 // If this is an arrow operator, the address is an offset from 12243 // the base's value, so the object the base refers to is 12244 // irrelevant. 12245 if (cast<MemberExpr>(E)->isArrow()) 12246 return nullptr; 12247 // Otherwise, the expression refers to a part of the base 12248 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 12249 case Stmt::ArraySubscriptExprClass: { 12250 // FIXME: This code shouldn't be necessary! We should catch the implicit 12251 // promotion of register arrays earlier. 12252 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 12253 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 12254 if (ICE->getSubExpr()->getType()->isArrayType()) 12255 return getPrimaryDecl(ICE->getSubExpr()); 12256 } 12257 return nullptr; 12258 } 12259 case Stmt::UnaryOperatorClass: { 12260 UnaryOperator *UO = cast<UnaryOperator>(E); 12261 12262 switch(UO->getOpcode()) { 12263 case UO_Real: 12264 case UO_Imag: 12265 case UO_Extension: 12266 return getPrimaryDecl(UO->getSubExpr()); 12267 default: 12268 return nullptr; 12269 } 12270 } 12271 case Stmt::ParenExprClass: 12272 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 12273 case Stmt::ImplicitCastExprClass: 12274 // If the result of an implicit cast is an l-value, we care about 12275 // the sub-expression; otherwise, the result here doesn't matter. 12276 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 12277 default: 12278 return nullptr; 12279 } 12280 } 12281 12282 namespace { 12283 enum { 12284 AO_Bit_Field = 0, 12285 AO_Vector_Element = 1, 12286 AO_Property_Expansion = 2, 12287 AO_Register_Variable = 3, 12288 AO_No_Error = 4 12289 }; 12290 } 12291 /// Diagnose invalid operand for address of operations. 12292 /// 12293 /// \param Type The type of operand which cannot have its address taken. 12294 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 12295 Expr *E, unsigned Type) { 12296 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 12297 } 12298 12299 /// CheckAddressOfOperand - The operand of & must be either a function 12300 /// designator or an lvalue designating an object. If it is an lvalue, the 12301 /// object cannot be declared with storage class register or be a bit field. 12302 /// Note: The usual conversions are *not* applied to the operand of the & 12303 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 12304 /// In C++, the operand might be an overloaded function name, in which case 12305 /// we allow the '&' but retain the overloaded-function type. 12306 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 12307 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 12308 if (PTy->getKind() == BuiltinType::Overload) { 12309 Expr *E = OrigOp.get()->IgnoreParens(); 12310 if (!isa<OverloadExpr>(E)) { 12311 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 12312 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 12313 << OrigOp.get()->getSourceRange(); 12314 return QualType(); 12315 } 12316 12317 OverloadExpr *Ovl = cast<OverloadExpr>(E); 12318 if (isa<UnresolvedMemberExpr>(Ovl)) 12319 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 12320 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 12321 << OrigOp.get()->getSourceRange(); 12322 return QualType(); 12323 } 12324 12325 return Context.OverloadTy; 12326 } 12327 12328 if (PTy->getKind() == BuiltinType::UnknownAny) 12329 return Context.UnknownAnyTy; 12330 12331 if (PTy->getKind() == BuiltinType::BoundMember) { 12332 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 12333 << OrigOp.get()->getSourceRange(); 12334 return QualType(); 12335 } 12336 12337 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 12338 if (OrigOp.isInvalid()) return QualType(); 12339 } 12340 12341 if (OrigOp.get()->isTypeDependent()) 12342 return Context.DependentTy; 12343 12344 assert(!OrigOp.get()->getType()->isPlaceholderType()); 12345 12346 // Make sure to ignore parentheses in subsequent checks 12347 Expr *op = OrigOp.get()->IgnoreParens(); 12348 12349 // In OpenCL captures for blocks called as lambda functions 12350 // are located in the private address space. Blocks used in 12351 // enqueue_kernel can be located in a different address space 12352 // depending on a vendor implementation. Thus preventing 12353 // taking an address of the capture to avoid invalid AS casts. 12354 if (LangOpts.OpenCL) { 12355 auto* VarRef = dyn_cast<DeclRefExpr>(op); 12356 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 12357 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 12358 return QualType(); 12359 } 12360 } 12361 12362 if (getLangOpts().C99) { 12363 // Implement C99-only parts of addressof rules. 12364 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 12365 if (uOp->getOpcode() == UO_Deref) 12366 // Per C99 6.5.3.2, the address of a deref always returns a valid result 12367 // (assuming the deref expression is valid). 12368 return uOp->getSubExpr()->getType(); 12369 } 12370 // Technically, there should be a check for array subscript 12371 // expressions here, but the result of one is always an lvalue anyway. 12372 } 12373 ValueDecl *dcl = getPrimaryDecl(op); 12374 12375 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 12376 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 12377 op->getBeginLoc())) 12378 return QualType(); 12379 12380 Expr::LValueClassification lval = op->ClassifyLValue(Context); 12381 unsigned AddressOfError = AO_No_Error; 12382 12383 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 12384 bool sfinae = (bool)isSFINAEContext(); 12385 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 12386 : diag::ext_typecheck_addrof_temporary) 12387 << op->getType() << op->getSourceRange(); 12388 if (sfinae) 12389 return QualType(); 12390 // Materialize the temporary as an lvalue so that we can take its address. 12391 OrigOp = op = 12392 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 12393 } else if (isa<ObjCSelectorExpr>(op)) { 12394 return Context.getPointerType(op->getType()); 12395 } else if (lval == Expr::LV_MemberFunction) { 12396 // If it's an instance method, make a member pointer. 12397 // The expression must have exactly the form &A::foo. 12398 12399 // If the underlying expression isn't a decl ref, give up. 12400 if (!isa<DeclRefExpr>(op)) { 12401 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 12402 << OrigOp.get()->getSourceRange(); 12403 return QualType(); 12404 } 12405 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 12406 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 12407 12408 // The id-expression was parenthesized. 12409 if (OrigOp.get() != DRE) { 12410 Diag(OpLoc, diag::err_parens_pointer_member_function) 12411 << OrigOp.get()->getSourceRange(); 12412 12413 // The method was named without a qualifier. 12414 } else if (!DRE->getQualifier()) { 12415 if (MD->getParent()->getName().empty()) 12416 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 12417 << op->getSourceRange(); 12418 else { 12419 SmallString<32> Str; 12420 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 12421 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 12422 << op->getSourceRange() 12423 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 12424 } 12425 } 12426 12427 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 12428 if (isa<CXXDestructorDecl>(MD)) 12429 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 12430 12431 QualType MPTy = Context.getMemberPointerType( 12432 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 12433 // Under the MS ABI, lock down the inheritance model now. 12434 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 12435 (void)isCompleteType(OpLoc, MPTy); 12436 return MPTy; 12437 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 12438 // C99 6.5.3.2p1 12439 // The operand must be either an l-value or a function designator 12440 if (!op->getType()->isFunctionType()) { 12441 // Use a special diagnostic for loads from property references. 12442 if (isa<PseudoObjectExpr>(op)) { 12443 AddressOfError = AO_Property_Expansion; 12444 } else { 12445 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 12446 << op->getType() << op->getSourceRange(); 12447 return QualType(); 12448 } 12449 } 12450 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 12451 // The operand cannot be a bit-field 12452 AddressOfError = AO_Bit_Field; 12453 } else if (op->getObjectKind() == OK_VectorComponent) { 12454 // The operand cannot be an element of a vector 12455 AddressOfError = AO_Vector_Element; 12456 } else if (dcl) { // C99 6.5.3.2p1 12457 // We have an lvalue with a decl. Make sure the decl is not declared 12458 // with the register storage-class specifier. 12459 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 12460 // in C++ it is not error to take address of a register 12461 // variable (c++03 7.1.1P3) 12462 if (vd->getStorageClass() == SC_Register && 12463 !getLangOpts().CPlusPlus) { 12464 AddressOfError = AO_Register_Variable; 12465 } 12466 } else if (isa<MSPropertyDecl>(dcl)) { 12467 AddressOfError = AO_Property_Expansion; 12468 } else if (isa<FunctionTemplateDecl>(dcl)) { 12469 return Context.OverloadTy; 12470 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 12471 // Okay: we can take the address of a field. 12472 // Could be a pointer to member, though, if there is an explicit 12473 // scope qualifier for the class. 12474 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 12475 DeclContext *Ctx = dcl->getDeclContext(); 12476 if (Ctx && Ctx->isRecord()) { 12477 if (dcl->getType()->isReferenceType()) { 12478 Diag(OpLoc, 12479 diag::err_cannot_form_pointer_to_member_of_reference_type) 12480 << dcl->getDeclName() << dcl->getType(); 12481 return QualType(); 12482 } 12483 12484 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 12485 Ctx = Ctx->getParent(); 12486 12487 QualType MPTy = Context.getMemberPointerType( 12488 op->getType(), 12489 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 12490 // Under the MS ABI, lock down the inheritance model now. 12491 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 12492 (void)isCompleteType(OpLoc, MPTy); 12493 return MPTy; 12494 } 12495 } 12496 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 12497 !isa<BindingDecl>(dcl)) 12498 llvm_unreachable("Unknown/unexpected decl type"); 12499 } 12500 12501 if (AddressOfError != AO_No_Error) { 12502 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 12503 return QualType(); 12504 } 12505 12506 if (lval == Expr::LV_IncompleteVoidType) { 12507 // Taking the address of a void variable is technically illegal, but we 12508 // allow it in cases which are otherwise valid. 12509 // Example: "extern void x; void* y = &x;". 12510 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 12511 } 12512 12513 // If the operand has type "type", the result has type "pointer to type". 12514 if (op->getType()->isObjCObjectType()) 12515 return Context.getObjCObjectPointerType(op->getType()); 12516 12517 CheckAddressOfPackedMember(op); 12518 12519 return Context.getPointerType(op->getType()); 12520 } 12521 12522 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 12523 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 12524 if (!DRE) 12525 return; 12526 const Decl *D = DRE->getDecl(); 12527 if (!D) 12528 return; 12529 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 12530 if (!Param) 12531 return; 12532 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 12533 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 12534 return; 12535 if (FunctionScopeInfo *FD = S.getCurFunction()) 12536 if (!FD->ModifiedNonNullParams.count(Param)) 12537 FD->ModifiedNonNullParams.insert(Param); 12538 } 12539 12540 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 12541 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 12542 SourceLocation OpLoc) { 12543 if (Op->isTypeDependent()) 12544 return S.Context.DependentTy; 12545 12546 ExprResult ConvResult = S.UsualUnaryConversions(Op); 12547 if (ConvResult.isInvalid()) 12548 return QualType(); 12549 Op = ConvResult.get(); 12550 QualType OpTy = Op->getType(); 12551 QualType Result; 12552 12553 if (isa<CXXReinterpretCastExpr>(Op)) { 12554 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 12555 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 12556 Op->getSourceRange()); 12557 } 12558 12559 if (const PointerType *PT = OpTy->getAs<PointerType>()) 12560 { 12561 Result = PT->getPointeeType(); 12562 } 12563 else if (const ObjCObjectPointerType *OPT = 12564 OpTy->getAs<ObjCObjectPointerType>()) 12565 Result = OPT->getPointeeType(); 12566 else { 12567 ExprResult PR = S.CheckPlaceholderExpr(Op); 12568 if (PR.isInvalid()) return QualType(); 12569 if (PR.get() != Op) 12570 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 12571 } 12572 12573 if (Result.isNull()) { 12574 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 12575 << OpTy << Op->getSourceRange(); 12576 return QualType(); 12577 } 12578 12579 // Note that per both C89 and C99, indirection is always legal, even if Result 12580 // is an incomplete type or void. It would be possible to warn about 12581 // dereferencing a void pointer, but it's completely well-defined, and such a 12582 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 12583 // for pointers to 'void' but is fine for any other pointer type: 12584 // 12585 // C++ [expr.unary.op]p1: 12586 // [...] the expression to which [the unary * operator] is applied shall 12587 // be a pointer to an object type, or a pointer to a function type 12588 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 12589 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 12590 << OpTy << Op->getSourceRange(); 12591 12592 // Dereferences are usually l-values... 12593 VK = VK_LValue; 12594 12595 // ...except that certain expressions are never l-values in C. 12596 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 12597 VK = VK_RValue; 12598 12599 return Result; 12600 } 12601 12602 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 12603 BinaryOperatorKind Opc; 12604 switch (Kind) { 12605 default: llvm_unreachable("Unknown binop!"); 12606 case tok::periodstar: Opc = BO_PtrMemD; break; 12607 case tok::arrowstar: Opc = BO_PtrMemI; break; 12608 case tok::star: Opc = BO_Mul; break; 12609 case tok::slash: Opc = BO_Div; break; 12610 case tok::percent: Opc = BO_Rem; break; 12611 case tok::plus: Opc = BO_Add; break; 12612 case tok::minus: Opc = BO_Sub; break; 12613 case tok::lessless: Opc = BO_Shl; break; 12614 case tok::greatergreater: Opc = BO_Shr; break; 12615 case tok::lessequal: Opc = BO_LE; break; 12616 case tok::less: Opc = BO_LT; break; 12617 case tok::greaterequal: Opc = BO_GE; break; 12618 case tok::greater: Opc = BO_GT; break; 12619 case tok::exclaimequal: Opc = BO_NE; break; 12620 case tok::equalequal: Opc = BO_EQ; break; 12621 case tok::spaceship: Opc = BO_Cmp; break; 12622 case tok::amp: Opc = BO_And; break; 12623 case tok::caret: Opc = BO_Xor; break; 12624 case tok::pipe: Opc = BO_Or; break; 12625 case tok::ampamp: Opc = BO_LAnd; break; 12626 case tok::pipepipe: Opc = BO_LOr; break; 12627 case tok::equal: Opc = BO_Assign; break; 12628 case tok::starequal: Opc = BO_MulAssign; break; 12629 case tok::slashequal: Opc = BO_DivAssign; break; 12630 case tok::percentequal: Opc = BO_RemAssign; break; 12631 case tok::plusequal: Opc = BO_AddAssign; break; 12632 case tok::minusequal: Opc = BO_SubAssign; break; 12633 case tok::lesslessequal: Opc = BO_ShlAssign; break; 12634 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 12635 case tok::ampequal: Opc = BO_AndAssign; break; 12636 case tok::caretequal: Opc = BO_XorAssign; break; 12637 case tok::pipeequal: Opc = BO_OrAssign; break; 12638 case tok::comma: Opc = BO_Comma; break; 12639 } 12640 return Opc; 12641 } 12642 12643 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 12644 tok::TokenKind Kind) { 12645 UnaryOperatorKind Opc; 12646 switch (Kind) { 12647 default: llvm_unreachable("Unknown unary op!"); 12648 case tok::plusplus: Opc = UO_PreInc; break; 12649 case tok::minusminus: Opc = UO_PreDec; break; 12650 case tok::amp: Opc = UO_AddrOf; break; 12651 case tok::star: Opc = UO_Deref; break; 12652 case tok::plus: Opc = UO_Plus; break; 12653 case tok::minus: Opc = UO_Minus; break; 12654 case tok::tilde: Opc = UO_Not; break; 12655 case tok::exclaim: Opc = UO_LNot; break; 12656 case tok::kw___real: Opc = UO_Real; break; 12657 case tok::kw___imag: Opc = UO_Imag; break; 12658 case tok::kw___extension__: Opc = UO_Extension; break; 12659 } 12660 return Opc; 12661 } 12662 12663 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 12664 /// This warning suppressed in the event of macro expansions. 12665 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 12666 SourceLocation OpLoc, bool IsBuiltin) { 12667 if (S.inTemplateInstantiation()) 12668 return; 12669 if (S.isUnevaluatedContext()) 12670 return; 12671 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 12672 return; 12673 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 12674 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 12675 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 12676 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 12677 if (!LHSDeclRef || !RHSDeclRef || 12678 LHSDeclRef->getLocation().isMacroID() || 12679 RHSDeclRef->getLocation().isMacroID()) 12680 return; 12681 const ValueDecl *LHSDecl = 12682 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 12683 const ValueDecl *RHSDecl = 12684 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 12685 if (LHSDecl != RHSDecl) 12686 return; 12687 if (LHSDecl->getType().isVolatileQualified()) 12688 return; 12689 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 12690 if (RefTy->getPointeeType().isVolatileQualified()) 12691 return; 12692 12693 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 12694 : diag::warn_self_assignment_overloaded) 12695 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 12696 << RHSExpr->getSourceRange(); 12697 } 12698 12699 /// Check if a bitwise-& is performed on an Objective-C pointer. This 12700 /// is usually indicative of introspection within the Objective-C pointer. 12701 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 12702 SourceLocation OpLoc) { 12703 if (!S.getLangOpts().ObjC) 12704 return; 12705 12706 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 12707 const Expr *LHS = L.get(); 12708 const Expr *RHS = R.get(); 12709 12710 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 12711 ObjCPointerExpr = LHS; 12712 OtherExpr = RHS; 12713 } 12714 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 12715 ObjCPointerExpr = RHS; 12716 OtherExpr = LHS; 12717 } 12718 12719 // This warning is deliberately made very specific to reduce false 12720 // positives with logic that uses '&' for hashing. This logic mainly 12721 // looks for code trying to introspect into tagged pointers, which 12722 // code should generally never do. 12723 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 12724 unsigned Diag = diag::warn_objc_pointer_masking; 12725 // Determine if we are introspecting the result of performSelectorXXX. 12726 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 12727 // Special case messages to -performSelector and friends, which 12728 // can return non-pointer values boxed in a pointer value. 12729 // Some clients may wish to silence warnings in this subcase. 12730 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 12731 Selector S = ME->getSelector(); 12732 StringRef SelArg0 = S.getNameForSlot(0); 12733 if (SelArg0.startswith("performSelector")) 12734 Diag = diag::warn_objc_pointer_masking_performSelector; 12735 } 12736 12737 S.Diag(OpLoc, Diag) 12738 << ObjCPointerExpr->getSourceRange(); 12739 } 12740 } 12741 12742 static NamedDecl *getDeclFromExpr(Expr *E) { 12743 if (!E) 12744 return nullptr; 12745 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 12746 return DRE->getDecl(); 12747 if (auto *ME = dyn_cast<MemberExpr>(E)) 12748 return ME->getMemberDecl(); 12749 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 12750 return IRE->getDecl(); 12751 return nullptr; 12752 } 12753 12754 // This helper function promotes a binary operator's operands (which are of a 12755 // half vector type) to a vector of floats and then truncates the result to 12756 // a vector of either half or short. 12757 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 12758 BinaryOperatorKind Opc, QualType ResultTy, 12759 ExprValueKind VK, ExprObjectKind OK, 12760 bool IsCompAssign, SourceLocation OpLoc, 12761 FPOptions FPFeatures) { 12762 auto &Context = S.getASTContext(); 12763 assert((isVector(ResultTy, Context.HalfTy) || 12764 isVector(ResultTy, Context.ShortTy)) && 12765 "Result must be a vector of half or short"); 12766 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 12767 isVector(RHS.get()->getType(), Context.HalfTy) && 12768 "both operands expected to be a half vector"); 12769 12770 RHS = convertVector(RHS.get(), Context.FloatTy, S); 12771 QualType BinOpResTy = RHS.get()->getType(); 12772 12773 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 12774 // change BinOpResTy to a vector of ints. 12775 if (isVector(ResultTy, Context.ShortTy)) 12776 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 12777 12778 if (IsCompAssign) 12779 return new (Context) CompoundAssignOperator( 12780 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy, 12781 OpLoc, FPFeatures); 12782 12783 LHS = convertVector(LHS.get(), Context.FloatTy, S); 12784 auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy, 12785 VK, OK, OpLoc, FPFeatures); 12786 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 12787 } 12788 12789 static std::pair<ExprResult, ExprResult> 12790 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 12791 Expr *RHSExpr) { 12792 ExprResult LHS = LHSExpr, RHS = RHSExpr; 12793 if (!S.getLangOpts().CPlusPlus) { 12794 // C cannot handle TypoExpr nodes on either side of a binop because it 12795 // doesn't handle dependent types properly, so make sure any TypoExprs have 12796 // been dealt with before checking the operands. 12797 LHS = S.CorrectDelayedTyposInExpr(LHS); 12798 RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) { 12799 if (Opc != BO_Assign) 12800 return ExprResult(E); 12801 // Avoid correcting the RHS to the same Expr as the LHS. 12802 Decl *D = getDeclFromExpr(E); 12803 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 12804 }); 12805 } 12806 return std::make_pair(LHS, RHS); 12807 } 12808 12809 /// Returns true if conversion between vectors of halfs and vectors of floats 12810 /// is needed. 12811 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 12812 QualType SrcType) { 12813 return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType && 12814 !Ctx.getTargetInfo().useFP16ConversionIntrinsics() && 12815 isVector(SrcType, Ctx.HalfTy); 12816 } 12817 12818 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 12819 /// operator @p Opc at location @c TokLoc. This routine only supports 12820 /// built-in operations; ActOnBinOp handles overloaded operators. 12821 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 12822 BinaryOperatorKind Opc, 12823 Expr *LHSExpr, Expr *RHSExpr) { 12824 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 12825 // The syntax only allows initializer lists on the RHS of assignment, 12826 // so we don't need to worry about accepting invalid code for 12827 // non-assignment operators. 12828 // C++11 5.17p9: 12829 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 12830 // of x = {} is x = T(). 12831 InitializationKind Kind = InitializationKind::CreateDirectList( 12832 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 12833 InitializedEntity Entity = 12834 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 12835 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 12836 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 12837 if (Init.isInvalid()) 12838 return Init; 12839 RHSExpr = Init.get(); 12840 } 12841 12842 ExprResult LHS = LHSExpr, RHS = RHSExpr; 12843 QualType ResultTy; // Result type of the binary operator. 12844 // The following two variables are used for compound assignment operators 12845 QualType CompLHSTy; // Type of LHS after promotions for computation 12846 QualType CompResultTy; // Type of computation result 12847 ExprValueKind VK = VK_RValue; 12848 ExprObjectKind OK = OK_Ordinary; 12849 bool ConvertHalfVec = false; 12850 12851 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 12852 if (!LHS.isUsable() || !RHS.isUsable()) 12853 return ExprError(); 12854 12855 if (getLangOpts().OpenCL) { 12856 QualType LHSTy = LHSExpr->getType(); 12857 QualType RHSTy = RHSExpr->getType(); 12858 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 12859 // the ATOMIC_VAR_INIT macro. 12860 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 12861 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 12862 if (BO_Assign == Opc) 12863 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 12864 else 12865 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 12866 return ExprError(); 12867 } 12868 12869 // OpenCL special types - image, sampler, pipe, and blocks are to be used 12870 // only with a builtin functions and therefore should be disallowed here. 12871 if (LHSTy->isImageType() || RHSTy->isImageType() || 12872 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 12873 LHSTy->isPipeType() || RHSTy->isPipeType() || 12874 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 12875 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 12876 return ExprError(); 12877 } 12878 } 12879 12880 // Diagnose operations on the unsupported types for OpenMP device compilation. 12881 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) { 12882 if (Opc != BO_Assign && Opc != BO_Comma) { 12883 checkOpenMPDeviceExpr(LHSExpr); 12884 checkOpenMPDeviceExpr(RHSExpr); 12885 } 12886 } 12887 12888 switch (Opc) { 12889 case BO_Assign: 12890 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 12891 if (getLangOpts().CPlusPlus && 12892 LHS.get()->getObjectKind() != OK_ObjCProperty) { 12893 VK = LHS.get()->getValueKind(); 12894 OK = LHS.get()->getObjectKind(); 12895 } 12896 if (!ResultTy.isNull()) { 12897 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 12898 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 12899 12900 // Avoid copying a block to the heap if the block is assigned to a local 12901 // auto variable that is declared in the same scope as the block. This 12902 // optimization is unsafe if the local variable is declared in an outer 12903 // scope. For example: 12904 // 12905 // BlockTy b; 12906 // { 12907 // b = ^{...}; 12908 // } 12909 // // It is unsafe to invoke the block here if it wasn't copied to the 12910 // // heap. 12911 // b(); 12912 12913 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 12914 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 12915 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 12916 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 12917 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 12918 12919 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 12920 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 12921 NTCUC_Assignment, NTCUK_Copy); 12922 } 12923 RecordModifiableNonNullParam(*this, LHS.get()); 12924 break; 12925 case BO_PtrMemD: 12926 case BO_PtrMemI: 12927 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 12928 Opc == BO_PtrMemI); 12929 break; 12930 case BO_Mul: 12931 case BO_Div: 12932 ConvertHalfVec = true; 12933 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 12934 Opc == BO_Div); 12935 break; 12936 case BO_Rem: 12937 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 12938 break; 12939 case BO_Add: 12940 ConvertHalfVec = true; 12941 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 12942 break; 12943 case BO_Sub: 12944 ConvertHalfVec = true; 12945 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 12946 break; 12947 case BO_Shl: 12948 case BO_Shr: 12949 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 12950 break; 12951 case BO_LE: 12952 case BO_LT: 12953 case BO_GE: 12954 case BO_GT: 12955 ConvertHalfVec = true; 12956 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12957 break; 12958 case BO_EQ: 12959 case BO_NE: 12960 ConvertHalfVec = true; 12961 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12962 break; 12963 case BO_Cmp: 12964 ConvertHalfVec = true; 12965 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12966 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 12967 break; 12968 case BO_And: 12969 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 12970 LLVM_FALLTHROUGH; 12971 case BO_Xor: 12972 case BO_Or: 12973 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 12974 break; 12975 case BO_LAnd: 12976 case BO_LOr: 12977 ConvertHalfVec = true; 12978 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 12979 break; 12980 case BO_MulAssign: 12981 case BO_DivAssign: 12982 ConvertHalfVec = true; 12983 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 12984 Opc == BO_DivAssign); 12985 CompLHSTy = CompResultTy; 12986 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12987 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12988 break; 12989 case BO_RemAssign: 12990 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 12991 CompLHSTy = CompResultTy; 12992 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12993 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12994 break; 12995 case BO_AddAssign: 12996 ConvertHalfVec = true; 12997 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 12998 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12999 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13000 break; 13001 case BO_SubAssign: 13002 ConvertHalfVec = true; 13003 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 13004 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13005 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13006 break; 13007 case BO_ShlAssign: 13008 case BO_ShrAssign: 13009 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 13010 CompLHSTy = CompResultTy; 13011 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13012 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13013 break; 13014 case BO_AndAssign: 13015 case BO_OrAssign: // fallthrough 13016 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 13017 LLVM_FALLTHROUGH; 13018 case BO_XorAssign: 13019 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 13020 CompLHSTy = CompResultTy; 13021 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13022 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13023 break; 13024 case BO_Comma: 13025 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 13026 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 13027 VK = RHS.get()->getValueKind(); 13028 OK = RHS.get()->getObjectKind(); 13029 } 13030 break; 13031 } 13032 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 13033 return ExprError(); 13034 13035 if (ResultTy->isRealFloatingType() && 13036 (getLangOpts().getFPRoundingMode() != LangOptions::FPR_ToNearest || 13037 getLangOpts().getFPExceptionMode() != LangOptions::FPE_Ignore)) 13038 // Mark the current function as usng floating point constrained intrinsics 13039 if (FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) 13040 { 13041 F->setUsesFPIntrin(true); 13042 printf("Enclosing function uses fp intrinsics\n"); 13043 } 13044 13045 // Some of the binary operations require promoting operands of half vector to 13046 // float vectors and truncating the result back to half vector. For now, we do 13047 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 13048 // arm64). 13049 assert(isVector(RHS.get()->getType(), Context.HalfTy) == 13050 isVector(LHS.get()->getType(), Context.HalfTy) && 13051 "both sides are half vectors or neither sides are"); 13052 ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context, 13053 LHS.get()->getType()); 13054 13055 // Check for array bounds violations for both sides of the BinaryOperator 13056 CheckArrayAccess(LHS.get()); 13057 CheckArrayAccess(RHS.get()); 13058 13059 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 13060 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 13061 &Context.Idents.get("object_setClass"), 13062 SourceLocation(), LookupOrdinaryName); 13063 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 13064 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 13065 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 13066 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 13067 "object_setClass(") 13068 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 13069 ",") 13070 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 13071 } 13072 else 13073 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 13074 } 13075 else if (const ObjCIvarRefExpr *OIRE = 13076 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 13077 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 13078 13079 // Opc is not a compound assignment if CompResultTy is null. 13080 if (CompResultTy.isNull()) { 13081 if (ConvertHalfVec) 13082 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 13083 OpLoc, FPFeatures); 13084 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 13085 OK, OpLoc, FPFeatures); 13086 } 13087 13088 // Handle compound assignments. 13089 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 13090 OK_ObjCProperty) { 13091 VK = VK_LValue; 13092 OK = LHS.get()->getObjectKind(); 13093 } 13094 13095 if (ConvertHalfVec) 13096 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 13097 OpLoc, FPFeatures); 13098 13099 return new (Context) CompoundAssignOperator( 13100 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 13101 OpLoc, FPFeatures); 13102 } 13103 13104 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 13105 /// operators are mixed in a way that suggests that the programmer forgot that 13106 /// comparison operators have higher precedence. The most typical example of 13107 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 13108 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 13109 SourceLocation OpLoc, Expr *LHSExpr, 13110 Expr *RHSExpr) { 13111 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 13112 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 13113 13114 // Check that one of the sides is a comparison operator and the other isn't. 13115 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 13116 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 13117 if (isLeftComp == isRightComp) 13118 return; 13119 13120 // Bitwise operations are sometimes used as eager logical ops. 13121 // Don't diagnose this. 13122 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 13123 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 13124 if (isLeftBitwise || isRightBitwise) 13125 return; 13126 13127 SourceRange DiagRange = isLeftComp 13128 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 13129 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 13130 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 13131 SourceRange ParensRange = 13132 isLeftComp 13133 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 13134 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 13135 13136 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 13137 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 13138 SuggestParentheses(Self, OpLoc, 13139 Self.PDiag(diag::note_precedence_silence) << OpStr, 13140 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 13141 SuggestParentheses(Self, OpLoc, 13142 Self.PDiag(diag::note_precedence_bitwise_first) 13143 << BinaryOperator::getOpcodeStr(Opc), 13144 ParensRange); 13145 } 13146 13147 /// It accepts a '&&' expr that is inside a '||' one. 13148 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 13149 /// in parentheses. 13150 static void 13151 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 13152 BinaryOperator *Bop) { 13153 assert(Bop->getOpcode() == BO_LAnd); 13154 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 13155 << Bop->getSourceRange() << OpLoc; 13156 SuggestParentheses(Self, Bop->getOperatorLoc(), 13157 Self.PDiag(diag::note_precedence_silence) 13158 << Bop->getOpcodeStr(), 13159 Bop->getSourceRange()); 13160 } 13161 13162 /// Returns true if the given expression can be evaluated as a constant 13163 /// 'true'. 13164 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 13165 bool Res; 13166 return !E->isValueDependent() && 13167 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 13168 } 13169 13170 /// Returns true if the given expression can be evaluated as a constant 13171 /// 'false'. 13172 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 13173 bool Res; 13174 return !E->isValueDependent() && 13175 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 13176 } 13177 13178 /// Look for '&&' in the left hand of a '||' expr. 13179 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 13180 Expr *LHSExpr, Expr *RHSExpr) { 13181 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 13182 if (Bop->getOpcode() == BO_LAnd) { 13183 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 13184 if (EvaluatesAsFalse(S, RHSExpr)) 13185 return; 13186 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 13187 if (!EvaluatesAsTrue(S, Bop->getLHS())) 13188 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 13189 } else if (Bop->getOpcode() == BO_LOr) { 13190 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 13191 // If it's "a || b && 1 || c" we didn't warn earlier for 13192 // "a || b && 1", but warn now. 13193 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 13194 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 13195 } 13196 } 13197 } 13198 } 13199 13200 /// Look for '&&' in the right hand of a '||' expr. 13201 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 13202 Expr *LHSExpr, Expr *RHSExpr) { 13203 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 13204 if (Bop->getOpcode() == BO_LAnd) { 13205 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 13206 if (EvaluatesAsFalse(S, LHSExpr)) 13207 return; 13208 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 13209 if (!EvaluatesAsTrue(S, Bop->getRHS())) 13210 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 13211 } 13212 } 13213 } 13214 13215 /// Look for bitwise op in the left or right hand of a bitwise op with 13216 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 13217 /// the '&' expression in parentheses. 13218 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 13219 SourceLocation OpLoc, Expr *SubExpr) { 13220 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 13221 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 13222 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 13223 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 13224 << Bop->getSourceRange() << OpLoc; 13225 SuggestParentheses(S, Bop->getOperatorLoc(), 13226 S.PDiag(diag::note_precedence_silence) 13227 << Bop->getOpcodeStr(), 13228 Bop->getSourceRange()); 13229 } 13230 } 13231 } 13232 13233 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 13234 Expr *SubExpr, StringRef Shift) { 13235 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 13236 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 13237 StringRef Op = Bop->getOpcodeStr(); 13238 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 13239 << Bop->getSourceRange() << OpLoc << Shift << Op; 13240 SuggestParentheses(S, Bop->getOperatorLoc(), 13241 S.PDiag(diag::note_precedence_silence) << Op, 13242 Bop->getSourceRange()); 13243 } 13244 } 13245 } 13246 13247 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 13248 Expr *LHSExpr, Expr *RHSExpr) { 13249 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 13250 if (!OCE) 13251 return; 13252 13253 FunctionDecl *FD = OCE->getDirectCallee(); 13254 if (!FD || !FD->isOverloadedOperator()) 13255 return; 13256 13257 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 13258 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 13259 return; 13260 13261 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 13262 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 13263 << (Kind == OO_LessLess); 13264 SuggestParentheses(S, OCE->getOperatorLoc(), 13265 S.PDiag(diag::note_precedence_silence) 13266 << (Kind == OO_LessLess ? "<<" : ">>"), 13267 OCE->getSourceRange()); 13268 SuggestParentheses( 13269 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 13270 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 13271 } 13272 13273 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 13274 /// precedence. 13275 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 13276 SourceLocation OpLoc, Expr *LHSExpr, 13277 Expr *RHSExpr){ 13278 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 13279 if (BinaryOperator::isBitwiseOp(Opc)) 13280 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 13281 13282 // Diagnose "arg1 & arg2 | arg3" 13283 if ((Opc == BO_Or || Opc == BO_Xor) && 13284 !OpLoc.isMacroID()/* Don't warn in macros. */) { 13285 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 13286 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 13287 } 13288 13289 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 13290 // We don't warn for 'assert(a || b && "bad")' since this is safe. 13291 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 13292 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 13293 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 13294 } 13295 13296 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 13297 || Opc == BO_Shr) { 13298 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 13299 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 13300 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 13301 } 13302 13303 // Warn on overloaded shift operators and comparisons, such as: 13304 // cout << 5 == 4; 13305 if (BinaryOperator::isComparisonOp(Opc)) 13306 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 13307 } 13308 13309 // Binary Operators. 'Tok' is the token for the operator. 13310 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 13311 tok::TokenKind Kind, 13312 Expr *LHSExpr, Expr *RHSExpr) { 13313 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 13314 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 13315 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 13316 13317 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 13318 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 13319 13320 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 13321 } 13322 13323 /// Build an overloaded binary operator expression in the given scope. 13324 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 13325 BinaryOperatorKind Opc, 13326 Expr *LHS, Expr *RHS) { 13327 switch (Opc) { 13328 case BO_Assign: 13329 case BO_DivAssign: 13330 case BO_RemAssign: 13331 case BO_SubAssign: 13332 case BO_AndAssign: 13333 case BO_OrAssign: 13334 case BO_XorAssign: 13335 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 13336 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 13337 break; 13338 default: 13339 break; 13340 } 13341 13342 // Find all of the overloaded operators visible from this 13343 // point. We perform both an operator-name lookup from the local 13344 // scope and an argument-dependent lookup based on the types of 13345 // the arguments. 13346 UnresolvedSet<16> Functions; 13347 OverloadedOperatorKind OverOp 13348 = BinaryOperator::getOverloadedOperator(Opc); 13349 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 13350 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 13351 RHS->getType(), Functions); 13352 13353 // In C++20 onwards, we may have a second operator to look up. 13354 if (S.getLangOpts().CPlusPlus2a) { 13355 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 13356 S.LookupOverloadedOperatorName(ExtraOp, Sc, LHS->getType(), 13357 RHS->getType(), Functions); 13358 } 13359 13360 // Build the (potentially-overloaded, potentially-dependent) 13361 // binary operation. 13362 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 13363 } 13364 13365 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 13366 BinaryOperatorKind Opc, 13367 Expr *LHSExpr, Expr *RHSExpr) { 13368 ExprResult LHS, RHS; 13369 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 13370 if (!LHS.isUsable() || !RHS.isUsable()) 13371 return ExprError(); 13372 LHSExpr = LHS.get(); 13373 RHSExpr = RHS.get(); 13374 13375 // We want to end up calling one of checkPseudoObjectAssignment 13376 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 13377 // both expressions are overloadable or either is type-dependent), 13378 // or CreateBuiltinBinOp (in any other case). We also want to get 13379 // any placeholder types out of the way. 13380 13381 // Handle pseudo-objects in the LHS. 13382 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 13383 // Assignments with a pseudo-object l-value need special analysis. 13384 if (pty->getKind() == BuiltinType::PseudoObject && 13385 BinaryOperator::isAssignmentOp(Opc)) 13386 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 13387 13388 // Don't resolve overloads if the other type is overloadable. 13389 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 13390 // We can't actually test that if we still have a placeholder, 13391 // though. Fortunately, none of the exceptions we see in that 13392 // code below are valid when the LHS is an overload set. Note 13393 // that an overload set can be dependently-typed, but it never 13394 // instantiates to having an overloadable type. 13395 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 13396 if (resolvedRHS.isInvalid()) return ExprError(); 13397 RHSExpr = resolvedRHS.get(); 13398 13399 if (RHSExpr->isTypeDependent() || 13400 RHSExpr->getType()->isOverloadableType()) 13401 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13402 } 13403 13404 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 13405 // template, diagnose the missing 'template' keyword instead of diagnosing 13406 // an invalid use of a bound member function. 13407 // 13408 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 13409 // to C++1z [over.over]/1.4, but we already checked for that case above. 13410 if (Opc == BO_LT && inTemplateInstantiation() && 13411 (pty->getKind() == BuiltinType::BoundMember || 13412 pty->getKind() == BuiltinType::Overload)) { 13413 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 13414 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 13415 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 13416 return isa<FunctionTemplateDecl>(ND); 13417 })) { 13418 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 13419 : OE->getNameLoc(), 13420 diag::err_template_kw_missing) 13421 << OE->getName().getAsString() << ""; 13422 return ExprError(); 13423 } 13424 } 13425 13426 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 13427 if (LHS.isInvalid()) return ExprError(); 13428 LHSExpr = LHS.get(); 13429 } 13430 13431 // Handle pseudo-objects in the RHS. 13432 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 13433 // An overload in the RHS can potentially be resolved by the type 13434 // being assigned to. 13435 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 13436 if (getLangOpts().CPlusPlus && 13437 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 13438 LHSExpr->getType()->isOverloadableType())) 13439 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13440 13441 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 13442 } 13443 13444 // Don't resolve overloads if the other type is overloadable. 13445 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 13446 LHSExpr->getType()->isOverloadableType()) 13447 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13448 13449 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 13450 if (!resolvedRHS.isUsable()) return ExprError(); 13451 RHSExpr = resolvedRHS.get(); 13452 } 13453 13454 if (getLangOpts().CPlusPlus) { 13455 // If either expression is type-dependent, always build an 13456 // overloaded op. 13457 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 13458 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13459 13460 // Otherwise, build an overloaded op if either expression has an 13461 // overloadable type. 13462 if (LHSExpr->getType()->isOverloadableType() || 13463 RHSExpr->getType()->isOverloadableType()) 13464 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13465 } 13466 13467 // Build a built-in binary operation. 13468 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 13469 } 13470 13471 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 13472 if (T.isNull() || T->isDependentType()) 13473 return false; 13474 13475 if (!T->isPromotableIntegerType()) 13476 return true; 13477 13478 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 13479 } 13480 13481 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 13482 UnaryOperatorKind Opc, 13483 Expr *InputExpr) { 13484 ExprResult Input = InputExpr; 13485 ExprValueKind VK = VK_RValue; 13486 ExprObjectKind OK = OK_Ordinary; 13487 QualType resultType; 13488 bool CanOverflow = false; 13489 13490 bool ConvertHalfVec = false; 13491 if (getLangOpts().OpenCL) { 13492 QualType Ty = InputExpr->getType(); 13493 // The only legal unary operation for atomics is '&'. 13494 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 13495 // OpenCL special types - image, sampler, pipe, and blocks are to be used 13496 // only with a builtin functions and therefore should be disallowed here. 13497 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 13498 || Ty->isBlockPointerType())) { 13499 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13500 << InputExpr->getType() 13501 << Input.get()->getSourceRange()); 13502 } 13503 } 13504 // Diagnose operations on the unsupported types for OpenMP device compilation. 13505 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) { 13506 if (UnaryOperator::isIncrementDecrementOp(Opc) || 13507 UnaryOperator::isArithmeticOp(Opc)) 13508 checkOpenMPDeviceExpr(InputExpr); 13509 } 13510 13511 switch (Opc) { 13512 case UO_PreInc: 13513 case UO_PreDec: 13514 case UO_PostInc: 13515 case UO_PostDec: 13516 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 13517 OpLoc, 13518 Opc == UO_PreInc || 13519 Opc == UO_PostInc, 13520 Opc == UO_PreInc || 13521 Opc == UO_PreDec); 13522 CanOverflow = isOverflowingIntegerType(Context, resultType); 13523 break; 13524 case UO_AddrOf: 13525 resultType = CheckAddressOfOperand(Input, OpLoc); 13526 CheckAddressOfNoDeref(InputExpr); 13527 RecordModifiableNonNullParam(*this, InputExpr); 13528 break; 13529 case UO_Deref: { 13530 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 13531 if (Input.isInvalid()) return ExprError(); 13532 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 13533 break; 13534 } 13535 case UO_Plus: 13536 case UO_Minus: 13537 CanOverflow = Opc == UO_Minus && 13538 isOverflowingIntegerType(Context, Input.get()->getType()); 13539 Input = UsualUnaryConversions(Input.get()); 13540 if (Input.isInvalid()) return ExprError(); 13541 // Unary plus and minus require promoting an operand of half vector to a 13542 // float vector and truncating the result back to a half vector. For now, we 13543 // do this only when HalfArgsAndReturns is set (that is, when the target is 13544 // arm or arm64). 13545 ConvertHalfVec = 13546 needsConversionOfHalfVec(true, Context, Input.get()->getType()); 13547 13548 // If the operand is a half vector, promote it to a float vector. 13549 if (ConvertHalfVec) 13550 Input = convertVector(Input.get(), Context.FloatTy, *this); 13551 resultType = Input.get()->getType(); 13552 if (resultType->isDependentType()) 13553 break; 13554 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 13555 break; 13556 else if (resultType->isVectorType() && 13557 // The z vector extensions don't allow + or - with bool vectors. 13558 (!Context.getLangOpts().ZVector || 13559 resultType->castAs<VectorType>()->getVectorKind() != 13560 VectorType::AltiVecBool)) 13561 break; 13562 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 13563 Opc == UO_Plus && 13564 resultType->isPointerType()) 13565 break; 13566 13567 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13568 << resultType << Input.get()->getSourceRange()); 13569 13570 case UO_Not: // bitwise complement 13571 Input = UsualUnaryConversions(Input.get()); 13572 if (Input.isInvalid()) 13573 return ExprError(); 13574 resultType = Input.get()->getType(); 13575 if (resultType->isDependentType()) 13576 break; 13577 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 13578 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 13579 // C99 does not support '~' for complex conjugation. 13580 Diag(OpLoc, diag::ext_integer_complement_complex) 13581 << resultType << Input.get()->getSourceRange(); 13582 else if (resultType->hasIntegerRepresentation()) 13583 break; 13584 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 13585 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 13586 // on vector float types. 13587 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 13588 if (!T->isIntegerType()) 13589 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13590 << resultType << Input.get()->getSourceRange()); 13591 } else { 13592 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13593 << resultType << Input.get()->getSourceRange()); 13594 } 13595 break; 13596 13597 case UO_LNot: // logical negation 13598 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 13599 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 13600 if (Input.isInvalid()) return ExprError(); 13601 resultType = Input.get()->getType(); 13602 13603 // Though we still have to promote half FP to float... 13604 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 13605 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 13606 resultType = Context.FloatTy; 13607 } 13608 13609 if (resultType->isDependentType()) 13610 break; 13611 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 13612 // C99 6.5.3.3p1: ok, fallthrough; 13613 if (Context.getLangOpts().CPlusPlus) { 13614 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 13615 // operand contextually converted to bool. 13616 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 13617 ScalarTypeToBooleanCastKind(resultType)); 13618 } else if (Context.getLangOpts().OpenCL && 13619 Context.getLangOpts().OpenCLVersion < 120) { 13620 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 13621 // operate on scalar float types. 13622 if (!resultType->isIntegerType() && !resultType->isPointerType()) 13623 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13624 << resultType << Input.get()->getSourceRange()); 13625 } 13626 } else if (resultType->isExtVectorType()) { 13627 if (Context.getLangOpts().OpenCL && 13628 Context.getLangOpts().OpenCLVersion < 120 && 13629 !Context.getLangOpts().OpenCLCPlusPlus) { 13630 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 13631 // operate on vector float types. 13632 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 13633 if (!T->isIntegerType()) 13634 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13635 << resultType << Input.get()->getSourceRange()); 13636 } 13637 // Vector logical not returns the signed variant of the operand type. 13638 resultType = GetSignedVectorType(resultType); 13639 break; 13640 } else { 13641 // FIXME: GCC's vector extension permits the usage of '!' with a vector 13642 // type in C++. We should allow that here too. 13643 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13644 << resultType << Input.get()->getSourceRange()); 13645 } 13646 13647 // LNot always has type int. C99 6.5.3.3p5. 13648 // In C++, it's bool. C++ 5.3.1p8 13649 resultType = Context.getLogicalOperationType(); 13650 break; 13651 case UO_Real: 13652 case UO_Imag: 13653 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 13654 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 13655 // complex l-values to ordinary l-values and all other values to r-values. 13656 if (Input.isInvalid()) return ExprError(); 13657 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 13658 if (Input.get()->getValueKind() != VK_RValue && 13659 Input.get()->getObjectKind() == OK_Ordinary) 13660 VK = Input.get()->getValueKind(); 13661 } else if (!getLangOpts().CPlusPlus) { 13662 // In C, a volatile scalar is read by __imag. In C++, it is not. 13663 Input = DefaultLvalueConversion(Input.get()); 13664 } 13665 break; 13666 case UO_Extension: 13667 resultType = Input.get()->getType(); 13668 VK = Input.get()->getValueKind(); 13669 OK = Input.get()->getObjectKind(); 13670 break; 13671 case UO_Coawait: 13672 // It's unnecessary to represent the pass-through operator co_await in the 13673 // AST; just return the input expression instead. 13674 assert(!Input.get()->getType()->isDependentType() && 13675 "the co_await expression must be non-dependant before " 13676 "building operator co_await"); 13677 return Input; 13678 } 13679 if (resultType.isNull() || Input.isInvalid()) 13680 return ExprError(); 13681 13682 // Check for array bounds violations in the operand of the UnaryOperator, 13683 // except for the '*' and '&' operators that have to be handled specially 13684 // by CheckArrayAccess (as there are special cases like &array[arraysize] 13685 // that are explicitly defined as valid by the standard). 13686 if (Opc != UO_AddrOf && Opc != UO_Deref) 13687 CheckArrayAccess(Input.get()); 13688 13689 auto *UO = new (Context) 13690 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow); 13691 13692 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 13693 !isa<ArrayType>(UO->getType().getDesugaredType(Context))) 13694 ExprEvalContexts.back().PossibleDerefs.insert(UO); 13695 13696 // Convert the result back to a half vector. 13697 if (ConvertHalfVec) 13698 return convertVector(UO, Context.HalfTy, *this); 13699 return UO; 13700 } 13701 13702 /// Determine whether the given expression is a qualified member 13703 /// access expression, of a form that could be turned into a pointer to member 13704 /// with the address-of operator. 13705 bool Sema::isQualifiedMemberAccess(Expr *E) { 13706 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13707 if (!DRE->getQualifier()) 13708 return false; 13709 13710 ValueDecl *VD = DRE->getDecl(); 13711 if (!VD->isCXXClassMember()) 13712 return false; 13713 13714 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 13715 return true; 13716 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 13717 return Method->isInstance(); 13718 13719 return false; 13720 } 13721 13722 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 13723 if (!ULE->getQualifier()) 13724 return false; 13725 13726 for (NamedDecl *D : ULE->decls()) { 13727 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 13728 if (Method->isInstance()) 13729 return true; 13730 } else { 13731 // Overload set does not contain methods. 13732 break; 13733 } 13734 } 13735 13736 return false; 13737 } 13738 13739 return false; 13740 } 13741 13742 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 13743 UnaryOperatorKind Opc, Expr *Input) { 13744 // First things first: handle placeholders so that the 13745 // overloaded-operator check considers the right type. 13746 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 13747 // Increment and decrement of pseudo-object references. 13748 if (pty->getKind() == BuiltinType::PseudoObject && 13749 UnaryOperator::isIncrementDecrementOp(Opc)) 13750 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 13751 13752 // extension is always a builtin operator. 13753 if (Opc == UO_Extension) 13754 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13755 13756 // & gets special logic for several kinds of placeholder. 13757 // The builtin code knows what to do. 13758 if (Opc == UO_AddrOf && 13759 (pty->getKind() == BuiltinType::Overload || 13760 pty->getKind() == BuiltinType::UnknownAny || 13761 pty->getKind() == BuiltinType::BoundMember)) 13762 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13763 13764 // Anything else needs to be handled now. 13765 ExprResult Result = CheckPlaceholderExpr(Input); 13766 if (Result.isInvalid()) return ExprError(); 13767 Input = Result.get(); 13768 } 13769 13770 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 13771 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 13772 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 13773 // Find all of the overloaded operators visible from this 13774 // point. We perform both an operator-name lookup from the local 13775 // scope and an argument-dependent lookup based on the types of 13776 // the arguments. 13777 UnresolvedSet<16> Functions; 13778 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 13779 if (S && OverOp != OO_None) 13780 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 13781 Functions); 13782 13783 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 13784 } 13785 13786 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13787 } 13788 13789 // Unary Operators. 'Tok' is the token for the operator. 13790 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 13791 tok::TokenKind Op, Expr *Input) { 13792 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 13793 } 13794 13795 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 13796 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 13797 LabelDecl *TheDecl) { 13798 TheDecl->markUsed(Context); 13799 // Create the AST node. The address of a label always has type 'void*'. 13800 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 13801 Context.getPointerType(Context.VoidTy)); 13802 } 13803 13804 void Sema::ActOnStartStmtExpr() { 13805 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 13806 } 13807 13808 void Sema::ActOnStmtExprError() { 13809 // Note that function is also called by TreeTransform when leaving a 13810 // StmtExpr scope without rebuilding anything. 13811 13812 DiscardCleanupsInEvaluationContext(); 13813 PopExpressionEvaluationContext(); 13814 } 13815 13816 ExprResult 13817 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 13818 SourceLocation RPLoc) { // "({..})" 13819 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 13820 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 13821 13822 if (hasAnyUnrecoverableErrorsInThisFunction()) 13823 DiscardCleanupsInEvaluationContext(); 13824 assert(!Cleanup.exprNeedsCleanups() && 13825 "cleanups within StmtExpr not correctly bound!"); 13826 PopExpressionEvaluationContext(); 13827 13828 // FIXME: there are a variety of strange constraints to enforce here, for 13829 // example, it is not possible to goto into a stmt expression apparently. 13830 // More semantic analysis is needed. 13831 13832 // If there are sub-stmts in the compound stmt, take the type of the last one 13833 // as the type of the stmtexpr. 13834 QualType Ty = Context.VoidTy; 13835 bool StmtExprMayBindToTemp = false; 13836 if (!Compound->body_empty()) { 13837 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 13838 if (const auto *LastStmt = 13839 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 13840 if (const Expr *Value = LastStmt->getExprStmt()) { 13841 StmtExprMayBindToTemp = true; 13842 Ty = Value->getType(); 13843 } 13844 } 13845 } 13846 13847 // FIXME: Check that expression type is complete/non-abstract; statement 13848 // expressions are not lvalues. 13849 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 13850 if (StmtExprMayBindToTemp) 13851 return MaybeBindToTemporary(ResStmtExpr); 13852 return ResStmtExpr; 13853 } 13854 13855 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 13856 if (ER.isInvalid()) 13857 return ExprError(); 13858 13859 // Do function/array conversion on the last expression, but not 13860 // lvalue-to-rvalue. However, initialize an unqualified type. 13861 ER = DefaultFunctionArrayConversion(ER.get()); 13862 if (ER.isInvalid()) 13863 return ExprError(); 13864 Expr *E = ER.get(); 13865 13866 if (E->isTypeDependent()) 13867 return E; 13868 13869 // In ARC, if the final expression ends in a consume, splice 13870 // the consume out and bind it later. In the alternate case 13871 // (when dealing with a retainable type), the result 13872 // initialization will create a produce. In both cases the 13873 // result will be +1, and we'll need to balance that out with 13874 // a bind. 13875 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 13876 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 13877 return Cast->getSubExpr(); 13878 13879 // FIXME: Provide a better location for the initialization. 13880 return PerformCopyInitialization( 13881 InitializedEntity::InitializeStmtExprResult( 13882 E->getBeginLoc(), E->getType().getUnqualifiedType()), 13883 SourceLocation(), E); 13884 } 13885 13886 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 13887 TypeSourceInfo *TInfo, 13888 ArrayRef<OffsetOfComponent> Components, 13889 SourceLocation RParenLoc) { 13890 QualType ArgTy = TInfo->getType(); 13891 bool Dependent = ArgTy->isDependentType(); 13892 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 13893 13894 // We must have at least one component that refers to the type, and the first 13895 // one is known to be a field designator. Verify that the ArgTy represents 13896 // a struct/union/class. 13897 if (!Dependent && !ArgTy->isRecordType()) 13898 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 13899 << ArgTy << TypeRange); 13900 13901 // Type must be complete per C99 7.17p3 because a declaring a variable 13902 // with an incomplete type would be ill-formed. 13903 if (!Dependent 13904 && RequireCompleteType(BuiltinLoc, ArgTy, 13905 diag::err_offsetof_incomplete_type, TypeRange)) 13906 return ExprError(); 13907 13908 bool DidWarnAboutNonPOD = false; 13909 QualType CurrentType = ArgTy; 13910 SmallVector<OffsetOfNode, 4> Comps; 13911 SmallVector<Expr*, 4> Exprs; 13912 for (const OffsetOfComponent &OC : Components) { 13913 if (OC.isBrackets) { 13914 // Offset of an array sub-field. TODO: Should we allow vector elements? 13915 if (!CurrentType->isDependentType()) { 13916 const ArrayType *AT = Context.getAsArrayType(CurrentType); 13917 if(!AT) 13918 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 13919 << CurrentType); 13920 CurrentType = AT->getElementType(); 13921 } else 13922 CurrentType = Context.DependentTy; 13923 13924 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 13925 if (IdxRval.isInvalid()) 13926 return ExprError(); 13927 Expr *Idx = IdxRval.get(); 13928 13929 // The expression must be an integral expression. 13930 // FIXME: An integral constant expression? 13931 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 13932 !Idx->getType()->isIntegerType()) 13933 return ExprError( 13934 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 13935 << Idx->getSourceRange()); 13936 13937 // Record this array index. 13938 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 13939 Exprs.push_back(Idx); 13940 continue; 13941 } 13942 13943 // Offset of a field. 13944 if (CurrentType->isDependentType()) { 13945 // We have the offset of a field, but we can't look into the dependent 13946 // type. Just record the identifier of the field. 13947 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 13948 CurrentType = Context.DependentTy; 13949 continue; 13950 } 13951 13952 // We need to have a complete type to look into. 13953 if (RequireCompleteType(OC.LocStart, CurrentType, 13954 diag::err_offsetof_incomplete_type)) 13955 return ExprError(); 13956 13957 // Look for the designated field. 13958 const RecordType *RC = CurrentType->getAs<RecordType>(); 13959 if (!RC) 13960 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 13961 << CurrentType); 13962 RecordDecl *RD = RC->getDecl(); 13963 13964 // C++ [lib.support.types]p5: 13965 // The macro offsetof accepts a restricted set of type arguments in this 13966 // International Standard. type shall be a POD structure or a POD union 13967 // (clause 9). 13968 // C++11 [support.types]p4: 13969 // If type is not a standard-layout class (Clause 9), the results are 13970 // undefined. 13971 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 13972 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 13973 unsigned DiagID = 13974 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 13975 : diag::ext_offsetof_non_pod_type; 13976 13977 if (!IsSafe && !DidWarnAboutNonPOD && 13978 DiagRuntimeBehavior(BuiltinLoc, nullptr, 13979 PDiag(DiagID) 13980 << SourceRange(Components[0].LocStart, OC.LocEnd) 13981 << CurrentType)) 13982 DidWarnAboutNonPOD = true; 13983 } 13984 13985 // Look for the field. 13986 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 13987 LookupQualifiedName(R, RD); 13988 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 13989 IndirectFieldDecl *IndirectMemberDecl = nullptr; 13990 if (!MemberDecl) { 13991 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 13992 MemberDecl = IndirectMemberDecl->getAnonField(); 13993 } 13994 13995 if (!MemberDecl) 13996 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 13997 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 13998 OC.LocEnd)); 13999 14000 // C99 7.17p3: 14001 // (If the specified member is a bit-field, the behavior is undefined.) 14002 // 14003 // We diagnose this as an error. 14004 if (MemberDecl->isBitField()) { 14005 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 14006 << MemberDecl->getDeclName() 14007 << SourceRange(BuiltinLoc, RParenLoc); 14008 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 14009 return ExprError(); 14010 } 14011 14012 RecordDecl *Parent = MemberDecl->getParent(); 14013 if (IndirectMemberDecl) 14014 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 14015 14016 // If the member was found in a base class, introduce OffsetOfNodes for 14017 // the base class indirections. 14018 CXXBasePaths Paths; 14019 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 14020 Paths)) { 14021 if (Paths.getDetectedVirtual()) { 14022 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 14023 << MemberDecl->getDeclName() 14024 << SourceRange(BuiltinLoc, RParenLoc); 14025 return ExprError(); 14026 } 14027 14028 CXXBasePath &Path = Paths.front(); 14029 for (const CXXBasePathElement &B : Path) 14030 Comps.push_back(OffsetOfNode(B.Base)); 14031 } 14032 14033 if (IndirectMemberDecl) { 14034 for (auto *FI : IndirectMemberDecl->chain()) { 14035 assert(isa<FieldDecl>(FI)); 14036 Comps.push_back(OffsetOfNode(OC.LocStart, 14037 cast<FieldDecl>(FI), OC.LocEnd)); 14038 } 14039 } else 14040 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 14041 14042 CurrentType = MemberDecl->getType().getNonReferenceType(); 14043 } 14044 14045 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 14046 Comps, Exprs, RParenLoc); 14047 } 14048 14049 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 14050 SourceLocation BuiltinLoc, 14051 SourceLocation TypeLoc, 14052 ParsedType ParsedArgTy, 14053 ArrayRef<OffsetOfComponent> Components, 14054 SourceLocation RParenLoc) { 14055 14056 TypeSourceInfo *ArgTInfo; 14057 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 14058 if (ArgTy.isNull()) 14059 return ExprError(); 14060 14061 if (!ArgTInfo) 14062 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 14063 14064 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 14065 } 14066 14067 14068 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 14069 Expr *CondExpr, 14070 Expr *LHSExpr, Expr *RHSExpr, 14071 SourceLocation RPLoc) { 14072 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 14073 14074 ExprValueKind VK = VK_RValue; 14075 ExprObjectKind OK = OK_Ordinary; 14076 QualType resType; 14077 bool ValueDependent = false; 14078 bool CondIsTrue = false; 14079 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 14080 resType = Context.DependentTy; 14081 ValueDependent = true; 14082 } else { 14083 // The conditional expression is required to be a constant expression. 14084 llvm::APSInt condEval(32); 14085 ExprResult CondICE 14086 = VerifyIntegerConstantExpression(CondExpr, &condEval, 14087 diag::err_typecheck_choose_expr_requires_constant, false); 14088 if (CondICE.isInvalid()) 14089 return ExprError(); 14090 CondExpr = CondICE.get(); 14091 CondIsTrue = condEval.getZExtValue(); 14092 14093 // If the condition is > zero, then the AST type is the same as the LHSExpr. 14094 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 14095 14096 resType = ActiveExpr->getType(); 14097 ValueDependent = ActiveExpr->isValueDependent(); 14098 VK = ActiveExpr->getValueKind(); 14099 OK = ActiveExpr->getObjectKind(); 14100 } 14101 14102 return new (Context) 14103 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 14104 CondIsTrue, resType->isDependentType(), ValueDependent); 14105 } 14106 14107 //===----------------------------------------------------------------------===// 14108 // Clang Extensions. 14109 //===----------------------------------------------------------------------===// 14110 14111 /// ActOnBlockStart - This callback is invoked when a block literal is started. 14112 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 14113 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 14114 14115 if (LangOpts.CPlusPlus) { 14116 MangleNumberingContext *MCtx; 14117 Decl *ManglingContextDecl; 14118 std::tie(MCtx, ManglingContextDecl) = 14119 getCurrentMangleNumberContext(Block->getDeclContext()); 14120 if (MCtx) { 14121 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 14122 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 14123 } 14124 } 14125 14126 PushBlockScope(CurScope, Block); 14127 CurContext->addDecl(Block); 14128 if (CurScope) 14129 PushDeclContext(CurScope, Block); 14130 else 14131 CurContext = Block; 14132 14133 getCurBlock()->HasImplicitReturnType = true; 14134 14135 // Enter a new evaluation context to insulate the block from any 14136 // cleanups from the enclosing full-expression. 14137 PushExpressionEvaluationContext( 14138 ExpressionEvaluationContext::PotentiallyEvaluated); 14139 } 14140 14141 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 14142 Scope *CurScope) { 14143 assert(ParamInfo.getIdentifier() == nullptr && 14144 "block-id should have no identifier!"); 14145 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext); 14146 BlockScopeInfo *CurBlock = getCurBlock(); 14147 14148 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 14149 QualType T = Sig->getType(); 14150 14151 // FIXME: We should allow unexpanded parameter packs here, but that would, 14152 // in turn, make the block expression contain unexpanded parameter packs. 14153 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 14154 // Drop the parameters. 14155 FunctionProtoType::ExtProtoInfo EPI; 14156 EPI.HasTrailingReturn = false; 14157 EPI.TypeQuals.addConst(); 14158 T = Context.getFunctionType(Context.DependentTy, None, EPI); 14159 Sig = Context.getTrivialTypeSourceInfo(T); 14160 } 14161 14162 // GetTypeForDeclarator always produces a function type for a block 14163 // literal signature. Furthermore, it is always a FunctionProtoType 14164 // unless the function was written with a typedef. 14165 assert(T->isFunctionType() && 14166 "GetTypeForDeclarator made a non-function block signature"); 14167 14168 // Look for an explicit signature in that function type. 14169 FunctionProtoTypeLoc ExplicitSignature; 14170 14171 if ((ExplicitSignature = Sig->getTypeLoc() 14172 .getAsAdjusted<FunctionProtoTypeLoc>())) { 14173 14174 // Check whether that explicit signature was synthesized by 14175 // GetTypeForDeclarator. If so, don't save that as part of the 14176 // written signature. 14177 if (ExplicitSignature.getLocalRangeBegin() == 14178 ExplicitSignature.getLocalRangeEnd()) { 14179 // This would be much cheaper if we stored TypeLocs instead of 14180 // TypeSourceInfos. 14181 TypeLoc Result = ExplicitSignature.getReturnLoc(); 14182 unsigned Size = Result.getFullDataSize(); 14183 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 14184 Sig->getTypeLoc().initializeFullCopy(Result, Size); 14185 14186 ExplicitSignature = FunctionProtoTypeLoc(); 14187 } 14188 } 14189 14190 CurBlock->TheDecl->setSignatureAsWritten(Sig); 14191 CurBlock->FunctionType = T; 14192 14193 const FunctionType *Fn = T->getAs<FunctionType>(); 14194 QualType RetTy = Fn->getReturnType(); 14195 bool isVariadic = 14196 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 14197 14198 CurBlock->TheDecl->setIsVariadic(isVariadic); 14199 14200 // Context.DependentTy is used as a placeholder for a missing block 14201 // return type. TODO: what should we do with declarators like: 14202 // ^ * { ... } 14203 // If the answer is "apply template argument deduction".... 14204 if (RetTy != Context.DependentTy) { 14205 CurBlock->ReturnType = RetTy; 14206 CurBlock->TheDecl->setBlockMissingReturnType(false); 14207 CurBlock->HasImplicitReturnType = false; 14208 } 14209 14210 // Push block parameters from the declarator if we had them. 14211 SmallVector<ParmVarDecl*, 8> Params; 14212 if (ExplicitSignature) { 14213 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 14214 ParmVarDecl *Param = ExplicitSignature.getParam(I); 14215 if (Param->getIdentifier() == nullptr && 14216 !Param->isImplicit() && 14217 !Param->isInvalidDecl() && 14218 !getLangOpts().CPlusPlus) 14219 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 14220 Params.push_back(Param); 14221 } 14222 14223 // Fake up parameter variables if we have a typedef, like 14224 // ^ fntype { ... } 14225 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 14226 for (const auto &I : Fn->param_types()) { 14227 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 14228 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 14229 Params.push_back(Param); 14230 } 14231 } 14232 14233 // Set the parameters on the block decl. 14234 if (!Params.empty()) { 14235 CurBlock->TheDecl->setParams(Params); 14236 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 14237 /*CheckParameterNames=*/false); 14238 } 14239 14240 // Finally we can process decl attributes. 14241 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 14242 14243 // Put the parameter variables in scope. 14244 for (auto AI : CurBlock->TheDecl->parameters()) { 14245 AI->setOwningFunction(CurBlock->TheDecl); 14246 14247 // If this has an identifier, add it to the scope stack. 14248 if (AI->getIdentifier()) { 14249 CheckShadow(CurBlock->TheScope, AI); 14250 14251 PushOnScopeChains(AI, CurBlock->TheScope); 14252 } 14253 } 14254 } 14255 14256 /// ActOnBlockError - If there is an error parsing a block, this callback 14257 /// is invoked to pop the information about the block from the action impl. 14258 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 14259 // Leave the expression-evaluation context. 14260 DiscardCleanupsInEvaluationContext(); 14261 PopExpressionEvaluationContext(); 14262 14263 // Pop off CurBlock, handle nested blocks. 14264 PopDeclContext(); 14265 PopFunctionScopeInfo(); 14266 } 14267 14268 /// ActOnBlockStmtExpr - This is called when the body of a block statement 14269 /// literal was successfully completed. ^(int x){...} 14270 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 14271 Stmt *Body, Scope *CurScope) { 14272 // If blocks are disabled, emit an error. 14273 if (!LangOpts.Blocks) 14274 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 14275 14276 // Leave the expression-evaluation context. 14277 if (hasAnyUnrecoverableErrorsInThisFunction()) 14278 DiscardCleanupsInEvaluationContext(); 14279 assert(!Cleanup.exprNeedsCleanups() && 14280 "cleanups within block not correctly bound!"); 14281 PopExpressionEvaluationContext(); 14282 14283 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 14284 BlockDecl *BD = BSI->TheDecl; 14285 14286 if (BSI->HasImplicitReturnType) 14287 deduceClosureReturnType(*BSI); 14288 14289 QualType RetTy = Context.VoidTy; 14290 if (!BSI->ReturnType.isNull()) 14291 RetTy = BSI->ReturnType; 14292 14293 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 14294 QualType BlockTy; 14295 14296 // If the user wrote a function type in some form, try to use that. 14297 if (!BSI->FunctionType.isNull()) { 14298 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 14299 14300 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 14301 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 14302 14303 // Turn protoless block types into nullary block types. 14304 if (isa<FunctionNoProtoType>(FTy)) { 14305 FunctionProtoType::ExtProtoInfo EPI; 14306 EPI.ExtInfo = Ext; 14307 BlockTy = Context.getFunctionType(RetTy, None, EPI); 14308 14309 // Otherwise, if we don't need to change anything about the function type, 14310 // preserve its sugar structure. 14311 } else if (FTy->getReturnType() == RetTy && 14312 (!NoReturn || FTy->getNoReturnAttr())) { 14313 BlockTy = BSI->FunctionType; 14314 14315 // Otherwise, make the minimal modifications to the function type. 14316 } else { 14317 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 14318 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 14319 EPI.TypeQuals = Qualifiers(); 14320 EPI.ExtInfo = Ext; 14321 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 14322 } 14323 14324 // If we don't have a function type, just build one from nothing. 14325 } else { 14326 FunctionProtoType::ExtProtoInfo EPI; 14327 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 14328 BlockTy = Context.getFunctionType(RetTy, None, EPI); 14329 } 14330 14331 DiagnoseUnusedParameters(BD->parameters()); 14332 BlockTy = Context.getBlockPointerType(BlockTy); 14333 14334 // If needed, diagnose invalid gotos and switches in the block. 14335 if (getCurFunction()->NeedsScopeChecking() && 14336 !PP.isCodeCompletionEnabled()) 14337 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 14338 14339 BD->setBody(cast<CompoundStmt>(Body)); 14340 14341 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 14342 DiagnoseUnguardedAvailabilityViolations(BD); 14343 14344 // Try to apply the named return value optimization. We have to check again 14345 // if we can do this, though, because blocks keep return statements around 14346 // to deduce an implicit return type. 14347 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 14348 !BD->isDependentContext()) 14349 computeNRVO(Body, BSI); 14350 14351 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 14352 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 14353 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 14354 NTCUK_Destruct|NTCUK_Copy); 14355 14356 PopDeclContext(); 14357 14358 // Pop the block scope now but keep it alive to the end of this function. 14359 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14360 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 14361 14362 // Set the captured variables on the block. 14363 SmallVector<BlockDecl::Capture, 4> Captures; 14364 for (Capture &Cap : BSI->Captures) { 14365 if (Cap.isInvalid() || Cap.isThisCapture()) 14366 continue; 14367 14368 VarDecl *Var = Cap.getVariable(); 14369 Expr *CopyExpr = nullptr; 14370 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 14371 if (const RecordType *Record = 14372 Cap.getCaptureType()->getAs<RecordType>()) { 14373 // The capture logic needs the destructor, so make sure we mark it. 14374 // Usually this is unnecessary because most local variables have 14375 // their destructors marked at declaration time, but parameters are 14376 // an exception because it's technically only the call site that 14377 // actually requires the destructor. 14378 if (isa<ParmVarDecl>(Var)) 14379 FinalizeVarWithDestructor(Var, Record); 14380 14381 // Enter a separate potentially-evaluated context while building block 14382 // initializers to isolate their cleanups from those of the block 14383 // itself. 14384 // FIXME: Is this appropriate even when the block itself occurs in an 14385 // unevaluated operand? 14386 EnterExpressionEvaluationContext EvalContext( 14387 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 14388 14389 SourceLocation Loc = Cap.getLocation(); 14390 14391 ExprResult Result = BuildDeclarationNameExpr( 14392 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 14393 14394 // According to the blocks spec, the capture of a variable from 14395 // the stack requires a const copy constructor. This is not true 14396 // of the copy/move done to move a __block variable to the heap. 14397 if (!Result.isInvalid() && 14398 !Result.get()->getType().isConstQualified()) { 14399 Result = ImpCastExprToType(Result.get(), 14400 Result.get()->getType().withConst(), 14401 CK_NoOp, VK_LValue); 14402 } 14403 14404 if (!Result.isInvalid()) { 14405 Result = PerformCopyInitialization( 14406 InitializedEntity::InitializeBlock(Var->getLocation(), 14407 Cap.getCaptureType(), false), 14408 Loc, Result.get()); 14409 } 14410 14411 // Build a full-expression copy expression if initialization 14412 // succeeded and used a non-trivial constructor. Recover from 14413 // errors by pretending that the copy isn't necessary. 14414 if (!Result.isInvalid() && 14415 !cast<CXXConstructExpr>(Result.get())->getConstructor() 14416 ->isTrivial()) { 14417 Result = MaybeCreateExprWithCleanups(Result); 14418 CopyExpr = Result.get(); 14419 } 14420 } 14421 } 14422 14423 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 14424 CopyExpr); 14425 Captures.push_back(NewCap); 14426 } 14427 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 14428 14429 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 14430 14431 // If the block isn't obviously global, i.e. it captures anything at 14432 // all, then we need to do a few things in the surrounding context: 14433 if (Result->getBlockDecl()->hasCaptures()) { 14434 // First, this expression has a new cleanup object. 14435 ExprCleanupObjects.push_back(Result->getBlockDecl()); 14436 Cleanup.setExprNeedsCleanups(true); 14437 14438 // It also gets a branch-protected scope if any of the captured 14439 // variables needs destruction. 14440 for (const auto &CI : Result->getBlockDecl()->captures()) { 14441 const VarDecl *var = CI.getVariable(); 14442 if (var->getType().isDestructedType() != QualType::DK_none) { 14443 setFunctionHasBranchProtectedScope(); 14444 break; 14445 } 14446 } 14447 } 14448 14449 if (getCurFunction()) 14450 getCurFunction()->addBlock(BD); 14451 14452 return Result; 14453 } 14454 14455 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 14456 SourceLocation RPLoc) { 14457 TypeSourceInfo *TInfo; 14458 GetTypeFromParser(Ty, &TInfo); 14459 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 14460 } 14461 14462 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 14463 Expr *E, TypeSourceInfo *TInfo, 14464 SourceLocation RPLoc) { 14465 Expr *OrigExpr = E; 14466 bool IsMS = false; 14467 14468 // CUDA device code does not support varargs. 14469 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 14470 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 14471 CUDAFunctionTarget T = IdentifyCUDATarget(F); 14472 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 14473 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 14474 } 14475 } 14476 14477 // NVPTX does not support va_arg expression. 14478 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 14479 Context.getTargetInfo().getTriple().isNVPTX()) 14480 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 14481 14482 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 14483 // as Microsoft ABI on an actual Microsoft platform, where 14484 // __builtin_ms_va_list and __builtin_va_list are the same.) 14485 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 14486 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 14487 QualType MSVaListType = Context.getBuiltinMSVaListType(); 14488 if (Context.hasSameType(MSVaListType, E->getType())) { 14489 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 14490 return ExprError(); 14491 IsMS = true; 14492 } 14493 } 14494 14495 // Get the va_list type 14496 QualType VaListType = Context.getBuiltinVaListType(); 14497 if (!IsMS) { 14498 if (VaListType->isArrayType()) { 14499 // Deal with implicit array decay; for example, on x86-64, 14500 // va_list is an array, but it's supposed to decay to 14501 // a pointer for va_arg. 14502 VaListType = Context.getArrayDecayedType(VaListType); 14503 // Make sure the input expression also decays appropriately. 14504 ExprResult Result = UsualUnaryConversions(E); 14505 if (Result.isInvalid()) 14506 return ExprError(); 14507 E = Result.get(); 14508 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 14509 // If va_list is a record type and we are compiling in C++ mode, 14510 // check the argument using reference binding. 14511 InitializedEntity Entity = InitializedEntity::InitializeParameter( 14512 Context, Context.getLValueReferenceType(VaListType), false); 14513 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 14514 if (Init.isInvalid()) 14515 return ExprError(); 14516 E = Init.getAs<Expr>(); 14517 } else { 14518 // Otherwise, the va_list argument must be an l-value because 14519 // it is modified by va_arg. 14520 if (!E->isTypeDependent() && 14521 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 14522 return ExprError(); 14523 } 14524 } 14525 14526 if (!IsMS && !E->isTypeDependent() && 14527 !Context.hasSameType(VaListType, E->getType())) 14528 return ExprError( 14529 Diag(E->getBeginLoc(), 14530 diag::err_first_argument_to_va_arg_not_of_type_va_list) 14531 << OrigExpr->getType() << E->getSourceRange()); 14532 14533 if (!TInfo->getType()->isDependentType()) { 14534 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 14535 diag::err_second_parameter_to_va_arg_incomplete, 14536 TInfo->getTypeLoc())) 14537 return ExprError(); 14538 14539 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 14540 TInfo->getType(), 14541 diag::err_second_parameter_to_va_arg_abstract, 14542 TInfo->getTypeLoc())) 14543 return ExprError(); 14544 14545 if (!TInfo->getType().isPODType(Context)) { 14546 Diag(TInfo->getTypeLoc().getBeginLoc(), 14547 TInfo->getType()->isObjCLifetimeType() 14548 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 14549 : diag::warn_second_parameter_to_va_arg_not_pod) 14550 << TInfo->getType() 14551 << TInfo->getTypeLoc().getSourceRange(); 14552 } 14553 14554 // Check for va_arg where arguments of the given type will be promoted 14555 // (i.e. this va_arg is guaranteed to have undefined behavior). 14556 QualType PromoteType; 14557 if (TInfo->getType()->isPromotableIntegerType()) { 14558 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 14559 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 14560 PromoteType = QualType(); 14561 } 14562 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 14563 PromoteType = Context.DoubleTy; 14564 if (!PromoteType.isNull()) 14565 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 14566 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 14567 << TInfo->getType() 14568 << PromoteType 14569 << TInfo->getTypeLoc().getSourceRange()); 14570 } 14571 14572 QualType T = TInfo->getType().getNonLValueExprType(Context); 14573 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 14574 } 14575 14576 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 14577 // The type of __null will be int or long, depending on the size of 14578 // pointers on the target. 14579 QualType Ty; 14580 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 14581 if (pw == Context.getTargetInfo().getIntWidth()) 14582 Ty = Context.IntTy; 14583 else if (pw == Context.getTargetInfo().getLongWidth()) 14584 Ty = Context.LongTy; 14585 else if (pw == Context.getTargetInfo().getLongLongWidth()) 14586 Ty = Context.LongLongTy; 14587 else { 14588 llvm_unreachable("I don't know size of pointer!"); 14589 } 14590 14591 return new (Context) GNUNullExpr(Ty, TokenLoc); 14592 } 14593 14594 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 14595 SourceLocation BuiltinLoc, 14596 SourceLocation RPLoc) { 14597 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); 14598 } 14599 14600 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 14601 SourceLocation BuiltinLoc, 14602 SourceLocation RPLoc, 14603 DeclContext *ParentContext) { 14604 return new (Context) 14605 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); 14606 } 14607 14608 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 14609 bool Diagnose) { 14610 if (!getLangOpts().ObjC) 14611 return false; 14612 14613 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 14614 if (!PT) 14615 return false; 14616 14617 if (!PT->isObjCIdType()) { 14618 // Check if the destination is the 'NSString' interface. 14619 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 14620 if (!ID || !ID->getIdentifier()->isStr("NSString")) 14621 return false; 14622 } 14623 14624 // Ignore any parens, implicit casts (should only be 14625 // array-to-pointer decays), and not-so-opaque values. The last is 14626 // important for making this trigger for property assignments. 14627 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 14628 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 14629 if (OV->getSourceExpr()) 14630 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 14631 14632 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 14633 if (!SL || !SL->isAscii()) 14634 return false; 14635 if (Diagnose) { 14636 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 14637 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 14638 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 14639 } 14640 return true; 14641 } 14642 14643 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 14644 const Expr *SrcExpr) { 14645 if (!DstType->isFunctionPointerType() || 14646 !SrcExpr->getType()->isFunctionType()) 14647 return false; 14648 14649 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 14650 if (!DRE) 14651 return false; 14652 14653 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 14654 if (!FD) 14655 return false; 14656 14657 return !S.checkAddressOfFunctionIsAvailable(FD, 14658 /*Complain=*/true, 14659 SrcExpr->getBeginLoc()); 14660 } 14661 14662 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 14663 SourceLocation Loc, 14664 QualType DstType, QualType SrcType, 14665 Expr *SrcExpr, AssignmentAction Action, 14666 bool *Complained) { 14667 if (Complained) 14668 *Complained = false; 14669 14670 // Decode the result (notice that AST's are still created for extensions). 14671 bool CheckInferredResultType = false; 14672 bool isInvalid = false; 14673 unsigned DiagKind = 0; 14674 FixItHint Hint; 14675 ConversionFixItGenerator ConvHints; 14676 bool MayHaveConvFixit = false; 14677 bool MayHaveFunctionDiff = false; 14678 const ObjCInterfaceDecl *IFace = nullptr; 14679 const ObjCProtocolDecl *PDecl = nullptr; 14680 14681 switch (ConvTy) { 14682 case Compatible: 14683 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 14684 return false; 14685 14686 case PointerToInt: 14687 DiagKind = diag::ext_typecheck_convert_pointer_int; 14688 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14689 MayHaveConvFixit = true; 14690 break; 14691 case IntToPointer: 14692 DiagKind = diag::ext_typecheck_convert_int_pointer; 14693 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14694 MayHaveConvFixit = true; 14695 break; 14696 case IncompatiblePointer: 14697 if (Action == AA_Passing_CFAudited) 14698 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 14699 else if (SrcType->isFunctionPointerType() && 14700 DstType->isFunctionPointerType()) 14701 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 14702 else 14703 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 14704 14705 CheckInferredResultType = DstType->isObjCObjectPointerType() && 14706 SrcType->isObjCObjectPointerType(); 14707 if (Hint.isNull() && !CheckInferredResultType) { 14708 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14709 } 14710 else if (CheckInferredResultType) { 14711 SrcType = SrcType.getUnqualifiedType(); 14712 DstType = DstType.getUnqualifiedType(); 14713 } 14714 MayHaveConvFixit = true; 14715 break; 14716 case IncompatiblePointerSign: 14717 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 14718 break; 14719 case FunctionVoidPointer: 14720 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 14721 break; 14722 case IncompatiblePointerDiscardsQualifiers: { 14723 // Perform array-to-pointer decay if necessary. 14724 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 14725 14726 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 14727 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 14728 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 14729 DiagKind = diag::err_typecheck_incompatible_address_space; 14730 break; 14731 14732 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 14733 DiagKind = diag::err_typecheck_incompatible_ownership; 14734 break; 14735 } 14736 14737 llvm_unreachable("unknown error case for discarding qualifiers!"); 14738 // fallthrough 14739 } 14740 case CompatiblePointerDiscardsQualifiers: 14741 // If the qualifiers lost were because we were applying the 14742 // (deprecated) C++ conversion from a string literal to a char* 14743 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 14744 // Ideally, this check would be performed in 14745 // checkPointerTypesForAssignment. However, that would require a 14746 // bit of refactoring (so that the second argument is an 14747 // expression, rather than a type), which should be done as part 14748 // of a larger effort to fix checkPointerTypesForAssignment for 14749 // C++ semantics. 14750 if (getLangOpts().CPlusPlus && 14751 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 14752 return false; 14753 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 14754 break; 14755 case IncompatibleNestedPointerQualifiers: 14756 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 14757 break; 14758 case IncompatibleNestedPointerAddressSpaceMismatch: 14759 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 14760 break; 14761 case IntToBlockPointer: 14762 DiagKind = diag::err_int_to_block_pointer; 14763 break; 14764 case IncompatibleBlockPointer: 14765 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 14766 break; 14767 case IncompatibleObjCQualifiedId: { 14768 if (SrcType->isObjCQualifiedIdType()) { 14769 const ObjCObjectPointerType *srcOPT = 14770 SrcType->castAs<ObjCObjectPointerType>(); 14771 for (auto *srcProto : srcOPT->quals()) { 14772 PDecl = srcProto; 14773 break; 14774 } 14775 if (const ObjCInterfaceType *IFaceT = 14776 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 14777 IFace = IFaceT->getDecl(); 14778 } 14779 else if (DstType->isObjCQualifiedIdType()) { 14780 const ObjCObjectPointerType *dstOPT = 14781 DstType->castAs<ObjCObjectPointerType>(); 14782 for (auto *dstProto : dstOPT->quals()) { 14783 PDecl = dstProto; 14784 break; 14785 } 14786 if (const ObjCInterfaceType *IFaceT = 14787 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 14788 IFace = IFaceT->getDecl(); 14789 } 14790 DiagKind = diag::warn_incompatible_qualified_id; 14791 break; 14792 } 14793 case IncompatibleVectors: 14794 DiagKind = diag::warn_incompatible_vectors; 14795 break; 14796 case IncompatibleObjCWeakRef: 14797 DiagKind = diag::err_arc_weak_unavailable_assign; 14798 break; 14799 case Incompatible: 14800 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 14801 if (Complained) 14802 *Complained = true; 14803 return true; 14804 } 14805 14806 DiagKind = diag::err_typecheck_convert_incompatible; 14807 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14808 MayHaveConvFixit = true; 14809 isInvalid = true; 14810 MayHaveFunctionDiff = true; 14811 break; 14812 } 14813 14814 QualType FirstType, SecondType; 14815 switch (Action) { 14816 case AA_Assigning: 14817 case AA_Initializing: 14818 // The destination type comes first. 14819 FirstType = DstType; 14820 SecondType = SrcType; 14821 break; 14822 14823 case AA_Returning: 14824 case AA_Passing: 14825 case AA_Passing_CFAudited: 14826 case AA_Converting: 14827 case AA_Sending: 14828 case AA_Casting: 14829 // The source type comes first. 14830 FirstType = SrcType; 14831 SecondType = DstType; 14832 break; 14833 } 14834 14835 PartialDiagnostic FDiag = PDiag(DiagKind); 14836 if (Action == AA_Passing_CFAudited) 14837 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 14838 else 14839 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 14840 14841 // If we can fix the conversion, suggest the FixIts. 14842 assert(ConvHints.isNull() || Hint.isNull()); 14843 if (!ConvHints.isNull()) { 14844 for (FixItHint &H : ConvHints.Hints) 14845 FDiag << H; 14846 } else { 14847 FDiag << Hint; 14848 } 14849 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 14850 14851 if (MayHaveFunctionDiff) 14852 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 14853 14854 Diag(Loc, FDiag); 14855 if (DiagKind == diag::warn_incompatible_qualified_id && 14856 PDecl && IFace && !IFace->hasDefinition()) 14857 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 14858 << IFace << PDecl; 14859 14860 if (SecondType == Context.OverloadTy) 14861 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 14862 FirstType, /*TakingAddress=*/true); 14863 14864 if (CheckInferredResultType) 14865 EmitRelatedResultTypeNote(SrcExpr); 14866 14867 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 14868 EmitRelatedResultTypeNoteForReturn(DstType); 14869 14870 if (Complained) 14871 *Complained = true; 14872 return isInvalid; 14873 } 14874 14875 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 14876 llvm::APSInt *Result) { 14877 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 14878 public: 14879 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 14880 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 14881 } 14882 } Diagnoser; 14883 14884 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 14885 } 14886 14887 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 14888 llvm::APSInt *Result, 14889 unsigned DiagID, 14890 bool AllowFold) { 14891 class IDDiagnoser : public VerifyICEDiagnoser { 14892 unsigned DiagID; 14893 14894 public: 14895 IDDiagnoser(unsigned DiagID) 14896 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 14897 14898 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 14899 S.Diag(Loc, DiagID) << SR; 14900 } 14901 } Diagnoser(DiagID); 14902 14903 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 14904 } 14905 14906 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 14907 SourceRange SR) { 14908 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 14909 } 14910 14911 ExprResult 14912 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 14913 VerifyICEDiagnoser &Diagnoser, 14914 bool AllowFold) { 14915 SourceLocation DiagLoc = E->getBeginLoc(); 14916 14917 if (getLangOpts().CPlusPlus11) { 14918 // C++11 [expr.const]p5: 14919 // If an expression of literal class type is used in a context where an 14920 // integral constant expression is required, then that class type shall 14921 // have a single non-explicit conversion function to an integral or 14922 // unscoped enumeration type 14923 ExprResult Converted; 14924 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 14925 public: 14926 CXX11ConvertDiagnoser(bool Silent) 14927 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 14928 Silent, true) {} 14929 14930 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 14931 QualType T) override { 14932 return S.Diag(Loc, diag::err_ice_not_integral) << T; 14933 } 14934 14935 SemaDiagnosticBuilder diagnoseIncomplete( 14936 Sema &S, SourceLocation Loc, QualType T) override { 14937 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 14938 } 14939 14940 SemaDiagnosticBuilder diagnoseExplicitConv( 14941 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 14942 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 14943 } 14944 14945 SemaDiagnosticBuilder noteExplicitConv( 14946 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 14947 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 14948 << ConvTy->isEnumeralType() << ConvTy; 14949 } 14950 14951 SemaDiagnosticBuilder diagnoseAmbiguous( 14952 Sema &S, SourceLocation Loc, QualType T) override { 14953 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 14954 } 14955 14956 SemaDiagnosticBuilder noteAmbiguous( 14957 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 14958 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 14959 << ConvTy->isEnumeralType() << ConvTy; 14960 } 14961 14962 SemaDiagnosticBuilder diagnoseConversion( 14963 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 14964 llvm_unreachable("conversion functions are permitted"); 14965 } 14966 } ConvertDiagnoser(Diagnoser.Suppress); 14967 14968 Converted = PerformContextualImplicitConversion(DiagLoc, E, 14969 ConvertDiagnoser); 14970 if (Converted.isInvalid()) 14971 return Converted; 14972 E = Converted.get(); 14973 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 14974 return ExprError(); 14975 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 14976 // An ICE must be of integral or unscoped enumeration type. 14977 if (!Diagnoser.Suppress) 14978 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 14979 return ExprError(); 14980 } 14981 14982 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 14983 // in the non-ICE case. 14984 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 14985 if (Result) 14986 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 14987 if (!isa<ConstantExpr>(E)) 14988 E = ConstantExpr::Create(Context, E); 14989 return E; 14990 } 14991 14992 Expr::EvalResult EvalResult; 14993 SmallVector<PartialDiagnosticAt, 8> Notes; 14994 EvalResult.Diag = &Notes; 14995 14996 // Try to evaluate the expression, and produce diagnostics explaining why it's 14997 // not a constant expression as a side-effect. 14998 bool Folded = 14999 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 15000 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 15001 15002 if (!isa<ConstantExpr>(E)) 15003 E = ConstantExpr::Create(Context, E, EvalResult.Val); 15004 15005 // In C++11, we can rely on diagnostics being produced for any expression 15006 // which is not a constant expression. If no diagnostics were produced, then 15007 // this is a constant expression. 15008 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 15009 if (Result) 15010 *Result = EvalResult.Val.getInt(); 15011 return E; 15012 } 15013 15014 // If our only note is the usual "invalid subexpression" note, just point 15015 // the caret at its location rather than producing an essentially 15016 // redundant note. 15017 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 15018 diag::note_invalid_subexpr_in_const_expr) { 15019 DiagLoc = Notes[0].first; 15020 Notes.clear(); 15021 } 15022 15023 if (!Folded || !AllowFold) { 15024 if (!Diagnoser.Suppress) { 15025 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 15026 for (const PartialDiagnosticAt &Note : Notes) 15027 Diag(Note.first, Note.second); 15028 } 15029 15030 return ExprError(); 15031 } 15032 15033 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 15034 for (const PartialDiagnosticAt &Note : Notes) 15035 Diag(Note.first, Note.second); 15036 15037 if (Result) 15038 *Result = EvalResult.Val.getInt(); 15039 return E; 15040 } 15041 15042 namespace { 15043 // Handle the case where we conclude a expression which we speculatively 15044 // considered to be unevaluated is actually evaluated. 15045 class TransformToPE : public TreeTransform<TransformToPE> { 15046 typedef TreeTransform<TransformToPE> BaseTransform; 15047 15048 public: 15049 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 15050 15051 // Make sure we redo semantic analysis 15052 bool AlwaysRebuild() { return true; } 15053 bool ReplacingOriginal() { return true; } 15054 15055 // We need to special-case DeclRefExprs referring to FieldDecls which 15056 // are not part of a member pointer formation; normal TreeTransforming 15057 // doesn't catch this case because of the way we represent them in the AST. 15058 // FIXME: This is a bit ugly; is it really the best way to handle this 15059 // case? 15060 // 15061 // Error on DeclRefExprs referring to FieldDecls. 15062 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 15063 if (isa<FieldDecl>(E->getDecl()) && 15064 !SemaRef.isUnevaluatedContext()) 15065 return SemaRef.Diag(E->getLocation(), 15066 diag::err_invalid_non_static_member_use) 15067 << E->getDecl() << E->getSourceRange(); 15068 15069 return BaseTransform::TransformDeclRefExpr(E); 15070 } 15071 15072 // Exception: filter out member pointer formation 15073 ExprResult TransformUnaryOperator(UnaryOperator *E) { 15074 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 15075 return E; 15076 15077 return BaseTransform::TransformUnaryOperator(E); 15078 } 15079 15080 // The body of a lambda-expression is in a separate expression evaluation 15081 // context so never needs to be transformed. 15082 // FIXME: Ideally we wouldn't transform the closure type either, and would 15083 // just recreate the capture expressions and lambda expression. 15084 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 15085 return SkipLambdaBody(E, Body); 15086 } 15087 }; 15088 } 15089 15090 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 15091 assert(isUnevaluatedContext() && 15092 "Should only transform unevaluated expressions"); 15093 ExprEvalContexts.back().Context = 15094 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 15095 if (isUnevaluatedContext()) 15096 return E; 15097 return TransformToPE(*this).TransformExpr(E); 15098 } 15099 15100 void 15101 Sema::PushExpressionEvaluationContext( 15102 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 15103 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 15104 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 15105 LambdaContextDecl, ExprContext); 15106 Cleanup.reset(); 15107 if (!MaybeODRUseExprs.empty()) 15108 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 15109 } 15110 15111 void 15112 Sema::PushExpressionEvaluationContext( 15113 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 15114 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 15115 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 15116 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 15117 } 15118 15119 namespace { 15120 15121 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 15122 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 15123 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 15124 if (E->getOpcode() == UO_Deref) 15125 return CheckPossibleDeref(S, E->getSubExpr()); 15126 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 15127 return CheckPossibleDeref(S, E->getBase()); 15128 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 15129 return CheckPossibleDeref(S, E->getBase()); 15130 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 15131 QualType Inner; 15132 QualType Ty = E->getType(); 15133 if (const auto *Ptr = Ty->getAs<PointerType>()) 15134 Inner = Ptr->getPointeeType(); 15135 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 15136 Inner = Arr->getElementType(); 15137 else 15138 return nullptr; 15139 15140 if (Inner->hasAttr(attr::NoDeref)) 15141 return E; 15142 } 15143 return nullptr; 15144 } 15145 15146 } // namespace 15147 15148 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 15149 for (const Expr *E : Rec.PossibleDerefs) { 15150 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 15151 if (DeclRef) { 15152 const ValueDecl *Decl = DeclRef->getDecl(); 15153 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 15154 << Decl->getName() << E->getSourceRange(); 15155 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 15156 } else { 15157 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 15158 << E->getSourceRange(); 15159 } 15160 } 15161 Rec.PossibleDerefs.clear(); 15162 } 15163 15164 /// Check whether E, which is either a discarded-value expression or an 15165 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 15166 /// and if so, remove it from the list of volatile-qualified assignments that 15167 /// we are going to warn are deprecated. 15168 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 15169 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus2a) 15170 return; 15171 15172 // Note: ignoring parens here is not justified by the standard rules, but 15173 // ignoring parentheses seems like a more reasonable approach, and this only 15174 // drives a deprecation warning so doesn't affect conformance. 15175 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 15176 if (BO->getOpcode() == BO_Assign) { 15177 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 15178 LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()), 15179 LHSs.end()); 15180 } 15181 } 15182 } 15183 15184 void Sema::PopExpressionEvaluationContext() { 15185 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 15186 unsigned NumTypos = Rec.NumTypos; 15187 15188 if (!Rec.Lambdas.empty()) { 15189 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 15190 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() || 15191 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) { 15192 unsigned D; 15193 if (Rec.isUnevaluated()) { 15194 // C++11 [expr.prim.lambda]p2: 15195 // A lambda-expression shall not appear in an unevaluated operand 15196 // (Clause 5). 15197 D = diag::err_lambda_unevaluated_operand; 15198 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 15199 // C++1y [expr.const]p2: 15200 // A conditional-expression e is a core constant expression unless the 15201 // evaluation of e, following the rules of the abstract machine, would 15202 // evaluate [...] a lambda-expression. 15203 D = diag::err_lambda_in_constant_expression; 15204 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 15205 // C++17 [expr.prim.lamda]p2: 15206 // A lambda-expression shall not appear [...] in a template-argument. 15207 D = diag::err_lambda_in_invalid_context; 15208 } else 15209 llvm_unreachable("Couldn't infer lambda error message."); 15210 15211 for (const auto *L : Rec.Lambdas) 15212 Diag(L->getBeginLoc(), D); 15213 } 15214 } 15215 15216 WarnOnPendingNoDerefs(Rec); 15217 15218 // Warn on any volatile-qualified simple-assignments that are not discarded- 15219 // value expressions nor unevaluated operands (those cases get removed from 15220 // this list by CheckUnusedVolatileAssignment). 15221 for (auto *BO : Rec.VolatileAssignmentLHSs) 15222 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 15223 << BO->getType(); 15224 15225 // When are coming out of an unevaluated context, clear out any 15226 // temporaries that we may have created as part of the evaluation of 15227 // the expression in that context: they aren't relevant because they 15228 // will never be constructed. 15229 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 15230 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 15231 ExprCleanupObjects.end()); 15232 Cleanup = Rec.ParentCleanup; 15233 CleanupVarDeclMarking(); 15234 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 15235 // Otherwise, merge the contexts together. 15236 } else { 15237 Cleanup.mergeFrom(Rec.ParentCleanup); 15238 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 15239 Rec.SavedMaybeODRUseExprs.end()); 15240 } 15241 15242 // Pop the current expression evaluation context off the stack. 15243 ExprEvalContexts.pop_back(); 15244 15245 // The global expression evaluation context record is never popped. 15246 ExprEvalContexts.back().NumTypos += NumTypos; 15247 } 15248 15249 void Sema::DiscardCleanupsInEvaluationContext() { 15250 ExprCleanupObjects.erase( 15251 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 15252 ExprCleanupObjects.end()); 15253 Cleanup.reset(); 15254 MaybeODRUseExprs.clear(); 15255 } 15256 15257 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 15258 ExprResult Result = CheckPlaceholderExpr(E); 15259 if (Result.isInvalid()) 15260 return ExprError(); 15261 E = Result.get(); 15262 if (!E->getType()->isVariablyModifiedType()) 15263 return E; 15264 return TransformToPotentiallyEvaluated(E); 15265 } 15266 15267 /// Are we in a context that is potentially constant evaluated per C++20 15268 /// [expr.const]p12? 15269 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 15270 /// C++2a [expr.const]p12: 15271 // An expression or conversion is potentially constant evaluated if it is 15272 switch (SemaRef.ExprEvalContexts.back().Context) { 15273 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 15274 // -- a manifestly constant-evaluated expression, 15275 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 15276 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 15277 case Sema::ExpressionEvaluationContext::DiscardedStatement: 15278 // -- a potentially-evaluated expression, 15279 case Sema::ExpressionEvaluationContext::UnevaluatedList: 15280 // -- an immediate subexpression of a braced-init-list, 15281 15282 // -- [FIXME] an expression of the form & cast-expression that occurs 15283 // within a templated entity 15284 // -- a subexpression of one of the above that is not a subexpression of 15285 // a nested unevaluated operand. 15286 return true; 15287 15288 case Sema::ExpressionEvaluationContext::Unevaluated: 15289 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 15290 // Expressions in this context are never evaluated. 15291 return false; 15292 } 15293 llvm_unreachable("Invalid context"); 15294 } 15295 15296 /// Return true if this function has a calling convention that requires mangling 15297 /// in the size of the parameter pack. 15298 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 15299 // These manglings don't do anything on non-Windows or non-x86 platforms, so 15300 // we don't need parameter type sizes. 15301 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 15302 if (!TT.isOSWindows() || (TT.getArch() != llvm::Triple::x86 && 15303 TT.getArch() != llvm::Triple::x86_64)) 15304 return false; 15305 15306 // If this is C++ and this isn't an extern "C" function, parameters do not 15307 // need to be complete. In this case, C++ mangling will apply, which doesn't 15308 // use the size of the parameters. 15309 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 15310 return false; 15311 15312 // Stdcall, fastcall, and vectorcall need this special treatment. 15313 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 15314 switch (CC) { 15315 case CC_X86StdCall: 15316 case CC_X86FastCall: 15317 case CC_X86VectorCall: 15318 return true; 15319 default: 15320 break; 15321 } 15322 return false; 15323 } 15324 15325 /// Require that all of the parameter types of function be complete. Normally, 15326 /// parameter types are only required to be complete when a function is called 15327 /// or defined, but to mangle functions with certain calling conventions, the 15328 /// mangler needs to know the size of the parameter list. In this situation, 15329 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 15330 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 15331 /// result in a linker error. Clang doesn't implement this behavior, and instead 15332 /// attempts to error at compile time. 15333 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 15334 SourceLocation Loc) { 15335 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 15336 FunctionDecl *FD; 15337 ParmVarDecl *Param; 15338 15339 public: 15340 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 15341 : FD(FD), Param(Param) {} 15342 15343 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 15344 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 15345 StringRef CCName; 15346 switch (CC) { 15347 case CC_X86StdCall: 15348 CCName = "stdcall"; 15349 break; 15350 case CC_X86FastCall: 15351 CCName = "fastcall"; 15352 break; 15353 case CC_X86VectorCall: 15354 CCName = "vectorcall"; 15355 break; 15356 default: 15357 llvm_unreachable("CC does not need mangling"); 15358 } 15359 15360 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 15361 << Param->getDeclName() << FD->getDeclName() << CCName; 15362 } 15363 }; 15364 15365 for (ParmVarDecl *Param : FD->parameters()) { 15366 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 15367 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 15368 } 15369 } 15370 15371 namespace { 15372 enum class OdrUseContext { 15373 /// Declarations in this context are not odr-used. 15374 None, 15375 /// Declarations in this context are formally odr-used, but this is a 15376 /// dependent context. 15377 Dependent, 15378 /// Declarations in this context are odr-used but not actually used (yet). 15379 FormallyOdrUsed, 15380 /// Declarations in this context are used. 15381 Used 15382 }; 15383 } 15384 15385 /// Are we within a context in which references to resolved functions or to 15386 /// variables result in odr-use? 15387 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 15388 OdrUseContext Result; 15389 15390 switch (SemaRef.ExprEvalContexts.back().Context) { 15391 case Sema::ExpressionEvaluationContext::Unevaluated: 15392 case Sema::ExpressionEvaluationContext::UnevaluatedList: 15393 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 15394 return OdrUseContext::None; 15395 15396 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 15397 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 15398 Result = OdrUseContext::Used; 15399 break; 15400 15401 case Sema::ExpressionEvaluationContext::DiscardedStatement: 15402 Result = OdrUseContext::FormallyOdrUsed; 15403 break; 15404 15405 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 15406 // A default argument formally results in odr-use, but doesn't actually 15407 // result in a use in any real sense until it itself is used. 15408 Result = OdrUseContext::FormallyOdrUsed; 15409 break; 15410 } 15411 15412 if (SemaRef.CurContext->isDependentContext()) 15413 return OdrUseContext::Dependent; 15414 15415 return Result; 15416 } 15417 15418 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 15419 return Func->isConstexpr() && 15420 (Func->isImplicitlyInstantiable() || !Func->isUserProvided()); 15421 } 15422 15423 /// Mark a function referenced, and check whether it is odr-used 15424 /// (C++ [basic.def.odr]p2, C99 6.9p3) 15425 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 15426 bool MightBeOdrUse) { 15427 assert(Func && "No function?"); 15428 15429 Func->setReferenced(); 15430 15431 // Recursive functions aren't really used until they're used from some other 15432 // context. 15433 bool IsRecursiveCall = CurContext == Func; 15434 15435 // C++11 [basic.def.odr]p3: 15436 // A function whose name appears as a potentially-evaluated expression is 15437 // odr-used if it is the unique lookup result or the selected member of a 15438 // set of overloaded functions [...]. 15439 // 15440 // We (incorrectly) mark overload resolution as an unevaluated context, so we 15441 // can just check that here. 15442 OdrUseContext OdrUse = 15443 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 15444 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 15445 OdrUse = OdrUseContext::FormallyOdrUsed; 15446 15447 // Trivial default constructors and destructors are never actually used. 15448 // FIXME: What about other special members? 15449 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 15450 OdrUse == OdrUseContext::Used) { 15451 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 15452 if (Constructor->isDefaultConstructor()) 15453 OdrUse = OdrUseContext::FormallyOdrUsed; 15454 if (isa<CXXDestructorDecl>(Func)) 15455 OdrUse = OdrUseContext::FormallyOdrUsed; 15456 } 15457 15458 // C++20 [expr.const]p12: 15459 // A function [...] is needed for constant evaluation if it is [...] a 15460 // constexpr function that is named by an expression that is potentially 15461 // constant evaluated 15462 bool NeededForConstantEvaluation = 15463 isPotentiallyConstantEvaluatedContext(*this) && 15464 isImplicitlyDefinableConstexprFunction(Func); 15465 15466 // Determine whether we require a function definition to exist, per 15467 // C++11 [temp.inst]p3: 15468 // Unless a function template specialization has been explicitly 15469 // instantiated or explicitly specialized, the function template 15470 // specialization is implicitly instantiated when the specialization is 15471 // referenced in a context that requires a function definition to exist. 15472 // C++20 [temp.inst]p7: 15473 // The existence of a definition of a [...] function is considered to 15474 // affect the semantics of the program if the [...] function is needed for 15475 // constant evaluation by an expression 15476 // C++20 [basic.def.odr]p10: 15477 // Every program shall contain exactly one definition of every non-inline 15478 // function or variable that is odr-used in that program outside of a 15479 // discarded statement 15480 // C++20 [special]p1: 15481 // The implementation will implicitly define [defaulted special members] 15482 // if they are odr-used or needed for constant evaluation. 15483 // 15484 // Note that we skip the implicit instantiation of templates that are only 15485 // used in unused default arguments or by recursive calls to themselves. 15486 // This is formally non-conforming, but seems reasonable in practice. 15487 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 15488 NeededForConstantEvaluation); 15489 15490 // C++14 [temp.expl.spec]p6: 15491 // If a template [...] is explicitly specialized then that specialization 15492 // shall be declared before the first use of that specialization that would 15493 // cause an implicit instantiation to take place, in every translation unit 15494 // in which such a use occurs 15495 if (NeedDefinition && 15496 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 15497 Func->getMemberSpecializationInfo())) 15498 checkSpecializationVisibility(Loc, Func); 15499 15500 // C++14 [except.spec]p17: 15501 // An exception-specification is considered to be needed when: 15502 // - the function is odr-used or, if it appears in an unevaluated operand, 15503 // would be odr-used if the expression were potentially-evaluated; 15504 // 15505 // Note, we do this even if MightBeOdrUse is false. That indicates that the 15506 // function is a pure virtual function we're calling, and in that case the 15507 // function was selected by overload resolution and we need to resolve its 15508 // exception specification for a different reason. 15509 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 15510 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 15511 ResolveExceptionSpec(Loc, FPT); 15512 15513 if (getLangOpts().CUDA) 15514 CheckCUDACall(Loc, Func); 15515 15516 // If we need a definition, try to create one. 15517 if (NeedDefinition && !Func->getBody()) { 15518 runWithSufficientStackSpace(Loc, [&] { 15519 if (CXXConstructorDecl *Constructor = 15520 dyn_cast<CXXConstructorDecl>(Func)) { 15521 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 15522 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 15523 if (Constructor->isDefaultConstructor()) { 15524 if (Constructor->isTrivial() && 15525 !Constructor->hasAttr<DLLExportAttr>()) 15526 return; 15527 DefineImplicitDefaultConstructor(Loc, Constructor); 15528 } else if (Constructor->isCopyConstructor()) { 15529 DefineImplicitCopyConstructor(Loc, Constructor); 15530 } else if (Constructor->isMoveConstructor()) { 15531 DefineImplicitMoveConstructor(Loc, Constructor); 15532 } 15533 } else if (Constructor->getInheritedConstructor()) { 15534 DefineInheritingConstructor(Loc, Constructor); 15535 } 15536 } else if (CXXDestructorDecl *Destructor = 15537 dyn_cast<CXXDestructorDecl>(Func)) { 15538 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 15539 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 15540 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 15541 return; 15542 DefineImplicitDestructor(Loc, Destructor); 15543 } 15544 if (Destructor->isVirtual() && getLangOpts().AppleKext) 15545 MarkVTableUsed(Loc, Destructor->getParent()); 15546 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 15547 if (MethodDecl->isOverloadedOperator() && 15548 MethodDecl->getOverloadedOperator() == OO_Equal) { 15549 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 15550 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 15551 if (MethodDecl->isCopyAssignmentOperator()) 15552 DefineImplicitCopyAssignment(Loc, MethodDecl); 15553 else if (MethodDecl->isMoveAssignmentOperator()) 15554 DefineImplicitMoveAssignment(Loc, MethodDecl); 15555 } 15556 } else if (isa<CXXConversionDecl>(MethodDecl) && 15557 MethodDecl->getParent()->isLambda()) { 15558 CXXConversionDecl *Conversion = 15559 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 15560 if (Conversion->isLambdaToBlockPointerConversion()) 15561 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 15562 else 15563 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 15564 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 15565 MarkVTableUsed(Loc, MethodDecl->getParent()); 15566 } 15567 15568 if (Func->isDefaulted() && !Func->isDeleted()) { 15569 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); 15570 if (DCK != DefaultedComparisonKind::None) 15571 DefineDefaultedComparison(Loc, Func, DCK); 15572 } 15573 15574 // Implicit instantiation of function templates and member functions of 15575 // class templates. 15576 if (Func->isImplicitlyInstantiable()) { 15577 TemplateSpecializationKind TSK = 15578 Func->getTemplateSpecializationKindForInstantiation(); 15579 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 15580 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 15581 if (FirstInstantiation) { 15582 PointOfInstantiation = Loc; 15583 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 15584 } else if (TSK != TSK_ImplicitInstantiation) { 15585 // Use the point of use as the point of instantiation, instead of the 15586 // point of explicit instantiation (which we track as the actual point 15587 // of instantiation). This gives better backtraces in diagnostics. 15588 PointOfInstantiation = Loc; 15589 } 15590 15591 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 15592 Func->isConstexpr()) { 15593 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 15594 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 15595 CodeSynthesisContexts.size()) 15596 PendingLocalImplicitInstantiations.push_back( 15597 std::make_pair(Func, PointOfInstantiation)); 15598 else if (Func->isConstexpr()) 15599 // Do not defer instantiations of constexpr functions, to avoid the 15600 // expression evaluator needing to call back into Sema if it sees a 15601 // call to such a function. 15602 InstantiateFunctionDefinition(PointOfInstantiation, Func); 15603 else { 15604 Func->setInstantiationIsPending(true); 15605 PendingInstantiations.push_back( 15606 std::make_pair(Func, PointOfInstantiation)); 15607 // Notify the consumer that a function was implicitly instantiated. 15608 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 15609 } 15610 } 15611 } else { 15612 // Walk redefinitions, as some of them may be instantiable. 15613 for (auto i : Func->redecls()) { 15614 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 15615 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 15616 } 15617 } 15618 }); 15619 } 15620 15621 // If this is the first "real" use, act on that. 15622 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 15623 // Keep track of used but undefined functions. 15624 if (!Func->isDefined()) { 15625 if (mightHaveNonExternalLinkage(Func)) 15626 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 15627 else if (Func->getMostRecentDecl()->isInlined() && 15628 !LangOpts.GNUInline && 15629 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 15630 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 15631 else if (isExternalWithNoLinkageType(Func)) 15632 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 15633 } 15634 15635 // Some x86 Windows calling conventions mangle the size of the parameter 15636 // pack into the name. Computing the size of the parameters requires the 15637 // parameter types to be complete. Check that now. 15638 if (funcHasParameterSizeMangling(*this, Func)) 15639 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 15640 15641 Func->markUsed(Context); 15642 } 15643 15644 if (LangOpts.OpenMP) { 15645 markOpenMPDeclareVariantFuncsReferenced(Loc, Func, MightBeOdrUse); 15646 if (LangOpts.OpenMPIsDevice) 15647 checkOpenMPDeviceFunction(Loc, Func); 15648 else 15649 checkOpenMPHostFunction(Loc, Func); 15650 } 15651 } 15652 15653 /// Directly mark a variable odr-used. Given a choice, prefer to use 15654 /// MarkVariableReferenced since it does additional checks and then 15655 /// calls MarkVarDeclODRUsed. 15656 /// If the variable must be captured: 15657 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 15658 /// - else capture it in the DeclContext that maps to the 15659 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 15660 static void 15661 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 15662 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 15663 // Keep track of used but undefined variables. 15664 // FIXME: We shouldn't suppress this warning for static data members. 15665 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 15666 (!Var->isExternallyVisible() || Var->isInline() || 15667 SemaRef.isExternalWithNoLinkageType(Var)) && 15668 !(Var->isStaticDataMember() && Var->hasInit())) { 15669 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 15670 if (old.isInvalid()) 15671 old = Loc; 15672 } 15673 QualType CaptureType, DeclRefType; 15674 if (SemaRef.LangOpts.OpenMP) 15675 SemaRef.tryCaptureOpenMPLambdas(Var); 15676 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 15677 /*EllipsisLoc*/ SourceLocation(), 15678 /*BuildAndDiagnose*/ true, 15679 CaptureType, DeclRefType, 15680 FunctionScopeIndexToStopAt); 15681 15682 Var->markUsed(SemaRef.Context); 15683 } 15684 15685 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 15686 SourceLocation Loc, 15687 unsigned CapturingScopeIndex) { 15688 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 15689 } 15690 15691 static void 15692 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 15693 ValueDecl *var, DeclContext *DC) { 15694 DeclContext *VarDC = var->getDeclContext(); 15695 15696 // If the parameter still belongs to the translation unit, then 15697 // we're actually just using one parameter in the declaration of 15698 // the next. 15699 if (isa<ParmVarDecl>(var) && 15700 isa<TranslationUnitDecl>(VarDC)) 15701 return; 15702 15703 // For C code, don't diagnose about capture if we're not actually in code 15704 // right now; it's impossible to write a non-constant expression outside of 15705 // function context, so we'll get other (more useful) diagnostics later. 15706 // 15707 // For C++, things get a bit more nasty... it would be nice to suppress this 15708 // diagnostic for certain cases like using a local variable in an array bound 15709 // for a member of a local class, but the correct predicate is not obvious. 15710 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 15711 return; 15712 15713 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 15714 unsigned ContextKind = 3; // unknown 15715 if (isa<CXXMethodDecl>(VarDC) && 15716 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 15717 ContextKind = 2; 15718 } else if (isa<FunctionDecl>(VarDC)) { 15719 ContextKind = 0; 15720 } else if (isa<BlockDecl>(VarDC)) { 15721 ContextKind = 1; 15722 } 15723 15724 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 15725 << var << ValueKind << ContextKind << VarDC; 15726 S.Diag(var->getLocation(), diag::note_entity_declared_at) 15727 << var; 15728 15729 // FIXME: Add additional diagnostic info about class etc. which prevents 15730 // capture. 15731 } 15732 15733 15734 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 15735 bool &SubCapturesAreNested, 15736 QualType &CaptureType, 15737 QualType &DeclRefType) { 15738 // Check whether we've already captured it. 15739 if (CSI->CaptureMap.count(Var)) { 15740 // If we found a capture, any subcaptures are nested. 15741 SubCapturesAreNested = true; 15742 15743 // Retrieve the capture type for this variable. 15744 CaptureType = CSI->getCapture(Var).getCaptureType(); 15745 15746 // Compute the type of an expression that refers to this variable. 15747 DeclRefType = CaptureType.getNonReferenceType(); 15748 15749 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 15750 // are mutable in the sense that user can change their value - they are 15751 // private instances of the captured declarations. 15752 const Capture &Cap = CSI->getCapture(Var); 15753 if (Cap.isCopyCapture() && 15754 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 15755 !(isa<CapturedRegionScopeInfo>(CSI) && 15756 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 15757 DeclRefType.addConst(); 15758 return true; 15759 } 15760 return false; 15761 } 15762 15763 // Only block literals, captured statements, and lambda expressions can 15764 // capture; other scopes don't work. 15765 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 15766 SourceLocation Loc, 15767 const bool Diagnose, Sema &S) { 15768 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 15769 return getLambdaAwareParentOfDeclContext(DC); 15770 else if (Var->hasLocalStorage()) { 15771 if (Diagnose) 15772 diagnoseUncapturableValueReference(S, Loc, Var, DC); 15773 } 15774 return nullptr; 15775 } 15776 15777 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 15778 // certain types of variables (unnamed, variably modified types etc.) 15779 // so check for eligibility. 15780 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 15781 SourceLocation Loc, 15782 const bool Diagnose, Sema &S) { 15783 15784 bool IsBlock = isa<BlockScopeInfo>(CSI); 15785 bool IsLambda = isa<LambdaScopeInfo>(CSI); 15786 15787 // Lambdas are not allowed to capture unnamed variables 15788 // (e.g. anonymous unions). 15789 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 15790 // assuming that's the intent. 15791 if (IsLambda && !Var->getDeclName()) { 15792 if (Diagnose) { 15793 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 15794 S.Diag(Var->getLocation(), diag::note_declared_at); 15795 } 15796 return false; 15797 } 15798 15799 // Prohibit variably-modified types in blocks; they're difficult to deal with. 15800 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 15801 if (Diagnose) { 15802 S.Diag(Loc, diag::err_ref_vm_type); 15803 S.Diag(Var->getLocation(), diag::note_previous_decl) 15804 << Var->getDeclName(); 15805 } 15806 return false; 15807 } 15808 // Prohibit structs with flexible array members too. 15809 // We cannot capture what is in the tail end of the struct. 15810 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 15811 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 15812 if (Diagnose) { 15813 if (IsBlock) 15814 S.Diag(Loc, diag::err_ref_flexarray_type); 15815 else 15816 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 15817 << Var->getDeclName(); 15818 S.Diag(Var->getLocation(), diag::note_previous_decl) 15819 << Var->getDeclName(); 15820 } 15821 return false; 15822 } 15823 } 15824 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 15825 // Lambdas and captured statements are not allowed to capture __block 15826 // variables; they don't support the expected semantics. 15827 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 15828 if (Diagnose) { 15829 S.Diag(Loc, diag::err_capture_block_variable) 15830 << Var->getDeclName() << !IsLambda; 15831 S.Diag(Var->getLocation(), diag::note_previous_decl) 15832 << Var->getDeclName(); 15833 } 15834 return false; 15835 } 15836 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 15837 if (S.getLangOpts().OpenCL && IsBlock && 15838 Var->getType()->isBlockPointerType()) { 15839 if (Diagnose) 15840 S.Diag(Loc, diag::err_opencl_block_ref_block); 15841 return false; 15842 } 15843 15844 return true; 15845 } 15846 15847 // Returns true if the capture by block was successful. 15848 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 15849 SourceLocation Loc, 15850 const bool BuildAndDiagnose, 15851 QualType &CaptureType, 15852 QualType &DeclRefType, 15853 const bool Nested, 15854 Sema &S, bool Invalid) { 15855 bool ByRef = false; 15856 15857 // Blocks are not allowed to capture arrays, excepting OpenCL. 15858 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 15859 // (decayed to pointers). 15860 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 15861 if (BuildAndDiagnose) { 15862 S.Diag(Loc, diag::err_ref_array_type); 15863 S.Diag(Var->getLocation(), diag::note_previous_decl) 15864 << Var->getDeclName(); 15865 Invalid = true; 15866 } else { 15867 return false; 15868 } 15869 } 15870 15871 // Forbid the block-capture of autoreleasing variables. 15872 if (!Invalid && 15873 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 15874 if (BuildAndDiagnose) { 15875 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 15876 << /*block*/ 0; 15877 S.Diag(Var->getLocation(), diag::note_previous_decl) 15878 << Var->getDeclName(); 15879 Invalid = true; 15880 } else { 15881 return false; 15882 } 15883 } 15884 15885 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 15886 if (const auto *PT = CaptureType->getAs<PointerType>()) { 15887 QualType PointeeTy = PT->getPointeeType(); 15888 15889 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 15890 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 15891 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 15892 if (BuildAndDiagnose) { 15893 SourceLocation VarLoc = Var->getLocation(); 15894 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 15895 S.Diag(VarLoc, diag::note_declare_parameter_strong); 15896 } 15897 } 15898 } 15899 15900 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 15901 if (HasBlocksAttr || CaptureType->isReferenceType() || 15902 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 15903 // Block capture by reference does not change the capture or 15904 // declaration reference types. 15905 ByRef = true; 15906 } else { 15907 // Block capture by copy introduces 'const'. 15908 CaptureType = CaptureType.getNonReferenceType().withConst(); 15909 DeclRefType = CaptureType; 15910 } 15911 15912 // Actually capture the variable. 15913 if (BuildAndDiagnose) 15914 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 15915 CaptureType, Invalid); 15916 15917 return !Invalid; 15918 } 15919 15920 15921 /// Capture the given variable in the captured region. 15922 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 15923 VarDecl *Var, 15924 SourceLocation Loc, 15925 const bool BuildAndDiagnose, 15926 QualType &CaptureType, 15927 QualType &DeclRefType, 15928 const bool RefersToCapturedVariable, 15929 Sema &S, bool Invalid) { 15930 // By default, capture variables by reference. 15931 bool ByRef = true; 15932 // Using an LValue reference type is consistent with Lambdas (see below). 15933 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 15934 if (S.isOpenMPCapturedDecl(Var)) { 15935 bool HasConst = DeclRefType.isConstQualified(); 15936 DeclRefType = DeclRefType.getUnqualifiedType(); 15937 // Don't lose diagnostics about assignments to const. 15938 if (HasConst) 15939 DeclRefType.addConst(); 15940 } 15941 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 15942 RSI->OpenMPCaptureLevel); 15943 } 15944 15945 if (ByRef) 15946 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 15947 else 15948 CaptureType = DeclRefType; 15949 15950 // Actually capture the variable. 15951 if (BuildAndDiagnose) 15952 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 15953 Loc, SourceLocation(), CaptureType, Invalid); 15954 15955 return !Invalid; 15956 } 15957 15958 /// Capture the given variable in the lambda. 15959 static bool captureInLambda(LambdaScopeInfo *LSI, 15960 VarDecl *Var, 15961 SourceLocation Loc, 15962 const bool BuildAndDiagnose, 15963 QualType &CaptureType, 15964 QualType &DeclRefType, 15965 const bool RefersToCapturedVariable, 15966 const Sema::TryCaptureKind Kind, 15967 SourceLocation EllipsisLoc, 15968 const bool IsTopScope, 15969 Sema &S, bool Invalid) { 15970 // Determine whether we are capturing by reference or by value. 15971 bool ByRef = false; 15972 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 15973 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 15974 } else { 15975 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 15976 } 15977 15978 // Compute the type of the field that will capture this variable. 15979 if (ByRef) { 15980 // C++11 [expr.prim.lambda]p15: 15981 // An entity is captured by reference if it is implicitly or 15982 // explicitly captured but not captured by copy. It is 15983 // unspecified whether additional unnamed non-static data 15984 // members are declared in the closure type for entities 15985 // captured by reference. 15986 // 15987 // FIXME: It is not clear whether we want to build an lvalue reference 15988 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 15989 // to do the former, while EDG does the latter. Core issue 1249 will 15990 // clarify, but for now we follow GCC because it's a more permissive and 15991 // easily defensible position. 15992 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 15993 } else { 15994 // C++11 [expr.prim.lambda]p14: 15995 // For each entity captured by copy, an unnamed non-static 15996 // data member is declared in the closure type. The 15997 // declaration order of these members is unspecified. The type 15998 // of such a data member is the type of the corresponding 15999 // captured entity if the entity is not a reference to an 16000 // object, or the referenced type otherwise. [Note: If the 16001 // captured entity is a reference to a function, the 16002 // corresponding data member is also a reference to a 16003 // function. - end note ] 16004 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 16005 if (!RefType->getPointeeType()->isFunctionType()) 16006 CaptureType = RefType->getPointeeType(); 16007 } 16008 16009 // Forbid the lambda copy-capture of autoreleasing variables. 16010 if (!Invalid && 16011 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 16012 if (BuildAndDiagnose) { 16013 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 16014 S.Diag(Var->getLocation(), diag::note_previous_decl) 16015 << Var->getDeclName(); 16016 Invalid = true; 16017 } else { 16018 return false; 16019 } 16020 } 16021 16022 // Make sure that by-copy captures are of a complete and non-abstract type. 16023 if (!Invalid && BuildAndDiagnose) { 16024 if (!CaptureType->isDependentType() && 16025 S.RequireCompleteType(Loc, CaptureType, 16026 diag::err_capture_of_incomplete_type, 16027 Var->getDeclName())) 16028 Invalid = true; 16029 else if (S.RequireNonAbstractType(Loc, CaptureType, 16030 diag::err_capture_of_abstract_type)) 16031 Invalid = true; 16032 } 16033 } 16034 16035 // Compute the type of a reference to this captured variable. 16036 if (ByRef) 16037 DeclRefType = CaptureType.getNonReferenceType(); 16038 else { 16039 // C++ [expr.prim.lambda]p5: 16040 // The closure type for a lambda-expression has a public inline 16041 // function call operator [...]. This function call operator is 16042 // declared const (9.3.1) if and only if the lambda-expression's 16043 // parameter-declaration-clause is not followed by mutable. 16044 DeclRefType = CaptureType.getNonReferenceType(); 16045 if (!LSI->Mutable && !CaptureType->isReferenceType()) 16046 DeclRefType.addConst(); 16047 } 16048 16049 // Add the capture. 16050 if (BuildAndDiagnose) 16051 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 16052 Loc, EllipsisLoc, CaptureType, Invalid); 16053 16054 return !Invalid; 16055 } 16056 16057 bool Sema::tryCaptureVariable( 16058 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 16059 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 16060 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 16061 // An init-capture is notionally from the context surrounding its 16062 // declaration, but its parent DC is the lambda class. 16063 DeclContext *VarDC = Var->getDeclContext(); 16064 if (Var->isInitCapture()) 16065 VarDC = VarDC->getParent(); 16066 16067 DeclContext *DC = CurContext; 16068 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 16069 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 16070 // We need to sync up the Declaration Context with the 16071 // FunctionScopeIndexToStopAt 16072 if (FunctionScopeIndexToStopAt) { 16073 unsigned FSIndex = FunctionScopes.size() - 1; 16074 while (FSIndex != MaxFunctionScopesIndex) { 16075 DC = getLambdaAwareParentOfDeclContext(DC); 16076 --FSIndex; 16077 } 16078 } 16079 16080 16081 // If the variable is declared in the current context, there is no need to 16082 // capture it. 16083 if (VarDC == DC) return true; 16084 16085 // Capture global variables if it is required to use private copy of this 16086 // variable. 16087 bool IsGlobal = !Var->hasLocalStorage(); 16088 if (IsGlobal && 16089 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 16090 MaxFunctionScopesIndex))) 16091 return true; 16092 Var = Var->getCanonicalDecl(); 16093 16094 // Walk up the stack to determine whether we can capture the variable, 16095 // performing the "simple" checks that don't depend on type. We stop when 16096 // we've either hit the declared scope of the variable or find an existing 16097 // capture of that variable. We start from the innermost capturing-entity 16098 // (the DC) and ensure that all intervening capturing-entities 16099 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 16100 // declcontext can either capture the variable or have already captured 16101 // the variable. 16102 CaptureType = Var->getType(); 16103 DeclRefType = CaptureType.getNonReferenceType(); 16104 bool Nested = false; 16105 bool Explicit = (Kind != TryCapture_Implicit); 16106 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 16107 do { 16108 // Only block literals, captured statements, and lambda expressions can 16109 // capture; other scopes don't work. 16110 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 16111 ExprLoc, 16112 BuildAndDiagnose, 16113 *this); 16114 // We need to check for the parent *first* because, if we *have* 16115 // private-captured a global variable, we need to recursively capture it in 16116 // intermediate blocks, lambdas, etc. 16117 if (!ParentDC) { 16118 if (IsGlobal) { 16119 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 16120 break; 16121 } 16122 return true; 16123 } 16124 16125 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 16126 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 16127 16128 16129 // Check whether we've already captured it. 16130 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 16131 DeclRefType)) { 16132 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 16133 break; 16134 } 16135 // If we are instantiating a generic lambda call operator body, 16136 // we do not want to capture new variables. What was captured 16137 // during either a lambdas transformation or initial parsing 16138 // should be used. 16139 if (isGenericLambdaCallOperatorSpecialization(DC)) { 16140 if (BuildAndDiagnose) { 16141 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 16142 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 16143 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 16144 Diag(Var->getLocation(), diag::note_previous_decl) 16145 << Var->getDeclName(); 16146 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 16147 } else 16148 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 16149 } 16150 return true; 16151 } 16152 16153 // Try to capture variable-length arrays types. 16154 if (Var->getType()->isVariablyModifiedType()) { 16155 // We're going to walk down into the type and look for VLA 16156 // expressions. 16157 QualType QTy = Var->getType(); 16158 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 16159 QTy = PVD->getOriginalType(); 16160 captureVariablyModifiedType(Context, QTy, CSI); 16161 } 16162 16163 if (getLangOpts().OpenMP) { 16164 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 16165 // OpenMP private variables should not be captured in outer scope, so 16166 // just break here. Similarly, global variables that are captured in a 16167 // target region should not be captured outside the scope of the region. 16168 if (RSI->CapRegionKind == CR_OpenMP) { 16169 bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel); 16170 // If the variable is private (i.e. not captured) and has variably 16171 // modified type, we still need to capture the type for correct 16172 // codegen in all regions, associated with the construct. Currently, 16173 // it is captured in the innermost captured region only. 16174 if (IsOpenMPPrivateDecl && Var->getType()->isVariablyModifiedType()) { 16175 QualType QTy = Var->getType(); 16176 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 16177 QTy = PVD->getOriginalType(); 16178 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 16179 I < E; ++I) { 16180 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 16181 FunctionScopes[FunctionScopesIndex - I]); 16182 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 16183 "Wrong number of captured regions associated with the " 16184 "OpenMP construct."); 16185 captureVariablyModifiedType(Context, QTy, OuterRSI); 16186 } 16187 } 16188 bool IsTargetCap = !IsOpenMPPrivateDecl && 16189 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 16190 // When we detect target captures we are looking from inside the 16191 // target region, therefore we need to propagate the capture from the 16192 // enclosing region. Therefore, the capture is not initially nested. 16193 if (IsTargetCap) 16194 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 16195 16196 if (IsTargetCap || IsOpenMPPrivateDecl) { 16197 Nested = !IsTargetCap; 16198 DeclRefType = DeclRefType.getUnqualifiedType(); 16199 CaptureType = Context.getLValueReferenceType(DeclRefType); 16200 break; 16201 } 16202 } 16203 } 16204 } 16205 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 16206 // No capture-default, and this is not an explicit capture 16207 // so cannot capture this variable. 16208 if (BuildAndDiagnose) { 16209 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 16210 Diag(Var->getLocation(), diag::note_previous_decl) 16211 << Var->getDeclName(); 16212 if (cast<LambdaScopeInfo>(CSI)->Lambda) 16213 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(), 16214 diag::note_lambda_decl); 16215 // FIXME: If we error out because an outer lambda can not implicitly 16216 // capture a variable that an inner lambda explicitly captures, we 16217 // should have the inner lambda do the explicit capture - because 16218 // it makes for cleaner diagnostics later. This would purely be done 16219 // so that the diagnostic does not misleadingly claim that a variable 16220 // can not be captured by a lambda implicitly even though it is captured 16221 // explicitly. Suggestion: 16222 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 16223 // at the function head 16224 // - cache the StartingDeclContext - this must be a lambda 16225 // - captureInLambda in the innermost lambda the variable. 16226 } 16227 return true; 16228 } 16229 16230 FunctionScopesIndex--; 16231 DC = ParentDC; 16232 Explicit = false; 16233 } while (!VarDC->Equals(DC)); 16234 16235 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 16236 // computing the type of the capture at each step, checking type-specific 16237 // requirements, and adding captures if requested. 16238 // If the variable had already been captured previously, we start capturing 16239 // at the lambda nested within that one. 16240 bool Invalid = false; 16241 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 16242 ++I) { 16243 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 16244 16245 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 16246 // certain types of variables (unnamed, variably modified types etc.) 16247 // so check for eligibility. 16248 if (!Invalid) 16249 Invalid = 16250 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 16251 16252 // After encountering an error, if we're actually supposed to capture, keep 16253 // capturing in nested contexts to suppress any follow-on diagnostics. 16254 if (Invalid && !BuildAndDiagnose) 16255 return true; 16256 16257 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 16258 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 16259 DeclRefType, Nested, *this, Invalid); 16260 Nested = true; 16261 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 16262 Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose, 16263 CaptureType, DeclRefType, Nested, 16264 *this, Invalid); 16265 Nested = true; 16266 } else { 16267 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 16268 Invalid = 16269 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 16270 DeclRefType, Nested, Kind, EllipsisLoc, 16271 /*IsTopScope*/ I == N - 1, *this, Invalid); 16272 Nested = true; 16273 } 16274 16275 if (Invalid && !BuildAndDiagnose) 16276 return true; 16277 } 16278 return Invalid; 16279 } 16280 16281 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 16282 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 16283 QualType CaptureType; 16284 QualType DeclRefType; 16285 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 16286 /*BuildAndDiagnose=*/true, CaptureType, 16287 DeclRefType, nullptr); 16288 } 16289 16290 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 16291 QualType CaptureType; 16292 QualType DeclRefType; 16293 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 16294 /*BuildAndDiagnose=*/false, CaptureType, 16295 DeclRefType, nullptr); 16296 } 16297 16298 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 16299 QualType CaptureType; 16300 QualType DeclRefType; 16301 16302 // Determine whether we can capture this variable. 16303 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 16304 /*BuildAndDiagnose=*/false, CaptureType, 16305 DeclRefType, nullptr)) 16306 return QualType(); 16307 16308 return DeclRefType; 16309 } 16310 16311 namespace { 16312 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 16313 // The produced TemplateArgumentListInfo* points to data stored within this 16314 // object, so should only be used in contexts where the pointer will not be 16315 // used after the CopiedTemplateArgs object is destroyed. 16316 class CopiedTemplateArgs { 16317 bool HasArgs; 16318 TemplateArgumentListInfo TemplateArgStorage; 16319 public: 16320 template<typename RefExpr> 16321 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 16322 if (HasArgs) 16323 E->copyTemplateArgumentsInto(TemplateArgStorage); 16324 } 16325 operator TemplateArgumentListInfo*() 16326 #ifdef __has_cpp_attribute 16327 #if __has_cpp_attribute(clang::lifetimebound) 16328 [[clang::lifetimebound]] 16329 #endif 16330 #endif 16331 { 16332 return HasArgs ? &TemplateArgStorage : nullptr; 16333 } 16334 }; 16335 } 16336 16337 /// Walk the set of potential results of an expression and mark them all as 16338 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 16339 /// 16340 /// \return A new expression if we found any potential results, ExprEmpty() if 16341 /// not, and ExprError() if we diagnosed an error. 16342 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 16343 NonOdrUseReason NOUR) { 16344 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 16345 // an object that satisfies the requirements for appearing in a 16346 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 16347 // is immediately applied." This function handles the lvalue-to-rvalue 16348 // conversion part. 16349 // 16350 // If we encounter a node that claims to be an odr-use but shouldn't be, we 16351 // transform it into the relevant kind of non-odr-use node and rebuild the 16352 // tree of nodes leading to it. 16353 // 16354 // This is a mini-TreeTransform that only transforms a restricted subset of 16355 // nodes (and only certain operands of them). 16356 16357 // Rebuild a subexpression. 16358 auto Rebuild = [&](Expr *Sub) { 16359 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 16360 }; 16361 16362 // Check whether a potential result satisfies the requirements of NOUR. 16363 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 16364 // Any entity other than a VarDecl is always odr-used whenever it's named 16365 // in a potentially-evaluated expression. 16366 auto *VD = dyn_cast<VarDecl>(D); 16367 if (!VD) 16368 return true; 16369 16370 // C++2a [basic.def.odr]p4: 16371 // A variable x whose name appears as a potentially-evalauted expression 16372 // e is odr-used by e unless 16373 // -- x is a reference that is usable in constant expressions, or 16374 // -- x is a variable of non-reference type that is usable in constant 16375 // expressions and has no mutable subobjects, and e is an element of 16376 // the set of potential results of an expression of 16377 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 16378 // conversion is applied, or 16379 // -- x is a variable of non-reference type, and e is an element of the 16380 // set of potential results of a discarded-value expression to which 16381 // the lvalue-to-rvalue conversion is not applied 16382 // 16383 // We check the first bullet and the "potentially-evaluated" condition in 16384 // BuildDeclRefExpr. We check the type requirements in the second bullet 16385 // in CheckLValueToRValueConversionOperand below. 16386 switch (NOUR) { 16387 case NOUR_None: 16388 case NOUR_Unevaluated: 16389 llvm_unreachable("unexpected non-odr-use-reason"); 16390 16391 case NOUR_Constant: 16392 // Constant references were handled when they were built. 16393 if (VD->getType()->isReferenceType()) 16394 return true; 16395 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 16396 if (RD->hasMutableFields()) 16397 return true; 16398 if (!VD->isUsableInConstantExpressions(S.Context)) 16399 return true; 16400 break; 16401 16402 case NOUR_Discarded: 16403 if (VD->getType()->isReferenceType()) 16404 return true; 16405 break; 16406 } 16407 return false; 16408 }; 16409 16410 // Mark that this expression does not constitute an odr-use. 16411 auto MarkNotOdrUsed = [&] { 16412 S.MaybeODRUseExprs.erase(E); 16413 if (LambdaScopeInfo *LSI = S.getCurLambda()) 16414 LSI->markVariableExprAsNonODRUsed(E); 16415 }; 16416 16417 // C++2a [basic.def.odr]p2: 16418 // The set of potential results of an expression e is defined as follows: 16419 switch (E->getStmtClass()) { 16420 // -- If e is an id-expression, ... 16421 case Expr::DeclRefExprClass: { 16422 auto *DRE = cast<DeclRefExpr>(E); 16423 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 16424 break; 16425 16426 // Rebuild as a non-odr-use DeclRefExpr. 16427 MarkNotOdrUsed(); 16428 return DeclRefExpr::Create( 16429 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 16430 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 16431 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 16432 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 16433 } 16434 16435 case Expr::FunctionParmPackExprClass: { 16436 auto *FPPE = cast<FunctionParmPackExpr>(E); 16437 // If any of the declarations in the pack is odr-used, then the expression 16438 // as a whole constitutes an odr-use. 16439 for (VarDecl *D : *FPPE) 16440 if (IsPotentialResultOdrUsed(D)) 16441 return ExprEmpty(); 16442 16443 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 16444 // nothing cares about whether we marked this as an odr-use, but it might 16445 // be useful for non-compiler tools. 16446 MarkNotOdrUsed(); 16447 break; 16448 } 16449 16450 // -- If e is a subscripting operation with an array operand... 16451 case Expr::ArraySubscriptExprClass: { 16452 auto *ASE = cast<ArraySubscriptExpr>(E); 16453 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 16454 if (!OldBase->getType()->isArrayType()) 16455 break; 16456 ExprResult Base = Rebuild(OldBase); 16457 if (!Base.isUsable()) 16458 return Base; 16459 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 16460 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 16461 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 16462 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 16463 ASE->getRBracketLoc()); 16464 } 16465 16466 case Expr::MemberExprClass: { 16467 auto *ME = cast<MemberExpr>(E); 16468 // -- If e is a class member access expression [...] naming a non-static 16469 // data member... 16470 if (isa<FieldDecl>(ME->getMemberDecl())) { 16471 ExprResult Base = Rebuild(ME->getBase()); 16472 if (!Base.isUsable()) 16473 return Base; 16474 return MemberExpr::Create( 16475 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 16476 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 16477 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 16478 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 16479 ME->getObjectKind(), ME->isNonOdrUse()); 16480 } 16481 16482 if (ME->getMemberDecl()->isCXXInstanceMember()) 16483 break; 16484 16485 // -- If e is a class member access expression naming a static data member, 16486 // ... 16487 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 16488 break; 16489 16490 // Rebuild as a non-odr-use MemberExpr. 16491 MarkNotOdrUsed(); 16492 return MemberExpr::Create( 16493 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 16494 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 16495 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 16496 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 16497 return ExprEmpty(); 16498 } 16499 16500 case Expr::BinaryOperatorClass: { 16501 auto *BO = cast<BinaryOperator>(E); 16502 Expr *LHS = BO->getLHS(); 16503 Expr *RHS = BO->getRHS(); 16504 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 16505 if (BO->getOpcode() == BO_PtrMemD) { 16506 ExprResult Sub = Rebuild(LHS); 16507 if (!Sub.isUsable()) 16508 return Sub; 16509 LHS = Sub.get(); 16510 // -- If e is a comma expression, ... 16511 } else if (BO->getOpcode() == BO_Comma) { 16512 ExprResult Sub = Rebuild(RHS); 16513 if (!Sub.isUsable()) 16514 return Sub; 16515 RHS = Sub.get(); 16516 } else { 16517 break; 16518 } 16519 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 16520 LHS, RHS); 16521 } 16522 16523 // -- If e has the form (e1)... 16524 case Expr::ParenExprClass: { 16525 auto *PE = cast<ParenExpr>(E); 16526 ExprResult Sub = Rebuild(PE->getSubExpr()); 16527 if (!Sub.isUsable()) 16528 return Sub; 16529 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 16530 } 16531 16532 // -- If e is a glvalue conditional expression, ... 16533 // We don't apply this to a binary conditional operator. FIXME: Should we? 16534 case Expr::ConditionalOperatorClass: { 16535 auto *CO = cast<ConditionalOperator>(E); 16536 ExprResult LHS = Rebuild(CO->getLHS()); 16537 if (LHS.isInvalid()) 16538 return ExprError(); 16539 ExprResult RHS = Rebuild(CO->getRHS()); 16540 if (RHS.isInvalid()) 16541 return ExprError(); 16542 if (!LHS.isUsable() && !RHS.isUsable()) 16543 return ExprEmpty(); 16544 if (!LHS.isUsable()) 16545 LHS = CO->getLHS(); 16546 if (!RHS.isUsable()) 16547 RHS = CO->getRHS(); 16548 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 16549 CO->getCond(), LHS.get(), RHS.get()); 16550 } 16551 16552 // [Clang extension] 16553 // -- If e has the form __extension__ e1... 16554 case Expr::UnaryOperatorClass: { 16555 auto *UO = cast<UnaryOperator>(E); 16556 if (UO->getOpcode() != UO_Extension) 16557 break; 16558 ExprResult Sub = Rebuild(UO->getSubExpr()); 16559 if (!Sub.isUsable()) 16560 return Sub; 16561 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 16562 Sub.get()); 16563 } 16564 16565 // [Clang extension] 16566 // -- If e has the form _Generic(...), the set of potential results is the 16567 // union of the sets of potential results of the associated expressions. 16568 case Expr::GenericSelectionExprClass: { 16569 auto *GSE = cast<GenericSelectionExpr>(E); 16570 16571 SmallVector<Expr *, 4> AssocExprs; 16572 bool AnyChanged = false; 16573 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 16574 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 16575 if (AssocExpr.isInvalid()) 16576 return ExprError(); 16577 if (AssocExpr.isUsable()) { 16578 AssocExprs.push_back(AssocExpr.get()); 16579 AnyChanged = true; 16580 } else { 16581 AssocExprs.push_back(OrigAssocExpr); 16582 } 16583 } 16584 16585 return AnyChanged ? S.CreateGenericSelectionExpr( 16586 GSE->getGenericLoc(), GSE->getDefaultLoc(), 16587 GSE->getRParenLoc(), GSE->getControllingExpr(), 16588 GSE->getAssocTypeSourceInfos(), AssocExprs) 16589 : ExprEmpty(); 16590 } 16591 16592 // [Clang extension] 16593 // -- If e has the form __builtin_choose_expr(...), the set of potential 16594 // results is the union of the sets of potential results of the 16595 // second and third subexpressions. 16596 case Expr::ChooseExprClass: { 16597 auto *CE = cast<ChooseExpr>(E); 16598 16599 ExprResult LHS = Rebuild(CE->getLHS()); 16600 if (LHS.isInvalid()) 16601 return ExprError(); 16602 16603 ExprResult RHS = Rebuild(CE->getLHS()); 16604 if (RHS.isInvalid()) 16605 return ExprError(); 16606 16607 if (!LHS.get() && !RHS.get()) 16608 return ExprEmpty(); 16609 if (!LHS.isUsable()) 16610 LHS = CE->getLHS(); 16611 if (!RHS.isUsable()) 16612 RHS = CE->getRHS(); 16613 16614 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 16615 RHS.get(), CE->getRParenLoc()); 16616 } 16617 16618 // Step through non-syntactic nodes. 16619 case Expr::ConstantExprClass: { 16620 auto *CE = cast<ConstantExpr>(E); 16621 ExprResult Sub = Rebuild(CE->getSubExpr()); 16622 if (!Sub.isUsable()) 16623 return Sub; 16624 return ConstantExpr::Create(S.Context, Sub.get()); 16625 } 16626 16627 // We could mostly rely on the recursive rebuilding to rebuild implicit 16628 // casts, but not at the top level, so rebuild them here. 16629 case Expr::ImplicitCastExprClass: { 16630 auto *ICE = cast<ImplicitCastExpr>(E); 16631 // Only step through the narrow set of cast kinds we expect to encounter. 16632 // Anything else suggests we've left the region in which potential results 16633 // can be found. 16634 switch (ICE->getCastKind()) { 16635 case CK_NoOp: 16636 case CK_DerivedToBase: 16637 case CK_UncheckedDerivedToBase: { 16638 ExprResult Sub = Rebuild(ICE->getSubExpr()); 16639 if (!Sub.isUsable()) 16640 return Sub; 16641 CXXCastPath Path(ICE->path()); 16642 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 16643 ICE->getValueKind(), &Path); 16644 } 16645 16646 default: 16647 break; 16648 } 16649 break; 16650 } 16651 16652 default: 16653 break; 16654 } 16655 16656 // Can't traverse through this node. Nothing to do. 16657 return ExprEmpty(); 16658 } 16659 16660 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 16661 // Check whether the operand is or contains an object of non-trivial C union 16662 // type. 16663 if (E->getType().isVolatileQualified() && 16664 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 16665 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 16666 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 16667 Sema::NTCUC_LValueToRValueVolatile, 16668 NTCUK_Destruct|NTCUK_Copy); 16669 16670 // C++2a [basic.def.odr]p4: 16671 // [...] an expression of non-volatile-qualified non-class type to which 16672 // the lvalue-to-rvalue conversion is applied [...] 16673 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 16674 return E; 16675 16676 ExprResult Result = 16677 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 16678 if (Result.isInvalid()) 16679 return ExprError(); 16680 return Result.get() ? Result : E; 16681 } 16682 16683 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 16684 Res = CorrectDelayedTyposInExpr(Res); 16685 16686 if (!Res.isUsable()) 16687 return Res; 16688 16689 // If a constant-expression is a reference to a variable where we delay 16690 // deciding whether it is an odr-use, just assume we will apply the 16691 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 16692 // (a non-type template argument), we have special handling anyway. 16693 return CheckLValueToRValueConversionOperand(Res.get()); 16694 } 16695 16696 void Sema::CleanupVarDeclMarking() { 16697 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 16698 // call. 16699 MaybeODRUseExprSet LocalMaybeODRUseExprs; 16700 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 16701 16702 for (Expr *E : LocalMaybeODRUseExprs) { 16703 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 16704 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 16705 DRE->getLocation(), *this); 16706 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 16707 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 16708 *this); 16709 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 16710 for (VarDecl *VD : *FP) 16711 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 16712 } else { 16713 llvm_unreachable("Unexpected expression"); 16714 } 16715 } 16716 16717 assert(MaybeODRUseExprs.empty() && 16718 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 16719 } 16720 16721 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 16722 VarDecl *Var, Expr *E) { 16723 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 16724 isa<FunctionParmPackExpr>(E)) && 16725 "Invalid Expr argument to DoMarkVarDeclReferenced"); 16726 Var->setReferenced(); 16727 16728 if (Var->isInvalidDecl()) 16729 return; 16730 16731 auto *MSI = Var->getMemberSpecializationInfo(); 16732 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 16733 : Var->getTemplateSpecializationKind(); 16734 16735 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 16736 bool UsableInConstantExpr = 16737 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 16738 16739 // C++20 [expr.const]p12: 16740 // A variable [...] is needed for constant evaluation if it is [...] a 16741 // variable whose name appears as a potentially constant evaluated 16742 // expression that is either a contexpr variable or is of non-volatile 16743 // const-qualified integral type or of reference type 16744 bool NeededForConstantEvaluation = 16745 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 16746 16747 bool NeedDefinition = 16748 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 16749 16750 VarTemplateSpecializationDecl *VarSpec = 16751 dyn_cast<VarTemplateSpecializationDecl>(Var); 16752 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 16753 "Can't instantiate a partial template specialization."); 16754 16755 // If this might be a member specialization of a static data member, check 16756 // the specialization is visible. We already did the checks for variable 16757 // template specializations when we created them. 16758 if (NeedDefinition && TSK != TSK_Undeclared && 16759 !isa<VarTemplateSpecializationDecl>(Var)) 16760 SemaRef.checkSpecializationVisibility(Loc, Var); 16761 16762 // Perform implicit instantiation of static data members, static data member 16763 // templates of class templates, and variable template specializations. Delay 16764 // instantiations of variable templates, except for those that could be used 16765 // in a constant expression. 16766 if (NeedDefinition && isTemplateInstantiation(TSK)) { 16767 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 16768 // instantiation declaration if a variable is usable in a constant 16769 // expression (among other cases). 16770 bool TryInstantiating = 16771 TSK == TSK_ImplicitInstantiation || 16772 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 16773 16774 if (TryInstantiating) { 16775 SourceLocation PointOfInstantiation = 16776 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 16777 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 16778 if (FirstInstantiation) { 16779 PointOfInstantiation = Loc; 16780 if (MSI) 16781 MSI->setPointOfInstantiation(PointOfInstantiation); 16782 else 16783 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 16784 } 16785 16786 bool InstantiationDependent = false; 16787 bool IsNonDependent = 16788 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 16789 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 16790 : true; 16791 16792 // Do not instantiate specializations that are still type-dependent. 16793 if (IsNonDependent) { 16794 if (UsableInConstantExpr) { 16795 // Do not defer instantiations of variables that could be used in a 16796 // constant expression. 16797 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 16798 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 16799 }); 16800 } else if (FirstInstantiation || 16801 isa<VarTemplateSpecializationDecl>(Var)) { 16802 // FIXME: For a specialization of a variable template, we don't 16803 // distinguish between "declaration and type implicitly instantiated" 16804 // and "implicit instantiation of definition requested", so we have 16805 // no direct way to avoid enqueueing the pending instantiation 16806 // multiple times. 16807 SemaRef.PendingInstantiations 16808 .push_back(std::make_pair(Var, PointOfInstantiation)); 16809 } 16810 } 16811 } 16812 } 16813 16814 // C++2a [basic.def.odr]p4: 16815 // A variable x whose name appears as a potentially-evaluated expression e 16816 // is odr-used by e unless 16817 // -- x is a reference that is usable in constant expressions 16818 // -- x is a variable of non-reference type that is usable in constant 16819 // expressions and has no mutable subobjects [FIXME], and e is an 16820 // element of the set of potential results of an expression of 16821 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 16822 // conversion is applied 16823 // -- x is a variable of non-reference type, and e is an element of the set 16824 // of potential results of a discarded-value expression to which the 16825 // lvalue-to-rvalue conversion is not applied [FIXME] 16826 // 16827 // We check the first part of the second bullet here, and 16828 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 16829 // FIXME: To get the third bullet right, we need to delay this even for 16830 // variables that are not usable in constant expressions. 16831 16832 // If we already know this isn't an odr-use, there's nothing more to do. 16833 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 16834 if (DRE->isNonOdrUse()) 16835 return; 16836 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 16837 if (ME->isNonOdrUse()) 16838 return; 16839 16840 switch (OdrUse) { 16841 case OdrUseContext::None: 16842 assert((!E || isa<FunctionParmPackExpr>(E)) && 16843 "missing non-odr-use marking for unevaluated decl ref"); 16844 break; 16845 16846 case OdrUseContext::FormallyOdrUsed: 16847 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 16848 // behavior. 16849 break; 16850 16851 case OdrUseContext::Used: 16852 // If we might later find that this expression isn't actually an odr-use, 16853 // delay the marking. 16854 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 16855 SemaRef.MaybeODRUseExprs.insert(E); 16856 else 16857 MarkVarDeclODRUsed(Var, Loc, SemaRef); 16858 break; 16859 16860 case OdrUseContext::Dependent: 16861 // If this is a dependent context, we don't need to mark variables as 16862 // odr-used, but we may still need to track them for lambda capture. 16863 // FIXME: Do we also need to do this inside dependent typeid expressions 16864 // (which are modeled as unevaluated at this point)? 16865 const bool RefersToEnclosingScope = 16866 (SemaRef.CurContext != Var->getDeclContext() && 16867 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 16868 if (RefersToEnclosingScope) { 16869 LambdaScopeInfo *const LSI = 16870 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 16871 if (LSI && (!LSI->CallOperator || 16872 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 16873 // If a variable could potentially be odr-used, defer marking it so 16874 // until we finish analyzing the full expression for any 16875 // lvalue-to-rvalue 16876 // or discarded value conversions that would obviate odr-use. 16877 // Add it to the list of potential captures that will be analyzed 16878 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 16879 // unless the variable is a reference that was initialized by a constant 16880 // expression (this will never need to be captured or odr-used). 16881 // 16882 // FIXME: We can simplify this a lot after implementing P0588R1. 16883 assert(E && "Capture variable should be used in an expression."); 16884 if (!Var->getType()->isReferenceType() || 16885 !Var->isUsableInConstantExpressions(SemaRef.Context)) 16886 LSI->addPotentialCapture(E->IgnoreParens()); 16887 } 16888 } 16889 break; 16890 } 16891 } 16892 16893 /// Mark a variable referenced, and check whether it is odr-used 16894 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 16895 /// used directly for normal expressions referring to VarDecl. 16896 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 16897 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 16898 } 16899 16900 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 16901 Decl *D, Expr *E, bool MightBeOdrUse) { 16902 if (SemaRef.isInOpenMPDeclareTargetContext()) 16903 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 16904 16905 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 16906 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 16907 return; 16908 } 16909 16910 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 16911 16912 // If this is a call to a method via a cast, also mark the method in the 16913 // derived class used in case codegen can devirtualize the call. 16914 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 16915 if (!ME) 16916 return; 16917 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 16918 if (!MD) 16919 return; 16920 // Only attempt to devirtualize if this is truly a virtual call. 16921 bool IsVirtualCall = MD->isVirtual() && 16922 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 16923 if (!IsVirtualCall) 16924 return; 16925 16926 // If it's possible to devirtualize the call, mark the called function 16927 // referenced. 16928 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 16929 ME->getBase(), SemaRef.getLangOpts().AppleKext); 16930 if (DM) 16931 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 16932 } 16933 16934 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 16935 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 16936 // TODO: update this with DR# once a defect report is filed. 16937 // C++11 defect. The address of a pure member should not be an ODR use, even 16938 // if it's a qualified reference. 16939 bool OdrUse = true; 16940 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 16941 if (Method->isVirtual() && 16942 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 16943 OdrUse = false; 16944 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 16945 } 16946 16947 /// Perform reference-marking and odr-use handling for a MemberExpr. 16948 void Sema::MarkMemberReferenced(MemberExpr *E) { 16949 // C++11 [basic.def.odr]p2: 16950 // A non-overloaded function whose name appears as a potentially-evaluated 16951 // expression or a member of a set of candidate functions, if selected by 16952 // overload resolution when referred to from a potentially-evaluated 16953 // expression, is odr-used, unless it is a pure virtual function and its 16954 // name is not explicitly qualified. 16955 bool MightBeOdrUse = true; 16956 if (E->performsVirtualDispatch(getLangOpts())) { 16957 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 16958 if (Method->isPure()) 16959 MightBeOdrUse = false; 16960 } 16961 SourceLocation Loc = 16962 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 16963 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 16964 } 16965 16966 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 16967 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 16968 for (VarDecl *VD : *E) 16969 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true); 16970 } 16971 16972 /// Perform marking for a reference to an arbitrary declaration. It 16973 /// marks the declaration referenced, and performs odr-use checking for 16974 /// functions and variables. This method should not be used when building a 16975 /// normal expression which refers to a variable. 16976 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 16977 bool MightBeOdrUse) { 16978 if (MightBeOdrUse) { 16979 if (auto *VD = dyn_cast<VarDecl>(D)) { 16980 MarkVariableReferenced(Loc, VD); 16981 return; 16982 } 16983 } 16984 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 16985 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 16986 return; 16987 } 16988 D->setReferenced(); 16989 } 16990 16991 namespace { 16992 // Mark all of the declarations used by a type as referenced. 16993 // FIXME: Not fully implemented yet! We need to have a better understanding 16994 // of when we're entering a context we should not recurse into. 16995 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 16996 // TreeTransforms rebuilding the type in a new context. Rather than 16997 // duplicating the TreeTransform logic, we should consider reusing it here. 16998 // Currently that causes problems when rebuilding LambdaExprs. 16999 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 17000 Sema &S; 17001 SourceLocation Loc; 17002 17003 public: 17004 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 17005 17006 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 17007 17008 bool TraverseTemplateArgument(const TemplateArgument &Arg); 17009 }; 17010 } 17011 17012 bool MarkReferencedDecls::TraverseTemplateArgument( 17013 const TemplateArgument &Arg) { 17014 { 17015 // A non-type template argument is a constant-evaluated context. 17016 EnterExpressionEvaluationContext Evaluated( 17017 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 17018 if (Arg.getKind() == TemplateArgument::Declaration) { 17019 if (Decl *D = Arg.getAsDecl()) 17020 S.MarkAnyDeclReferenced(Loc, D, true); 17021 } else if (Arg.getKind() == TemplateArgument::Expression) { 17022 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 17023 } 17024 } 17025 17026 return Inherited::TraverseTemplateArgument(Arg); 17027 } 17028 17029 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 17030 MarkReferencedDecls Marker(*this, Loc); 17031 Marker.TraverseType(T); 17032 } 17033 17034 namespace { 17035 /// Helper class that marks all of the declarations referenced by 17036 /// potentially-evaluated subexpressions as "referenced". 17037 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 17038 Sema &S; 17039 bool SkipLocalVariables; 17040 17041 public: 17042 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 17043 17044 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 17045 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 17046 17047 void VisitDeclRefExpr(DeclRefExpr *E) { 17048 // If we were asked not to visit local variables, don't. 17049 if (SkipLocalVariables) { 17050 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 17051 if (VD->hasLocalStorage()) 17052 return; 17053 } 17054 17055 S.MarkDeclRefReferenced(E); 17056 } 17057 17058 void VisitMemberExpr(MemberExpr *E) { 17059 S.MarkMemberReferenced(E); 17060 Inherited::VisitMemberExpr(E); 17061 } 17062 17063 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 17064 S.MarkFunctionReferenced( 17065 E->getBeginLoc(), 17066 const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor())); 17067 Visit(E->getSubExpr()); 17068 } 17069 17070 void VisitCXXNewExpr(CXXNewExpr *E) { 17071 if (E->getOperatorNew()) 17072 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew()); 17073 if (E->getOperatorDelete()) 17074 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete()); 17075 Inherited::VisitCXXNewExpr(E); 17076 } 17077 17078 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 17079 if (E->getOperatorDelete()) 17080 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete()); 17081 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 17082 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 17083 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 17084 S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record)); 17085 } 17086 17087 Inherited::VisitCXXDeleteExpr(E); 17088 } 17089 17090 void VisitCXXConstructExpr(CXXConstructExpr *E) { 17091 S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor()); 17092 Inherited::VisitCXXConstructExpr(E); 17093 } 17094 17095 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 17096 Visit(E->getExpr()); 17097 } 17098 }; 17099 } 17100 17101 /// Mark any declarations that appear within this expression or any 17102 /// potentially-evaluated subexpressions as "referenced". 17103 /// 17104 /// \param SkipLocalVariables If true, don't mark local variables as 17105 /// 'referenced'. 17106 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 17107 bool SkipLocalVariables) { 17108 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 17109 } 17110 17111 /// Emit a diagnostic that describes an effect on the run-time behavior 17112 /// of the program being compiled. 17113 /// 17114 /// This routine emits the given diagnostic when the code currently being 17115 /// type-checked is "potentially evaluated", meaning that there is a 17116 /// possibility that the code will actually be executable. Code in sizeof() 17117 /// expressions, code used only during overload resolution, etc., are not 17118 /// potentially evaluated. This routine will suppress such diagnostics or, 17119 /// in the absolutely nutty case of potentially potentially evaluated 17120 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 17121 /// later. 17122 /// 17123 /// This routine should be used for all diagnostics that describe the run-time 17124 /// behavior of a program, such as passing a non-POD value through an ellipsis. 17125 /// Failure to do so will likely result in spurious diagnostics or failures 17126 /// during overload resolution or within sizeof/alignof/typeof/typeid. 17127 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 17128 const PartialDiagnostic &PD) { 17129 switch (ExprEvalContexts.back().Context) { 17130 case ExpressionEvaluationContext::Unevaluated: 17131 case ExpressionEvaluationContext::UnevaluatedList: 17132 case ExpressionEvaluationContext::UnevaluatedAbstract: 17133 case ExpressionEvaluationContext::DiscardedStatement: 17134 // The argument will never be evaluated, so don't complain. 17135 break; 17136 17137 case ExpressionEvaluationContext::ConstantEvaluated: 17138 // Relevant diagnostics should be produced by constant evaluation. 17139 break; 17140 17141 case ExpressionEvaluationContext::PotentiallyEvaluated: 17142 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 17143 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 17144 FunctionScopes.back()->PossiblyUnreachableDiags. 17145 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 17146 return true; 17147 } 17148 17149 // The initializer of a constexpr variable or of the first declaration of a 17150 // static data member is not syntactically a constant evaluated constant, 17151 // but nonetheless is always required to be a constant expression, so we 17152 // can skip diagnosing. 17153 // FIXME: Using the mangling context here is a hack. 17154 if (auto *VD = dyn_cast_or_null<VarDecl>( 17155 ExprEvalContexts.back().ManglingContextDecl)) { 17156 if (VD->isConstexpr() || 17157 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 17158 break; 17159 // FIXME: For any other kind of variable, we should build a CFG for its 17160 // initializer and check whether the context in question is reachable. 17161 } 17162 17163 Diag(Loc, PD); 17164 return true; 17165 } 17166 17167 return false; 17168 } 17169 17170 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 17171 const PartialDiagnostic &PD) { 17172 return DiagRuntimeBehavior( 17173 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 17174 } 17175 17176 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 17177 CallExpr *CE, FunctionDecl *FD) { 17178 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 17179 return false; 17180 17181 // If we're inside a decltype's expression, don't check for a valid return 17182 // type or construct temporaries until we know whether this is the last call. 17183 if (ExprEvalContexts.back().ExprContext == 17184 ExpressionEvaluationContextRecord::EK_Decltype) { 17185 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 17186 return false; 17187 } 17188 17189 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 17190 FunctionDecl *FD; 17191 CallExpr *CE; 17192 17193 public: 17194 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 17195 : FD(FD), CE(CE) { } 17196 17197 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 17198 if (!FD) { 17199 S.Diag(Loc, diag::err_call_incomplete_return) 17200 << T << CE->getSourceRange(); 17201 return; 17202 } 17203 17204 S.Diag(Loc, diag::err_call_function_incomplete_return) 17205 << CE->getSourceRange() << FD->getDeclName() << T; 17206 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 17207 << FD->getDeclName(); 17208 } 17209 } Diagnoser(FD, CE); 17210 17211 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 17212 return true; 17213 17214 return false; 17215 } 17216 17217 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 17218 // will prevent this condition from triggering, which is what we want. 17219 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 17220 SourceLocation Loc; 17221 17222 unsigned diagnostic = diag::warn_condition_is_assignment; 17223 bool IsOrAssign = false; 17224 17225 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 17226 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 17227 return; 17228 17229 IsOrAssign = Op->getOpcode() == BO_OrAssign; 17230 17231 // Greylist some idioms by putting them into a warning subcategory. 17232 if (ObjCMessageExpr *ME 17233 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 17234 Selector Sel = ME->getSelector(); 17235 17236 // self = [<foo> init...] 17237 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 17238 diagnostic = diag::warn_condition_is_idiomatic_assignment; 17239 17240 // <foo> = [<bar> nextObject] 17241 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 17242 diagnostic = diag::warn_condition_is_idiomatic_assignment; 17243 } 17244 17245 Loc = Op->getOperatorLoc(); 17246 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 17247 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 17248 return; 17249 17250 IsOrAssign = Op->getOperator() == OO_PipeEqual; 17251 Loc = Op->getOperatorLoc(); 17252 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 17253 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 17254 else { 17255 // Not an assignment. 17256 return; 17257 } 17258 17259 Diag(Loc, diagnostic) << E->getSourceRange(); 17260 17261 SourceLocation Open = E->getBeginLoc(); 17262 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 17263 Diag(Loc, diag::note_condition_assign_silence) 17264 << FixItHint::CreateInsertion(Open, "(") 17265 << FixItHint::CreateInsertion(Close, ")"); 17266 17267 if (IsOrAssign) 17268 Diag(Loc, diag::note_condition_or_assign_to_comparison) 17269 << FixItHint::CreateReplacement(Loc, "!="); 17270 else 17271 Diag(Loc, diag::note_condition_assign_to_comparison) 17272 << FixItHint::CreateReplacement(Loc, "=="); 17273 } 17274 17275 /// Redundant parentheses over an equality comparison can indicate 17276 /// that the user intended an assignment used as condition. 17277 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 17278 // Don't warn if the parens came from a macro. 17279 SourceLocation parenLoc = ParenE->getBeginLoc(); 17280 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 17281 return; 17282 // Don't warn for dependent expressions. 17283 if (ParenE->isTypeDependent()) 17284 return; 17285 17286 Expr *E = ParenE->IgnoreParens(); 17287 17288 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 17289 if (opE->getOpcode() == BO_EQ && 17290 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 17291 == Expr::MLV_Valid) { 17292 SourceLocation Loc = opE->getOperatorLoc(); 17293 17294 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 17295 SourceRange ParenERange = ParenE->getSourceRange(); 17296 Diag(Loc, diag::note_equality_comparison_silence) 17297 << FixItHint::CreateRemoval(ParenERange.getBegin()) 17298 << FixItHint::CreateRemoval(ParenERange.getEnd()); 17299 Diag(Loc, diag::note_equality_comparison_to_assign) 17300 << FixItHint::CreateReplacement(Loc, "="); 17301 } 17302 } 17303 17304 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 17305 bool IsConstexpr) { 17306 DiagnoseAssignmentAsCondition(E); 17307 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 17308 DiagnoseEqualityWithExtraParens(parenE); 17309 17310 ExprResult result = CheckPlaceholderExpr(E); 17311 if (result.isInvalid()) return ExprError(); 17312 E = result.get(); 17313 17314 if (!E->isTypeDependent()) { 17315 if (getLangOpts().CPlusPlus) 17316 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 17317 17318 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 17319 if (ERes.isInvalid()) 17320 return ExprError(); 17321 E = ERes.get(); 17322 17323 QualType T = E->getType(); 17324 if (!T->isScalarType()) { // C99 6.8.4.1p1 17325 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 17326 << T << E->getSourceRange(); 17327 return ExprError(); 17328 } 17329 CheckBoolLikeConversion(E, Loc); 17330 } 17331 17332 return E; 17333 } 17334 17335 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 17336 Expr *SubExpr, ConditionKind CK) { 17337 // Empty conditions are valid in for-statements. 17338 if (!SubExpr) 17339 return ConditionResult(); 17340 17341 ExprResult Cond; 17342 switch (CK) { 17343 case ConditionKind::Boolean: 17344 Cond = CheckBooleanCondition(Loc, SubExpr); 17345 break; 17346 17347 case ConditionKind::ConstexprIf: 17348 Cond = CheckBooleanCondition(Loc, SubExpr, true); 17349 break; 17350 17351 case ConditionKind::Switch: 17352 Cond = CheckSwitchCondition(Loc, SubExpr); 17353 break; 17354 } 17355 if (Cond.isInvalid()) 17356 return ConditionError(); 17357 17358 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 17359 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 17360 if (!FullExpr.get()) 17361 return ConditionError(); 17362 17363 return ConditionResult(*this, nullptr, FullExpr, 17364 CK == ConditionKind::ConstexprIf); 17365 } 17366 17367 namespace { 17368 /// A visitor for rebuilding a call to an __unknown_any expression 17369 /// to have an appropriate type. 17370 struct RebuildUnknownAnyFunction 17371 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 17372 17373 Sema &S; 17374 17375 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 17376 17377 ExprResult VisitStmt(Stmt *S) { 17378 llvm_unreachable("unexpected statement!"); 17379 } 17380 17381 ExprResult VisitExpr(Expr *E) { 17382 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 17383 << E->getSourceRange(); 17384 return ExprError(); 17385 } 17386 17387 /// Rebuild an expression which simply semantically wraps another 17388 /// expression which it shares the type and value kind of. 17389 template <class T> ExprResult rebuildSugarExpr(T *E) { 17390 ExprResult SubResult = Visit(E->getSubExpr()); 17391 if (SubResult.isInvalid()) return ExprError(); 17392 17393 Expr *SubExpr = SubResult.get(); 17394 E->setSubExpr(SubExpr); 17395 E->setType(SubExpr->getType()); 17396 E->setValueKind(SubExpr->getValueKind()); 17397 assert(E->getObjectKind() == OK_Ordinary); 17398 return E; 17399 } 17400 17401 ExprResult VisitParenExpr(ParenExpr *E) { 17402 return rebuildSugarExpr(E); 17403 } 17404 17405 ExprResult VisitUnaryExtension(UnaryOperator *E) { 17406 return rebuildSugarExpr(E); 17407 } 17408 17409 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 17410 ExprResult SubResult = Visit(E->getSubExpr()); 17411 if (SubResult.isInvalid()) return ExprError(); 17412 17413 Expr *SubExpr = SubResult.get(); 17414 E->setSubExpr(SubExpr); 17415 E->setType(S.Context.getPointerType(SubExpr->getType())); 17416 assert(E->getValueKind() == VK_RValue); 17417 assert(E->getObjectKind() == OK_Ordinary); 17418 return E; 17419 } 17420 17421 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 17422 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 17423 17424 E->setType(VD->getType()); 17425 17426 assert(E->getValueKind() == VK_RValue); 17427 if (S.getLangOpts().CPlusPlus && 17428 !(isa<CXXMethodDecl>(VD) && 17429 cast<CXXMethodDecl>(VD)->isInstance())) 17430 E->setValueKind(VK_LValue); 17431 17432 return E; 17433 } 17434 17435 ExprResult VisitMemberExpr(MemberExpr *E) { 17436 return resolveDecl(E, E->getMemberDecl()); 17437 } 17438 17439 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 17440 return resolveDecl(E, E->getDecl()); 17441 } 17442 }; 17443 } 17444 17445 /// Given a function expression of unknown-any type, try to rebuild it 17446 /// to have a function type. 17447 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 17448 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 17449 if (Result.isInvalid()) return ExprError(); 17450 return S.DefaultFunctionArrayConversion(Result.get()); 17451 } 17452 17453 namespace { 17454 /// A visitor for rebuilding an expression of type __unknown_anytype 17455 /// into one which resolves the type directly on the referring 17456 /// expression. Strict preservation of the original source 17457 /// structure is not a goal. 17458 struct RebuildUnknownAnyExpr 17459 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 17460 17461 Sema &S; 17462 17463 /// The current destination type. 17464 QualType DestType; 17465 17466 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 17467 : S(S), DestType(CastType) {} 17468 17469 ExprResult VisitStmt(Stmt *S) { 17470 llvm_unreachable("unexpected statement!"); 17471 } 17472 17473 ExprResult VisitExpr(Expr *E) { 17474 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 17475 << E->getSourceRange(); 17476 return ExprError(); 17477 } 17478 17479 ExprResult VisitCallExpr(CallExpr *E); 17480 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 17481 17482 /// Rebuild an expression which simply semantically wraps another 17483 /// expression which it shares the type and value kind of. 17484 template <class T> ExprResult rebuildSugarExpr(T *E) { 17485 ExprResult SubResult = Visit(E->getSubExpr()); 17486 if (SubResult.isInvalid()) return ExprError(); 17487 Expr *SubExpr = SubResult.get(); 17488 E->setSubExpr(SubExpr); 17489 E->setType(SubExpr->getType()); 17490 E->setValueKind(SubExpr->getValueKind()); 17491 assert(E->getObjectKind() == OK_Ordinary); 17492 return E; 17493 } 17494 17495 ExprResult VisitParenExpr(ParenExpr *E) { 17496 return rebuildSugarExpr(E); 17497 } 17498 17499 ExprResult VisitUnaryExtension(UnaryOperator *E) { 17500 return rebuildSugarExpr(E); 17501 } 17502 17503 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 17504 const PointerType *Ptr = DestType->getAs<PointerType>(); 17505 if (!Ptr) { 17506 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 17507 << E->getSourceRange(); 17508 return ExprError(); 17509 } 17510 17511 if (isa<CallExpr>(E->getSubExpr())) { 17512 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 17513 << E->getSourceRange(); 17514 return ExprError(); 17515 } 17516 17517 assert(E->getValueKind() == VK_RValue); 17518 assert(E->getObjectKind() == OK_Ordinary); 17519 E->setType(DestType); 17520 17521 // Build the sub-expression as if it were an object of the pointee type. 17522 DestType = Ptr->getPointeeType(); 17523 ExprResult SubResult = Visit(E->getSubExpr()); 17524 if (SubResult.isInvalid()) return ExprError(); 17525 E->setSubExpr(SubResult.get()); 17526 return E; 17527 } 17528 17529 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 17530 17531 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 17532 17533 ExprResult VisitMemberExpr(MemberExpr *E) { 17534 return resolveDecl(E, E->getMemberDecl()); 17535 } 17536 17537 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 17538 return resolveDecl(E, E->getDecl()); 17539 } 17540 }; 17541 } 17542 17543 /// Rebuilds a call expression which yielded __unknown_anytype. 17544 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 17545 Expr *CalleeExpr = E->getCallee(); 17546 17547 enum FnKind { 17548 FK_MemberFunction, 17549 FK_FunctionPointer, 17550 FK_BlockPointer 17551 }; 17552 17553 FnKind Kind; 17554 QualType CalleeType = CalleeExpr->getType(); 17555 if (CalleeType == S.Context.BoundMemberTy) { 17556 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 17557 Kind = FK_MemberFunction; 17558 CalleeType = Expr::findBoundMemberType(CalleeExpr); 17559 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 17560 CalleeType = Ptr->getPointeeType(); 17561 Kind = FK_FunctionPointer; 17562 } else { 17563 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 17564 Kind = FK_BlockPointer; 17565 } 17566 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 17567 17568 // Verify that this is a legal result type of a function. 17569 if (DestType->isArrayType() || DestType->isFunctionType()) { 17570 unsigned diagID = diag::err_func_returning_array_function; 17571 if (Kind == FK_BlockPointer) 17572 diagID = diag::err_block_returning_array_function; 17573 17574 S.Diag(E->getExprLoc(), diagID) 17575 << DestType->isFunctionType() << DestType; 17576 return ExprError(); 17577 } 17578 17579 // Otherwise, go ahead and set DestType as the call's result. 17580 E->setType(DestType.getNonLValueExprType(S.Context)); 17581 E->setValueKind(Expr::getValueKindForType(DestType)); 17582 assert(E->getObjectKind() == OK_Ordinary); 17583 17584 // Rebuild the function type, replacing the result type with DestType. 17585 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 17586 if (Proto) { 17587 // __unknown_anytype(...) is a special case used by the debugger when 17588 // it has no idea what a function's signature is. 17589 // 17590 // We want to build this call essentially under the K&R 17591 // unprototyped rules, but making a FunctionNoProtoType in C++ 17592 // would foul up all sorts of assumptions. However, we cannot 17593 // simply pass all arguments as variadic arguments, nor can we 17594 // portably just call the function under a non-variadic type; see 17595 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 17596 // However, it turns out that in practice it is generally safe to 17597 // call a function declared as "A foo(B,C,D);" under the prototype 17598 // "A foo(B,C,D,...);". The only known exception is with the 17599 // Windows ABI, where any variadic function is implicitly cdecl 17600 // regardless of its normal CC. Therefore we change the parameter 17601 // types to match the types of the arguments. 17602 // 17603 // This is a hack, but it is far superior to moving the 17604 // corresponding target-specific code from IR-gen to Sema/AST. 17605 17606 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 17607 SmallVector<QualType, 8> ArgTypes; 17608 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 17609 ArgTypes.reserve(E->getNumArgs()); 17610 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 17611 Expr *Arg = E->getArg(i); 17612 QualType ArgType = Arg->getType(); 17613 if (E->isLValue()) { 17614 ArgType = S.Context.getLValueReferenceType(ArgType); 17615 } else if (E->isXValue()) { 17616 ArgType = S.Context.getRValueReferenceType(ArgType); 17617 } 17618 ArgTypes.push_back(ArgType); 17619 } 17620 ParamTypes = ArgTypes; 17621 } 17622 DestType = S.Context.getFunctionType(DestType, ParamTypes, 17623 Proto->getExtProtoInfo()); 17624 } else { 17625 DestType = S.Context.getFunctionNoProtoType(DestType, 17626 FnType->getExtInfo()); 17627 } 17628 17629 // Rebuild the appropriate pointer-to-function type. 17630 switch (Kind) { 17631 case FK_MemberFunction: 17632 // Nothing to do. 17633 break; 17634 17635 case FK_FunctionPointer: 17636 DestType = S.Context.getPointerType(DestType); 17637 break; 17638 17639 case FK_BlockPointer: 17640 DestType = S.Context.getBlockPointerType(DestType); 17641 break; 17642 } 17643 17644 // Finally, we can recurse. 17645 ExprResult CalleeResult = Visit(CalleeExpr); 17646 if (!CalleeResult.isUsable()) return ExprError(); 17647 E->setCallee(CalleeResult.get()); 17648 17649 // Bind a temporary if necessary. 17650 return S.MaybeBindToTemporary(E); 17651 } 17652 17653 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 17654 // Verify that this is a legal result type of a call. 17655 if (DestType->isArrayType() || DestType->isFunctionType()) { 17656 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 17657 << DestType->isFunctionType() << DestType; 17658 return ExprError(); 17659 } 17660 17661 // Rewrite the method result type if available. 17662 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 17663 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 17664 Method->setReturnType(DestType); 17665 } 17666 17667 // Change the type of the message. 17668 E->setType(DestType.getNonReferenceType()); 17669 E->setValueKind(Expr::getValueKindForType(DestType)); 17670 17671 return S.MaybeBindToTemporary(E); 17672 } 17673 17674 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 17675 // The only case we should ever see here is a function-to-pointer decay. 17676 if (E->getCastKind() == CK_FunctionToPointerDecay) { 17677 assert(E->getValueKind() == VK_RValue); 17678 assert(E->getObjectKind() == OK_Ordinary); 17679 17680 E->setType(DestType); 17681 17682 // Rebuild the sub-expression as the pointee (function) type. 17683 DestType = DestType->castAs<PointerType>()->getPointeeType(); 17684 17685 ExprResult Result = Visit(E->getSubExpr()); 17686 if (!Result.isUsable()) return ExprError(); 17687 17688 E->setSubExpr(Result.get()); 17689 return E; 17690 } else if (E->getCastKind() == CK_LValueToRValue) { 17691 assert(E->getValueKind() == VK_RValue); 17692 assert(E->getObjectKind() == OK_Ordinary); 17693 17694 assert(isa<BlockPointerType>(E->getType())); 17695 17696 E->setType(DestType); 17697 17698 // The sub-expression has to be a lvalue reference, so rebuild it as such. 17699 DestType = S.Context.getLValueReferenceType(DestType); 17700 17701 ExprResult Result = Visit(E->getSubExpr()); 17702 if (!Result.isUsable()) return ExprError(); 17703 17704 E->setSubExpr(Result.get()); 17705 return E; 17706 } else { 17707 llvm_unreachable("Unhandled cast type!"); 17708 } 17709 } 17710 17711 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 17712 ExprValueKind ValueKind = VK_LValue; 17713 QualType Type = DestType; 17714 17715 // We know how to make this work for certain kinds of decls: 17716 17717 // - functions 17718 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 17719 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 17720 DestType = Ptr->getPointeeType(); 17721 ExprResult Result = resolveDecl(E, VD); 17722 if (Result.isInvalid()) return ExprError(); 17723 return S.ImpCastExprToType(Result.get(), Type, 17724 CK_FunctionToPointerDecay, VK_RValue); 17725 } 17726 17727 if (!Type->isFunctionType()) { 17728 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 17729 << VD << E->getSourceRange(); 17730 return ExprError(); 17731 } 17732 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 17733 // We must match the FunctionDecl's type to the hack introduced in 17734 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 17735 // type. See the lengthy commentary in that routine. 17736 QualType FDT = FD->getType(); 17737 const FunctionType *FnType = FDT->castAs<FunctionType>(); 17738 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 17739 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 17740 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 17741 SourceLocation Loc = FD->getLocation(); 17742 FunctionDecl *NewFD = FunctionDecl::Create( 17743 S.Context, FD->getDeclContext(), Loc, Loc, 17744 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 17745 SC_None, false /*isInlineSpecified*/, FD->hasPrototype(), 17746 /*ConstexprKind*/ CSK_unspecified); 17747 17748 if (FD->getQualifier()) 17749 NewFD->setQualifierInfo(FD->getQualifierLoc()); 17750 17751 SmallVector<ParmVarDecl*, 16> Params; 17752 for (const auto &AI : FT->param_types()) { 17753 ParmVarDecl *Param = 17754 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 17755 Param->setScopeInfo(0, Params.size()); 17756 Params.push_back(Param); 17757 } 17758 NewFD->setParams(Params); 17759 DRE->setDecl(NewFD); 17760 VD = DRE->getDecl(); 17761 } 17762 } 17763 17764 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 17765 if (MD->isInstance()) { 17766 ValueKind = VK_RValue; 17767 Type = S.Context.BoundMemberTy; 17768 } 17769 17770 // Function references aren't l-values in C. 17771 if (!S.getLangOpts().CPlusPlus) 17772 ValueKind = VK_RValue; 17773 17774 // - variables 17775 } else if (isa<VarDecl>(VD)) { 17776 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 17777 Type = RefTy->getPointeeType(); 17778 } else if (Type->isFunctionType()) { 17779 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 17780 << VD << E->getSourceRange(); 17781 return ExprError(); 17782 } 17783 17784 // - nothing else 17785 } else { 17786 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 17787 << VD << E->getSourceRange(); 17788 return ExprError(); 17789 } 17790 17791 // Modifying the declaration like this is friendly to IR-gen but 17792 // also really dangerous. 17793 VD->setType(DestType); 17794 E->setType(Type); 17795 E->setValueKind(ValueKind); 17796 return E; 17797 } 17798 17799 /// Check a cast of an unknown-any type. We intentionally only 17800 /// trigger this for C-style casts. 17801 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 17802 Expr *CastExpr, CastKind &CastKind, 17803 ExprValueKind &VK, CXXCastPath &Path) { 17804 // The type we're casting to must be either void or complete. 17805 if (!CastType->isVoidType() && 17806 RequireCompleteType(TypeRange.getBegin(), CastType, 17807 diag::err_typecheck_cast_to_incomplete)) 17808 return ExprError(); 17809 17810 // Rewrite the casted expression from scratch. 17811 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 17812 if (!result.isUsable()) return ExprError(); 17813 17814 CastExpr = result.get(); 17815 VK = CastExpr->getValueKind(); 17816 CastKind = CK_NoOp; 17817 17818 return CastExpr; 17819 } 17820 17821 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 17822 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 17823 } 17824 17825 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 17826 Expr *arg, QualType ¶mType) { 17827 // If the syntactic form of the argument is not an explicit cast of 17828 // any sort, just do default argument promotion. 17829 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 17830 if (!castArg) { 17831 ExprResult result = DefaultArgumentPromotion(arg); 17832 if (result.isInvalid()) return ExprError(); 17833 paramType = result.get()->getType(); 17834 return result; 17835 } 17836 17837 // Otherwise, use the type that was written in the explicit cast. 17838 assert(!arg->hasPlaceholderType()); 17839 paramType = castArg->getTypeAsWritten(); 17840 17841 // Copy-initialize a parameter of that type. 17842 InitializedEntity entity = 17843 InitializedEntity::InitializeParameter(Context, paramType, 17844 /*consumed*/ false); 17845 return PerformCopyInitialization(entity, callLoc, arg); 17846 } 17847 17848 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 17849 Expr *orig = E; 17850 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 17851 while (true) { 17852 E = E->IgnoreParenImpCasts(); 17853 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 17854 E = call->getCallee(); 17855 diagID = diag::err_uncasted_call_of_unknown_any; 17856 } else { 17857 break; 17858 } 17859 } 17860 17861 SourceLocation loc; 17862 NamedDecl *d; 17863 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 17864 loc = ref->getLocation(); 17865 d = ref->getDecl(); 17866 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 17867 loc = mem->getMemberLoc(); 17868 d = mem->getMemberDecl(); 17869 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 17870 diagID = diag::err_uncasted_call_of_unknown_any; 17871 loc = msg->getSelectorStartLoc(); 17872 d = msg->getMethodDecl(); 17873 if (!d) { 17874 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 17875 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 17876 << orig->getSourceRange(); 17877 return ExprError(); 17878 } 17879 } else { 17880 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 17881 << E->getSourceRange(); 17882 return ExprError(); 17883 } 17884 17885 S.Diag(loc, diagID) << d << orig->getSourceRange(); 17886 17887 // Never recoverable. 17888 return ExprError(); 17889 } 17890 17891 /// Check for operands with placeholder types and complain if found. 17892 /// Returns ExprError() if there was an error and no recovery was possible. 17893 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 17894 if (!getLangOpts().CPlusPlus) { 17895 // C cannot handle TypoExpr nodes on either side of a binop because it 17896 // doesn't handle dependent types properly, so make sure any TypoExprs have 17897 // been dealt with before checking the operands. 17898 ExprResult Result = CorrectDelayedTyposInExpr(E); 17899 if (!Result.isUsable()) return ExprError(); 17900 E = Result.get(); 17901 } 17902 17903 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 17904 if (!placeholderType) return E; 17905 17906 switch (placeholderType->getKind()) { 17907 17908 // Overloaded expressions. 17909 case BuiltinType::Overload: { 17910 // Try to resolve a single function template specialization. 17911 // This is obligatory. 17912 ExprResult Result = E; 17913 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 17914 return Result; 17915 17916 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 17917 // leaves Result unchanged on failure. 17918 Result = E; 17919 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) 17920 return Result; 17921 17922 // If that failed, try to recover with a call. 17923 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 17924 /*complain*/ true); 17925 return Result; 17926 } 17927 17928 // Bound member functions. 17929 case BuiltinType::BoundMember: { 17930 ExprResult result = E; 17931 const Expr *BME = E->IgnoreParens(); 17932 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 17933 // Try to give a nicer diagnostic if it is a bound member that we recognize. 17934 if (isa<CXXPseudoDestructorExpr>(BME)) { 17935 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 17936 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 17937 if (ME->getMemberNameInfo().getName().getNameKind() == 17938 DeclarationName::CXXDestructorName) 17939 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 17940 } 17941 tryToRecoverWithCall(result, PD, 17942 /*complain*/ true); 17943 return result; 17944 } 17945 17946 // ARC unbridged casts. 17947 case BuiltinType::ARCUnbridgedCast: { 17948 Expr *realCast = stripARCUnbridgedCast(E); 17949 diagnoseARCUnbridgedCast(realCast); 17950 return realCast; 17951 } 17952 17953 // Expressions of unknown type. 17954 case BuiltinType::UnknownAny: 17955 return diagnoseUnknownAnyExpr(*this, E); 17956 17957 // Pseudo-objects. 17958 case BuiltinType::PseudoObject: 17959 return checkPseudoObjectRValue(E); 17960 17961 case BuiltinType::BuiltinFn: { 17962 // Accept __noop without parens by implicitly converting it to a call expr. 17963 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 17964 if (DRE) { 17965 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 17966 if (FD->getBuiltinID() == Builtin::BI__noop) { 17967 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 17968 CK_BuiltinFnToFnPtr) 17969 .get(); 17970 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 17971 VK_RValue, SourceLocation()); 17972 } 17973 } 17974 17975 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 17976 return ExprError(); 17977 } 17978 17979 // Expressions of unknown type. 17980 case BuiltinType::OMPArraySection: 17981 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 17982 return ExprError(); 17983 17984 // Everything else should be impossible. 17985 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 17986 case BuiltinType::Id: 17987 #include "clang/Basic/OpenCLImageTypes.def" 17988 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 17989 case BuiltinType::Id: 17990 #include "clang/Basic/OpenCLExtensionTypes.def" 17991 #define SVE_TYPE(Name, Id, SingletonId) \ 17992 case BuiltinType::Id: 17993 #include "clang/Basic/AArch64SVEACLETypes.def" 17994 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 17995 #define PLACEHOLDER_TYPE(Id, SingletonId) 17996 #include "clang/AST/BuiltinTypes.def" 17997 break; 17998 } 17999 18000 llvm_unreachable("invalid placeholder type!"); 18001 } 18002 18003 bool Sema::CheckCaseExpression(Expr *E) { 18004 if (E->isTypeDependent()) 18005 return true; 18006 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 18007 return E->getType()->isIntegralOrEnumerationType(); 18008 return false; 18009 } 18010 18011 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 18012 ExprResult 18013 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 18014 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 18015 "Unknown Objective-C Boolean value!"); 18016 QualType BoolT = Context.ObjCBuiltinBoolTy; 18017 if (!Context.getBOOLDecl()) { 18018 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 18019 Sema::LookupOrdinaryName); 18020 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 18021 NamedDecl *ND = Result.getFoundDecl(); 18022 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 18023 Context.setBOOLDecl(TD); 18024 } 18025 } 18026 if (Context.getBOOLDecl()) 18027 BoolT = Context.getBOOLType(); 18028 return new (Context) 18029 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 18030 } 18031 18032 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 18033 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 18034 SourceLocation RParen) { 18035 18036 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 18037 18038 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 18039 return Spec.getPlatform() == Platform; 18040 }); 18041 18042 VersionTuple Version; 18043 if (Spec != AvailSpecs.end()) 18044 Version = Spec->getVersion(); 18045 18046 // The use of `@available` in the enclosing function should be analyzed to 18047 // warn when it's used inappropriately (i.e. not if(@available)). 18048 if (getCurFunctionOrMethodDecl()) 18049 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 18050 else if (getCurBlock() || getCurLambda()) 18051 getCurFunction()->HasPotentialAvailabilityViolations = true; 18052 18053 return new (Context) 18054 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 18055 } 18056