1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for expressions. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "TreeTransform.h" 14 #include "clang/AST/ASTConsumer.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTLambda.h" 17 #include "clang/AST/ASTMutationListener.h" 18 #include "clang/AST/CXXInheritance.h" 19 #include "clang/AST/DeclObjC.h" 20 #include "clang/AST/DeclTemplate.h" 21 #include "clang/AST/EvaluatedExprVisitor.h" 22 #include "clang/AST/Expr.h" 23 #include "clang/AST/ExprCXX.h" 24 #include "clang/AST/ExprObjC.h" 25 #include "clang/AST/ExprOpenMP.h" 26 #include "clang/AST/RecursiveASTVisitor.h" 27 #include "clang/AST/TypeLoc.h" 28 #include "clang/Basic/FixedPoint.h" 29 #include "clang/Basic/PartialDiagnostic.h" 30 #include "clang/Basic/SourceManager.h" 31 #include "clang/Basic/TargetInfo.h" 32 #include "clang/Lex/LiteralSupport.h" 33 #include "clang/Lex/Preprocessor.h" 34 #include "clang/Sema/AnalysisBasedWarnings.h" 35 #include "clang/Sema/DeclSpec.h" 36 #include "clang/Sema/DelayedDiagnostic.h" 37 #include "clang/Sema/Designator.h" 38 #include "clang/Sema/Initialization.h" 39 #include "clang/Sema/Lookup.h" 40 #include "clang/Sema/Overload.h" 41 #include "clang/Sema/ParsedTemplate.h" 42 #include "clang/Sema/Scope.h" 43 #include "clang/Sema/ScopeInfo.h" 44 #include "clang/Sema/SemaFixItUtils.h" 45 #include "clang/Sema/SemaInternal.h" 46 #include "clang/Sema/Template.h" 47 #include "llvm/Support/ConvertUTF.h" 48 using namespace clang; 49 using namespace sema; 50 51 /// Determine whether the use of this declaration is valid, without 52 /// emitting diagnostics. 53 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 54 // See if this is an auto-typed variable whose initializer we are parsing. 55 if (ParsingInitForAutoVars.count(D)) 56 return false; 57 58 // See if this is a deleted function. 59 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 60 if (FD->isDeleted()) 61 return false; 62 63 // If the function has a deduced return type, and we can't deduce it, 64 // then we can't use it either. 65 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 66 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 67 return false; 68 69 // See if this is an aligned allocation/deallocation function that is 70 // unavailable. 71 if (TreatUnavailableAsInvalid && 72 isUnavailableAlignedAllocationFunction(*FD)) 73 return false; 74 } 75 76 // See if this function is unavailable. 77 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 78 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 79 return false; 80 81 return true; 82 } 83 84 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 85 // Warn if this is used but marked unused. 86 if (const auto *A = D->getAttr<UnusedAttr>()) { 87 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 88 // should diagnose them. 89 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 90 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 91 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 92 if (DC && !DC->hasAttr<UnusedAttr>()) 93 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 94 } 95 } 96 } 97 98 /// Emit a note explaining that this function is deleted. 99 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 100 assert(Decl->isDeleted()); 101 102 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 103 104 if (Method && Method->isDeleted() && Method->isDefaulted()) { 105 // If the method was explicitly defaulted, point at that declaration. 106 if (!Method->isImplicit()) 107 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 108 109 // Try to diagnose why this special member function was implicitly 110 // deleted. This might fail, if that reason no longer applies. 111 CXXSpecialMember CSM = getSpecialMember(Method); 112 if (CSM != CXXInvalid) 113 ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true); 114 115 return; 116 } 117 118 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 119 if (Ctor && Ctor->isInheritingConstructor()) 120 return NoteDeletedInheritingConstructor(Ctor); 121 122 Diag(Decl->getLocation(), diag::note_availability_specified_here) 123 << Decl << 1; 124 } 125 126 /// Determine whether a FunctionDecl was ever declared with an 127 /// explicit storage class. 128 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 129 for (auto I : D->redecls()) { 130 if (I->getStorageClass() != SC_None) 131 return true; 132 } 133 return false; 134 } 135 136 /// Check whether we're in an extern inline function and referring to a 137 /// variable or function with internal linkage (C11 6.7.4p3). 138 /// 139 /// This is only a warning because we used to silently accept this code, but 140 /// in many cases it will not behave correctly. This is not enabled in C++ mode 141 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 142 /// and so while there may still be user mistakes, most of the time we can't 143 /// prove that there are errors. 144 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 145 const NamedDecl *D, 146 SourceLocation Loc) { 147 // This is disabled under C++; there are too many ways for this to fire in 148 // contexts where the warning is a false positive, or where it is technically 149 // correct but benign. 150 if (S.getLangOpts().CPlusPlus) 151 return; 152 153 // Check if this is an inlined function or method. 154 FunctionDecl *Current = S.getCurFunctionDecl(); 155 if (!Current) 156 return; 157 if (!Current->isInlined()) 158 return; 159 if (!Current->isExternallyVisible()) 160 return; 161 162 // Check if the decl has internal linkage. 163 if (D->getFormalLinkage() != InternalLinkage) 164 return; 165 166 // Downgrade from ExtWarn to Extension if 167 // (1) the supposedly external inline function is in the main file, 168 // and probably won't be included anywhere else. 169 // (2) the thing we're referencing is a pure function. 170 // (3) the thing we're referencing is another inline function. 171 // This last can give us false negatives, but it's better than warning on 172 // wrappers for simple C library functions. 173 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 174 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 175 if (!DowngradeWarning && UsedFn) 176 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 177 178 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 179 : diag::ext_internal_in_extern_inline) 180 << /*IsVar=*/!UsedFn << D; 181 182 S.MaybeSuggestAddingStaticToDecl(Current); 183 184 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 185 << D; 186 } 187 188 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 189 const FunctionDecl *First = Cur->getFirstDecl(); 190 191 // Suggest "static" on the function, if possible. 192 if (!hasAnyExplicitStorageClass(First)) { 193 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 194 Diag(DeclBegin, diag::note_convert_inline_to_static) 195 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 196 } 197 } 198 199 /// Determine whether the use of this declaration is valid, and 200 /// emit any corresponding diagnostics. 201 /// 202 /// This routine diagnoses various problems with referencing 203 /// declarations that can occur when using a declaration. For example, 204 /// it might warn if a deprecated or unavailable declaration is being 205 /// used, or produce an error (and return true) if a C++0x deleted 206 /// function is being used. 207 /// 208 /// \returns true if there was an error (this declaration cannot be 209 /// referenced), false otherwise. 210 /// 211 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 212 const ObjCInterfaceDecl *UnknownObjCClass, 213 bool ObjCPropertyAccess, 214 bool AvoidPartialAvailabilityChecks, 215 ObjCInterfaceDecl *ClassReceiver) { 216 SourceLocation Loc = Locs.front(); 217 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 218 // If there were any diagnostics suppressed by template argument deduction, 219 // emit them now. 220 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 221 if (Pos != SuppressedDiagnostics.end()) { 222 for (const PartialDiagnosticAt &Suppressed : Pos->second) 223 Diag(Suppressed.first, Suppressed.second); 224 225 // Clear out the list of suppressed diagnostics, so that we don't emit 226 // them again for this specialization. However, we don't obsolete this 227 // entry from the table, because we want to avoid ever emitting these 228 // diagnostics again. 229 Pos->second.clear(); 230 } 231 232 // C++ [basic.start.main]p3: 233 // The function 'main' shall not be used within a program. 234 if (cast<FunctionDecl>(D)->isMain()) 235 Diag(Loc, diag::ext_main_used); 236 237 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); 238 } 239 240 // See if this is an auto-typed variable whose initializer we are parsing. 241 if (ParsingInitForAutoVars.count(D)) { 242 if (isa<BindingDecl>(D)) { 243 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 244 << D->getDeclName(); 245 } else { 246 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 247 << D->getDeclName() << cast<VarDecl>(D)->getType(); 248 } 249 return true; 250 } 251 252 // See if this is a deleted function. 253 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 254 if (FD->isDeleted()) { 255 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 256 if (Ctor && Ctor->isInheritingConstructor()) 257 Diag(Loc, diag::err_deleted_inherited_ctor_use) 258 << Ctor->getParent() 259 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 260 else 261 Diag(Loc, diag::err_deleted_function_use); 262 NoteDeletedFunction(FD); 263 return true; 264 } 265 266 // If the function has a deduced return type, and we can't deduce it, 267 // then we can't use it either. 268 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 269 DeduceReturnType(FD, Loc)) 270 return true; 271 272 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 273 return true; 274 } 275 276 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 277 // Lambdas are only default-constructible or assignable in C++2a onwards. 278 if (MD->getParent()->isLambda() && 279 ((isa<CXXConstructorDecl>(MD) && 280 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || 281 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { 282 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) 283 << !isa<CXXConstructorDecl>(MD); 284 } 285 } 286 287 auto getReferencedObjCProp = [](const NamedDecl *D) -> 288 const ObjCPropertyDecl * { 289 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 290 return MD->findPropertyDecl(); 291 return nullptr; 292 }; 293 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 294 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 295 return true; 296 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 297 return true; 298 } 299 300 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 301 // Only the variables omp_in and omp_out are allowed in the combiner. 302 // Only the variables omp_priv and omp_orig are allowed in the 303 // initializer-clause. 304 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 305 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 306 isa<VarDecl>(D)) { 307 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 308 << getCurFunction()->HasOMPDeclareReductionCombiner; 309 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 310 return true; 311 } 312 313 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions 314 // List-items in map clauses on this construct may only refer to the declared 315 // variable var and entities that could be referenced by a procedure defined 316 // at the same location 317 auto *DMD = dyn_cast<OMPDeclareMapperDecl>(CurContext); 318 if (LangOpts.OpenMP && DMD && !CurContext->containsDecl(D) && 319 isa<VarDecl>(D)) { 320 Diag(Loc, diag::err_omp_declare_mapper_wrong_var) 321 << DMD->getVarName().getAsString(); 322 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 323 return true; 324 } 325 326 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 327 AvoidPartialAvailabilityChecks, ClassReceiver); 328 329 DiagnoseUnusedOfDecl(*this, D, Loc); 330 331 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 332 333 return false; 334 } 335 336 /// DiagnoseSentinelCalls - This routine checks whether a call or 337 /// message-send is to a declaration with the sentinel attribute, and 338 /// if so, it checks that the requirements of the sentinel are 339 /// satisfied. 340 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 341 ArrayRef<Expr *> Args) { 342 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 343 if (!attr) 344 return; 345 346 // The number of formal parameters of the declaration. 347 unsigned numFormalParams; 348 349 // The kind of declaration. This is also an index into a %select in 350 // the diagnostic. 351 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 352 353 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 354 numFormalParams = MD->param_size(); 355 calleeType = CT_Method; 356 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 357 numFormalParams = FD->param_size(); 358 calleeType = CT_Function; 359 } else if (isa<VarDecl>(D)) { 360 QualType type = cast<ValueDecl>(D)->getType(); 361 const FunctionType *fn = nullptr; 362 if (const PointerType *ptr = type->getAs<PointerType>()) { 363 fn = ptr->getPointeeType()->getAs<FunctionType>(); 364 if (!fn) return; 365 calleeType = CT_Function; 366 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 367 fn = ptr->getPointeeType()->castAs<FunctionType>(); 368 calleeType = CT_Block; 369 } else { 370 return; 371 } 372 373 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 374 numFormalParams = proto->getNumParams(); 375 } else { 376 numFormalParams = 0; 377 } 378 } else { 379 return; 380 } 381 382 // "nullPos" is the number of formal parameters at the end which 383 // effectively count as part of the variadic arguments. This is 384 // useful if you would prefer to not have *any* formal parameters, 385 // but the language forces you to have at least one. 386 unsigned nullPos = attr->getNullPos(); 387 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 388 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 389 390 // The number of arguments which should follow the sentinel. 391 unsigned numArgsAfterSentinel = attr->getSentinel(); 392 393 // If there aren't enough arguments for all the formal parameters, 394 // the sentinel, and the args after the sentinel, complain. 395 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 396 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 397 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 398 return; 399 } 400 401 // Otherwise, find the sentinel expression. 402 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 403 if (!sentinelExpr) return; 404 if (sentinelExpr->isValueDependent()) return; 405 if (Context.isSentinelNullExpr(sentinelExpr)) return; 406 407 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 408 // or 'NULL' if those are actually defined in the context. Only use 409 // 'nil' for ObjC methods, where it's much more likely that the 410 // variadic arguments form a list of object pointers. 411 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 412 std::string NullValue; 413 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 414 NullValue = "nil"; 415 else if (getLangOpts().CPlusPlus11) 416 NullValue = "nullptr"; 417 else if (PP.isMacroDefined("NULL")) 418 NullValue = "NULL"; 419 else 420 NullValue = "(void*) 0"; 421 422 if (MissingNilLoc.isInvalid()) 423 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 424 else 425 Diag(MissingNilLoc, diag::warn_missing_sentinel) 426 << int(calleeType) 427 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 428 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 429 } 430 431 SourceRange Sema::getExprRange(Expr *E) const { 432 return E ? E->getSourceRange() : SourceRange(); 433 } 434 435 //===----------------------------------------------------------------------===// 436 // Standard Promotions and Conversions 437 //===----------------------------------------------------------------------===// 438 439 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 440 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 441 // Handle any placeholder expressions which made it here. 442 if (E->getType()->isPlaceholderType()) { 443 ExprResult result = CheckPlaceholderExpr(E); 444 if (result.isInvalid()) return ExprError(); 445 E = result.get(); 446 } 447 448 QualType Ty = E->getType(); 449 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 450 451 if (Ty->isFunctionType()) { 452 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 453 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 454 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 455 return ExprError(); 456 457 E = ImpCastExprToType(E, Context.getPointerType(Ty), 458 CK_FunctionToPointerDecay).get(); 459 } else if (Ty->isArrayType()) { 460 // In C90 mode, arrays only promote to pointers if the array expression is 461 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 462 // type 'array of type' is converted to an expression that has type 'pointer 463 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 464 // that has type 'array of type' ...". The relevant change is "an lvalue" 465 // (C90) to "an expression" (C99). 466 // 467 // C++ 4.2p1: 468 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 469 // T" can be converted to an rvalue of type "pointer to T". 470 // 471 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 472 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 473 CK_ArrayToPointerDecay).get(); 474 } 475 return E; 476 } 477 478 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 479 // Check to see if we are dereferencing a null pointer. If so, 480 // and if not volatile-qualified, this is undefined behavior that the 481 // optimizer will delete, so warn about it. People sometimes try to use this 482 // to get a deterministic trap and are surprised by clang's behavior. This 483 // only handles the pattern "*null", which is a very syntactic check. 484 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); 485 if (UO && UO->getOpcode() == UO_Deref) { 486 const LangAS AS = 487 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); 488 if ((!isTargetAddressSpace(AS) || 489 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && 490 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( 491 S.Context, Expr::NPC_ValueDependentIsNotNull) && 492 !UO->getType().isVolatileQualified()) { 493 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 494 S.PDiag(diag::warn_indirection_through_null) 495 << UO->getSubExpr()->getSourceRange()); 496 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 497 S.PDiag(diag::note_indirection_through_null)); 498 } 499 } 500 } 501 502 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 503 SourceLocation AssignLoc, 504 const Expr* RHS) { 505 const ObjCIvarDecl *IV = OIRE->getDecl(); 506 if (!IV) 507 return; 508 509 DeclarationName MemberName = IV->getDeclName(); 510 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 511 if (!Member || !Member->isStr("isa")) 512 return; 513 514 const Expr *Base = OIRE->getBase(); 515 QualType BaseType = Base->getType(); 516 if (OIRE->isArrow()) 517 BaseType = BaseType->getPointeeType(); 518 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 519 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 520 ObjCInterfaceDecl *ClassDeclared = nullptr; 521 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 522 if (!ClassDeclared->getSuperClass() 523 && (*ClassDeclared->ivar_begin()) == IV) { 524 if (RHS) { 525 NamedDecl *ObjectSetClass = 526 S.LookupSingleName(S.TUScope, 527 &S.Context.Idents.get("object_setClass"), 528 SourceLocation(), S.LookupOrdinaryName); 529 if (ObjectSetClass) { 530 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 531 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 532 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 533 "object_setClass(") 534 << FixItHint::CreateReplacement( 535 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 536 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 537 } 538 else 539 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 540 } else { 541 NamedDecl *ObjectGetClass = 542 S.LookupSingleName(S.TUScope, 543 &S.Context.Idents.get("object_getClass"), 544 SourceLocation(), S.LookupOrdinaryName); 545 if (ObjectGetClass) 546 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 547 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 548 "object_getClass(") 549 << FixItHint::CreateReplacement( 550 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 551 else 552 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 553 } 554 S.Diag(IV->getLocation(), diag::note_ivar_decl); 555 } 556 } 557 } 558 559 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 560 // Handle any placeholder expressions which made it here. 561 if (E->getType()->isPlaceholderType()) { 562 ExprResult result = CheckPlaceholderExpr(E); 563 if (result.isInvalid()) return ExprError(); 564 E = result.get(); 565 } 566 567 // C++ [conv.lval]p1: 568 // A glvalue of a non-function, non-array type T can be 569 // converted to a prvalue. 570 if (!E->isGLValue()) return E; 571 572 QualType T = E->getType(); 573 assert(!T.isNull() && "r-value conversion on typeless expression?"); 574 575 // We don't want to throw lvalue-to-rvalue casts on top of 576 // expressions of certain types in C++. 577 if (getLangOpts().CPlusPlus && 578 (E->getType() == Context.OverloadTy || 579 T->isDependentType() || 580 T->isRecordType())) 581 return E; 582 583 // The C standard is actually really unclear on this point, and 584 // DR106 tells us what the result should be but not why. It's 585 // generally best to say that void types just doesn't undergo 586 // lvalue-to-rvalue at all. Note that expressions of unqualified 587 // 'void' type are never l-values, but qualified void can be. 588 if (T->isVoidType()) 589 return E; 590 591 // OpenCL usually rejects direct accesses to values of 'half' type. 592 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 593 T->isHalfType()) { 594 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 595 << 0 << T; 596 return ExprError(); 597 } 598 599 CheckForNullPointerDereference(*this, E); 600 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 601 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 602 &Context.Idents.get("object_getClass"), 603 SourceLocation(), LookupOrdinaryName); 604 if (ObjectGetClass) 605 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 606 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 607 << FixItHint::CreateReplacement( 608 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 609 else 610 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 611 } 612 else if (const ObjCIvarRefExpr *OIRE = 613 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 614 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 615 616 // C++ [conv.lval]p1: 617 // [...] If T is a non-class type, the type of the prvalue is the 618 // cv-unqualified version of T. Otherwise, the type of the 619 // rvalue is T. 620 // 621 // C99 6.3.2.1p2: 622 // If the lvalue has qualified type, the value has the unqualified 623 // version of the type of the lvalue; otherwise, the value has the 624 // type of the lvalue. 625 if (T.hasQualifiers()) 626 T = T.getUnqualifiedType(); 627 628 // Under the MS ABI, lock down the inheritance model now. 629 if (T->isMemberPointerType() && 630 Context.getTargetInfo().getCXXABI().isMicrosoft()) 631 (void)isCompleteType(E->getExprLoc(), T); 632 633 ExprResult Res = CheckLValueToRValueConversionOperand(E); 634 if (Res.isInvalid()) 635 return Res; 636 E = Res.get(); 637 638 // Loading a __weak object implicitly retains the value, so we need a cleanup to 639 // balance that. 640 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 641 Cleanup.setExprNeedsCleanups(true); 642 643 // C++ [conv.lval]p3: 644 // If T is cv std::nullptr_t, the result is a null pointer constant. 645 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; 646 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue); 647 648 // C11 6.3.2.1p2: 649 // ... if the lvalue has atomic type, the value has the non-atomic version 650 // of the type of the lvalue ... 651 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 652 T = Atomic->getValueType().getUnqualifiedType(); 653 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 654 nullptr, VK_RValue); 655 } 656 657 return Res; 658 } 659 660 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 661 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 662 if (Res.isInvalid()) 663 return ExprError(); 664 Res = DefaultLvalueConversion(Res.get()); 665 if (Res.isInvalid()) 666 return ExprError(); 667 return Res; 668 } 669 670 /// CallExprUnaryConversions - a special case of an unary conversion 671 /// performed on a function designator of a call expression. 672 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 673 QualType Ty = E->getType(); 674 ExprResult Res = E; 675 // Only do implicit cast for a function type, but not for a pointer 676 // to function type. 677 if (Ty->isFunctionType()) { 678 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 679 CK_FunctionToPointerDecay).get(); 680 if (Res.isInvalid()) 681 return ExprError(); 682 } 683 Res = DefaultLvalueConversion(Res.get()); 684 if (Res.isInvalid()) 685 return ExprError(); 686 return Res.get(); 687 } 688 689 /// UsualUnaryConversions - Performs various conversions that are common to most 690 /// operators (C99 6.3). The conversions of array and function types are 691 /// sometimes suppressed. For example, the array->pointer conversion doesn't 692 /// apply if the array is an argument to the sizeof or address (&) operators. 693 /// In these instances, this routine should *not* be called. 694 ExprResult Sema::UsualUnaryConversions(Expr *E) { 695 // First, convert to an r-value. 696 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 697 if (Res.isInvalid()) 698 return ExprError(); 699 E = Res.get(); 700 701 QualType Ty = E->getType(); 702 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 703 704 // Half FP have to be promoted to float unless it is natively supported 705 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 706 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 707 708 // Try to perform integral promotions if the object has a theoretically 709 // promotable type. 710 if (Ty->isIntegralOrUnscopedEnumerationType()) { 711 // C99 6.3.1.1p2: 712 // 713 // The following may be used in an expression wherever an int or 714 // unsigned int may be used: 715 // - an object or expression with an integer type whose integer 716 // conversion rank is less than or equal to the rank of int 717 // and unsigned int. 718 // - A bit-field of type _Bool, int, signed int, or unsigned int. 719 // 720 // If an int can represent all values of the original type, the 721 // value is converted to an int; otherwise, it is converted to an 722 // unsigned int. These are called the integer promotions. All 723 // other types are unchanged by the integer promotions. 724 725 QualType PTy = Context.isPromotableBitField(E); 726 if (!PTy.isNull()) { 727 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 728 return E; 729 } 730 if (Ty->isPromotableIntegerType()) { 731 QualType PT = Context.getPromotedIntegerType(Ty); 732 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 733 return E; 734 } 735 } 736 return E; 737 } 738 739 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 740 /// do not have a prototype. Arguments that have type float or __fp16 741 /// are promoted to double. All other argument types are converted by 742 /// UsualUnaryConversions(). 743 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 744 QualType Ty = E->getType(); 745 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 746 747 ExprResult Res = UsualUnaryConversions(E); 748 if (Res.isInvalid()) 749 return ExprError(); 750 E = Res.get(); 751 752 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 753 // promote to double. 754 // Note that default argument promotion applies only to float (and 755 // half/fp16); it does not apply to _Float16. 756 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 757 if (BTy && (BTy->getKind() == BuiltinType::Half || 758 BTy->getKind() == BuiltinType::Float)) { 759 if (getLangOpts().OpenCL && 760 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 761 if (BTy->getKind() == BuiltinType::Half) { 762 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 763 } 764 } else { 765 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 766 } 767 } 768 769 // C++ performs lvalue-to-rvalue conversion as a default argument 770 // promotion, even on class types, but note: 771 // C++11 [conv.lval]p2: 772 // When an lvalue-to-rvalue conversion occurs in an unevaluated 773 // operand or a subexpression thereof the value contained in the 774 // referenced object is not accessed. Otherwise, if the glvalue 775 // has a class type, the conversion copy-initializes a temporary 776 // of type T from the glvalue and the result of the conversion 777 // is a prvalue for the temporary. 778 // FIXME: add some way to gate this entire thing for correctness in 779 // potentially potentially evaluated contexts. 780 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 781 ExprResult Temp = PerformCopyInitialization( 782 InitializedEntity::InitializeTemporary(E->getType()), 783 E->getExprLoc(), E); 784 if (Temp.isInvalid()) 785 return ExprError(); 786 E = Temp.get(); 787 } 788 789 return E; 790 } 791 792 /// Determine the degree of POD-ness for an expression. 793 /// Incomplete types are considered POD, since this check can be performed 794 /// when we're in an unevaluated context. 795 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 796 if (Ty->isIncompleteType()) { 797 // C++11 [expr.call]p7: 798 // After these conversions, if the argument does not have arithmetic, 799 // enumeration, pointer, pointer to member, or class type, the program 800 // is ill-formed. 801 // 802 // Since we've already performed array-to-pointer and function-to-pointer 803 // decay, the only such type in C++ is cv void. This also handles 804 // initializer lists as variadic arguments. 805 if (Ty->isVoidType()) 806 return VAK_Invalid; 807 808 if (Ty->isObjCObjectType()) 809 return VAK_Invalid; 810 return VAK_Valid; 811 } 812 813 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 814 return VAK_Invalid; 815 816 if (Ty.isCXX98PODType(Context)) 817 return VAK_Valid; 818 819 // C++11 [expr.call]p7: 820 // Passing a potentially-evaluated argument of class type (Clause 9) 821 // having a non-trivial copy constructor, a non-trivial move constructor, 822 // or a non-trivial destructor, with no corresponding parameter, 823 // is conditionally-supported with implementation-defined semantics. 824 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 825 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 826 if (!Record->hasNonTrivialCopyConstructor() && 827 !Record->hasNonTrivialMoveConstructor() && 828 !Record->hasNonTrivialDestructor()) 829 return VAK_ValidInCXX11; 830 831 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 832 return VAK_Valid; 833 834 if (Ty->isObjCObjectType()) 835 return VAK_Invalid; 836 837 if (getLangOpts().MSVCCompat) 838 return VAK_MSVCUndefined; 839 840 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 841 // permitted to reject them. We should consider doing so. 842 return VAK_Undefined; 843 } 844 845 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 846 // Don't allow one to pass an Objective-C interface to a vararg. 847 const QualType &Ty = E->getType(); 848 VarArgKind VAK = isValidVarArgType(Ty); 849 850 // Complain about passing non-POD types through varargs. 851 switch (VAK) { 852 case VAK_ValidInCXX11: 853 DiagRuntimeBehavior( 854 E->getBeginLoc(), nullptr, 855 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 856 LLVM_FALLTHROUGH; 857 case VAK_Valid: 858 if (Ty->isRecordType()) { 859 // This is unlikely to be what the user intended. If the class has a 860 // 'c_str' member function, the user probably meant to call that. 861 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 862 PDiag(diag::warn_pass_class_arg_to_vararg) 863 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 864 } 865 break; 866 867 case VAK_Undefined: 868 case VAK_MSVCUndefined: 869 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 870 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 871 << getLangOpts().CPlusPlus11 << Ty << CT); 872 break; 873 874 case VAK_Invalid: 875 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 876 Diag(E->getBeginLoc(), 877 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 878 << Ty << CT; 879 else if (Ty->isObjCObjectType()) 880 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 881 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 882 << Ty << CT); 883 else 884 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 885 << isa<InitListExpr>(E) << Ty << CT; 886 break; 887 } 888 } 889 890 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 891 /// will create a trap if the resulting type is not a POD type. 892 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 893 FunctionDecl *FDecl) { 894 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 895 // Strip the unbridged-cast placeholder expression off, if applicable. 896 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 897 (CT == VariadicMethod || 898 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 899 E = stripARCUnbridgedCast(E); 900 901 // Otherwise, do normal placeholder checking. 902 } else { 903 ExprResult ExprRes = CheckPlaceholderExpr(E); 904 if (ExprRes.isInvalid()) 905 return ExprError(); 906 E = ExprRes.get(); 907 } 908 } 909 910 ExprResult ExprRes = DefaultArgumentPromotion(E); 911 if (ExprRes.isInvalid()) 912 return ExprError(); 913 E = ExprRes.get(); 914 915 // Diagnostics regarding non-POD argument types are 916 // emitted along with format string checking in Sema::CheckFunctionCall(). 917 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 918 // Turn this into a trap. 919 CXXScopeSpec SS; 920 SourceLocation TemplateKWLoc; 921 UnqualifiedId Name; 922 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 923 E->getBeginLoc()); 924 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 925 /*HasTrailingLParen=*/true, 926 /*IsAddressOfOperand=*/false); 927 if (TrapFn.isInvalid()) 928 return ExprError(); 929 930 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 931 None, E->getEndLoc()); 932 if (Call.isInvalid()) 933 return ExprError(); 934 935 ExprResult Comma = 936 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 937 if (Comma.isInvalid()) 938 return ExprError(); 939 return Comma.get(); 940 } 941 942 if (!getLangOpts().CPlusPlus && 943 RequireCompleteType(E->getExprLoc(), E->getType(), 944 diag::err_call_incomplete_argument)) 945 return ExprError(); 946 947 return E; 948 } 949 950 /// Converts an integer to complex float type. Helper function of 951 /// UsualArithmeticConversions() 952 /// 953 /// \return false if the integer expression is an integer type and is 954 /// successfully converted to the complex type. 955 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 956 ExprResult &ComplexExpr, 957 QualType IntTy, 958 QualType ComplexTy, 959 bool SkipCast) { 960 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 961 if (SkipCast) return false; 962 if (IntTy->isIntegerType()) { 963 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 964 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 965 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 966 CK_FloatingRealToComplex); 967 } else { 968 assert(IntTy->isComplexIntegerType()); 969 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 970 CK_IntegralComplexToFloatingComplex); 971 } 972 return false; 973 } 974 975 /// Handle arithmetic conversion with complex types. Helper function of 976 /// UsualArithmeticConversions() 977 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 978 ExprResult &RHS, QualType LHSType, 979 QualType RHSType, 980 bool IsCompAssign) { 981 // if we have an integer operand, the result is the complex type. 982 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 983 /*skipCast*/false)) 984 return LHSType; 985 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 986 /*skipCast*/IsCompAssign)) 987 return RHSType; 988 989 // This handles complex/complex, complex/float, or float/complex. 990 // When both operands are complex, the shorter operand is converted to the 991 // type of the longer, and that is the type of the result. This corresponds 992 // to what is done when combining two real floating-point operands. 993 // The fun begins when size promotion occur across type domains. 994 // From H&S 6.3.4: When one operand is complex and the other is a real 995 // floating-point type, the less precise type is converted, within it's 996 // real or complex domain, to the precision of the other type. For example, 997 // when combining a "long double" with a "double _Complex", the 998 // "double _Complex" is promoted to "long double _Complex". 999 1000 // Compute the rank of the two types, regardless of whether they are complex. 1001 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1002 1003 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1004 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1005 QualType LHSElementType = 1006 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1007 QualType RHSElementType = 1008 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1009 1010 QualType ResultType = S.Context.getComplexType(LHSElementType); 1011 if (Order < 0) { 1012 // Promote the precision of the LHS if not an assignment. 1013 ResultType = S.Context.getComplexType(RHSElementType); 1014 if (!IsCompAssign) { 1015 if (LHSComplexType) 1016 LHS = 1017 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1018 else 1019 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1020 } 1021 } else if (Order > 0) { 1022 // Promote the precision of the RHS. 1023 if (RHSComplexType) 1024 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1025 else 1026 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1027 } 1028 return ResultType; 1029 } 1030 1031 /// Handle arithmetic conversion from integer to float. Helper function 1032 /// of UsualArithmeticConversions() 1033 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1034 ExprResult &IntExpr, 1035 QualType FloatTy, QualType IntTy, 1036 bool ConvertFloat, bool ConvertInt) { 1037 if (IntTy->isIntegerType()) { 1038 if (ConvertInt) 1039 // Convert intExpr to the lhs floating point type. 1040 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1041 CK_IntegralToFloating); 1042 return FloatTy; 1043 } 1044 1045 // Convert both sides to the appropriate complex float. 1046 assert(IntTy->isComplexIntegerType()); 1047 QualType result = S.Context.getComplexType(FloatTy); 1048 1049 // _Complex int -> _Complex float 1050 if (ConvertInt) 1051 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1052 CK_IntegralComplexToFloatingComplex); 1053 1054 // float -> _Complex float 1055 if (ConvertFloat) 1056 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1057 CK_FloatingRealToComplex); 1058 1059 return result; 1060 } 1061 1062 /// Handle arithmethic conversion with floating point types. Helper 1063 /// function of UsualArithmeticConversions() 1064 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1065 ExprResult &RHS, QualType LHSType, 1066 QualType RHSType, bool IsCompAssign) { 1067 bool LHSFloat = LHSType->isRealFloatingType(); 1068 bool RHSFloat = RHSType->isRealFloatingType(); 1069 1070 // If we have two real floating types, convert the smaller operand 1071 // to the bigger result. 1072 if (LHSFloat && RHSFloat) { 1073 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1074 if (order > 0) { 1075 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1076 return LHSType; 1077 } 1078 1079 assert(order < 0 && "illegal float comparison"); 1080 if (!IsCompAssign) 1081 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1082 return RHSType; 1083 } 1084 1085 if (LHSFloat) { 1086 // Half FP has to be promoted to float unless it is natively supported 1087 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1088 LHSType = S.Context.FloatTy; 1089 1090 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1091 /*ConvertFloat=*/!IsCompAssign, 1092 /*ConvertInt=*/ true); 1093 } 1094 assert(RHSFloat); 1095 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1096 /*convertInt=*/ true, 1097 /*convertFloat=*/!IsCompAssign); 1098 } 1099 1100 /// Diagnose attempts to convert between __float128 and long double if 1101 /// there is no support for such conversion. Helper function of 1102 /// UsualArithmeticConversions(). 1103 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1104 QualType RHSType) { 1105 /* No issue converting if at least one of the types is not a floating point 1106 type or the two types have the same rank. 1107 */ 1108 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1109 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1110 return false; 1111 1112 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1113 "The remaining types must be floating point types."); 1114 1115 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1116 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1117 1118 QualType LHSElemType = LHSComplex ? 1119 LHSComplex->getElementType() : LHSType; 1120 QualType RHSElemType = RHSComplex ? 1121 RHSComplex->getElementType() : RHSType; 1122 1123 // No issue if the two types have the same representation 1124 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1125 &S.Context.getFloatTypeSemantics(RHSElemType)) 1126 return false; 1127 1128 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1129 RHSElemType == S.Context.LongDoubleTy); 1130 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1131 RHSElemType == S.Context.Float128Ty); 1132 1133 // We've handled the situation where __float128 and long double have the same 1134 // representation. We allow all conversions for all possible long double types 1135 // except PPC's double double. 1136 return Float128AndLongDouble && 1137 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1138 &llvm::APFloat::PPCDoubleDouble()); 1139 } 1140 1141 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1142 1143 namespace { 1144 /// These helper callbacks are placed in an anonymous namespace to 1145 /// permit their use as function template parameters. 1146 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1147 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1148 } 1149 1150 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1151 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1152 CK_IntegralComplexCast); 1153 } 1154 } 1155 1156 /// Handle integer arithmetic conversions. Helper function of 1157 /// UsualArithmeticConversions() 1158 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1159 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1160 ExprResult &RHS, QualType LHSType, 1161 QualType RHSType, bool IsCompAssign) { 1162 // The rules for this case are in C99 6.3.1.8 1163 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1164 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1165 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1166 if (LHSSigned == RHSSigned) { 1167 // Same signedness; use the higher-ranked type 1168 if (order >= 0) { 1169 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1170 return LHSType; 1171 } else if (!IsCompAssign) 1172 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1173 return RHSType; 1174 } else if (order != (LHSSigned ? 1 : -1)) { 1175 // The unsigned type has greater than or equal rank to the 1176 // signed type, so use the unsigned type 1177 if (RHSSigned) { 1178 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1179 return LHSType; 1180 } else if (!IsCompAssign) 1181 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1182 return RHSType; 1183 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1184 // The two types are different widths; if we are here, that 1185 // means the signed type is larger than the unsigned type, so 1186 // use the signed type. 1187 if (LHSSigned) { 1188 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1189 return LHSType; 1190 } else if (!IsCompAssign) 1191 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1192 return RHSType; 1193 } else { 1194 // The signed type is higher-ranked than the unsigned type, 1195 // but isn't actually any bigger (like unsigned int and long 1196 // on most 32-bit systems). Use the unsigned type corresponding 1197 // to the signed type. 1198 QualType result = 1199 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1200 RHS = (*doRHSCast)(S, RHS.get(), result); 1201 if (!IsCompAssign) 1202 LHS = (*doLHSCast)(S, LHS.get(), result); 1203 return result; 1204 } 1205 } 1206 1207 /// Handle conversions with GCC complex int extension. Helper function 1208 /// of UsualArithmeticConversions() 1209 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1210 ExprResult &RHS, QualType LHSType, 1211 QualType RHSType, 1212 bool IsCompAssign) { 1213 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1214 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1215 1216 if (LHSComplexInt && RHSComplexInt) { 1217 QualType LHSEltType = LHSComplexInt->getElementType(); 1218 QualType RHSEltType = RHSComplexInt->getElementType(); 1219 QualType ScalarType = 1220 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1221 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1222 1223 return S.Context.getComplexType(ScalarType); 1224 } 1225 1226 if (LHSComplexInt) { 1227 QualType LHSEltType = LHSComplexInt->getElementType(); 1228 QualType ScalarType = 1229 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1230 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1231 QualType ComplexType = S.Context.getComplexType(ScalarType); 1232 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1233 CK_IntegralRealToComplex); 1234 1235 return ComplexType; 1236 } 1237 1238 assert(RHSComplexInt); 1239 1240 QualType RHSEltType = RHSComplexInt->getElementType(); 1241 QualType ScalarType = 1242 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1243 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1244 QualType ComplexType = S.Context.getComplexType(ScalarType); 1245 1246 if (!IsCompAssign) 1247 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1248 CK_IntegralRealToComplex); 1249 return ComplexType; 1250 } 1251 1252 /// Return the rank of a given fixed point or integer type. The value itself 1253 /// doesn't matter, but the values must be increasing with proper increasing 1254 /// rank as described in N1169 4.1.1. 1255 static unsigned GetFixedPointRank(QualType Ty) { 1256 const auto *BTy = Ty->getAs<BuiltinType>(); 1257 assert(BTy && "Expected a builtin type."); 1258 1259 switch (BTy->getKind()) { 1260 case BuiltinType::ShortFract: 1261 case BuiltinType::UShortFract: 1262 case BuiltinType::SatShortFract: 1263 case BuiltinType::SatUShortFract: 1264 return 1; 1265 case BuiltinType::Fract: 1266 case BuiltinType::UFract: 1267 case BuiltinType::SatFract: 1268 case BuiltinType::SatUFract: 1269 return 2; 1270 case BuiltinType::LongFract: 1271 case BuiltinType::ULongFract: 1272 case BuiltinType::SatLongFract: 1273 case BuiltinType::SatULongFract: 1274 return 3; 1275 case BuiltinType::ShortAccum: 1276 case BuiltinType::UShortAccum: 1277 case BuiltinType::SatShortAccum: 1278 case BuiltinType::SatUShortAccum: 1279 return 4; 1280 case BuiltinType::Accum: 1281 case BuiltinType::UAccum: 1282 case BuiltinType::SatAccum: 1283 case BuiltinType::SatUAccum: 1284 return 5; 1285 case BuiltinType::LongAccum: 1286 case BuiltinType::ULongAccum: 1287 case BuiltinType::SatLongAccum: 1288 case BuiltinType::SatULongAccum: 1289 return 6; 1290 default: 1291 if (BTy->isInteger()) 1292 return 0; 1293 llvm_unreachable("Unexpected fixed point or integer type"); 1294 } 1295 } 1296 1297 /// handleFixedPointConversion - Fixed point operations between fixed 1298 /// point types and integers or other fixed point types do not fall under 1299 /// usual arithmetic conversion since these conversions could result in loss 1300 /// of precsision (N1169 4.1.4). These operations should be calculated with 1301 /// the full precision of their result type (N1169 4.1.6.2.1). 1302 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1303 QualType RHSTy) { 1304 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1305 "Expected at least one of the operands to be a fixed point type"); 1306 assert((LHSTy->isFixedPointOrIntegerType() || 1307 RHSTy->isFixedPointOrIntegerType()) && 1308 "Special fixed point arithmetic operation conversions are only " 1309 "applied to ints or other fixed point types"); 1310 1311 // If one operand has signed fixed-point type and the other operand has 1312 // unsigned fixed-point type, then the unsigned fixed-point operand is 1313 // converted to its corresponding signed fixed-point type and the resulting 1314 // type is the type of the converted operand. 1315 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1316 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1317 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1318 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1319 1320 // The result type is the type with the highest rank, whereby a fixed-point 1321 // conversion rank is always greater than an integer conversion rank; if the 1322 // type of either of the operands is a saturating fixedpoint type, the result 1323 // type shall be the saturating fixed-point type corresponding to the type 1324 // with the highest rank; the resulting value is converted (taking into 1325 // account rounding and overflow) to the precision of the resulting type. 1326 // Same ranks between signed and unsigned types are resolved earlier, so both 1327 // types are either signed or both unsigned at this point. 1328 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1329 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1330 1331 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1332 1333 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1334 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1335 1336 return ResultTy; 1337 } 1338 1339 /// UsualArithmeticConversions - Performs various conversions that are common to 1340 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1341 /// routine returns the first non-arithmetic type found. The client is 1342 /// responsible for emitting appropriate error diagnostics. 1343 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1344 bool IsCompAssign) { 1345 if (!IsCompAssign) { 1346 LHS = UsualUnaryConversions(LHS.get()); 1347 if (LHS.isInvalid()) 1348 return QualType(); 1349 } 1350 1351 RHS = UsualUnaryConversions(RHS.get()); 1352 if (RHS.isInvalid()) 1353 return QualType(); 1354 1355 // For conversion purposes, we ignore any qualifiers. 1356 // For example, "const float" and "float" are equivalent. 1357 QualType LHSType = 1358 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1359 QualType RHSType = 1360 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1361 1362 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1363 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1364 LHSType = AtomicLHS->getValueType(); 1365 1366 // If both types are identical, no conversion is needed. 1367 if (LHSType == RHSType) 1368 return LHSType; 1369 1370 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1371 // The caller can deal with this (e.g. pointer + int). 1372 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1373 return QualType(); 1374 1375 // Apply unary and bitfield promotions to the LHS's type. 1376 QualType LHSUnpromotedType = LHSType; 1377 if (LHSType->isPromotableIntegerType()) 1378 LHSType = Context.getPromotedIntegerType(LHSType); 1379 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1380 if (!LHSBitfieldPromoteTy.isNull()) 1381 LHSType = LHSBitfieldPromoteTy; 1382 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1383 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1384 1385 // If both types are identical, no conversion is needed. 1386 if (LHSType == RHSType) 1387 return LHSType; 1388 1389 // At this point, we have two different arithmetic types. 1390 1391 // Diagnose attempts to convert between __float128 and long double where 1392 // such conversions currently can't be handled. 1393 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1394 return QualType(); 1395 1396 // Handle complex types first (C99 6.3.1.8p1). 1397 if (LHSType->isComplexType() || RHSType->isComplexType()) 1398 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1399 IsCompAssign); 1400 1401 // Now handle "real" floating types (i.e. float, double, long double). 1402 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1403 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1404 IsCompAssign); 1405 1406 // Handle GCC complex int extension. 1407 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1408 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1409 IsCompAssign); 1410 1411 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1412 return handleFixedPointConversion(*this, LHSType, RHSType); 1413 1414 // Finally, we have two differing integer types. 1415 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1416 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1417 } 1418 1419 //===----------------------------------------------------------------------===// 1420 // Semantic Analysis for various Expression Types 1421 //===----------------------------------------------------------------------===// 1422 1423 1424 ExprResult 1425 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1426 SourceLocation DefaultLoc, 1427 SourceLocation RParenLoc, 1428 Expr *ControllingExpr, 1429 ArrayRef<ParsedType> ArgTypes, 1430 ArrayRef<Expr *> ArgExprs) { 1431 unsigned NumAssocs = ArgTypes.size(); 1432 assert(NumAssocs == ArgExprs.size()); 1433 1434 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1435 for (unsigned i = 0; i < NumAssocs; ++i) { 1436 if (ArgTypes[i]) 1437 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1438 else 1439 Types[i] = nullptr; 1440 } 1441 1442 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1443 ControllingExpr, 1444 llvm::makeArrayRef(Types, NumAssocs), 1445 ArgExprs); 1446 delete [] Types; 1447 return ER; 1448 } 1449 1450 ExprResult 1451 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1452 SourceLocation DefaultLoc, 1453 SourceLocation RParenLoc, 1454 Expr *ControllingExpr, 1455 ArrayRef<TypeSourceInfo *> Types, 1456 ArrayRef<Expr *> Exprs) { 1457 unsigned NumAssocs = Types.size(); 1458 assert(NumAssocs == Exprs.size()); 1459 1460 // Decay and strip qualifiers for the controlling expression type, and handle 1461 // placeholder type replacement. See committee discussion from WG14 DR423. 1462 { 1463 EnterExpressionEvaluationContext Unevaluated( 1464 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1465 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1466 if (R.isInvalid()) 1467 return ExprError(); 1468 ControllingExpr = R.get(); 1469 } 1470 1471 // The controlling expression is an unevaluated operand, so side effects are 1472 // likely unintended. 1473 if (!inTemplateInstantiation() && 1474 ControllingExpr->HasSideEffects(Context, false)) 1475 Diag(ControllingExpr->getExprLoc(), 1476 diag::warn_side_effects_unevaluated_context); 1477 1478 bool TypeErrorFound = false, 1479 IsResultDependent = ControllingExpr->isTypeDependent(), 1480 ContainsUnexpandedParameterPack 1481 = ControllingExpr->containsUnexpandedParameterPack(); 1482 1483 for (unsigned i = 0; i < NumAssocs; ++i) { 1484 if (Exprs[i]->containsUnexpandedParameterPack()) 1485 ContainsUnexpandedParameterPack = true; 1486 1487 if (Types[i]) { 1488 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1489 ContainsUnexpandedParameterPack = true; 1490 1491 if (Types[i]->getType()->isDependentType()) { 1492 IsResultDependent = true; 1493 } else { 1494 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1495 // complete object type other than a variably modified type." 1496 unsigned D = 0; 1497 if (Types[i]->getType()->isIncompleteType()) 1498 D = diag::err_assoc_type_incomplete; 1499 else if (!Types[i]->getType()->isObjectType()) 1500 D = diag::err_assoc_type_nonobject; 1501 else if (Types[i]->getType()->isVariablyModifiedType()) 1502 D = diag::err_assoc_type_variably_modified; 1503 1504 if (D != 0) { 1505 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1506 << Types[i]->getTypeLoc().getSourceRange() 1507 << Types[i]->getType(); 1508 TypeErrorFound = true; 1509 } 1510 1511 // C11 6.5.1.1p2 "No two generic associations in the same generic 1512 // selection shall specify compatible types." 1513 for (unsigned j = i+1; j < NumAssocs; ++j) 1514 if (Types[j] && !Types[j]->getType()->isDependentType() && 1515 Context.typesAreCompatible(Types[i]->getType(), 1516 Types[j]->getType())) { 1517 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1518 diag::err_assoc_compatible_types) 1519 << Types[j]->getTypeLoc().getSourceRange() 1520 << Types[j]->getType() 1521 << Types[i]->getType(); 1522 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1523 diag::note_compat_assoc) 1524 << Types[i]->getTypeLoc().getSourceRange() 1525 << Types[i]->getType(); 1526 TypeErrorFound = true; 1527 } 1528 } 1529 } 1530 } 1531 if (TypeErrorFound) 1532 return ExprError(); 1533 1534 // If we determined that the generic selection is result-dependent, don't 1535 // try to compute the result expression. 1536 if (IsResultDependent) 1537 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1538 Exprs, DefaultLoc, RParenLoc, 1539 ContainsUnexpandedParameterPack); 1540 1541 SmallVector<unsigned, 1> CompatIndices; 1542 unsigned DefaultIndex = -1U; 1543 for (unsigned i = 0; i < NumAssocs; ++i) { 1544 if (!Types[i]) 1545 DefaultIndex = i; 1546 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1547 Types[i]->getType())) 1548 CompatIndices.push_back(i); 1549 } 1550 1551 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1552 // type compatible with at most one of the types named in its generic 1553 // association list." 1554 if (CompatIndices.size() > 1) { 1555 // We strip parens here because the controlling expression is typically 1556 // parenthesized in macro definitions. 1557 ControllingExpr = ControllingExpr->IgnoreParens(); 1558 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1559 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1560 << (unsigned)CompatIndices.size(); 1561 for (unsigned I : CompatIndices) { 1562 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1563 diag::note_compat_assoc) 1564 << Types[I]->getTypeLoc().getSourceRange() 1565 << Types[I]->getType(); 1566 } 1567 return ExprError(); 1568 } 1569 1570 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1571 // its controlling expression shall have type compatible with exactly one of 1572 // the types named in its generic association list." 1573 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1574 // We strip parens here because the controlling expression is typically 1575 // parenthesized in macro definitions. 1576 ControllingExpr = ControllingExpr->IgnoreParens(); 1577 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1578 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1579 return ExprError(); 1580 } 1581 1582 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1583 // type name that is compatible with the type of the controlling expression, 1584 // then the result expression of the generic selection is the expression 1585 // in that generic association. Otherwise, the result expression of the 1586 // generic selection is the expression in the default generic association." 1587 unsigned ResultIndex = 1588 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1589 1590 return GenericSelectionExpr::Create( 1591 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1592 ContainsUnexpandedParameterPack, ResultIndex); 1593 } 1594 1595 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1596 /// location of the token and the offset of the ud-suffix within it. 1597 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1598 unsigned Offset) { 1599 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1600 S.getLangOpts()); 1601 } 1602 1603 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1604 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1605 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1606 IdentifierInfo *UDSuffix, 1607 SourceLocation UDSuffixLoc, 1608 ArrayRef<Expr*> Args, 1609 SourceLocation LitEndLoc) { 1610 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1611 1612 QualType ArgTy[2]; 1613 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1614 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1615 if (ArgTy[ArgIdx]->isArrayType()) 1616 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1617 } 1618 1619 DeclarationName OpName = 1620 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1621 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1622 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1623 1624 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1625 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1626 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1627 /*AllowStringTemplate*/ false, 1628 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1629 return ExprError(); 1630 1631 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1632 } 1633 1634 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1635 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1636 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1637 /// multiple tokens. However, the common case is that StringToks points to one 1638 /// string. 1639 /// 1640 ExprResult 1641 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1642 assert(!StringToks.empty() && "Must have at least one string!"); 1643 1644 StringLiteralParser Literal(StringToks, PP); 1645 if (Literal.hadError) 1646 return ExprError(); 1647 1648 SmallVector<SourceLocation, 4> StringTokLocs; 1649 for (const Token &Tok : StringToks) 1650 StringTokLocs.push_back(Tok.getLocation()); 1651 1652 QualType CharTy = Context.CharTy; 1653 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1654 if (Literal.isWide()) { 1655 CharTy = Context.getWideCharType(); 1656 Kind = StringLiteral::Wide; 1657 } else if (Literal.isUTF8()) { 1658 if (getLangOpts().Char8) 1659 CharTy = Context.Char8Ty; 1660 Kind = StringLiteral::UTF8; 1661 } else if (Literal.isUTF16()) { 1662 CharTy = Context.Char16Ty; 1663 Kind = StringLiteral::UTF16; 1664 } else if (Literal.isUTF32()) { 1665 CharTy = Context.Char32Ty; 1666 Kind = StringLiteral::UTF32; 1667 } else if (Literal.isPascal()) { 1668 CharTy = Context.UnsignedCharTy; 1669 } 1670 1671 // Warn on initializing an array of char from a u8 string literal; this 1672 // becomes ill-formed in C++2a. 1673 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus2a && 1674 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1675 Diag(StringTokLocs.front(), diag::warn_cxx2a_compat_utf8_string); 1676 1677 // Create removals for all 'u8' prefixes in the string literal(s). This 1678 // ensures C++2a compatibility (but may change the program behavior when 1679 // built by non-Clang compilers for which the execution character set is 1680 // not always UTF-8). 1681 auto RemovalDiag = PDiag(diag::note_cxx2a_compat_utf8_string_remove_u8); 1682 SourceLocation RemovalDiagLoc; 1683 for (const Token &Tok : StringToks) { 1684 if (Tok.getKind() == tok::utf8_string_literal) { 1685 if (RemovalDiagLoc.isInvalid()) 1686 RemovalDiagLoc = Tok.getLocation(); 1687 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1688 Tok.getLocation(), 1689 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1690 getSourceManager(), getLangOpts()))); 1691 } 1692 } 1693 Diag(RemovalDiagLoc, RemovalDiag); 1694 } 1695 1696 QualType StrTy = 1697 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); 1698 1699 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1700 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1701 Kind, Literal.Pascal, StrTy, 1702 &StringTokLocs[0], 1703 StringTokLocs.size()); 1704 if (Literal.getUDSuffix().empty()) 1705 return Lit; 1706 1707 // We're building a user-defined literal. 1708 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1709 SourceLocation UDSuffixLoc = 1710 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1711 Literal.getUDSuffixOffset()); 1712 1713 // Make sure we're allowed user-defined literals here. 1714 if (!UDLScope) 1715 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1716 1717 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1718 // operator "" X (str, len) 1719 QualType SizeType = Context.getSizeType(); 1720 1721 DeclarationName OpName = 1722 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1723 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1724 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1725 1726 QualType ArgTy[] = { 1727 Context.getArrayDecayedType(StrTy), SizeType 1728 }; 1729 1730 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1731 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1732 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1733 /*AllowStringTemplate*/ true, 1734 /*DiagnoseMissing*/ true)) { 1735 1736 case LOLR_Cooked: { 1737 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1738 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1739 StringTokLocs[0]); 1740 Expr *Args[] = { Lit, LenArg }; 1741 1742 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1743 } 1744 1745 case LOLR_StringTemplate: { 1746 TemplateArgumentListInfo ExplicitArgs; 1747 1748 unsigned CharBits = Context.getIntWidth(CharTy); 1749 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1750 llvm::APSInt Value(CharBits, CharIsUnsigned); 1751 1752 TemplateArgument TypeArg(CharTy); 1753 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1754 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1755 1756 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1757 Value = Lit->getCodeUnit(I); 1758 TemplateArgument Arg(Context, Value, CharTy); 1759 TemplateArgumentLocInfo ArgInfo; 1760 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1761 } 1762 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1763 &ExplicitArgs); 1764 } 1765 case LOLR_Raw: 1766 case LOLR_Template: 1767 case LOLR_ErrorNoDiagnostic: 1768 llvm_unreachable("unexpected literal operator lookup result"); 1769 case LOLR_Error: 1770 return ExprError(); 1771 } 1772 llvm_unreachable("unexpected literal operator lookup result"); 1773 } 1774 1775 DeclRefExpr * 1776 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1777 SourceLocation Loc, 1778 const CXXScopeSpec *SS) { 1779 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1780 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1781 } 1782 1783 DeclRefExpr * 1784 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1785 const DeclarationNameInfo &NameInfo, 1786 const CXXScopeSpec *SS, NamedDecl *FoundD, 1787 SourceLocation TemplateKWLoc, 1788 const TemplateArgumentListInfo *TemplateArgs) { 1789 NestedNameSpecifierLoc NNS = 1790 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); 1791 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, 1792 TemplateArgs); 1793 } 1794 1795 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { 1796 // A declaration named in an unevaluated operand never constitutes an odr-use. 1797 if (isUnevaluatedContext()) 1798 return NOUR_Unevaluated; 1799 1800 // C++2a [basic.def.odr]p4: 1801 // A variable x whose name appears as a potentially-evaluated expression e 1802 // is odr-used by e unless [...] x is a reference that is usable in 1803 // constant expressions. 1804 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 1805 if (VD->getType()->isReferenceType() && 1806 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && 1807 VD->isUsableInConstantExpressions(Context)) 1808 return NOUR_Constant; 1809 } 1810 1811 // All remaining non-variable cases constitute an odr-use. For variables, we 1812 // need to wait and see how the expression is used. 1813 return NOUR_None; 1814 } 1815 1816 /// BuildDeclRefExpr - Build an expression that references a 1817 /// declaration that does not require a closure capture. 1818 DeclRefExpr * 1819 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1820 const DeclarationNameInfo &NameInfo, 1821 NestedNameSpecifierLoc NNS, NamedDecl *FoundD, 1822 SourceLocation TemplateKWLoc, 1823 const TemplateArgumentListInfo *TemplateArgs) { 1824 bool RefersToCapturedVariable = 1825 isa<VarDecl>(D) && 1826 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1827 1828 DeclRefExpr *E = DeclRefExpr::Create( 1829 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, 1830 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); 1831 MarkDeclRefReferenced(E); 1832 1833 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1834 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 1835 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 1836 getCurFunction()->recordUseOfWeak(E); 1837 1838 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1839 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 1840 FD = IFD->getAnonField(); 1841 if (FD) { 1842 UnusedPrivateFields.remove(FD); 1843 // Just in case we're building an illegal pointer-to-member. 1844 if (FD->isBitField()) 1845 E->setObjectKind(OK_BitField); 1846 } 1847 1848 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1849 // designates a bit-field. 1850 if (auto *BD = dyn_cast<BindingDecl>(D)) 1851 if (auto *BE = BD->getBinding()) 1852 E->setObjectKind(BE->getObjectKind()); 1853 1854 return E; 1855 } 1856 1857 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1858 /// possibly a list of template arguments. 1859 /// 1860 /// If this produces template arguments, it is permitted to call 1861 /// DecomposeTemplateName. 1862 /// 1863 /// This actually loses a lot of source location information for 1864 /// non-standard name kinds; we should consider preserving that in 1865 /// some way. 1866 void 1867 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1868 TemplateArgumentListInfo &Buffer, 1869 DeclarationNameInfo &NameInfo, 1870 const TemplateArgumentListInfo *&TemplateArgs) { 1871 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 1872 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1873 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1874 1875 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1876 Id.TemplateId->NumArgs); 1877 translateTemplateArguments(TemplateArgsPtr, Buffer); 1878 1879 TemplateName TName = Id.TemplateId->Template.get(); 1880 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1881 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1882 TemplateArgs = &Buffer; 1883 } else { 1884 NameInfo = GetNameFromUnqualifiedId(Id); 1885 TemplateArgs = nullptr; 1886 } 1887 } 1888 1889 static void emitEmptyLookupTypoDiagnostic( 1890 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1891 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1892 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1893 DeclContext *Ctx = 1894 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1895 if (!TC) { 1896 // Emit a special diagnostic for failed member lookups. 1897 // FIXME: computing the declaration context might fail here (?) 1898 if (Ctx) 1899 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1900 << SS.getRange(); 1901 else 1902 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1903 return; 1904 } 1905 1906 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1907 bool DroppedSpecifier = 1908 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1909 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1910 ? diag::note_implicit_param_decl 1911 : diag::note_previous_decl; 1912 if (!Ctx) 1913 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1914 SemaRef.PDiag(NoteID)); 1915 else 1916 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1917 << Typo << Ctx << DroppedSpecifier 1918 << SS.getRange(), 1919 SemaRef.PDiag(NoteID)); 1920 } 1921 1922 /// Diagnose an empty lookup. 1923 /// 1924 /// \return false if new lookup candidates were found 1925 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1926 CorrectionCandidateCallback &CCC, 1927 TemplateArgumentListInfo *ExplicitTemplateArgs, 1928 ArrayRef<Expr *> Args, TypoExpr **Out) { 1929 DeclarationName Name = R.getLookupName(); 1930 1931 unsigned diagnostic = diag::err_undeclared_var_use; 1932 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1933 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1934 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1935 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1936 diagnostic = diag::err_undeclared_use; 1937 diagnostic_suggest = diag::err_undeclared_use_suggest; 1938 } 1939 1940 // If the original lookup was an unqualified lookup, fake an 1941 // unqualified lookup. This is useful when (for example) the 1942 // original lookup would not have found something because it was a 1943 // dependent name. 1944 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1945 while (DC) { 1946 if (isa<CXXRecordDecl>(DC)) { 1947 LookupQualifiedName(R, DC); 1948 1949 if (!R.empty()) { 1950 // Don't give errors about ambiguities in this lookup. 1951 R.suppressDiagnostics(); 1952 1953 // During a default argument instantiation the CurContext points 1954 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1955 // function parameter list, hence add an explicit check. 1956 bool isDefaultArgument = 1957 !CodeSynthesisContexts.empty() && 1958 CodeSynthesisContexts.back().Kind == 1959 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 1960 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1961 bool isInstance = CurMethod && 1962 CurMethod->isInstance() && 1963 DC == CurMethod->getParent() && !isDefaultArgument; 1964 1965 // Give a code modification hint to insert 'this->'. 1966 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1967 // Actually quite difficult! 1968 if (getLangOpts().MSVCCompat) 1969 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1970 if (isInstance) { 1971 Diag(R.getNameLoc(), diagnostic) << Name 1972 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1973 CheckCXXThisCapture(R.getNameLoc()); 1974 } else { 1975 Diag(R.getNameLoc(), diagnostic) << Name; 1976 } 1977 1978 // Do we really want to note all of these? 1979 for (NamedDecl *D : R) 1980 Diag(D->getLocation(), diag::note_dependent_var_use); 1981 1982 // Return true if we are inside a default argument instantiation 1983 // and the found name refers to an instance member function, otherwise 1984 // the function calling DiagnoseEmptyLookup will try to create an 1985 // implicit member call and this is wrong for default argument. 1986 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1987 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1988 return true; 1989 } 1990 1991 // Tell the callee to try to recover. 1992 return false; 1993 } 1994 1995 R.clear(); 1996 } 1997 1998 DC = DC->getLookupParent(); 1999 } 2000 2001 // We didn't find anything, so try to correct for a typo. 2002 TypoCorrection Corrected; 2003 if (S && Out) { 2004 SourceLocation TypoLoc = R.getNameLoc(); 2005 assert(!ExplicitTemplateArgs && 2006 "Diagnosing an empty lookup with explicit template args!"); 2007 *Out = CorrectTypoDelayed( 2008 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 2009 [=](const TypoCorrection &TC) { 2010 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2011 diagnostic, diagnostic_suggest); 2012 }, 2013 nullptr, CTK_ErrorRecovery); 2014 if (*Out) 2015 return true; 2016 } else if (S && 2017 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 2018 S, &SS, CCC, CTK_ErrorRecovery))) { 2019 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2020 bool DroppedSpecifier = 2021 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2022 R.setLookupName(Corrected.getCorrection()); 2023 2024 bool AcceptableWithRecovery = false; 2025 bool AcceptableWithoutRecovery = false; 2026 NamedDecl *ND = Corrected.getFoundDecl(); 2027 if (ND) { 2028 if (Corrected.isOverloaded()) { 2029 OverloadCandidateSet OCS(R.getNameLoc(), 2030 OverloadCandidateSet::CSK_Normal); 2031 OverloadCandidateSet::iterator Best; 2032 for (NamedDecl *CD : Corrected) { 2033 if (FunctionTemplateDecl *FTD = 2034 dyn_cast<FunctionTemplateDecl>(CD)) 2035 AddTemplateOverloadCandidate( 2036 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2037 Args, OCS); 2038 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2039 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2040 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2041 Args, OCS); 2042 } 2043 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2044 case OR_Success: 2045 ND = Best->FoundDecl; 2046 Corrected.setCorrectionDecl(ND); 2047 break; 2048 default: 2049 // FIXME: Arbitrarily pick the first declaration for the note. 2050 Corrected.setCorrectionDecl(ND); 2051 break; 2052 } 2053 } 2054 R.addDecl(ND); 2055 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2056 CXXRecordDecl *Record = nullptr; 2057 if (Corrected.getCorrectionSpecifier()) { 2058 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2059 Record = Ty->getAsCXXRecordDecl(); 2060 } 2061 if (!Record) 2062 Record = cast<CXXRecordDecl>( 2063 ND->getDeclContext()->getRedeclContext()); 2064 R.setNamingClass(Record); 2065 } 2066 2067 auto *UnderlyingND = ND->getUnderlyingDecl(); 2068 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2069 isa<FunctionTemplateDecl>(UnderlyingND); 2070 // FIXME: If we ended up with a typo for a type name or 2071 // Objective-C class name, we're in trouble because the parser 2072 // is in the wrong place to recover. Suggest the typo 2073 // correction, but don't make it a fix-it since we're not going 2074 // to recover well anyway. 2075 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || 2076 getAsTypeTemplateDecl(UnderlyingND) || 2077 isa<ObjCInterfaceDecl>(UnderlyingND); 2078 } else { 2079 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2080 // because we aren't able to recover. 2081 AcceptableWithoutRecovery = true; 2082 } 2083 2084 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2085 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2086 ? diag::note_implicit_param_decl 2087 : diag::note_previous_decl; 2088 if (SS.isEmpty()) 2089 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2090 PDiag(NoteID), AcceptableWithRecovery); 2091 else 2092 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2093 << Name << computeDeclContext(SS, false) 2094 << DroppedSpecifier << SS.getRange(), 2095 PDiag(NoteID), AcceptableWithRecovery); 2096 2097 // Tell the callee whether to try to recover. 2098 return !AcceptableWithRecovery; 2099 } 2100 } 2101 R.clear(); 2102 2103 // Emit a special diagnostic for failed member lookups. 2104 // FIXME: computing the declaration context might fail here (?) 2105 if (!SS.isEmpty()) { 2106 Diag(R.getNameLoc(), diag::err_no_member) 2107 << Name << computeDeclContext(SS, false) 2108 << SS.getRange(); 2109 return true; 2110 } 2111 2112 // Give up, we can't recover. 2113 Diag(R.getNameLoc(), diagnostic) << Name; 2114 return true; 2115 } 2116 2117 /// In Microsoft mode, if we are inside a template class whose parent class has 2118 /// dependent base classes, and we can't resolve an unqualified identifier, then 2119 /// assume the identifier is a member of a dependent base class. We can only 2120 /// recover successfully in static methods, instance methods, and other contexts 2121 /// where 'this' is available. This doesn't precisely match MSVC's 2122 /// instantiation model, but it's close enough. 2123 static Expr * 2124 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2125 DeclarationNameInfo &NameInfo, 2126 SourceLocation TemplateKWLoc, 2127 const TemplateArgumentListInfo *TemplateArgs) { 2128 // Only try to recover from lookup into dependent bases in static methods or 2129 // contexts where 'this' is available. 2130 QualType ThisType = S.getCurrentThisType(); 2131 const CXXRecordDecl *RD = nullptr; 2132 if (!ThisType.isNull()) 2133 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2134 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2135 RD = MD->getParent(); 2136 if (!RD || !RD->hasAnyDependentBases()) 2137 return nullptr; 2138 2139 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2140 // is available, suggest inserting 'this->' as a fixit. 2141 SourceLocation Loc = NameInfo.getLoc(); 2142 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2143 DB << NameInfo.getName() << RD; 2144 2145 if (!ThisType.isNull()) { 2146 DB << FixItHint::CreateInsertion(Loc, "this->"); 2147 return CXXDependentScopeMemberExpr::Create( 2148 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2149 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2150 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); 2151 } 2152 2153 // Synthesize a fake NNS that points to the derived class. This will 2154 // perform name lookup during template instantiation. 2155 CXXScopeSpec SS; 2156 auto *NNS = 2157 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2158 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2159 return DependentScopeDeclRefExpr::Create( 2160 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2161 TemplateArgs); 2162 } 2163 2164 ExprResult 2165 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2166 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2167 bool HasTrailingLParen, bool IsAddressOfOperand, 2168 CorrectionCandidateCallback *CCC, 2169 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2170 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2171 "cannot be direct & operand and have a trailing lparen"); 2172 if (SS.isInvalid()) 2173 return ExprError(); 2174 2175 TemplateArgumentListInfo TemplateArgsBuffer; 2176 2177 // Decompose the UnqualifiedId into the following data. 2178 DeclarationNameInfo NameInfo; 2179 const TemplateArgumentListInfo *TemplateArgs; 2180 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2181 2182 DeclarationName Name = NameInfo.getName(); 2183 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2184 SourceLocation NameLoc = NameInfo.getLoc(); 2185 2186 if (II && II->isEditorPlaceholder()) { 2187 // FIXME: When typed placeholders are supported we can create a typed 2188 // placeholder expression node. 2189 return ExprError(); 2190 } 2191 2192 // C++ [temp.dep.expr]p3: 2193 // An id-expression is type-dependent if it contains: 2194 // -- an identifier that was declared with a dependent type, 2195 // (note: handled after lookup) 2196 // -- a template-id that is dependent, 2197 // (note: handled in BuildTemplateIdExpr) 2198 // -- a conversion-function-id that specifies a dependent type, 2199 // -- a nested-name-specifier that contains a class-name that 2200 // names a dependent type. 2201 // Determine whether this is a member of an unknown specialization; 2202 // we need to handle these differently. 2203 bool DependentID = false; 2204 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2205 Name.getCXXNameType()->isDependentType()) { 2206 DependentID = true; 2207 } else if (SS.isSet()) { 2208 if (DeclContext *DC = computeDeclContext(SS, false)) { 2209 if (RequireCompleteDeclContext(SS, DC)) 2210 return ExprError(); 2211 } else { 2212 DependentID = true; 2213 } 2214 } 2215 2216 if (DependentID) 2217 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2218 IsAddressOfOperand, TemplateArgs); 2219 2220 // Perform the required lookup. 2221 LookupResult R(*this, NameInfo, 2222 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2223 ? LookupObjCImplicitSelfParam 2224 : LookupOrdinaryName); 2225 if (TemplateKWLoc.isValid() || TemplateArgs) { 2226 // Lookup the template name again to correctly establish the context in 2227 // which it was found. This is really unfortunate as we already did the 2228 // lookup to determine that it was a template name in the first place. If 2229 // this becomes a performance hit, we can work harder to preserve those 2230 // results until we get here but it's likely not worth it. 2231 bool MemberOfUnknownSpecialization; 2232 AssumedTemplateKind AssumedTemplate; 2233 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2234 MemberOfUnknownSpecialization, TemplateKWLoc, 2235 &AssumedTemplate)) 2236 return ExprError(); 2237 2238 if (MemberOfUnknownSpecialization || 2239 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2240 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2241 IsAddressOfOperand, TemplateArgs); 2242 } else { 2243 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2244 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2245 2246 // If the result might be in a dependent base class, this is a dependent 2247 // id-expression. 2248 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2249 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2250 IsAddressOfOperand, TemplateArgs); 2251 2252 // If this reference is in an Objective-C method, then we need to do 2253 // some special Objective-C lookup, too. 2254 if (IvarLookupFollowUp) { 2255 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2256 if (E.isInvalid()) 2257 return ExprError(); 2258 2259 if (Expr *Ex = E.getAs<Expr>()) 2260 return Ex; 2261 } 2262 } 2263 2264 if (R.isAmbiguous()) 2265 return ExprError(); 2266 2267 // This could be an implicitly declared function reference (legal in C90, 2268 // extension in C99, forbidden in C++). 2269 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2270 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2271 if (D) R.addDecl(D); 2272 } 2273 2274 // Determine whether this name might be a candidate for 2275 // argument-dependent lookup. 2276 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2277 2278 if (R.empty() && !ADL) { 2279 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2280 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2281 TemplateKWLoc, TemplateArgs)) 2282 return E; 2283 } 2284 2285 // Don't diagnose an empty lookup for inline assembly. 2286 if (IsInlineAsmIdentifier) 2287 return ExprError(); 2288 2289 // If this name wasn't predeclared and if this is not a function 2290 // call, diagnose the problem. 2291 TypoExpr *TE = nullptr; 2292 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2293 : nullptr); 2294 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2295 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2296 "Typo correction callback misconfigured"); 2297 if (CCC) { 2298 // Make sure the callback knows what the typo being diagnosed is. 2299 CCC->setTypoName(II); 2300 if (SS.isValid()) 2301 CCC->setTypoNNS(SS.getScopeRep()); 2302 } 2303 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2304 // a template name, but we happen to have always already looked up the name 2305 // before we get here if it must be a template name. 2306 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2307 None, &TE)) { 2308 if (TE && KeywordReplacement) { 2309 auto &State = getTypoExprState(TE); 2310 auto BestTC = State.Consumer->getNextCorrection(); 2311 if (BestTC.isKeyword()) { 2312 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2313 if (State.DiagHandler) 2314 State.DiagHandler(BestTC); 2315 KeywordReplacement->startToken(); 2316 KeywordReplacement->setKind(II->getTokenID()); 2317 KeywordReplacement->setIdentifierInfo(II); 2318 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2319 // Clean up the state associated with the TypoExpr, since it has 2320 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2321 clearDelayedTypo(TE); 2322 // Signal that a correction to a keyword was performed by returning a 2323 // valid-but-null ExprResult. 2324 return (Expr*)nullptr; 2325 } 2326 State.Consumer->resetCorrectionStream(); 2327 } 2328 return TE ? TE : ExprError(); 2329 } 2330 2331 assert(!R.empty() && 2332 "DiagnoseEmptyLookup returned false but added no results"); 2333 2334 // If we found an Objective-C instance variable, let 2335 // LookupInObjCMethod build the appropriate expression to 2336 // reference the ivar. 2337 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2338 R.clear(); 2339 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2340 // In a hopelessly buggy code, Objective-C instance variable 2341 // lookup fails and no expression will be built to reference it. 2342 if (!E.isInvalid() && !E.get()) 2343 return ExprError(); 2344 return E; 2345 } 2346 } 2347 2348 // This is guaranteed from this point on. 2349 assert(!R.empty() || ADL); 2350 2351 // Check whether this might be a C++ implicit instance member access. 2352 // C++ [class.mfct.non-static]p3: 2353 // When an id-expression that is not part of a class member access 2354 // syntax and not used to form a pointer to member is used in the 2355 // body of a non-static member function of class X, if name lookup 2356 // resolves the name in the id-expression to a non-static non-type 2357 // member of some class C, the id-expression is transformed into a 2358 // class member access expression using (*this) as the 2359 // postfix-expression to the left of the . operator. 2360 // 2361 // But we don't actually need to do this for '&' operands if R 2362 // resolved to a function or overloaded function set, because the 2363 // expression is ill-formed if it actually works out to be a 2364 // non-static member function: 2365 // 2366 // C++ [expr.ref]p4: 2367 // Otherwise, if E1.E2 refers to a non-static member function. . . 2368 // [t]he expression can be used only as the left-hand operand of a 2369 // member function call. 2370 // 2371 // There are other safeguards against such uses, but it's important 2372 // to get this right here so that we don't end up making a 2373 // spuriously dependent expression if we're inside a dependent 2374 // instance method. 2375 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2376 bool MightBeImplicitMember; 2377 if (!IsAddressOfOperand) 2378 MightBeImplicitMember = true; 2379 else if (!SS.isEmpty()) 2380 MightBeImplicitMember = false; 2381 else if (R.isOverloadedResult()) 2382 MightBeImplicitMember = false; 2383 else if (R.isUnresolvableResult()) 2384 MightBeImplicitMember = true; 2385 else 2386 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2387 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2388 isa<MSPropertyDecl>(R.getFoundDecl()); 2389 2390 if (MightBeImplicitMember) 2391 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2392 R, TemplateArgs, S); 2393 } 2394 2395 if (TemplateArgs || TemplateKWLoc.isValid()) { 2396 2397 // In C++1y, if this is a variable template id, then check it 2398 // in BuildTemplateIdExpr(). 2399 // The single lookup result must be a variable template declaration. 2400 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2401 Id.TemplateId->Kind == TNK_Var_template) { 2402 assert(R.getAsSingle<VarTemplateDecl>() && 2403 "There should only be one declaration found."); 2404 } 2405 2406 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2407 } 2408 2409 return BuildDeclarationNameExpr(SS, R, ADL); 2410 } 2411 2412 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2413 /// declaration name, generally during template instantiation. 2414 /// There's a large number of things which don't need to be done along 2415 /// this path. 2416 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2417 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2418 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2419 DeclContext *DC = computeDeclContext(SS, false); 2420 if (!DC) 2421 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2422 NameInfo, /*TemplateArgs=*/nullptr); 2423 2424 if (RequireCompleteDeclContext(SS, DC)) 2425 return ExprError(); 2426 2427 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2428 LookupQualifiedName(R, DC); 2429 2430 if (R.isAmbiguous()) 2431 return ExprError(); 2432 2433 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2434 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2435 NameInfo, /*TemplateArgs=*/nullptr); 2436 2437 if (R.empty()) { 2438 Diag(NameInfo.getLoc(), diag::err_no_member) 2439 << NameInfo.getName() << DC << SS.getRange(); 2440 return ExprError(); 2441 } 2442 2443 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2444 // Diagnose a missing typename if this resolved unambiguously to a type in 2445 // a dependent context. If we can recover with a type, downgrade this to 2446 // a warning in Microsoft compatibility mode. 2447 unsigned DiagID = diag::err_typename_missing; 2448 if (RecoveryTSI && getLangOpts().MSVCCompat) 2449 DiagID = diag::ext_typename_missing; 2450 SourceLocation Loc = SS.getBeginLoc(); 2451 auto D = Diag(Loc, DiagID); 2452 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2453 << SourceRange(Loc, NameInfo.getEndLoc()); 2454 2455 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2456 // context. 2457 if (!RecoveryTSI) 2458 return ExprError(); 2459 2460 // Only issue the fixit if we're prepared to recover. 2461 D << FixItHint::CreateInsertion(Loc, "typename "); 2462 2463 // Recover by pretending this was an elaborated type. 2464 QualType Ty = Context.getTypeDeclType(TD); 2465 TypeLocBuilder TLB; 2466 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2467 2468 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2469 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2470 QTL.setElaboratedKeywordLoc(SourceLocation()); 2471 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2472 2473 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2474 2475 return ExprEmpty(); 2476 } 2477 2478 // Defend against this resolving to an implicit member access. We usually 2479 // won't get here if this might be a legitimate a class member (we end up in 2480 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2481 // a pointer-to-member or in an unevaluated context in C++11. 2482 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2483 return BuildPossibleImplicitMemberExpr(SS, 2484 /*TemplateKWLoc=*/SourceLocation(), 2485 R, /*TemplateArgs=*/nullptr, S); 2486 2487 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2488 } 2489 2490 /// The parser has read a name in, and Sema has detected that we're currently 2491 /// inside an ObjC method. Perform some additional checks and determine if we 2492 /// should form a reference to an ivar. 2493 /// 2494 /// Ideally, most of this would be done by lookup, but there's 2495 /// actually quite a lot of extra work involved. 2496 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 2497 IdentifierInfo *II) { 2498 SourceLocation Loc = Lookup.getNameLoc(); 2499 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2500 2501 // Check for error condition which is already reported. 2502 if (!CurMethod) 2503 return DeclResult(true); 2504 2505 // There are two cases to handle here. 1) scoped lookup could have failed, 2506 // in which case we should look for an ivar. 2) scoped lookup could have 2507 // found a decl, but that decl is outside the current instance method (i.e. 2508 // a global variable). In these two cases, we do a lookup for an ivar with 2509 // this name, if the lookup sucedes, we replace it our current decl. 2510 2511 // If we're in a class method, we don't normally want to look for 2512 // ivars. But if we don't find anything else, and there's an 2513 // ivar, that's an error. 2514 bool IsClassMethod = CurMethod->isClassMethod(); 2515 2516 bool LookForIvars; 2517 if (Lookup.empty()) 2518 LookForIvars = true; 2519 else if (IsClassMethod) 2520 LookForIvars = false; 2521 else 2522 LookForIvars = (Lookup.isSingleResult() && 2523 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2524 ObjCInterfaceDecl *IFace = nullptr; 2525 if (LookForIvars) { 2526 IFace = CurMethod->getClassInterface(); 2527 ObjCInterfaceDecl *ClassDeclared; 2528 ObjCIvarDecl *IV = nullptr; 2529 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2530 // Diagnose using an ivar in a class method. 2531 if (IsClassMethod) { 2532 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2533 return DeclResult(true); 2534 } 2535 2536 // Diagnose the use of an ivar outside of the declaring class. 2537 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2538 !declaresSameEntity(ClassDeclared, IFace) && 2539 !getLangOpts().DebuggerSupport) 2540 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2541 2542 // Success. 2543 return IV; 2544 } 2545 } else if (CurMethod->isInstanceMethod()) { 2546 // We should warn if a local variable hides an ivar. 2547 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2548 ObjCInterfaceDecl *ClassDeclared; 2549 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2550 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2551 declaresSameEntity(IFace, ClassDeclared)) 2552 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2553 } 2554 } 2555 } else if (Lookup.isSingleResult() && 2556 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2557 // If accessing a stand-alone ivar in a class method, this is an error. 2558 if (const ObjCIvarDecl *IV = 2559 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { 2560 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2561 return DeclResult(true); 2562 } 2563 } 2564 2565 // Didn't encounter an error, didn't find an ivar. 2566 return DeclResult(false); 2567 } 2568 2569 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, 2570 ObjCIvarDecl *IV) { 2571 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2572 assert(CurMethod && CurMethod->isInstanceMethod() && 2573 "should not reference ivar from this context"); 2574 2575 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 2576 assert(IFace && "should not reference ivar from this context"); 2577 2578 // If we're referencing an invalid decl, just return this as a silent 2579 // error node. The error diagnostic was already emitted on the decl. 2580 if (IV->isInvalidDecl()) 2581 return ExprError(); 2582 2583 // Check if referencing a field with __attribute__((deprecated)). 2584 if (DiagnoseUseOfDecl(IV, Loc)) 2585 return ExprError(); 2586 2587 // FIXME: This should use a new expr for a direct reference, don't 2588 // turn this into Self->ivar, just return a BareIVarExpr or something. 2589 IdentifierInfo &II = Context.Idents.get("self"); 2590 UnqualifiedId SelfName; 2591 SelfName.setIdentifier(&II, SourceLocation()); 2592 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam); 2593 CXXScopeSpec SelfScopeSpec; 2594 SourceLocation TemplateKWLoc; 2595 ExprResult SelfExpr = 2596 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2597 /*HasTrailingLParen=*/false, 2598 /*IsAddressOfOperand=*/false); 2599 if (SelfExpr.isInvalid()) 2600 return ExprError(); 2601 2602 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2603 if (SelfExpr.isInvalid()) 2604 return ExprError(); 2605 2606 MarkAnyDeclReferenced(Loc, IV, true); 2607 2608 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2609 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2610 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2611 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2612 2613 ObjCIvarRefExpr *Result = new (Context) 2614 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2615 IV->getLocation(), SelfExpr.get(), true, true); 2616 2617 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2618 if (!isUnevaluatedContext() && 2619 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2620 getCurFunction()->recordUseOfWeak(Result); 2621 } 2622 if (getLangOpts().ObjCAutoRefCount) 2623 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2624 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2625 2626 return Result; 2627 } 2628 2629 /// The parser has read a name in, and Sema has detected that we're currently 2630 /// inside an ObjC method. Perform some additional checks and determine if we 2631 /// should form a reference to an ivar. If so, build an expression referencing 2632 /// that ivar. 2633 ExprResult 2634 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2635 IdentifierInfo *II, bool AllowBuiltinCreation) { 2636 // FIXME: Integrate this lookup step into LookupParsedName. 2637 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); 2638 if (Ivar.isInvalid()) 2639 return ExprError(); 2640 if (Ivar.isUsable()) 2641 return BuildIvarRefExpr(S, Lookup.getNameLoc(), 2642 cast<ObjCIvarDecl>(Ivar.get())); 2643 2644 if (Lookup.empty() && II && AllowBuiltinCreation) 2645 LookupBuiltin(Lookup); 2646 2647 // Sentinel value saying that we didn't do anything special. 2648 return ExprResult(false); 2649 } 2650 2651 /// Cast a base object to a member's actual type. 2652 /// 2653 /// Logically this happens in three phases: 2654 /// 2655 /// * First we cast from the base type to the naming class. 2656 /// The naming class is the class into which we were looking 2657 /// when we found the member; it's the qualifier type if a 2658 /// qualifier was provided, and otherwise it's the base type. 2659 /// 2660 /// * Next we cast from the naming class to the declaring class. 2661 /// If the member we found was brought into a class's scope by 2662 /// a using declaration, this is that class; otherwise it's 2663 /// the class declaring the member. 2664 /// 2665 /// * Finally we cast from the declaring class to the "true" 2666 /// declaring class of the member. This conversion does not 2667 /// obey access control. 2668 ExprResult 2669 Sema::PerformObjectMemberConversion(Expr *From, 2670 NestedNameSpecifier *Qualifier, 2671 NamedDecl *FoundDecl, 2672 NamedDecl *Member) { 2673 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2674 if (!RD) 2675 return From; 2676 2677 QualType DestRecordType; 2678 QualType DestType; 2679 QualType FromRecordType; 2680 QualType FromType = From->getType(); 2681 bool PointerConversions = false; 2682 if (isa<FieldDecl>(Member)) { 2683 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2684 auto FromPtrType = FromType->getAs<PointerType>(); 2685 DestRecordType = Context.getAddrSpaceQualType( 2686 DestRecordType, FromPtrType 2687 ? FromType->getPointeeType().getAddressSpace() 2688 : FromType.getAddressSpace()); 2689 2690 if (FromPtrType) { 2691 DestType = Context.getPointerType(DestRecordType); 2692 FromRecordType = FromPtrType->getPointeeType(); 2693 PointerConversions = true; 2694 } else { 2695 DestType = DestRecordType; 2696 FromRecordType = FromType; 2697 } 2698 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2699 if (Method->isStatic()) 2700 return From; 2701 2702 DestType = Method->getThisType(); 2703 DestRecordType = DestType->getPointeeType(); 2704 2705 if (FromType->getAs<PointerType>()) { 2706 FromRecordType = FromType->getPointeeType(); 2707 PointerConversions = true; 2708 } else { 2709 FromRecordType = FromType; 2710 DestType = DestRecordType; 2711 } 2712 } else { 2713 // No conversion necessary. 2714 return From; 2715 } 2716 2717 if (DestType->isDependentType() || FromType->isDependentType()) 2718 return From; 2719 2720 // If the unqualified types are the same, no conversion is necessary. 2721 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2722 return From; 2723 2724 SourceRange FromRange = From->getSourceRange(); 2725 SourceLocation FromLoc = FromRange.getBegin(); 2726 2727 ExprValueKind VK = From->getValueKind(); 2728 2729 // C++ [class.member.lookup]p8: 2730 // [...] Ambiguities can often be resolved by qualifying a name with its 2731 // class name. 2732 // 2733 // If the member was a qualified name and the qualified referred to a 2734 // specific base subobject type, we'll cast to that intermediate type 2735 // first and then to the object in which the member is declared. That allows 2736 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2737 // 2738 // class Base { public: int x; }; 2739 // class Derived1 : public Base { }; 2740 // class Derived2 : public Base { }; 2741 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2742 // 2743 // void VeryDerived::f() { 2744 // x = 17; // error: ambiguous base subobjects 2745 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2746 // } 2747 if (Qualifier && Qualifier->getAsType()) { 2748 QualType QType = QualType(Qualifier->getAsType(), 0); 2749 assert(QType->isRecordType() && "lookup done with non-record type"); 2750 2751 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2752 2753 // In C++98, the qualifier type doesn't actually have to be a base 2754 // type of the object type, in which case we just ignore it. 2755 // Otherwise build the appropriate casts. 2756 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2757 CXXCastPath BasePath; 2758 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2759 FromLoc, FromRange, &BasePath)) 2760 return ExprError(); 2761 2762 if (PointerConversions) 2763 QType = Context.getPointerType(QType); 2764 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2765 VK, &BasePath).get(); 2766 2767 FromType = QType; 2768 FromRecordType = QRecordType; 2769 2770 // If the qualifier type was the same as the destination type, 2771 // we're done. 2772 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2773 return From; 2774 } 2775 } 2776 2777 bool IgnoreAccess = false; 2778 2779 // If we actually found the member through a using declaration, cast 2780 // down to the using declaration's type. 2781 // 2782 // Pointer equality is fine here because only one declaration of a 2783 // class ever has member declarations. 2784 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2785 assert(isa<UsingShadowDecl>(FoundDecl)); 2786 QualType URecordType = Context.getTypeDeclType( 2787 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2788 2789 // We only need to do this if the naming-class to declaring-class 2790 // conversion is non-trivial. 2791 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2792 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2793 CXXCastPath BasePath; 2794 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2795 FromLoc, FromRange, &BasePath)) 2796 return ExprError(); 2797 2798 QualType UType = URecordType; 2799 if (PointerConversions) 2800 UType = Context.getPointerType(UType); 2801 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2802 VK, &BasePath).get(); 2803 FromType = UType; 2804 FromRecordType = URecordType; 2805 } 2806 2807 // We don't do access control for the conversion from the 2808 // declaring class to the true declaring class. 2809 IgnoreAccess = true; 2810 } 2811 2812 CXXCastPath BasePath; 2813 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2814 FromLoc, FromRange, &BasePath, 2815 IgnoreAccess)) 2816 return ExprError(); 2817 2818 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2819 VK, &BasePath); 2820 } 2821 2822 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2823 const LookupResult &R, 2824 bool HasTrailingLParen) { 2825 // Only when used directly as the postfix-expression of a call. 2826 if (!HasTrailingLParen) 2827 return false; 2828 2829 // Never if a scope specifier was provided. 2830 if (SS.isSet()) 2831 return false; 2832 2833 // Only in C++ or ObjC++. 2834 if (!getLangOpts().CPlusPlus) 2835 return false; 2836 2837 // Turn off ADL when we find certain kinds of declarations during 2838 // normal lookup: 2839 for (NamedDecl *D : R) { 2840 // C++0x [basic.lookup.argdep]p3: 2841 // -- a declaration of a class member 2842 // Since using decls preserve this property, we check this on the 2843 // original decl. 2844 if (D->isCXXClassMember()) 2845 return false; 2846 2847 // C++0x [basic.lookup.argdep]p3: 2848 // -- a block-scope function declaration that is not a 2849 // using-declaration 2850 // NOTE: we also trigger this for function templates (in fact, we 2851 // don't check the decl type at all, since all other decl types 2852 // turn off ADL anyway). 2853 if (isa<UsingShadowDecl>(D)) 2854 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2855 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2856 return false; 2857 2858 // C++0x [basic.lookup.argdep]p3: 2859 // -- a declaration that is neither a function or a function 2860 // template 2861 // And also for builtin functions. 2862 if (isa<FunctionDecl>(D)) { 2863 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2864 2865 // But also builtin functions. 2866 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2867 return false; 2868 } else if (!isa<FunctionTemplateDecl>(D)) 2869 return false; 2870 } 2871 2872 return true; 2873 } 2874 2875 2876 /// Diagnoses obvious problems with the use of the given declaration 2877 /// as an expression. This is only actually called for lookups that 2878 /// were not overloaded, and it doesn't promise that the declaration 2879 /// will in fact be used. 2880 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2881 if (D->isInvalidDecl()) 2882 return true; 2883 2884 if (isa<TypedefNameDecl>(D)) { 2885 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2886 return true; 2887 } 2888 2889 if (isa<ObjCInterfaceDecl>(D)) { 2890 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2891 return true; 2892 } 2893 2894 if (isa<NamespaceDecl>(D)) { 2895 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2896 return true; 2897 } 2898 2899 return false; 2900 } 2901 2902 // Certain multiversion types should be treated as overloaded even when there is 2903 // only one result. 2904 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 2905 assert(R.isSingleResult() && "Expected only a single result"); 2906 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 2907 return FD && 2908 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 2909 } 2910 2911 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2912 LookupResult &R, bool NeedsADL, 2913 bool AcceptInvalidDecl) { 2914 // If this is a single, fully-resolved result and we don't need ADL, 2915 // just build an ordinary singleton decl ref. 2916 if (!NeedsADL && R.isSingleResult() && 2917 !R.getAsSingle<FunctionTemplateDecl>() && 2918 !ShouldLookupResultBeMultiVersionOverload(R)) 2919 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2920 R.getRepresentativeDecl(), nullptr, 2921 AcceptInvalidDecl); 2922 2923 // We only need to check the declaration if there's exactly one 2924 // result, because in the overloaded case the results can only be 2925 // functions and function templates. 2926 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 2927 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2928 return ExprError(); 2929 2930 // Otherwise, just build an unresolved lookup expression. Suppress 2931 // any lookup-related diagnostics; we'll hash these out later, when 2932 // we've picked a target. 2933 R.suppressDiagnostics(); 2934 2935 UnresolvedLookupExpr *ULE 2936 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2937 SS.getWithLocInContext(Context), 2938 R.getLookupNameInfo(), 2939 NeedsADL, R.isOverloadedResult(), 2940 R.begin(), R.end()); 2941 2942 return ULE; 2943 } 2944 2945 static void 2946 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 2947 ValueDecl *var, DeclContext *DC); 2948 2949 /// Complete semantic analysis for a reference to the given declaration. 2950 ExprResult Sema::BuildDeclarationNameExpr( 2951 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2952 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2953 bool AcceptInvalidDecl) { 2954 assert(D && "Cannot refer to a NULL declaration"); 2955 assert(!isa<FunctionTemplateDecl>(D) && 2956 "Cannot refer unambiguously to a function template"); 2957 2958 SourceLocation Loc = NameInfo.getLoc(); 2959 if (CheckDeclInExpr(*this, Loc, D)) 2960 return ExprError(); 2961 2962 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2963 // Specifically diagnose references to class templates that are missing 2964 // a template argument list. 2965 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 2966 return ExprError(); 2967 } 2968 2969 // Make sure that we're referring to a value. 2970 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2971 if (!VD) { 2972 Diag(Loc, diag::err_ref_non_value) 2973 << D << SS.getRange(); 2974 Diag(D->getLocation(), diag::note_declared_at); 2975 return ExprError(); 2976 } 2977 2978 // Check whether this declaration can be used. Note that we suppress 2979 // this check when we're going to perform argument-dependent lookup 2980 // on this function name, because this might not be the function 2981 // that overload resolution actually selects. 2982 if (DiagnoseUseOfDecl(VD, Loc)) 2983 return ExprError(); 2984 2985 // Only create DeclRefExpr's for valid Decl's. 2986 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2987 return ExprError(); 2988 2989 // Handle members of anonymous structs and unions. If we got here, 2990 // and the reference is to a class member indirect field, then this 2991 // must be the subject of a pointer-to-member expression. 2992 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2993 if (!indirectField->isCXXClassMember()) 2994 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2995 indirectField); 2996 2997 { 2998 QualType type = VD->getType(); 2999 if (type.isNull()) 3000 return ExprError(); 3001 if (auto *FPT = type->getAs<FunctionProtoType>()) { 3002 // C++ [except.spec]p17: 3003 // An exception-specification is considered to be needed when: 3004 // - in an expression, the function is the unique lookup result or 3005 // the selected member of a set of overloaded functions. 3006 ResolveExceptionSpec(Loc, FPT); 3007 type = VD->getType(); 3008 } 3009 ExprValueKind valueKind = VK_RValue; 3010 3011 switch (D->getKind()) { 3012 // Ignore all the non-ValueDecl kinds. 3013 #define ABSTRACT_DECL(kind) 3014 #define VALUE(type, base) 3015 #define DECL(type, base) \ 3016 case Decl::type: 3017 #include "clang/AST/DeclNodes.inc" 3018 llvm_unreachable("invalid value decl kind"); 3019 3020 // These shouldn't make it here. 3021 case Decl::ObjCAtDefsField: 3022 llvm_unreachable("forming non-member reference to ivar?"); 3023 3024 // Enum constants are always r-values and never references. 3025 // Unresolved using declarations are dependent. 3026 case Decl::EnumConstant: 3027 case Decl::UnresolvedUsingValue: 3028 case Decl::OMPDeclareReduction: 3029 case Decl::OMPDeclareMapper: 3030 valueKind = VK_RValue; 3031 break; 3032 3033 // Fields and indirect fields that got here must be for 3034 // pointer-to-member expressions; we just call them l-values for 3035 // internal consistency, because this subexpression doesn't really 3036 // exist in the high-level semantics. 3037 case Decl::Field: 3038 case Decl::IndirectField: 3039 case Decl::ObjCIvar: 3040 assert(getLangOpts().CPlusPlus && 3041 "building reference to field in C?"); 3042 3043 // These can't have reference type in well-formed programs, but 3044 // for internal consistency we do this anyway. 3045 type = type.getNonReferenceType(); 3046 valueKind = VK_LValue; 3047 break; 3048 3049 // Non-type template parameters are either l-values or r-values 3050 // depending on the type. 3051 case Decl::NonTypeTemplateParm: { 3052 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3053 type = reftype->getPointeeType(); 3054 valueKind = VK_LValue; // even if the parameter is an r-value reference 3055 break; 3056 } 3057 3058 // For non-references, we need to strip qualifiers just in case 3059 // the template parameter was declared as 'const int' or whatever. 3060 valueKind = VK_RValue; 3061 type = type.getUnqualifiedType(); 3062 break; 3063 } 3064 3065 case Decl::Var: 3066 case Decl::VarTemplateSpecialization: 3067 case Decl::VarTemplatePartialSpecialization: 3068 case Decl::Decomposition: 3069 case Decl::OMPCapturedExpr: 3070 // In C, "extern void blah;" is valid and is an r-value. 3071 if (!getLangOpts().CPlusPlus && 3072 !type.hasQualifiers() && 3073 type->isVoidType()) { 3074 valueKind = VK_RValue; 3075 break; 3076 } 3077 LLVM_FALLTHROUGH; 3078 3079 case Decl::ImplicitParam: 3080 case Decl::ParmVar: { 3081 // These are always l-values. 3082 valueKind = VK_LValue; 3083 type = type.getNonReferenceType(); 3084 3085 // FIXME: Does the addition of const really only apply in 3086 // potentially-evaluated contexts? Since the variable isn't actually 3087 // captured in an unevaluated context, it seems that the answer is no. 3088 if (!isUnevaluatedContext()) { 3089 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3090 if (!CapturedType.isNull()) 3091 type = CapturedType; 3092 } 3093 3094 break; 3095 } 3096 3097 case Decl::Binding: { 3098 // These are always lvalues. 3099 valueKind = VK_LValue; 3100 type = type.getNonReferenceType(); 3101 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3102 // decides how that's supposed to work. 3103 auto *BD = cast<BindingDecl>(VD); 3104 if (BD->getDeclContext() != CurContext) { 3105 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); 3106 if (DD && DD->hasLocalStorage()) 3107 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 3108 } 3109 break; 3110 } 3111 3112 case Decl::Function: { 3113 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3114 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3115 type = Context.BuiltinFnTy; 3116 valueKind = VK_RValue; 3117 break; 3118 } 3119 } 3120 3121 const FunctionType *fty = type->castAs<FunctionType>(); 3122 3123 // If we're referring to a function with an __unknown_anytype 3124 // result type, make the entire expression __unknown_anytype. 3125 if (fty->getReturnType() == Context.UnknownAnyTy) { 3126 type = Context.UnknownAnyTy; 3127 valueKind = VK_RValue; 3128 break; 3129 } 3130 3131 // Functions are l-values in C++. 3132 if (getLangOpts().CPlusPlus) { 3133 valueKind = VK_LValue; 3134 break; 3135 } 3136 3137 // C99 DR 316 says that, if a function type comes from a 3138 // function definition (without a prototype), that type is only 3139 // used for checking compatibility. Therefore, when referencing 3140 // the function, we pretend that we don't have the full function 3141 // type. 3142 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3143 isa<FunctionProtoType>(fty)) 3144 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3145 fty->getExtInfo()); 3146 3147 // Functions are r-values in C. 3148 valueKind = VK_RValue; 3149 break; 3150 } 3151 3152 case Decl::CXXDeductionGuide: 3153 llvm_unreachable("building reference to deduction guide"); 3154 3155 case Decl::MSProperty: 3156 valueKind = VK_LValue; 3157 break; 3158 3159 case Decl::CXXMethod: 3160 // If we're referring to a method with an __unknown_anytype 3161 // result type, make the entire expression __unknown_anytype. 3162 // This should only be possible with a type written directly. 3163 if (const FunctionProtoType *proto 3164 = dyn_cast<FunctionProtoType>(VD->getType())) 3165 if (proto->getReturnType() == Context.UnknownAnyTy) { 3166 type = Context.UnknownAnyTy; 3167 valueKind = VK_RValue; 3168 break; 3169 } 3170 3171 // C++ methods are l-values if static, r-values if non-static. 3172 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3173 valueKind = VK_LValue; 3174 break; 3175 } 3176 LLVM_FALLTHROUGH; 3177 3178 case Decl::CXXConversion: 3179 case Decl::CXXDestructor: 3180 case Decl::CXXConstructor: 3181 valueKind = VK_RValue; 3182 break; 3183 } 3184 3185 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3186 /*FIXME: TemplateKWLoc*/ SourceLocation(), 3187 TemplateArgs); 3188 } 3189 } 3190 3191 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3192 SmallString<32> &Target) { 3193 Target.resize(CharByteWidth * (Source.size() + 1)); 3194 char *ResultPtr = &Target[0]; 3195 const llvm::UTF8 *ErrorPtr; 3196 bool success = 3197 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3198 (void)success; 3199 assert(success); 3200 Target.resize(ResultPtr - &Target[0]); 3201 } 3202 3203 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3204 PredefinedExpr::IdentKind IK) { 3205 // Pick the current block, lambda, captured statement or function. 3206 Decl *currentDecl = nullptr; 3207 if (const BlockScopeInfo *BSI = getCurBlock()) 3208 currentDecl = BSI->TheDecl; 3209 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3210 currentDecl = LSI->CallOperator; 3211 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3212 currentDecl = CSI->TheCapturedDecl; 3213 else 3214 currentDecl = getCurFunctionOrMethodDecl(); 3215 3216 if (!currentDecl) { 3217 Diag(Loc, diag::ext_predef_outside_function); 3218 currentDecl = Context.getTranslationUnitDecl(); 3219 } 3220 3221 QualType ResTy; 3222 StringLiteral *SL = nullptr; 3223 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3224 ResTy = Context.DependentTy; 3225 else { 3226 // Pre-defined identifiers are of type char[x], where x is the length of 3227 // the string. 3228 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3229 unsigned Length = Str.length(); 3230 3231 llvm::APInt LengthI(32, Length + 1); 3232 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3233 ResTy = 3234 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3235 SmallString<32> RawChars; 3236 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3237 Str, RawChars); 3238 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3239 ArrayType::Normal, 3240 /*IndexTypeQuals*/ 0); 3241 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3242 /*Pascal*/ false, ResTy, Loc); 3243 } else { 3244 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3245 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3246 ArrayType::Normal, 3247 /*IndexTypeQuals*/ 0); 3248 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3249 /*Pascal*/ false, ResTy, Loc); 3250 } 3251 } 3252 3253 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3254 } 3255 3256 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3257 PredefinedExpr::IdentKind IK; 3258 3259 switch (Kind) { 3260 default: llvm_unreachable("Unknown simple primary expr!"); 3261 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3262 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3263 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3264 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3265 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3266 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3267 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3268 } 3269 3270 return BuildPredefinedExpr(Loc, IK); 3271 } 3272 3273 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3274 SmallString<16> CharBuffer; 3275 bool Invalid = false; 3276 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3277 if (Invalid) 3278 return ExprError(); 3279 3280 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3281 PP, Tok.getKind()); 3282 if (Literal.hadError()) 3283 return ExprError(); 3284 3285 QualType Ty; 3286 if (Literal.isWide()) 3287 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3288 else if (Literal.isUTF8() && getLangOpts().Char8) 3289 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3290 else if (Literal.isUTF16()) 3291 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3292 else if (Literal.isUTF32()) 3293 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3294 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3295 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3296 else 3297 Ty = Context.CharTy; // 'x' -> char in C++ 3298 3299 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3300 if (Literal.isWide()) 3301 Kind = CharacterLiteral::Wide; 3302 else if (Literal.isUTF16()) 3303 Kind = CharacterLiteral::UTF16; 3304 else if (Literal.isUTF32()) 3305 Kind = CharacterLiteral::UTF32; 3306 else if (Literal.isUTF8()) 3307 Kind = CharacterLiteral::UTF8; 3308 3309 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3310 Tok.getLocation()); 3311 3312 if (Literal.getUDSuffix().empty()) 3313 return Lit; 3314 3315 // We're building a user-defined literal. 3316 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3317 SourceLocation UDSuffixLoc = 3318 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3319 3320 // Make sure we're allowed user-defined literals here. 3321 if (!UDLScope) 3322 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3323 3324 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3325 // operator "" X (ch) 3326 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3327 Lit, Tok.getLocation()); 3328 } 3329 3330 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3331 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3332 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3333 Context.IntTy, Loc); 3334 } 3335 3336 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3337 QualType Ty, SourceLocation Loc) { 3338 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3339 3340 using llvm::APFloat; 3341 APFloat Val(Format); 3342 3343 APFloat::opStatus result = Literal.GetFloatValue(Val); 3344 3345 // Overflow is always an error, but underflow is only an error if 3346 // we underflowed to zero (APFloat reports denormals as underflow). 3347 if ((result & APFloat::opOverflow) || 3348 ((result & APFloat::opUnderflow) && Val.isZero())) { 3349 unsigned diagnostic; 3350 SmallString<20> buffer; 3351 if (result & APFloat::opOverflow) { 3352 diagnostic = diag::warn_float_overflow; 3353 APFloat::getLargest(Format).toString(buffer); 3354 } else { 3355 diagnostic = diag::warn_float_underflow; 3356 APFloat::getSmallest(Format).toString(buffer); 3357 } 3358 3359 S.Diag(Loc, diagnostic) 3360 << Ty 3361 << StringRef(buffer.data(), buffer.size()); 3362 } 3363 3364 bool isExact = (result == APFloat::opOK); 3365 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3366 } 3367 3368 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3369 assert(E && "Invalid expression"); 3370 3371 if (E->isValueDependent()) 3372 return false; 3373 3374 QualType QT = E->getType(); 3375 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3376 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3377 return true; 3378 } 3379 3380 llvm::APSInt ValueAPS; 3381 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3382 3383 if (R.isInvalid()) 3384 return true; 3385 3386 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3387 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3388 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3389 << ValueAPS.toString(10) << ValueIsPositive; 3390 return true; 3391 } 3392 3393 return false; 3394 } 3395 3396 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3397 // Fast path for a single digit (which is quite common). A single digit 3398 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3399 if (Tok.getLength() == 1) { 3400 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3401 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3402 } 3403 3404 SmallString<128> SpellingBuffer; 3405 // NumericLiteralParser wants to overread by one character. Add padding to 3406 // the buffer in case the token is copied to the buffer. If getSpelling() 3407 // returns a StringRef to the memory buffer, it should have a null char at 3408 // the EOF, so it is also safe. 3409 SpellingBuffer.resize(Tok.getLength() + 1); 3410 3411 // Get the spelling of the token, which eliminates trigraphs, etc. 3412 bool Invalid = false; 3413 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3414 if (Invalid) 3415 return ExprError(); 3416 3417 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3418 if (Literal.hadError) 3419 return ExprError(); 3420 3421 if (Literal.hasUDSuffix()) { 3422 // We're building a user-defined literal. 3423 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3424 SourceLocation UDSuffixLoc = 3425 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3426 3427 // Make sure we're allowed user-defined literals here. 3428 if (!UDLScope) 3429 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3430 3431 QualType CookedTy; 3432 if (Literal.isFloatingLiteral()) { 3433 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3434 // long double, the literal is treated as a call of the form 3435 // operator "" X (f L) 3436 CookedTy = Context.LongDoubleTy; 3437 } else { 3438 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3439 // unsigned long long, the literal is treated as a call of the form 3440 // operator "" X (n ULL) 3441 CookedTy = Context.UnsignedLongLongTy; 3442 } 3443 3444 DeclarationName OpName = 3445 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3446 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3447 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3448 3449 SourceLocation TokLoc = Tok.getLocation(); 3450 3451 // Perform literal operator lookup to determine if we're building a raw 3452 // literal or a cooked one. 3453 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3454 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3455 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3456 /*AllowStringTemplate*/ false, 3457 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3458 case LOLR_ErrorNoDiagnostic: 3459 // Lookup failure for imaginary constants isn't fatal, there's still the 3460 // GNU extension producing _Complex types. 3461 break; 3462 case LOLR_Error: 3463 return ExprError(); 3464 case LOLR_Cooked: { 3465 Expr *Lit; 3466 if (Literal.isFloatingLiteral()) { 3467 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3468 } else { 3469 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3470 if (Literal.GetIntegerValue(ResultVal)) 3471 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3472 << /* Unsigned */ 1; 3473 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3474 Tok.getLocation()); 3475 } 3476 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3477 } 3478 3479 case LOLR_Raw: { 3480 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3481 // literal is treated as a call of the form 3482 // operator "" X ("n") 3483 unsigned Length = Literal.getUDSuffixOffset(); 3484 QualType StrTy = Context.getConstantArrayType( 3485 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3486 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); 3487 Expr *Lit = StringLiteral::Create( 3488 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3489 /*Pascal*/false, StrTy, &TokLoc, 1); 3490 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3491 } 3492 3493 case LOLR_Template: { 3494 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3495 // template), L is treated as a call fo the form 3496 // operator "" X <'c1', 'c2', ... 'ck'>() 3497 // where n is the source character sequence c1 c2 ... ck. 3498 TemplateArgumentListInfo ExplicitArgs; 3499 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3500 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3501 llvm::APSInt Value(CharBits, CharIsUnsigned); 3502 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3503 Value = TokSpelling[I]; 3504 TemplateArgument Arg(Context, Value, Context.CharTy); 3505 TemplateArgumentLocInfo ArgInfo; 3506 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3507 } 3508 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3509 &ExplicitArgs); 3510 } 3511 case LOLR_StringTemplate: 3512 llvm_unreachable("unexpected literal operator lookup result"); 3513 } 3514 } 3515 3516 Expr *Res; 3517 3518 if (Literal.isFixedPointLiteral()) { 3519 QualType Ty; 3520 3521 if (Literal.isAccum) { 3522 if (Literal.isHalf) { 3523 Ty = Context.ShortAccumTy; 3524 } else if (Literal.isLong) { 3525 Ty = Context.LongAccumTy; 3526 } else { 3527 Ty = Context.AccumTy; 3528 } 3529 } else if (Literal.isFract) { 3530 if (Literal.isHalf) { 3531 Ty = Context.ShortFractTy; 3532 } else if (Literal.isLong) { 3533 Ty = Context.LongFractTy; 3534 } else { 3535 Ty = Context.FractTy; 3536 } 3537 } 3538 3539 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3540 3541 bool isSigned = !Literal.isUnsigned; 3542 unsigned scale = Context.getFixedPointScale(Ty); 3543 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3544 3545 llvm::APInt Val(bit_width, 0, isSigned); 3546 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3547 bool ValIsZero = Val.isNullValue() && !Overflowed; 3548 3549 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3550 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3551 // Clause 6.4.4 - The value of a constant shall be in the range of 3552 // representable values for its type, with exception for constants of a 3553 // fract type with a value of exactly 1; such a constant shall denote 3554 // the maximal value for the type. 3555 --Val; 3556 else if (Val.ugt(MaxVal) || Overflowed) 3557 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3558 3559 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3560 Tok.getLocation(), scale); 3561 } else if (Literal.isFloatingLiteral()) { 3562 QualType Ty; 3563 if (Literal.isHalf){ 3564 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3565 Ty = Context.HalfTy; 3566 else { 3567 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3568 return ExprError(); 3569 } 3570 } else if (Literal.isFloat) 3571 Ty = Context.FloatTy; 3572 else if (Literal.isLong) 3573 Ty = Context.LongDoubleTy; 3574 else if (Literal.isFloat16) 3575 Ty = Context.Float16Ty; 3576 else if (Literal.isFloat128) 3577 Ty = Context.Float128Ty; 3578 else 3579 Ty = Context.DoubleTy; 3580 3581 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3582 3583 if (Ty == Context.DoubleTy) { 3584 if (getLangOpts().SinglePrecisionConstants) { 3585 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3586 if (BTy->getKind() != BuiltinType::Float) { 3587 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3588 } 3589 } else if (getLangOpts().OpenCL && 3590 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3591 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3592 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3593 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3594 } 3595 } 3596 } else if (!Literal.isIntegerLiteral()) { 3597 return ExprError(); 3598 } else { 3599 QualType Ty; 3600 3601 // 'long long' is a C99 or C++11 feature. 3602 if (!getLangOpts().C99 && Literal.isLongLong) { 3603 if (getLangOpts().CPlusPlus) 3604 Diag(Tok.getLocation(), 3605 getLangOpts().CPlusPlus11 ? 3606 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3607 else 3608 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3609 } 3610 3611 // Get the value in the widest-possible width. 3612 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3613 llvm::APInt ResultVal(MaxWidth, 0); 3614 3615 if (Literal.GetIntegerValue(ResultVal)) { 3616 // If this value didn't fit into uintmax_t, error and force to ull. 3617 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3618 << /* Unsigned */ 1; 3619 Ty = Context.UnsignedLongLongTy; 3620 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3621 "long long is not intmax_t?"); 3622 } else { 3623 // If this value fits into a ULL, try to figure out what else it fits into 3624 // according to the rules of C99 6.4.4.1p5. 3625 3626 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3627 // be an unsigned int. 3628 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3629 3630 // Check from smallest to largest, picking the smallest type we can. 3631 unsigned Width = 0; 3632 3633 // Microsoft specific integer suffixes are explicitly sized. 3634 if (Literal.MicrosoftInteger) { 3635 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3636 Width = 8; 3637 Ty = Context.CharTy; 3638 } else { 3639 Width = Literal.MicrosoftInteger; 3640 Ty = Context.getIntTypeForBitwidth(Width, 3641 /*Signed=*/!Literal.isUnsigned); 3642 } 3643 } 3644 3645 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3646 // Are int/unsigned possibilities? 3647 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3648 3649 // Does it fit in a unsigned int? 3650 if (ResultVal.isIntN(IntSize)) { 3651 // Does it fit in a signed int? 3652 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3653 Ty = Context.IntTy; 3654 else if (AllowUnsigned) 3655 Ty = Context.UnsignedIntTy; 3656 Width = IntSize; 3657 } 3658 } 3659 3660 // Are long/unsigned long possibilities? 3661 if (Ty.isNull() && !Literal.isLongLong) { 3662 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3663 3664 // Does it fit in a unsigned long? 3665 if (ResultVal.isIntN(LongSize)) { 3666 // Does it fit in a signed long? 3667 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3668 Ty = Context.LongTy; 3669 else if (AllowUnsigned) 3670 Ty = Context.UnsignedLongTy; 3671 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3672 // is compatible. 3673 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3674 const unsigned LongLongSize = 3675 Context.getTargetInfo().getLongLongWidth(); 3676 Diag(Tok.getLocation(), 3677 getLangOpts().CPlusPlus 3678 ? Literal.isLong 3679 ? diag::warn_old_implicitly_unsigned_long_cxx 3680 : /*C++98 UB*/ diag:: 3681 ext_old_implicitly_unsigned_long_cxx 3682 : diag::warn_old_implicitly_unsigned_long) 3683 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3684 : /*will be ill-formed*/ 1); 3685 Ty = Context.UnsignedLongTy; 3686 } 3687 Width = LongSize; 3688 } 3689 } 3690 3691 // Check long long if needed. 3692 if (Ty.isNull()) { 3693 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3694 3695 // Does it fit in a unsigned long long? 3696 if (ResultVal.isIntN(LongLongSize)) { 3697 // Does it fit in a signed long long? 3698 // To be compatible with MSVC, hex integer literals ending with the 3699 // LL or i64 suffix are always signed in Microsoft mode. 3700 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3701 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3702 Ty = Context.LongLongTy; 3703 else if (AllowUnsigned) 3704 Ty = Context.UnsignedLongLongTy; 3705 Width = LongLongSize; 3706 } 3707 } 3708 3709 // If we still couldn't decide a type, we probably have something that 3710 // does not fit in a signed long long, but has no U suffix. 3711 if (Ty.isNull()) { 3712 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3713 Ty = Context.UnsignedLongLongTy; 3714 Width = Context.getTargetInfo().getLongLongWidth(); 3715 } 3716 3717 if (ResultVal.getBitWidth() != Width) 3718 ResultVal = ResultVal.trunc(Width); 3719 } 3720 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3721 } 3722 3723 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3724 if (Literal.isImaginary) { 3725 Res = new (Context) ImaginaryLiteral(Res, 3726 Context.getComplexType(Res->getType())); 3727 3728 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3729 } 3730 return Res; 3731 } 3732 3733 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3734 assert(E && "ActOnParenExpr() missing expr"); 3735 return new (Context) ParenExpr(L, R, E); 3736 } 3737 3738 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3739 SourceLocation Loc, 3740 SourceRange ArgRange) { 3741 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3742 // scalar or vector data type argument..." 3743 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3744 // type (C99 6.2.5p18) or void. 3745 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3746 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3747 << T << ArgRange; 3748 return true; 3749 } 3750 3751 assert((T->isVoidType() || !T->isIncompleteType()) && 3752 "Scalar types should always be complete"); 3753 return false; 3754 } 3755 3756 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3757 SourceLocation Loc, 3758 SourceRange ArgRange, 3759 UnaryExprOrTypeTrait TraitKind) { 3760 // Invalid types must be hard errors for SFINAE in C++. 3761 if (S.LangOpts.CPlusPlus) 3762 return true; 3763 3764 // C99 6.5.3.4p1: 3765 if (T->isFunctionType() && 3766 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 3767 TraitKind == UETT_PreferredAlignOf)) { 3768 // sizeof(function)/alignof(function) is allowed as an extension. 3769 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3770 << TraitKind << ArgRange; 3771 return false; 3772 } 3773 3774 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3775 // this is an error (OpenCL v1.1 s6.3.k) 3776 if (T->isVoidType()) { 3777 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3778 : diag::ext_sizeof_alignof_void_type; 3779 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3780 return false; 3781 } 3782 3783 return true; 3784 } 3785 3786 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3787 SourceLocation Loc, 3788 SourceRange ArgRange, 3789 UnaryExprOrTypeTrait TraitKind) { 3790 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3791 // runtime doesn't allow it. 3792 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3793 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3794 << T << (TraitKind == UETT_SizeOf) 3795 << ArgRange; 3796 return true; 3797 } 3798 3799 return false; 3800 } 3801 3802 /// Check whether E is a pointer from a decayed array type (the decayed 3803 /// pointer type is equal to T) and emit a warning if it is. 3804 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3805 Expr *E) { 3806 // Don't warn if the operation changed the type. 3807 if (T != E->getType()) 3808 return; 3809 3810 // Now look for array decays. 3811 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3812 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3813 return; 3814 3815 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3816 << ICE->getType() 3817 << ICE->getSubExpr()->getType(); 3818 } 3819 3820 /// Check the constraints on expression operands to unary type expression 3821 /// and type traits. 3822 /// 3823 /// Completes any types necessary and validates the constraints on the operand 3824 /// expression. The logic mostly mirrors the type-based overload, but may modify 3825 /// the expression as it completes the type for that expression through template 3826 /// instantiation, etc. 3827 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3828 UnaryExprOrTypeTrait ExprKind) { 3829 QualType ExprTy = E->getType(); 3830 assert(!ExprTy->isReferenceType()); 3831 3832 bool IsUnevaluatedOperand = 3833 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 3834 ExprKind == UETT_PreferredAlignOf); 3835 if (IsUnevaluatedOperand) { 3836 ExprResult Result = CheckUnevaluatedOperand(E); 3837 if (Result.isInvalid()) 3838 return true; 3839 E = Result.get(); 3840 } 3841 3842 if (ExprKind == UETT_VecStep) 3843 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3844 E->getSourceRange()); 3845 3846 // Whitelist some types as extensions 3847 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3848 E->getSourceRange(), ExprKind)) 3849 return false; 3850 3851 // 'alignof' applied to an expression only requires the base element type of 3852 // the expression to be complete. 'sizeof' requires the expression's type to 3853 // be complete (and will attempt to complete it if it's an array of unknown 3854 // bound). 3855 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 3856 if (RequireCompleteType(E->getExprLoc(), 3857 Context.getBaseElementType(E->getType()), 3858 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3859 E->getSourceRange())) 3860 return true; 3861 } else { 3862 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3863 ExprKind, E->getSourceRange())) 3864 return true; 3865 } 3866 3867 // Completing the expression's type may have changed it. 3868 ExprTy = E->getType(); 3869 assert(!ExprTy->isReferenceType()); 3870 3871 if (ExprTy->isFunctionType()) { 3872 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3873 << ExprKind << E->getSourceRange(); 3874 return true; 3875 } 3876 3877 // The operand for sizeof and alignof is in an unevaluated expression context, 3878 // so side effects could result in unintended consequences. 3879 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 3880 E->HasSideEffects(Context, false)) 3881 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3882 3883 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3884 E->getSourceRange(), ExprKind)) 3885 return true; 3886 3887 if (ExprKind == UETT_SizeOf) { 3888 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3889 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3890 QualType OType = PVD->getOriginalType(); 3891 QualType Type = PVD->getType(); 3892 if (Type->isPointerType() && OType->isArrayType()) { 3893 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3894 << Type << OType; 3895 Diag(PVD->getLocation(), diag::note_declared_at); 3896 } 3897 } 3898 } 3899 3900 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3901 // decays into a pointer and returns an unintended result. This is most 3902 // likely a typo for "sizeof(array) op x". 3903 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3904 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3905 BO->getLHS()); 3906 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3907 BO->getRHS()); 3908 } 3909 } 3910 3911 return false; 3912 } 3913 3914 /// Check the constraints on operands to unary expression and type 3915 /// traits. 3916 /// 3917 /// This will complete any types necessary, and validate the various constraints 3918 /// on those operands. 3919 /// 3920 /// The UsualUnaryConversions() function is *not* called by this routine. 3921 /// C99 6.3.2.1p[2-4] all state: 3922 /// Except when it is the operand of the sizeof operator ... 3923 /// 3924 /// C++ [expr.sizeof]p4 3925 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3926 /// standard conversions are not applied to the operand of sizeof. 3927 /// 3928 /// This policy is followed for all of the unary trait expressions. 3929 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3930 SourceLocation OpLoc, 3931 SourceRange ExprRange, 3932 UnaryExprOrTypeTrait ExprKind) { 3933 if (ExprType->isDependentType()) 3934 return false; 3935 3936 // C++ [expr.sizeof]p2: 3937 // When applied to a reference or a reference type, the result 3938 // is the size of the referenced type. 3939 // C++11 [expr.alignof]p3: 3940 // When alignof is applied to a reference type, the result 3941 // shall be the alignment of the referenced type. 3942 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3943 ExprType = Ref->getPointeeType(); 3944 3945 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3946 // When alignof or _Alignof is applied to an array type, the result 3947 // is the alignment of the element type. 3948 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 3949 ExprKind == UETT_OpenMPRequiredSimdAlign) 3950 ExprType = Context.getBaseElementType(ExprType); 3951 3952 if (ExprKind == UETT_VecStep) 3953 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3954 3955 // Whitelist some types as extensions 3956 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3957 ExprKind)) 3958 return false; 3959 3960 if (RequireCompleteType(OpLoc, ExprType, 3961 diag::err_sizeof_alignof_incomplete_type, 3962 ExprKind, ExprRange)) 3963 return true; 3964 3965 if (ExprType->isFunctionType()) { 3966 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3967 << ExprKind << ExprRange; 3968 return true; 3969 } 3970 3971 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3972 ExprKind)) 3973 return true; 3974 3975 return false; 3976 } 3977 3978 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 3979 // Cannot know anything else if the expression is dependent. 3980 if (E->isTypeDependent()) 3981 return false; 3982 3983 if (E->getObjectKind() == OK_BitField) { 3984 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3985 << 1 << E->getSourceRange(); 3986 return true; 3987 } 3988 3989 ValueDecl *D = nullptr; 3990 Expr *Inner = E->IgnoreParens(); 3991 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 3992 D = DRE->getDecl(); 3993 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 3994 D = ME->getMemberDecl(); 3995 } 3996 3997 // If it's a field, require the containing struct to have a 3998 // complete definition so that we can compute the layout. 3999 // 4000 // This can happen in C++11 onwards, either by naming the member 4001 // in a way that is not transformed into a member access expression 4002 // (in an unevaluated operand, for instance), or by naming the member 4003 // in a trailing-return-type. 4004 // 4005 // For the record, since __alignof__ on expressions is a GCC 4006 // extension, GCC seems to permit this but always gives the 4007 // nonsensical answer 0. 4008 // 4009 // We don't really need the layout here --- we could instead just 4010 // directly check for all the appropriate alignment-lowing 4011 // attributes --- but that would require duplicating a lot of 4012 // logic that just isn't worth duplicating for such a marginal 4013 // use-case. 4014 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4015 // Fast path this check, since we at least know the record has a 4016 // definition if we can find a member of it. 4017 if (!FD->getParent()->isCompleteDefinition()) { 4018 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4019 << E->getSourceRange(); 4020 return true; 4021 } 4022 4023 // Otherwise, if it's a field, and the field doesn't have 4024 // reference type, then it must have a complete type (or be a 4025 // flexible array member, which we explicitly want to 4026 // white-list anyway), which makes the following checks trivial. 4027 if (!FD->getType()->isReferenceType()) 4028 return false; 4029 } 4030 4031 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4032 } 4033 4034 bool Sema::CheckVecStepExpr(Expr *E) { 4035 E = E->IgnoreParens(); 4036 4037 // Cannot know anything else if the expression is dependent. 4038 if (E->isTypeDependent()) 4039 return false; 4040 4041 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4042 } 4043 4044 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4045 CapturingScopeInfo *CSI) { 4046 assert(T->isVariablyModifiedType()); 4047 assert(CSI != nullptr); 4048 4049 // We're going to walk down into the type and look for VLA expressions. 4050 do { 4051 const Type *Ty = T.getTypePtr(); 4052 switch (Ty->getTypeClass()) { 4053 #define TYPE(Class, Base) 4054 #define ABSTRACT_TYPE(Class, Base) 4055 #define NON_CANONICAL_TYPE(Class, Base) 4056 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4057 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4058 #include "clang/AST/TypeNodes.inc" 4059 T = QualType(); 4060 break; 4061 // These types are never variably-modified. 4062 case Type::Builtin: 4063 case Type::Complex: 4064 case Type::Vector: 4065 case Type::ExtVector: 4066 case Type::Record: 4067 case Type::Enum: 4068 case Type::Elaborated: 4069 case Type::TemplateSpecialization: 4070 case Type::ObjCObject: 4071 case Type::ObjCInterface: 4072 case Type::ObjCObjectPointer: 4073 case Type::ObjCTypeParam: 4074 case Type::Pipe: 4075 llvm_unreachable("type class is never variably-modified!"); 4076 case Type::Adjusted: 4077 T = cast<AdjustedType>(Ty)->getOriginalType(); 4078 break; 4079 case Type::Decayed: 4080 T = cast<DecayedType>(Ty)->getPointeeType(); 4081 break; 4082 case Type::Pointer: 4083 T = cast<PointerType>(Ty)->getPointeeType(); 4084 break; 4085 case Type::BlockPointer: 4086 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4087 break; 4088 case Type::LValueReference: 4089 case Type::RValueReference: 4090 T = cast<ReferenceType>(Ty)->getPointeeType(); 4091 break; 4092 case Type::MemberPointer: 4093 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4094 break; 4095 case Type::ConstantArray: 4096 case Type::IncompleteArray: 4097 // Losing element qualification here is fine. 4098 T = cast<ArrayType>(Ty)->getElementType(); 4099 break; 4100 case Type::VariableArray: { 4101 // Losing element qualification here is fine. 4102 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4103 4104 // Unknown size indication requires no size computation. 4105 // Otherwise, evaluate and record it. 4106 auto Size = VAT->getSizeExpr(); 4107 if (Size && !CSI->isVLATypeCaptured(VAT) && 4108 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4109 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4110 4111 T = VAT->getElementType(); 4112 break; 4113 } 4114 case Type::FunctionProto: 4115 case Type::FunctionNoProto: 4116 T = cast<FunctionType>(Ty)->getReturnType(); 4117 break; 4118 case Type::Paren: 4119 case Type::TypeOf: 4120 case Type::UnaryTransform: 4121 case Type::Attributed: 4122 case Type::SubstTemplateTypeParm: 4123 case Type::PackExpansion: 4124 case Type::MacroQualified: 4125 // Keep walking after single level desugaring. 4126 T = T.getSingleStepDesugaredType(Context); 4127 break; 4128 case Type::Typedef: 4129 T = cast<TypedefType>(Ty)->desugar(); 4130 break; 4131 case Type::Decltype: 4132 T = cast<DecltypeType>(Ty)->desugar(); 4133 break; 4134 case Type::Auto: 4135 case Type::DeducedTemplateSpecialization: 4136 T = cast<DeducedType>(Ty)->getDeducedType(); 4137 break; 4138 case Type::TypeOfExpr: 4139 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4140 break; 4141 case Type::Atomic: 4142 T = cast<AtomicType>(Ty)->getValueType(); 4143 break; 4144 } 4145 } while (!T.isNull() && T->isVariablyModifiedType()); 4146 } 4147 4148 /// Build a sizeof or alignof expression given a type operand. 4149 ExprResult 4150 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4151 SourceLocation OpLoc, 4152 UnaryExprOrTypeTrait ExprKind, 4153 SourceRange R) { 4154 if (!TInfo) 4155 return ExprError(); 4156 4157 QualType T = TInfo->getType(); 4158 4159 if (!T->isDependentType() && 4160 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4161 return ExprError(); 4162 4163 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4164 if (auto *TT = T->getAs<TypedefType>()) { 4165 for (auto I = FunctionScopes.rbegin(), 4166 E = std::prev(FunctionScopes.rend()); 4167 I != E; ++I) { 4168 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4169 if (CSI == nullptr) 4170 break; 4171 DeclContext *DC = nullptr; 4172 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4173 DC = LSI->CallOperator; 4174 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4175 DC = CRSI->TheCapturedDecl; 4176 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4177 DC = BSI->TheDecl; 4178 if (DC) { 4179 if (DC->containsDecl(TT->getDecl())) 4180 break; 4181 captureVariablyModifiedType(Context, T, CSI); 4182 } 4183 } 4184 } 4185 } 4186 4187 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4188 return new (Context) UnaryExprOrTypeTraitExpr( 4189 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4190 } 4191 4192 /// Build a sizeof or alignof expression given an expression 4193 /// operand. 4194 ExprResult 4195 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4196 UnaryExprOrTypeTrait ExprKind) { 4197 ExprResult PE = CheckPlaceholderExpr(E); 4198 if (PE.isInvalid()) 4199 return ExprError(); 4200 4201 E = PE.get(); 4202 4203 // Verify that the operand is valid. 4204 bool isInvalid = false; 4205 if (E->isTypeDependent()) { 4206 // Delay type-checking for type-dependent expressions. 4207 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4208 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4209 } else if (ExprKind == UETT_VecStep) { 4210 isInvalid = CheckVecStepExpr(E); 4211 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4212 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4213 isInvalid = true; 4214 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4215 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4216 isInvalid = true; 4217 } else { 4218 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4219 } 4220 4221 if (isInvalid) 4222 return ExprError(); 4223 4224 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4225 PE = TransformToPotentiallyEvaluated(E); 4226 if (PE.isInvalid()) return ExprError(); 4227 E = PE.get(); 4228 } 4229 4230 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4231 return new (Context) UnaryExprOrTypeTraitExpr( 4232 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4233 } 4234 4235 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4236 /// expr and the same for @c alignof and @c __alignof 4237 /// Note that the ArgRange is invalid if isType is false. 4238 ExprResult 4239 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4240 UnaryExprOrTypeTrait ExprKind, bool IsType, 4241 void *TyOrEx, SourceRange ArgRange) { 4242 // If error parsing type, ignore. 4243 if (!TyOrEx) return ExprError(); 4244 4245 if (IsType) { 4246 TypeSourceInfo *TInfo; 4247 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4248 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4249 } 4250 4251 Expr *ArgEx = (Expr *)TyOrEx; 4252 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4253 return Result; 4254 } 4255 4256 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4257 bool IsReal) { 4258 if (V.get()->isTypeDependent()) 4259 return S.Context.DependentTy; 4260 4261 // _Real and _Imag are only l-values for normal l-values. 4262 if (V.get()->getObjectKind() != OK_Ordinary) { 4263 V = S.DefaultLvalueConversion(V.get()); 4264 if (V.isInvalid()) 4265 return QualType(); 4266 } 4267 4268 // These operators return the element type of a complex type. 4269 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4270 return CT->getElementType(); 4271 4272 // Otherwise they pass through real integer and floating point types here. 4273 if (V.get()->getType()->isArithmeticType()) 4274 return V.get()->getType(); 4275 4276 // Test for placeholders. 4277 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4278 if (PR.isInvalid()) return QualType(); 4279 if (PR.get() != V.get()) { 4280 V = PR; 4281 return CheckRealImagOperand(S, V, Loc, IsReal); 4282 } 4283 4284 // Reject anything else. 4285 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4286 << (IsReal ? "__real" : "__imag"); 4287 return QualType(); 4288 } 4289 4290 4291 4292 ExprResult 4293 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4294 tok::TokenKind Kind, Expr *Input) { 4295 UnaryOperatorKind Opc; 4296 switch (Kind) { 4297 default: llvm_unreachable("Unknown unary op!"); 4298 case tok::plusplus: Opc = UO_PostInc; break; 4299 case tok::minusminus: Opc = UO_PostDec; break; 4300 } 4301 4302 // Since this might is a postfix expression, get rid of ParenListExprs. 4303 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4304 if (Result.isInvalid()) return ExprError(); 4305 Input = Result.get(); 4306 4307 return BuildUnaryOp(S, OpLoc, Opc, Input); 4308 } 4309 4310 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4311 /// 4312 /// \return true on error 4313 static bool checkArithmeticOnObjCPointer(Sema &S, 4314 SourceLocation opLoc, 4315 Expr *op) { 4316 assert(op->getType()->isObjCObjectPointerType()); 4317 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4318 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4319 return false; 4320 4321 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4322 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4323 << op->getSourceRange(); 4324 return true; 4325 } 4326 4327 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4328 auto *BaseNoParens = Base->IgnoreParens(); 4329 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4330 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4331 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4332 } 4333 4334 ExprResult 4335 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4336 Expr *idx, SourceLocation rbLoc) { 4337 if (base && !base->getType().isNull() && 4338 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4339 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4340 /*Length=*/nullptr, rbLoc); 4341 4342 // Since this might be a postfix expression, get rid of ParenListExprs. 4343 if (isa<ParenListExpr>(base)) { 4344 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4345 if (result.isInvalid()) return ExprError(); 4346 base = result.get(); 4347 } 4348 4349 // A comma-expression as the index is deprecated in C++2a onwards. 4350 if (getLangOpts().CPlusPlus2a && 4351 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4352 (isa<CXXOperatorCallExpr>(idx) && 4353 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { 4354 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4355 << SourceRange(base->getBeginLoc(), rbLoc); 4356 } 4357 4358 // Handle any non-overload placeholder types in the base and index 4359 // expressions. We can't handle overloads here because the other 4360 // operand might be an overloadable type, in which case the overload 4361 // resolution for the operator overload should get the first crack 4362 // at the overload. 4363 bool IsMSPropertySubscript = false; 4364 if (base->getType()->isNonOverloadPlaceholderType()) { 4365 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4366 if (!IsMSPropertySubscript) { 4367 ExprResult result = CheckPlaceholderExpr(base); 4368 if (result.isInvalid()) 4369 return ExprError(); 4370 base = result.get(); 4371 } 4372 } 4373 if (idx->getType()->isNonOverloadPlaceholderType()) { 4374 ExprResult result = CheckPlaceholderExpr(idx); 4375 if (result.isInvalid()) return ExprError(); 4376 idx = result.get(); 4377 } 4378 4379 // Build an unanalyzed expression if either operand is type-dependent. 4380 if (getLangOpts().CPlusPlus && 4381 (base->isTypeDependent() || idx->isTypeDependent())) { 4382 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4383 VK_LValue, OK_Ordinary, rbLoc); 4384 } 4385 4386 // MSDN, property (C++) 4387 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4388 // This attribute can also be used in the declaration of an empty array in a 4389 // class or structure definition. For example: 4390 // __declspec(property(get=GetX, put=PutX)) int x[]; 4391 // The above statement indicates that x[] can be used with one or more array 4392 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4393 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4394 if (IsMSPropertySubscript) { 4395 // Build MS property subscript expression if base is MS property reference 4396 // or MS property subscript. 4397 return new (Context) MSPropertySubscriptExpr( 4398 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4399 } 4400 4401 // Use C++ overloaded-operator rules if either operand has record 4402 // type. The spec says to do this if either type is *overloadable*, 4403 // but enum types can't declare subscript operators or conversion 4404 // operators, so there's nothing interesting for overload resolution 4405 // to do if there aren't any record types involved. 4406 // 4407 // ObjC pointers have their own subscripting logic that is not tied 4408 // to overload resolution and so should not take this path. 4409 if (getLangOpts().CPlusPlus && 4410 (base->getType()->isRecordType() || 4411 (!base->getType()->isObjCObjectPointerType() && 4412 idx->getType()->isRecordType()))) { 4413 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4414 } 4415 4416 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4417 4418 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4419 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4420 4421 return Res; 4422 } 4423 4424 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4425 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4426 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4427 4428 // For expressions like `&(*s).b`, the base is recorded and what should be 4429 // checked. 4430 const MemberExpr *Member = nullptr; 4431 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4432 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4433 4434 LastRecord.PossibleDerefs.erase(StrippedExpr); 4435 } 4436 4437 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4438 QualType ResultTy = E->getType(); 4439 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4440 4441 // Bail if the element is an array since it is not memory access. 4442 if (isa<ArrayType>(ResultTy)) 4443 return; 4444 4445 if (ResultTy->hasAttr(attr::NoDeref)) { 4446 LastRecord.PossibleDerefs.insert(E); 4447 return; 4448 } 4449 4450 // Check if the base type is a pointer to a member access of a struct 4451 // marked with noderef. 4452 const Expr *Base = E->getBase(); 4453 QualType BaseTy = Base->getType(); 4454 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4455 // Not a pointer access 4456 return; 4457 4458 const MemberExpr *Member = nullptr; 4459 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4460 Member->isArrow()) 4461 Base = Member->getBase(); 4462 4463 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4464 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4465 LastRecord.PossibleDerefs.insert(E); 4466 } 4467 } 4468 4469 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4470 Expr *LowerBound, 4471 SourceLocation ColonLoc, Expr *Length, 4472 SourceLocation RBLoc) { 4473 if (Base->getType()->isPlaceholderType() && 4474 !Base->getType()->isSpecificPlaceholderType( 4475 BuiltinType::OMPArraySection)) { 4476 ExprResult Result = CheckPlaceholderExpr(Base); 4477 if (Result.isInvalid()) 4478 return ExprError(); 4479 Base = Result.get(); 4480 } 4481 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4482 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4483 if (Result.isInvalid()) 4484 return ExprError(); 4485 Result = DefaultLvalueConversion(Result.get()); 4486 if (Result.isInvalid()) 4487 return ExprError(); 4488 LowerBound = Result.get(); 4489 } 4490 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4491 ExprResult Result = CheckPlaceholderExpr(Length); 4492 if (Result.isInvalid()) 4493 return ExprError(); 4494 Result = DefaultLvalueConversion(Result.get()); 4495 if (Result.isInvalid()) 4496 return ExprError(); 4497 Length = Result.get(); 4498 } 4499 4500 // Build an unanalyzed expression if either operand is type-dependent. 4501 if (Base->isTypeDependent() || 4502 (LowerBound && 4503 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4504 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4505 return new (Context) 4506 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4507 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4508 } 4509 4510 // Perform default conversions. 4511 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4512 QualType ResultTy; 4513 if (OriginalTy->isAnyPointerType()) { 4514 ResultTy = OriginalTy->getPointeeType(); 4515 } else if (OriginalTy->isArrayType()) { 4516 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4517 } else { 4518 return ExprError( 4519 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4520 << Base->getSourceRange()); 4521 } 4522 // C99 6.5.2.1p1 4523 if (LowerBound) { 4524 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4525 LowerBound); 4526 if (Res.isInvalid()) 4527 return ExprError(Diag(LowerBound->getExprLoc(), 4528 diag::err_omp_typecheck_section_not_integer) 4529 << 0 << LowerBound->getSourceRange()); 4530 LowerBound = Res.get(); 4531 4532 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4533 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4534 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4535 << 0 << LowerBound->getSourceRange(); 4536 } 4537 if (Length) { 4538 auto Res = 4539 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4540 if (Res.isInvalid()) 4541 return ExprError(Diag(Length->getExprLoc(), 4542 diag::err_omp_typecheck_section_not_integer) 4543 << 1 << Length->getSourceRange()); 4544 Length = Res.get(); 4545 4546 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4547 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4548 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4549 << 1 << Length->getSourceRange(); 4550 } 4551 4552 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4553 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4554 // type. Note that functions are not objects, and that (in C99 parlance) 4555 // incomplete types are not object types. 4556 if (ResultTy->isFunctionType()) { 4557 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4558 << ResultTy << Base->getSourceRange(); 4559 return ExprError(); 4560 } 4561 4562 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4563 diag::err_omp_section_incomplete_type, Base)) 4564 return ExprError(); 4565 4566 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4567 Expr::EvalResult Result; 4568 if (LowerBound->EvaluateAsInt(Result, Context)) { 4569 // OpenMP 4.5, [2.4 Array Sections] 4570 // The array section must be a subset of the original array. 4571 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 4572 if (LowerBoundValue.isNegative()) { 4573 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4574 << LowerBound->getSourceRange(); 4575 return ExprError(); 4576 } 4577 } 4578 } 4579 4580 if (Length) { 4581 Expr::EvalResult Result; 4582 if (Length->EvaluateAsInt(Result, Context)) { 4583 // OpenMP 4.5, [2.4 Array Sections] 4584 // The length must evaluate to non-negative integers. 4585 llvm::APSInt LengthValue = Result.Val.getInt(); 4586 if (LengthValue.isNegative()) { 4587 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4588 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4589 << Length->getSourceRange(); 4590 return ExprError(); 4591 } 4592 } 4593 } else if (ColonLoc.isValid() && 4594 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4595 !OriginalTy->isVariableArrayType()))) { 4596 // OpenMP 4.5, [2.4 Array Sections] 4597 // When the size of the array dimension is not known, the length must be 4598 // specified explicitly. 4599 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4600 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4601 return ExprError(); 4602 } 4603 4604 if (!Base->getType()->isSpecificPlaceholderType( 4605 BuiltinType::OMPArraySection)) { 4606 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4607 if (Result.isInvalid()) 4608 return ExprError(); 4609 Base = Result.get(); 4610 } 4611 return new (Context) 4612 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4613 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4614 } 4615 4616 ExprResult 4617 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4618 Expr *Idx, SourceLocation RLoc) { 4619 Expr *LHSExp = Base; 4620 Expr *RHSExp = Idx; 4621 4622 ExprValueKind VK = VK_LValue; 4623 ExprObjectKind OK = OK_Ordinary; 4624 4625 // Per C++ core issue 1213, the result is an xvalue if either operand is 4626 // a non-lvalue array, and an lvalue otherwise. 4627 if (getLangOpts().CPlusPlus11) { 4628 for (auto *Op : {LHSExp, RHSExp}) { 4629 Op = Op->IgnoreImplicit(); 4630 if (Op->getType()->isArrayType() && !Op->isLValue()) 4631 VK = VK_XValue; 4632 } 4633 } 4634 4635 // Perform default conversions. 4636 if (!LHSExp->getType()->getAs<VectorType>()) { 4637 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4638 if (Result.isInvalid()) 4639 return ExprError(); 4640 LHSExp = Result.get(); 4641 } 4642 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4643 if (Result.isInvalid()) 4644 return ExprError(); 4645 RHSExp = Result.get(); 4646 4647 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4648 4649 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4650 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4651 // in the subscript position. As a result, we need to derive the array base 4652 // and index from the expression types. 4653 Expr *BaseExpr, *IndexExpr; 4654 QualType ResultType; 4655 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4656 BaseExpr = LHSExp; 4657 IndexExpr = RHSExp; 4658 ResultType = Context.DependentTy; 4659 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4660 BaseExpr = LHSExp; 4661 IndexExpr = RHSExp; 4662 ResultType = PTy->getPointeeType(); 4663 } else if (const ObjCObjectPointerType *PTy = 4664 LHSTy->getAs<ObjCObjectPointerType>()) { 4665 BaseExpr = LHSExp; 4666 IndexExpr = RHSExp; 4667 4668 // Use custom logic if this should be the pseudo-object subscript 4669 // expression. 4670 if (!LangOpts.isSubscriptPointerArithmetic()) 4671 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4672 nullptr); 4673 4674 ResultType = PTy->getPointeeType(); 4675 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4676 // Handle the uncommon case of "123[Ptr]". 4677 BaseExpr = RHSExp; 4678 IndexExpr = LHSExp; 4679 ResultType = PTy->getPointeeType(); 4680 } else if (const ObjCObjectPointerType *PTy = 4681 RHSTy->getAs<ObjCObjectPointerType>()) { 4682 // Handle the uncommon case of "123[Ptr]". 4683 BaseExpr = RHSExp; 4684 IndexExpr = LHSExp; 4685 ResultType = PTy->getPointeeType(); 4686 if (!LangOpts.isSubscriptPointerArithmetic()) { 4687 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4688 << ResultType << BaseExpr->getSourceRange(); 4689 return ExprError(); 4690 } 4691 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4692 BaseExpr = LHSExp; // vectors: V[123] 4693 IndexExpr = RHSExp; 4694 // We apply C++ DR1213 to vector subscripting too. 4695 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { 4696 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 4697 if (Materialized.isInvalid()) 4698 return ExprError(); 4699 LHSExp = Materialized.get(); 4700 } 4701 VK = LHSExp->getValueKind(); 4702 if (VK != VK_RValue) 4703 OK = OK_VectorComponent; 4704 4705 ResultType = VTy->getElementType(); 4706 QualType BaseType = BaseExpr->getType(); 4707 Qualifiers BaseQuals = BaseType.getQualifiers(); 4708 Qualifiers MemberQuals = ResultType.getQualifiers(); 4709 Qualifiers Combined = BaseQuals + MemberQuals; 4710 if (Combined != MemberQuals) 4711 ResultType = Context.getQualifiedType(ResultType, Combined); 4712 } else if (LHSTy->isArrayType()) { 4713 // If we see an array that wasn't promoted by 4714 // DefaultFunctionArrayLvalueConversion, it must be an array that 4715 // wasn't promoted because of the C90 rule that doesn't 4716 // allow promoting non-lvalue arrays. Warn, then 4717 // force the promotion here. 4718 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 4719 << LHSExp->getSourceRange(); 4720 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4721 CK_ArrayToPointerDecay).get(); 4722 LHSTy = LHSExp->getType(); 4723 4724 BaseExpr = LHSExp; 4725 IndexExpr = RHSExp; 4726 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4727 } else if (RHSTy->isArrayType()) { 4728 // Same as previous, except for 123[f().a] case 4729 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 4730 << RHSExp->getSourceRange(); 4731 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4732 CK_ArrayToPointerDecay).get(); 4733 RHSTy = RHSExp->getType(); 4734 4735 BaseExpr = RHSExp; 4736 IndexExpr = LHSExp; 4737 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4738 } else { 4739 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4740 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4741 } 4742 // C99 6.5.2.1p1 4743 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4744 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4745 << IndexExpr->getSourceRange()); 4746 4747 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4748 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4749 && !IndexExpr->isTypeDependent()) 4750 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4751 4752 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4753 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4754 // type. Note that Functions are not objects, and that (in C99 parlance) 4755 // incomplete types are not object types. 4756 if (ResultType->isFunctionType()) { 4757 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 4758 << ResultType << BaseExpr->getSourceRange(); 4759 return ExprError(); 4760 } 4761 4762 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4763 // GNU extension: subscripting on pointer to void 4764 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4765 << BaseExpr->getSourceRange(); 4766 4767 // C forbids expressions of unqualified void type from being l-values. 4768 // See IsCForbiddenLValueType. 4769 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4770 } else if (!ResultType->isDependentType() && 4771 RequireCompleteType(LLoc, ResultType, 4772 diag::err_subscript_incomplete_type, BaseExpr)) 4773 return ExprError(); 4774 4775 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4776 !ResultType.isCForbiddenLValueType()); 4777 4778 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 4779 FunctionScopes.size() > 1) { 4780 if (auto *TT = 4781 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 4782 for (auto I = FunctionScopes.rbegin(), 4783 E = std::prev(FunctionScopes.rend()); 4784 I != E; ++I) { 4785 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4786 if (CSI == nullptr) 4787 break; 4788 DeclContext *DC = nullptr; 4789 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4790 DC = LSI->CallOperator; 4791 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4792 DC = CRSI->TheCapturedDecl; 4793 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4794 DC = BSI->TheDecl; 4795 if (DC) { 4796 if (DC->containsDecl(TT->getDecl())) 4797 break; 4798 captureVariablyModifiedType( 4799 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 4800 } 4801 } 4802 } 4803 } 4804 4805 return new (Context) 4806 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4807 } 4808 4809 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 4810 ParmVarDecl *Param) { 4811 if (Param->hasUnparsedDefaultArg()) { 4812 Diag(CallLoc, 4813 diag::err_use_of_default_argument_to_function_declared_later) << 4814 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4815 Diag(UnparsedDefaultArgLocs[Param], 4816 diag::note_default_argument_declared_here); 4817 return true; 4818 } 4819 4820 if (Param->hasUninstantiatedDefaultArg()) { 4821 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4822 4823 EnterExpressionEvaluationContext EvalContext( 4824 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 4825 4826 // Instantiate the expression. 4827 // 4828 // FIXME: Pass in a correct Pattern argument, otherwise 4829 // getTemplateInstantiationArgs uses the lexical context of FD, e.g. 4830 // 4831 // template<typename T> 4832 // struct A { 4833 // static int FooImpl(); 4834 // 4835 // template<typename Tp> 4836 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level 4837 // // template argument list [[T], [Tp]], should be [[Tp]]. 4838 // friend A<Tp> Foo(int a); 4839 // }; 4840 // 4841 // template<typename T> 4842 // A<T> Foo(int a = A<T>::FooImpl()); 4843 MultiLevelTemplateArgumentList MutiLevelArgList 4844 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4845 4846 InstantiatingTemplate Inst(*this, CallLoc, Param, 4847 MutiLevelArgList.getInnermost()); 4848 if (Inst.isInvalid()) 4849 return true; 4850 if (Inst.isAlreadyInstantiating()) { 4851 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 4852 Param->setInvalidDecl(); 4853 return true; 4854 } 4855 4856 ExprResult Result; 4857 { 4858 // C++ [dcl.fct.default]p5: 4859 // The names in the [default argument] expression are bound, and 4860 // the semantic constraints are checked, at the point where the 4861 // default argument expression appears. 4862 ContextRAII SavedContext(*this, FD); 4863 LocalInstantiationScope Local(*this); 4864 runWithSufficientStackSpace(CallLoc, [&] { 4865 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 4866 /*DirectInit*/false); 4867 }); 4868 } 4869 if (Result.isInvalid()) 4870 return true; 4871 4872 // Check the expression as an initializer for the parameter. 4873 InitializedEntity Entity 4874 = InitializedEntity::InitializeParameter(Context, Param); 4875 InitializationKind Kind = InitializationKind::CreateCopy( 4876 Param->getLocation(), 4877 /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc()); 4878 Expr *ResultE = Result.getAs<Expr>(); 4879 4880 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4881 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4882 if (Result.isInvalid()) 4883 return true; 4884 4885 Result = 4886 ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(), 4887 /*DiscardedValue*/ false); 4888 if (Result.isInvalid()) 4889 return true; 4890 4891 // Remember the instantiated default argument. 4892 Param->setDefaultArg(Result.getAs<Expr>()); 4893 if (ASTMutationListener *L = getASTMutationListener()) { 4894 L->DefaultArgumentInstantiated(Param); 4895 } 4896 } 4897 4898 // If the default argument expression is not set yet, we are building it now. 4899 if (!Param->hasInit()) { 4900 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 4901 Param->setInvalidDecl(); 4902 return true; 4903 } 4904 4905 // If the default expression creates temporaries, we need to 4906 // push them to the current stack of expression temporaries so they'll 4907 // be properly destroyed. 4908 // FIXME: We should really be rebuilding the default argument with new 4909 // bound temporaries; see the comment in PR5810. 4910 // We don't need to do that with block decls, though, because 4911 // blocks in default argument expression can never capture anything. 4912 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 4913 // Set the "needs cleanups" bit regardless of whether there are 4914 // any explicit objects. 4915 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 4916 4917 // Append all the objects to the cleanup list. Right now, this 4918 // should always be a no-op, because blocks in default argument 4919 // expressions should never be able to capture anything. 4920 assert(!Init->getNumObjects() && 4921 "default argument expression has capturing blocks?"); 4922 } 4923 4924 // We already type-checked the argument, so we know it works. 4925 // Just mark all of the declarations in this potentially-evaluated expression 4926 // as being "referenced". 4927 EnterExpressionEvaluationContext EvalContext( 4928 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 4929 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4930 /*SkipLocalVariables=*/true); 4931 return false; 4932 } 4933 4934 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4935 FunctionDecl *FD, ParmVarDecl *Param) { 4936 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 4937 return ExprError(); 4938 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 4939 } 4940 4941 Sema::VariadicCallType 4942 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4943 Expr *Fn) { 4944 if (Proto && Proto->isVariadic()) { 4945 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4946 return VariadicConstructor; 4947 else if (Fn && Fn->getType()->isBlockPointerType()) 4948 return VariadicBlock; 4949 else if (FDecl) { 4950 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4951 if (Method->isInstance()) 4952 return VariadicMethod; 4953 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4954 return VariadicMethod; 4955 return VariadicFunction; 4956 } 4957 return VariadicDoesNotApply; 4958 } 4959 4960 namespace { 4961 class FunctionCallCCC final : public FunctionCallFilterCCC { 4962 public: 4963 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4964 unsigned NumArgs, MemberExpr *ME) 4965 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4966 FunctionName(FuncName) {} 4967 4968 bool ValidateCandidate(const TypoCorrection &candidate) override { 4969 if (!candidate.getCorrectionSpecifier() || 4970 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4971 return false; 4972 } 4973 4974 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4975 } 4976 4977 std::unique_ptr<CorrectionCandidateCallback> clone() override { 4978 return std::make_unique<FunctionCallCCC>(*this); 4979 } 4980 4981 private: 4982 const IdentifierInfo *const FunctionName; 4983 }; 4984 } 4985 4986 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4987 FunctionDecl *FDecl, 4988 ArrayRef<Expr *> Args) { 4989 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4990 DeclarationName FuncName = FDecl->getDeclName(); 4991 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 4992 4993 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 4994 if (TypoCorrection Corrected = S.CorrectTypo( 4995 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4996 S.getScopeForContext(S.CurContext), nullptr, CCC, 4997 Sema::CTK_ErrorRecovery)) { 4998 if (NamedDecl *ND = Corrected.getFoundDecl()) { 4999 if (Corrected.isOverloaded()) { 5000 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 5001 OverloadCandidateSet::iterator Best; 5002 for (NamedDecl *CD : Corrected) { 5003 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 5004 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 5005 OCS); 5006 } 5007 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 5008 case OR_Success: 5009 ND = Best->FoundDecl; 5010 Corrected.setCorrectionDecl(ND); 5011 break; 5012 default: 5013 break; 5014 } 5015 } 5016 ND = ND->getUnderlyingDecl(); 5017 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 5018 return Corrected; 5019 } 5020 } 5021 return TypoCorrection(); 5022 } 5023 5024 /// ConvertArgumentsForCall - Converts the arguments specified in 5025 /// Args/NumArgs to the parameter types of the function FDecl with 5026 /// function prototype Proto. Call is the call expression itself, and 5027 /// Fn is the function expression. For a C++ member function, this 5028 /// routine does not attempt to convert the object argument. Returns 5029 /// true if the call is ill-formed. 5030 bool 5031 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5032 FunctionDecl *FDecl, 5033 const FunctionProtoType *Proto, 5034 ArrayRef<Expr *> Args, 5035 SourceLocation RParenLoc, 5036 bool IsExecConfig) { 5037 // Bail out early if calling a builtin with custom typechecking. 5038 if (FDecl) 5039 if (unsigned ID = FDecl->getBuiltinID()) 5040 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 5041 return false; 5042 5043 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 5044 // assignment, to the types of the corresponding parameter, ... 5045 unsigned NumParams = Proto->getNumParams(); 5046 bool Invalid = false; 5047 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 5048 unsigned FnKind = Fn->getType()->isBlockPointerType() 5049 ? 1 /* block */ 5050 : (IsExecConfig ? 3 /* kernel function (exec config) */ 5051 : 0 /* function */); 5052 5053 // If too few arguments are available (and we don't have default 5054 // arguments for the remaining parameters), don't make the call. 5055 if (Args.size() < NumParams) { 5056 if (Args.size() < MinArgs) { 5057 TypoCorrection TC; 5058 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5059 unsigned diag_id = 5060 MinArgs == NumParams && !Proto->isVariadic() 5061 ? diag::err_typecheck_call_too_few_args_suggest 5062 : diag::err_typecheck_call_too_few_args_at_least_suggest; 5063 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 5064 << static_cast<unsigned>(Args.size()) 5065 << TC.getCorrectionRange()); 5066 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 5067 Diag(RParenLoc, 5068 MinArgs == NumParams && !Proto->isVariadic() 5069 ? diag::err_typecheck_call_too_few_args_one 5070 : diag::err_typecheck_call_too_few_args_at_least_one) 5071 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 5072 else 5073 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 5074 ? diag::err_typecheck_call_too_few_args 5075 : diag::err_typecheck_call_too_few_args_at_least) 5076 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 5077 << Fn->getSourceRange(); 5078 5079 // Emit the location of the prototype. 5080 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5081 Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl; 5082 5083 return true; 5084 } 5085 // We reserve space for the default arguments when we create 5086 // the call expression, before calling ConvertArgumentsForCall. 5087 assert((Call->getNumArgs() == NumParams) && 5088 "We should have reserved space for the default arguments before!"); 5089 } 5090 5091 // If too many are passed and not variadic, error on the extras and drop 5092 // them. 5093 if (Args.size() > NumParams) { 5094 if (!Proto->isVariadic()) { 5095 TypoCorrection TC; 5096 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5097 unsigned diag_id = 5098 MinArgs == NumParams && !Proto->isVariadic() 5099 ? diag::err_typecheck_call_too_many_args_suggest 5100 : diag::err_typecheck_call_too_many_args_at_most_suggest; 5101 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 5102 << static_cast<unsigned>(Args.size()) 5103 << TC.getCorrectionRange()); 5104 } else if (NumParams == 1 && FDecl && 5105 FDecl->getParamDecl(0)->getDeclName()) 5106 Diag(Args[NumParams]->getBeginLoc(), 5107 MinArgs == NumParams 5108 ? diag::err_typecheck_call_too_many_args_one 5109 : diag::err_typecheck_call_too_many_args_at_most_one) 5110 << FnKind << FDecl->getParamDecl(0) 5111 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 5112 << SourceRange(Args[NumParams]->getBeginLoc(), 5113 Args.back()->getEndLoc()); 5114 else 5115 Diag(Args[NumParams]->getBeginLoc(), 5116 MinArgs == NumParams 5117 ? diag::err_typecheck_call_too_many_args 5118 : diag::err_typecheck_call_too_many_args_at_most) 5119 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 5120 << Fn->getSourceRange() 5121 << SourceRange(Args[NumParams]->getBeginLoc(), 5122 Args.back()->getEndLoc()); 5123 5124 // Emit the location of the prototype. 5125 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5126 Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl; 5127 5128 // This deletes the extra arguments. 5129 Call->shrinkNumArgs(NumParams); 5130 return true; 5131 } 5132 } 5133 SmallVector<Expr *, 8> AllArgs; 5134 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 5135 5136 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 5137 AllArgs, CallType); 5138 if (Invalid) 5139 return true; 5140 unsigned TotalNumArgs = AllArgs.size(); 5141 for (unsigned i = 0; i < TotalNumArgs; ++i) 5142 Call->setArg(i, AllArgs[i]); 5143 5144 return false; 5145 } 5146 5147 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 5148 const FunctionProtoType *Proto, 5149 unsigned FirstParam, ArrayRef<Expr *> Args, 5150 SmallVectorImpl<Expr *> &AllArgs, 5151 VariadicCallType CallType, bool AllowExplicit, 5152 bool IsListInitialization) { 5153 unsigned NumParams = Proto->getNumParams(); 5154 bool Invalid = false; 5155 size_t ArgIx = 0; 5156 // Continue to check argument types (even if we have too few/many args). 5157 for (unsigned i = FirstParam; i < NumParams; i++) { 5158 QualType ProtoArgType = Proto->getParamType(i); 5159 5160 Expr *Arg; 5161 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 5162 if (ArgIx < Args.size()) { 5163 Arg = Args[ArgIx++]; 5164 5165 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5166 diag::err_call_incomplete_argument, Arg)) 5167 return true; 5168 5169 // Strip the unbridged-cast placeholder expression off, if applicable. 5170 bool CFAudited = false; 5171 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5172 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5173 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5174 Arg = stripARCUnbridgedCast(Arg); 5175 else if (getLangOpts().ObjCAutoRefCount && 5176 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5177 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5178 CFAudited = true; 5179 5180 if (Proto->getExtParameterInfo(i).isNoEscape()) 5181 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 5182 BE->getBlockDecl()->setDoesNotEscape(); 5183 5184 InitializedEntity Entity = 5185 Param ? InitializedEntity::InitializeParameter(Context, Param, 5186 ProtoArgType) 5187 : InitializedEntity::InitializeParameter( 5188 Context, ProtoArgType, Proto->isParamConsumed(i)); 5189 5190 // Remember that parameter belongs to a CF audited API. 5191 if (CFAudited) 5192 Entity.setParameterCFAudited(); 5193 5194 ExprResult ArgE = PerformCopyInitialization( 5195 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 5196 if (ArgE.isInvalid()) 5197 return true; 5198 5199 Arg = ArgE.getAs<Expr>(); 5200 } else { 5201 assert(Param && "can't use default arguments without a known callee"); 5202 5203 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 5204 if (ArgExpr.isInvalid()) 5205 return true; 5206 5207 Arg = ArgExpr.getAs<Expr>(); 5208 } 5209 5210 // Check for array bounds violations for each argument to the call. This 5211 // check only triggers warnings when the argument isn't a more complex Expr 5212 // with its own checking, such as a BinaryOperator. 5213 CheckArrayAccess(Arg); 5214 5215 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 5216 CheckStaticArrayArgument(CallLoc, Param, Arg); 5217 5218 AllArgs.push_back(Arg); 5219 } 5220 5221 // If this is a variadic call, handle args passed through "...". 5222 if (CallType != VariadicDoesNotApply) { 5223 // Assume that extern "C" functions with variadic arguments that 5224 // return __unknown_anytype aren't *really* variadic. 5225 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 5226 FDecl->isExternC()) { 5227 for (Expr *A : Args.slice(ArgIx)) { 5228 QualType paramType; // ignored 5229 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 5230 Invalid |= arg.isInvalid(); 5231 AllArgs.push_back(arg.get()); 5232 } 5233 5234 // Otherwise do argument promotion, (C99 6.5.2.2p7). 5235 } else { 5236 for (Expr *A : Args.slice(ArgIx)) { 5237 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 5238 Invalid |= Arg.isInvalid(); 5239 AllArgs.push_back(Arg.get()); 5240 } 5241 } 5242 5243 // Check for array bounds violations. 5244 for (Expr *A : Args.slice(ArgIx)) 5245 CheckArrayAccess(A); 5246 } 5247 return Invalid; 5248 } 5249 5250 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 5251 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 5252 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 5253 TL = DTL.getOriginalLoc(); 5254 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 5255 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 5256 << ATL.getLocalSourceRange(); 5257 } 5258 5259 /// CheckStaticArrayArgument - If the given argument corresponds to a static 5260 /// array parameter, check that it is non-null, and that if it is formed by 5261 /// array-to-pointer decay, the underlying array is sufficiently large. 5262 /// 5263 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 5264 /// array type derivation, then for each call to the function, the value of the 5265 /// corresponding actual argument shall provide access to the first element of 5266 /// an array with at least as many elements as specified by the size expression. 5267 void 5268 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 5269 ParmVarDecl *Param, 5270 const Expr *ArgExpr) { 5271 // Static array parameters are not supported in C++. 5272 if (!Param || getLangOpts().CPlusPlus) 5273 return; 5274 5275 QualType OrigTy = Param->getOriginalType(); 5276 5277 const ArrayType *AT = Context.getAsArrayType(OrigTy); 5278 if (!AT || AT->getSizeModifier() != ArrayType::Static) 5279 return; 5280 5281 if (ArgExpr->isNullPointerConstant(Context, 5282 Expr::NPC_NeverValueDependent)) { 5283 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 5284 DiagnoseCalleeStaticArrayParam(*this, Param); 5285 return; 5286 } 5287 5288 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 5289 if (!CAT) 5290 return; 5291 5292 const ConstantArrayType *ArgCAT = 5293 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 5294 if (!ArgCAT) 5295 return; 5296 5297 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 5298 ArgCAT->getElementType())) { 5299 if (ArgCAT->getSize().ult(CAT->getSize())) { 5300 Diag(CallLoc, diag::warn_static_array_too_small) 5301 << ArgExpr->getSourceRange() 5302 << (unsigned)ArgCAT->getSize().getZExtValue() 5303 << (unsigned)CAT->getSize().getZExtValue() << 0; 5304 DiagnoseCalleeStaticArrayParam(*this, Param); 5305 } 5306 return; 5307 } 5308 5309 Optional<CharUnits> ArgSize = 5310 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 5311 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 5312 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 5313 Diag(CallLoc, diag::warn_static_array_too_small) 5314 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 5315 << (unsigned)ParmSize->getQuantity() << 1; 5316 DiagnoseCalleeStaticArrayParam(*this, Param); 5317 } 5318 } 5319 5320 /// Given a function expression of unknown-any type, try to rebuild it 5321 /// to have a function type. 5322 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 5323 5324 /// Is the given type a placeholder that we need to lower out 5325 /// immediately during argument processing? 5326 static bool isPlaceholderToRemoveAsArg(QualType type) { 5327 // Placeholders are never sugared. 5328 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 5329 if (!placeholder) return false; 5330 5331 switch (placeholder->getKind()) { 5332 // Ignore all the non-placeholder types. 5333 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 5334 case BuiltinType::Id: 5335 #include "clang/Basic/OpenCLImageTypes.def" 5336 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 5337 case BuiltinType::Id: 5338 #include "clang/Basic/OpenCLExtensionTypes.def" 5339 // In practice we'll never use this, since all SVE types are sugared 5340 // via TypedefTypes rather than exposed directly as BuiltinTypes. 5341 #define SVE_TYPE(Name, Id, SingletonId) \ 5342 case BuiltinType::Id: 5343 #include "clang/Basic/AArch64SVEACLETypes.def" 5344 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 5345 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 5346 #include "clang/AST/BuiltinTypes.def" 5347 return false; 5348 5349 // We cannot lower out overload sets; they might validly be resolved 5350 // by the call machinery. 5351 case BuiltinType::Overload: 5352 return false; 5353 5354 // Unbridged casts in ARC can be handled in some call positions and 5355 // should be left in place. 5356 case BuiltinType::ARCUnbridgedCast: 5357 return false; 5358 5359 // Pseudo-objects should be converted as soon as possible. 5360 case BuiltinType::PseudoObject: 5361 return true; 5362 5363 // The debugger mode could theoretically but currently does not try 5364 // to resolve unknown-typed arguments based on known parameter types. 5365 case BuiltinType::UnknownAny: 5366 return true; 5367 5368 // These are always invalid as call arguments and should be reported. 5369 case BuiltinType::BoundMember: 5370 case BuiltinType::BuiltinFn: 5371 case BuiltinType::OMPArraySection: 5372 return true; 5373 5374 } 5375 llvm_unreachable("bad builtin type kind"); 5376 } 5377 5378 /// Check an argument list for placeholders that we won't try to 5379 /// handle later. 5380 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5381 // Apply this processing to all the arguments at once instead of 5382 // dying at the first failure. 5383 bool hasInvalid = false; 5384 for (size_t i = 0, e = args.size(); i != e; i++) { 5385 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5386 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5387 if (result.isInvalid()) hasInvalid = true; 5388 else args[i] = result.get(); 5389 } else if (hasInvalid) { 5390 (void)S.CorrectDelayedTyposInExpr(args[i]); 5391 } 5392 } 5393 return hasInvalid; 5394 } 5395 5396 /// If a builtin function has a pointer argument with no explicit address 5397 /// space, then it should be able to accept a pointer to any address 5398 /// space as input. In order to do this, we need to replace the 5399 /// standard builtin declaration with one that uses the same address space 5400 /// as the call. 5401 /// 5402 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5403 /// it does not contain any pointer arguments without 5404 /// an address space qualifer. Otherwise the rewritten 5405 /// FunctionDecl is returned. 5406 /// TODO: Handle pointer return types. 5407 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5408 FunctionDecl *FDecl, 5409 MultiExprArg ArgExprs) { 5410 5411 QualType DeclType = FDecl->getType(); 5412 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5413 5414 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 5415 ArgExprs.size() < FT->getNumParams()) 5416 return nullptr; 5417 5418 bool NeedsNewDecl = false; 5419 unsigned i = 0; 5420 SmallVector<QualType, 8> OverloadParams; 5421 5422 for (QualType ParamType : FT->param_types()) { 5423 5424 // Convert array arguments to pointer to simplify type lookup. 5425 ExprResult ArgRes = 5426 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5427 if (ArgRes.isInvalid()) 5428 return nullptr; 5429 Expr *Arg = ArgRes.get(); 5430 QualType ArgType = Arg->getType(); 5431 if (!ParamType->isPointerType() || 5432 ParamType.getQualifiers().hasAddressSpace() || 5433 !ArgType->isPointerType() || 5434 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 5435 OverloadParams.push_back(ParamType); 5436 continue; 5437 } 5438 5439 QualType PointeeType = ParamType->getPointeeType(); 5440 if (PointeeType.getQualifiers().hasAddressSpace()) 5441 continue; 5442 5443 NeedsNewDecl = true; 5444 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 5445 5446 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5447 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5448 } 5449 5450 if (!NeedsNewDecl) 5451 return nullptr; 5452 5453 FunctionProtoType::ExtProtoInfo EPI; 5454 EPI.Variadic = FT->isVariadic(); 5455 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5456 OverloadParams, EPI); 5457 DeclContext *Parent = FDecl->getParent(); 5458 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5459 FDecl->getLocation(), 5460 FDecl->getLocation(), 5461 FDecl->getIdentifier(), 5462 OverloadTy, 5463 /*TInfo=*/nullptr, 5464 SC_Extern, false, 5465 /*hasPrototype=*/true); 5466 SmallVector<ParmVarDecl*, 16> Params; 5467 FT = cast<FunctionProtoType>(OverloadTy); 5468 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5469 QualType ParamType = FT->getParamType(i); 5470 ParmVarDecl *Parm = 5471 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5472 SourceLocation(), nullptr, ParamType, 5473 /*TInfo=*/nullptr, SC_None, nullptr); 5474 Parm->setScopeInfo(0, i); 5475 Params.push_back(Parm); 5476 } 5477 OverloadDecl->setParams(Params); 5478 return OverloadDecl; 5479 } 5480 5481 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 5482 FunctionDecl *Callee, 5483 MultiExprArg ArgExprs) { 5484 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 5485 // similar attributes) really don't like it when functions are called with an 5486 // invalid number of args. 5487 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 5488 /*PartialOverloading=*/false) && 5489 !Callee->isVariadic()) 5490 return; 5491 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 5492 return; 5493 5494 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) { 5495 S.Diag(Fn->getBeginLoc(), 5496 isa<CXXMethodDecl>(Callee) 5497 ? diag::err_ovl_no_viable_member_function_in_call 5498 : diag::err_ovl_no_viable_function_in_call) 5499 << Callee << Callee->getSourceRange(); 5500 S.Diag(Callee->getLocation(), 5501 diag::note_ovl_candidate_disabled_by_function_cond_attr) 5502 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5503 return; 5504 } 5505 } 5506 5507 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 5508 const UnresolvedMemberExpr *const UME, Sema &S) { 5509 5510 const auto GetFunctionLevelDCIfCXXClass = 5511 [](Sema &S) -> const CXXRecordDecl * { 5512 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 5513 if (!DC || !DC->getParent()) 5514 return nullptr; 5515 5516 // If the call to some member function was made from within a member 5517 // function body 'M' return return 'M's parent. 5518 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 5519 return MD->getParent()->getCanonicalDecl(); 5520 // else the call was made from within a default member initializer of a 5521 // class, so return the class. 5522 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 5523 return RD->getCanonicalDecl(); 5524 return nullptr; 5525 }; 5526 // If our DeclContext is neither a member function nor a class (in the 5527 // case of a lambda in a default member initializer), we can't have an 5528 // enclosing 'this'. 5529 5530 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 5531 if (!CurParentClass) 5532 return false; 5533 5534 // The naming class for implicit member functions call is the class in which 5535 // name lookup starts. 5536 const CXXRecordDecl *const NamingClass = 5537 UME->getNamingClass()->getCanonicalDecl(); 5538 assert(NamingClass && "Must have naming class even for implicit access"); 5539 5540 // If the unresolved member functions were found in a 'naming class' that is 5541 // related (either the same or derived from) to the class that contains the 5542 // member function that itself contained the implicit member access. 5543 5544 return CurParentClass == NamingClass || 5545 CurParentClass->isDerivedFrom(NamingClass); 5546 } 5547 5548 static void 5549 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5550 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 5551 5552 if (!UME) 5553 return; 5554 5555 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 5556 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 5557 // already been captured, or if this is an implicit member function call (if 5558 // it isn't, an attempt to capture 'this' should already have been made). 5559 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 5560 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 5561 return; 5562 5563 // Check if the naming class in which the unresolved members were found is 5564 // related (same as or is a base of) to the enclosing class. 5565 5566 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 5567 return; 5568 5569 5570 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 5571 // If the enclosing function is not dependent, then this lambda is 5572 // capture ready, so if we can capture this, do so. 5573 if (!EnclosingFunctionCtx->isDependentContext()) { 5574 // If the current lambda and all enclosing lambdas can capture 'this' - 5575 // then go ahead and capture 'this' (since our unresolved overload set 5576 // contains at least one non-static member function). 5577 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 5578 S.CheckCXXThisCapture(CallLoc); 5579 } else if (S.CurContext->isDependentContext()) { 5580 // ... since this is an implicit member reference, that might potentially 5581 // involve a 'this' capture, mark 'this' for potential capture in 5582 // enclosing lambdas. 5583 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 5584 CurLSI->addPotentialThisCapture(CallLoc); 5585 } 5586 } 5587 5588 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5589 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5590 Expr *ExecConfig) { 5591 ExprResult Call = 5592 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig); 5593 if (Call.isInvalid()) 5594 return Call; 5595 5596 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 5597 // language modes. 5598 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 5599 if (ULE->hasExplicitTemplateArgs() && 5600 ULE->decls_begin() == ULE->decls_end()) { 5601 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus2a 5602 ? diag::warn_cxx17_compat_adl_only_template_id 5603 : diag::ext_adl_only_template_id) 5604 << ULE->getName(); 5605 } 5606 } 5607 5608 return Call; 5609 } 5610 5611 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 5612 /// This provides the location of the left/right parens and a list of comma 5613 /// locations. 5614 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5615 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5616 Expr *ExecConfig, bool IsExecConfig) { 5617 // Since this might be a postfix expression, get rid of ParenListExprs. 5618 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 5619 if (Result.isInvalid()) return ExprError(); 5620 Fn = Result.get(); 5621 5622 if (checkArgsForPlaceholders(*this, ArgExprs)) 5623 return ExprError(); 5624 5625 if (getLangOpts().CPlusPlus) { 5626 // If this is a pseudo-destructor expression, build the call immediately. 5627 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5628 if (!ArgExprs.empty()) { 5629 // Pseudo-destructor calls should not have any arguments. 5630 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 5631 << FixItHint::CreateRemoval( 5632 SourceRange(ArgExprs.front()->getBeginLoc(), 5633 ArgExprs.back()->getEndLoc())); 5634 } 5635 5636 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 5637 VK_RValue, RParenLoc); 5638 } 5639 if (Fn->getType() == Context.PseudoObjectTy) { 5640 ExprResult result = CheckPlaceholderExpr(Fn); 5641 if (result.isInvalid()) return ExprError(); 5642 Fn = result.get(); 5643 } 5644 5645 // Determine whether this is a dependent call inside a C++ template, 5646 // in which case we won't do any semantic analysis now. 5647 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 5648 if (ExecConfig) { 5649 return CUDAKernelCallExpr::Create( 5650 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5651 Context.DependentTy, VK_RValue, RParenLoc); 5652 } else { 5653 5654 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5655 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 5656 Fn->getBeginLoc()); 5657 5658 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 5659 VK_RValue, RParenLoc); 5660 } 5661 } 5662 5663 // Determine whether this is a call to an object (C++ [over.call.object]). 5664 if (Fn->getType()->isRecordType()) 5665 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 5666 RParenLoc); 5667 5668 if (Fn->getType() == Context.UnknownAnyTy) { 5669 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5670 if (result.isInvalid()) return ExprError(); 5671 Fn = result.get(); 5672 } 5673 5674 if (Fn->getType() == Context.BoundMemberTy) { 5675 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5676 RParenLoc); 5677 } 5678 } 5679 5680 // Check for overloaded calls. This can happen even in C due to extensions. 5681 if (Fn->getType() == Context.OverloadTy) { 5682 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5683 5684 // We aren't supposed to apply this logic if there's an '&' involved. 5685 if (!find.HasFormOfMemberPointer) { 5686 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5687 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 5688 VK_RValue, RParenLoc); 5689 OverloadExpr *ovl = find.Expression; 5690 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5691 return BuildOverloadedCallExpr( 5692 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 5693 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 5694 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5695 RParenLoc); 5696 } 5697 } 5698 5699 // If we're directly calling a function, get the appropriate declaration. 5700 if (Fn->getType() == Context.UnknownAnyTy) { 5701 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5702 if (result.isInvalid()) return ExprError(); 5703 Fn = result.get(); 5704 } 5705 5706 Expr *NakedFn = Fn->IgnoreParens(); 5707 5708 bool CallingNDeclIndirectly = false; 5709 NamedDecl *NDecl = nullptr; 5710 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5711 if (UnOp->getOpcode() == UO_AddrOf) { 5712 CallingNDeclIndirectly = true; 5713 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5714 } 5715 } 5716 5717 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 5718 NDecl = DRE->getDecl(); 5719 5720 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5721 if (FDecl && FDecl->getBuiltinID()) { 5722 // Rewrite the function decl for this builtin by replacing parameters 5723 // with no explicit address space with the address space of the arguments 5724 // in ArgExprs. 5725 if ((FDecl = 5726 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5727 NDecl = FDecl; 5728 Fn = DeclRefExpr::Create( 5729 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 5730 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 5731 nullptr, DRE->isNonOdrUse()); 5732 } 5733 } 5734 } else if (isa<MemberExpr>(NakedFn)) 5735 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5736 5737 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5738 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 5739 FD, /*Complain=*/true, Fn->getBeginLoc())) 5740 return ExprError(); 5741 5742 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 5743 return ExprError(); 5744 5745 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 5746 } 5747 5748 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5749 ExecConfig, IsExecConfig); 5750 } 5751 5752 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5753 /// 5754 /// __builtin_astype( value, dst type ) 5755 /// 5756 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5757 SourceLocation BuiltinLoc, 5758 SourceLocation RParenLoc) { 5759 ExprValueKind VK = VK_RValue; 5760 ExprObjectKind OK = OK_Ordinary; 5761 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5762 QualType SrcTy = E->getType(); 5763 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5764 return ExprError(Diag(BuiltinLoc, 5765 diag::err_invalid_astype_of_different_size) 5766 << DstTy 5767 << SrcTy 5768 << E->getSourceRange()); 5769 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5770 } 5771 5772 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5773 /// provided arguments. 5774 /// 5775 /// __builtin_convertvector( value, dst type ) 5776 /// 5777 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5778 SourceLocation BuiltinLoc, 5779 SourceLocation RParenLoc) { 5780 TypeSourceInfo *TInfo; 5781 GetTypeFromParser(ParsedDestTy, &TInfo); 5782 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5783 } 5784 5785 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5786 /// i.e. an expression not of \p OverloadTy. The expression should 5787 /// unary-convert to an expression of function-pointer or 5788 /// block-pointer type. 5789 /// 5790 /// \param NDecl the declaration being called, if available 5791 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5792 SourceLocation LParenLoc, 5793 ArrayRef<Expr *> Args, 5794 SourceLocation RParenLoc, Expr *Config, 5795 bool IsExecConfig, ADLCallKind UsesADL) { 5796 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5797 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5798 5799 // Functions with 'interrupt' attribute cannot be called directly. 5800 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5801 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5802 return ExprError(); 5803 } 5804 5805 // Interrupt handlers don't save off the VFP regs automatically on ARM, 5806 // so there's some risk when calling out to non-interrupt handler functions 5807 // that the callee might not preserve them. This is easy to diagnose here, 5808 // but can be very challenging to debug. 5809 if (auto *Caller = getCurFunctionDecl()) 5810 if (Caller->hasAttr<ARMInterruptAttr>()) { 5811 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 5812 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) 5813 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 5814 } 5815 5816 // Promote the function operand. 5817 // We special-case function promotion here because we only allow promoting 5818 // builtin functions to function pointers in the callee of a call. 5819 ExprResult Result; 5820 QualType ResultTy; 5821 if (BuiltinID && 5822 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5823 // Extract the return type from the (builtin) function pointer type. 5824 // FIXME Several builtins still have setType in 5825 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 5826 // Builtins.def to ensure they are correct before removing setType calls. 5827 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 5828 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 5829 ResultTy = FDecl->getCallResultType(); 5830 } else { 5831 Result = CallExprUnaryConversions(Fn); 5832 ResultTy = Context.BoolTy; 5833 } 5834 if (Result.isInvalid()) 5835 return ExprError(); 5836 Fn = Result.get(); 5837 5838 // Check for a valid function type, but only if it is not a builtin which 5839 // requires custom type checking. These will be handled by 5840 // CheckBuiltinFunctionCall below just after creation of the call expression. 5841 const FunctionType *FuncT = nullptr; 5842 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 5843 retry: 5844 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5845 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5846 // have type pointer to function". 5847 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5848 if (!FuncT) 5849 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5850 << Fn->getType() << Fn->getSourceRange()); 5851 } else if (const BlockPointerType *BPT = 5852 Fn->getType()->getAs<BlockPointerType>()) { 5853 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5854 } else { 5855 // Handle calls to expressions of unknown-any type. 5856 if (Fn->getType() == Context.UnknownAnyTy) { 5857 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5858 if (rewrite.isInvalid()) 5859 return ExprError(); 5860 Fn = rewrite.get(); 5861 goto retry; 5862 } 5863 5864 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5865 << Fn->getType() << Fn->getSourceRange()); 5866 } 5867 } 5868 5869 // Get the number of parameters in the function prototype, if any. 5870 // We will allocate space for max(Args.size(), NumParams) arguments 5871 // in the call expression. 5872 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 5873 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 5874 5875 CallExpr *TheCall; 5876 if (Config) { 5877 assert(UsesADL == ADLCallKind::NotADL && 5878 "CUDAKernelCallExpr should not use ADL"); 5879 TheCall = 5880 CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args, 5881 ResultTy, VK_RValue, RParenLoc, NumParams); 5882 } else { 5883 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, 5884 RParenLoc, NumParams, UsesADL); 5885 } 5886 5887 if (!getLangOpts().CPlusPlus) { 5888 // Forget about the nulled arguments since typo correction 5889 // do not handle them well. 5890 TheCall->shrinkNumArgs(Args.size()); 5891 // C cannot always handle TypoExpr nodes in builtin calls and direct 5892 // function calls as their argument checking don't necessarily handle 5893 // dependent types properly, so make sure any TypoExprs have been 5894 // dealt with. 5895 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5896 if (!Result.isUsable()) return ExprError(); 5897 CallExpr *TheOldCall = TheCall; 5898 TheCall = dyn_cast<CallExpr>(Result.get()); 5899 bool CorrectedTypos = TheCall != TheOldCall; 5900 if (!TheCall) return Result; 5901 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5902 5903 // A new call expression node was created if some typos were corrected. 5904 // However it may not have been constructed with enough storage. In this 5905 // case, rebuild the node with enough storage. The waste of space is 5906 // immaterial since this only happens when some typos were corrected. 5907 if (CorrectedTypos && Args.size() < NumParams) { 5908 if (Config) 5909 TheCall = CUDAKernelCallExpr::Create( 5910 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue, 5911 RParenLoc, NumParams); 5912 else 5913 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, 5914 RParenLoc, NumParams, UsesADL); 5915 } 5916 // We can now handle the nulled arguments for the default arguments. 5917 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 5918 } 5919 5920 // Bail out early if calling a builtin with custom type checking. 5921 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5922 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5923 5924 if (getLangOpts().CUDA) { 5925 if (Config) { 5926 // CUDA: Kernel calls must be to global functions 5927 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5928 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5929 << FDecl << Fn->getSourceRange()); 5930 5931 // CUDA: Kernel function must have 'void' return type 5932 if (!FuncT->getReturnType()->isVoidType() && 5933 !FuncT->getReturnType()->getAs<AutoType>() && 5934 !FuncT->getReturnType()->isInstantiationDependentType()) 5935 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5936 << Fn->getType() << Fn->getSourceRange()); 5937 } else { 5938 // CUDA: Calls to global functions must be configured 5939 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5940 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5941 << FDecl << Fn->getSourceRange()); 5942 } 5943 } 5944 5945 // Check for a valid return type 5946 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 5947 FDecl)) 5948 return ExprError(); 5949 5950 // We know the result type of the call, set it. 5951 TheCall->setType(FuncT->getCallResultType(Context)); 5952 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5953 5954 if (Proto) { 5955 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5956 IsExecConfig)) 5957 return ExprError(); 5958 } else { 5959 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5960 5961 if (FDecl) { 5962 // Check if we have too few/too many template arguments, based 5963 // on our knowledge of the function definition. 5964 const FunctionDecl *Def = nullptr; 5965 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5966 Proto = Def->getType()->getAs<FunctionProtoType>(); 5967 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5968 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5969 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5970 } 5971 5972 // If the function we're calling isn't a function prototype, but we have 5973 // a function prototype from a prior declaratiom, use that prototype. 5974 if (!FDecl->hasPrototype()) 5975 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5976 } 5977 5978 // Promote the arguments (C99 6.5.2.2p6). 5979 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5980 Expr *Arg = Args[i]; 5981 5982 if (Proto && i < Proto->getNumParams()) { 5983 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5984 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5985 ExprResult ArgE = 5986 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5987 if (ArgE.isInvalid()) 5988 return true; 5989 5990 Arg = ArgE.getAs<Expr>(); 5991 5992 } else { 5993 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5994 5995 if (ArgE.isInvalid()) 5996 return true; 5997 5998 Arg = ArgE.getAs<Expr>(); 5999 } 6000 6001 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 6002 diag::err_call_incomplete_argument, Arg)) 6003 return ExprError(); 6004 6005 TheCall->setArg(i, Arg); 6006 } 6007 } 6008 6009 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 6010 if (!Method->isStatic()) 6011 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 6012 << Fn->getSourceRange()); 6013 6014 // Check for sentinels 6015 if (NDecl) 6016 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 6017 6018 // Do special checking on direct calls to functions. 6019 if (FDecl) { 6020 if (CheckFunctionCall(FDecl, TheCall, Proto)) 6021 return ExprError(); 6022 6023 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 6024 6025 if (BuiltinID) 6026 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6027 } else if (NDecl) { 6028 if (CheckPointerCall(NDecl, TheCall, Proto)) 6029 return ExprError(); 6030 } else { 6031 if (CheckOtherCall(TheCall, Proto)) 6032 return ExprError(); 6033 } 6034 6035 return MaybeBindToTemporary(TheCall); 6036 } 6037 6038 ExprResult 6039 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 6040 SourceLocation RParenLoc, Expr *InitExpr) { 6041 assert(Ty && "ActOnCompoundLiteral(): missing type"); 6042 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 6043 6044 TypeSourceInfo *TInfo; 6045 QualType literalType = GetTypeFromParser(Ty, &TInfo); 6046 if (!TInfo) 6047 TInfo = Context.getTrivialTypeSourceInfo(literalType); 6048 6049 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 6050 } 6051 6052 ExprResult 6053 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 6054 SourceLocation RParenLoc, Expr *LiteralExpr) { 6055 QualType literalType = TInfo->getType(); 6056 6057 if (literalType->isArrayType()) { 6058 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 6059 diag::err_illegal_decl_array_incomplete_type, 6060 SourceRange(LParenLoc, 6061 LiteralExpr->getSourceRange().getEnd()))) 6062 return ExprError(); 6063 if (literalType->isVariableArrayType()) 6064 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 6065 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 6066 } else if (!literalType->isDependentType() && 6067 RequireCompleteType(LParenLoc, literalType, 6068 diag::err_typecheck_decl_incomplete_type, 6069 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6070 return ExprError(); 6071 6072 InitializedEntity Entity 6073 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 6074 InitializationKind Kind 6075 = InitializationKind::CreateCStyleCast(LParenLoc, 6076 SourceRange(LParenLoc, RParenLoc), 6077 /*InitList=*/true); 6078 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 6079 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 6080 &literalType); 6081 if (Result.isInvalid()) 6082 return ExprError(); 6083 LiteralExpr = Result.get(); 6084 6085 bool isFileScope = !CurContext->isFunctionOrMethod(); 6086 6087 // In C, compound literals are l-values for some reason. 6088 // For GCC compatibility, in C++, file-scope array compound literals with 6089 // constant initializers are also l-values, and compound literals are 6090 // otherwise prvalues. 6091 // 6092 // (GCC also treats C++ list-initialized file-scope array prvalues with 6093 // constant initializers as l-values, but that's non-conforming, so we don't 6094 // follow it there.) 6095 // 6096 // FIXME: It would be better to handle the lvalue cases as materializing and 6097 // lifetime-extending a temporary object, but our materialized temporaries 6098 // representation only supports lifetime extension from a variable, not "out 6099 // of thin air". 6100 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 6101 // is bound to the result of applying array-to-pointer decay to the compound 6102 // literal. 6103 // FIXME: GCC supports compound literals of reference type, which should 6104 // obviously have a value kind derived from the kind of reference involved. 6105 ExprValueKind VK = 6106 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 6107 ? VK_RValue 6108 : VK_LValue; 6109 6110 if (isFileScope) 6111 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 6112 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 6113 Expr *Init = ILE->getInit(i); 6114 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 6115 } 6116 6117 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 6118 VK, LiteralExpr, isFileScope); 6119 if (isFileScope) { 6120 if (!LiteralExpr->isTypeDependent() && 6121 !LiteralExpr->isValueDependent() && 6122 !literalType->isDependentType()) // C99 6.5.2.5p3 6123 if (CheckForConstantInitializer(LiteralExpr, literalType)) 6124 return ExprError(); 6125 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 6126 literalType.getAddressSpace() != LangAS::Default) { 6127 // Embedded-C extensions to C99 6.5.2.5: 6128 // "If the compound literal occurs inside the body of a function, the 6129 // type name shall not be qualified by an address-space qualifier." 6130 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 6131 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 6132 return ExprError(); 6133 } 6134 6135 // Compound literals that have automatic storage duration are destroyed at 6136 // the end of the scope. Emit diagnostics if it is or contains a C union type 6137 // that is non-trivial to destruct. 6138 if (!isFileScope) 6139 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 6140 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 6141 NTCUC_CompoundLiteral, NTCUK_Destruct); 6142 6143 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 6144 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 6145 checkNonTrivialCUnionInInitializer(E->getInitializer(), 6146 E->getInitializer()->getExprLoc()); 6147 6148 return MaybeBindToTemporary(E); 6149 } 6150 6151 ExprResult 6152 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6153 SourceLocation RBraceLoc) { 6154 // Only produce each kind of designated initialization diagnostic once. 6155 SourceLocation FirstDesignator; 6156 bool DiagnosedArrayDesignator = false; 6157 bool DiagnosedNestedDesignator = false; 6158 bool DiagnosedMixedDesignator = false; 6159 6160 // Check that any designated initializers are syntactically valid in the 6161 // current language mode. 6162 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6163 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 6164 if (FirstDesignator.isInvalid()) 6165 FirstDesignator = DIE->getBeginLoc(); 6166 6167 if (!getLangOpts().CPlusPlus) 6168 break; 6169 6170 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 6171 DiagnosedNestedDesignator = true; 6172 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 6173 << DIE->getDesignatorsSourceRange(); 6174 } 6175 6176 for (auto &Desig : DIE->designators()) { 6177 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 6178 DiagnosedArrayDesignator = true; 6179 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 6180 << Desig.getSourceRange(); 6181 } 6182 } 6183 6184 if (!DiagnosedMixedDesignator && 6185 !isa<DesignatedInitExpr>(InitArgList[0])) { 6186 DiagnosedMixedDesignator = true; 6187 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6188 << DIE->getSourceRange(); 6189 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 6190 << InitArgList[0]->getSourceRange(); 6191 } 6192 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 6193 isa<DesignatedInitExpr>(InitArgList[0])) { 6194 DiagnosedMixedDesignator = true; 6195 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 6196 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6197 << DIE->getSourceRange(); 6198 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 6199 << InitArgList[I]->getSourceRange(); 6200 } 6201 } 6202 6203 if (FirstDesignator.isValid()) { 6204 // Only diagnose designated initiaization as a C++20 extension if we didn't 6205 // already diagnose use of (non-C++20) C99 designator syntax. 6206 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 6207 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 6208 Diag(FirstDesignator, getLangOpts().CPlusPlus2a 6209 ? diag::warn_cxx17_compat_designated_init 6210 : diag::ext_cxx_designated_init); 6211 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 6212 Diag(FirstDesignator, diag::ext_designated_init); 6213 } 6214 } 6215 6216 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 6217 } 6218 6219 ExprResult 6220 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6221 SourceLocation RBraceLoc) { 6222 // Semantic analysis for initializers is done by ActOnDeclarator() and 6223 // CheckInitializer() - it requires knowledge of the object being initialized. 6224 6225 // Immediately handle non-overload placeholders. Overloads can be 6226 // resolved contextually, but everything else here can't. 6227 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6228 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 6229 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 6230 6231 // Ignore failures; dropping the entire initializer list because 6232 // of one failure would be terrible for indexing/etc. 6233 if (result.isInvalid()) continue; 6234 6235 InitArgList[I] = result.get(); 6236 } 6237 } 6238 6239 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 6240 RBraceLoc); 6241 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 6242 return E; 6243 } 6244 6245 /// Do an explicit extend of the given block pointer if we're in ARC. 6246 void Sema::maybeExtendBlockObject(ExprResult &E) { 6247 assert(E.get()->getType()->isBlockPointerType()); 6248 assert(E.get()->isRValue()); 6249 6250 // Only do this in an r-value context. 6251 if (!getLangOpts().ObjCAutoRefCount) return; 6252 6253 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 6254 CK_ARCExtendBlockObject, E.get(), 6255 /*base path*/ nullptr, VK_RValue); 6256 Cleanup.setExprNeedsCleanups(true); 6257 } 6258 6259 /// Prepare a conversion of the given expression to an ObjC object 6260 /// pointer type. 6261 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 6262 QualType type = E.get()->getType(); 6263 if (type->isObjCObjectPointerType()) { 6264 return CK_BitCast; 6265 } else if (type->isBlockPointerType()) { 6266 maybeExtendBlockObject(E); 6267 return CK_BlockPointerToObjCPointerCast; 6268 } else { 6269 assert(type->isPointerType()); 6270 return CK_CPointerToObjCPointerCast; 6271 } 6272 } 6273 6274 /// Prepares for a scalar cast, performing all the necessary stages 6275 /// except the final cast and returning the kind required. 6276 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 6277 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 6278 // Also, callers should have filtered out the invalid cases with 6279 // pointers. Everything else should be possible. 6280 6281 QualType SrcTy = Src.get()->getType(); 6282 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 6283 return CK_NoOp; 6284 6285 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 6286 case Type::STK_MemberPointer: 6287 llvm_unreachable("member pointer type in C"); 6288 6289 case Type::STK_CPointer: 6290 case Type::STK_BlockPointer: 6291 case Type::STK_ObjCObjectPointer: 6292 switch (DestTy->getScalarTypeKind()) { 6293 case Type::STK_CPointer: { 6294 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 6295 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 6296 if (SrcAS != DestAS) 6297 return CK_AddressSpaceConversion; 6298 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 6299 return CK_NoOp; 6300 return CK_BitCast; 6301 } 6302 case Type::STK_BlockPointer: 6303 return (SrcKind == Type::STK_BlockPointer 6304 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 6305 case Type::STK_ObjCObjectPointer: 6306 if (SrcKind == Type::STK_ObjCObjectPointer) 6307 return CK_BitCast; 6308 if (SrcKind == Type::STK_CPointer) 6309 return CK_CPointerToObjCPointerCast; 6310 maybeExtendBlockObject(Src); 6311 return CK_BlockPointerToObjCPointerCast; 6312 case Type::STK_Bool: 6313 return CK_PointerToBoolean; 6314 case Type::STK_Integral: 6315 return CK_PointerToIntegral; 6316 case Type::STK_Floating: 6317 case Type::STK_FloatingComplex: 6318 case Type::STK_IntegralComplex: 6319 case Type::STK_MemberPointer: 6320 case Type::STK_FixedPoint: 6321 llvm_unreachable("illegal cast from pointer"); 6322 } 6323 llvm_unreachable("Should have returned before this"); 6324 6325 case Type::STK_FixedPoint: 6326 switch (DestTy->getScalarTypeKind()) { 6327 case Type::STK_FixedPoint: 6328 return CK_FixedPointCast; 6329 case Type::STK_Bool: 6330 return CK_FixedPointToBoolean; 6331 case Type::STK_Integral: 6332 return CK_FixedPointToIntegral; 6333 case Type::STK_Floating: 6334 case Type::STK_IntegralComplex: 6335 case Type::STK_FloatingComplex: 6336 Diag(Src.get()->getExprLoc(), 6337 diag::err_unimplemented_conversion_with_fixed_point_type) 6338 << DestTy; 6339 return CK_IntegralCast; 6340 case Type::STK_CPointer: 6341 case Type::STK_ObjCObjectPointer: 6342 case Type::STK_BlockPointer: 6343 case Type::STK_MemberPointer: 6344 llvm_unreachable("illegal cast to pointer type"); 6345 } 6346 llvm_unreachable("Should have returned before this"); 6347 6348 case Type::STK_Bool: // casting from bool is like casting from an integer 6349 case Type::STK_Integral: 6350 switch (DestTy->getScalarTypeKind()) { 6351 case Type::STK_CPointer: 6352 case Type::STK_ObjCObjectPointer: 6353 case Type::STK_BlockPointer: 6354 if (Src.get()->isNullPointerConstant(Context, 6355 Expr::NPC_ValueDependentIsNull)) 6356 return CK_NullToPointer; 6357 return CK_IntegralToPointer; 6358 case Type::STK_Bool: 6359 return CK_IntegralToBoolean; 6360 case Type::STK_Integral: 6361 return CK_IntegralCast; 6362 case Type::STK_Floating: 6363 return CK_IntegralToFloating; 6364 case Type::STK_IntegralComplex: 6365 Src = ImpCastExprToType(Src.get(), 6366 DestTy->castAs<ComplexType>()->getElementType(), 6367 CK_IntegralCast); 6368 return CK_IntegralRealToComplex; 6369 case Type::STK_FloatingComplex: 6370 Src = ImpCastExprToType(Src.get(), 6371 DestTy->castAs<ComplexType>()->getElementType(), 6372 CK_IntegralToFloating); 6373 return CK_FloatingRealToComplex; 6374 case Type::STK_MemberPointer: 6375 llvm_unreachable("member pointer type in C"); 6376 case Type::STK_FixedPoint: 6377 return CK_IntegralToFixedPoint; 6378 } 6379 llvm_unreachable("Should have returned before this"); 6380 6381 case Type::STK_Floating: 6382 switch (DestTy->getScalarTypeKind()) { 6383 case Type::STK_Floating: 6384 return CK_FloatingCast; 6385 case Type::STK_Bool: 6386 return CK_FloatingToBoolean; 6387 case Type::STK_Integral: 6388 return CK_FloatingToIntegral; 6389 case Type::STK_FloatingComplex: 6390 Src = ImpCastExprToType(Src.get(), 6391 DestTy->castAs<ComplexType>()->getElementType(), 6392 CK_FloatingCast); 6393 return CK_FloatingRealToComplex; 6394 case Type::STK_IntegralComplex: 6395 Src = ImpCastExprToType(Src.get(), 6396 DestTy->castAs<ComplexType>()->getElementType(), 6397 CK_FloatingToIntegral); 6398 return CK_IntegralRealToComplex; 6399 case Type::STK_CPointer: 6400 case Type::STK_ObjCObjectPointer: 6401 case Type::STK_BlockPointer: 6402 llvm_unreachable("valid float->pointer cast?"); 6403 case Type::STK_MemberPointer: 6404 llvm_unreachable("member pointer type in C"); 6405 case Type::STK_FixedPoint: 6406 Diag(Src.get()->getExprLoc(), 6407 diag::err_unimplemented_conversion_with_fixed_point_type) 6408 << SrcTy; 6409 return CK_IntegralCast; 6410 } 6411 llvm_unreachable("Should have returned before this"); 6412 6413 case Type::STK_FloatingComplex: 6414 switch (DestTy->getScalarTypeKind()) { 6415 case Type::STK_FloatingComplex: 6416 return CK_FloatingComplexCast; 6417 case Type::STK_IntegralComplex: 6418 return CK_FloatingComplexToIntegralComplex; 6419 case Type::STK_Floating: { 6420 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 6421 if (Context.hasSameType(ET, DestTy)) 6422 return CK_FloatingComplexToReal; 6423 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 6424 return CK_FloatingCast; 6425 } 6426 case Type::STK_Bool: 6427 return CK_FloatingComplexToBoolean; 6428 case Type::STK_Integral: 6429 Src = ImpCastExprToType(Src.get(), 6430 SrcTy->castAs<ComplexType>()->getElementType(), 6431 CK_FloatingComplexToReal); 6432 return CK_FloatingToIntegral; 6433 case Type::STK_CPointer: 6434 case Type::STK_ObjCObjectPointer: 6435 case Type::STK_BlockPointer: 6436 llvm_unreachable("valid complex float->pointer cast?"); 6437 case Type::STK_MemberPointer: 6438 llvm_unreachable("member pointer type in C"); 6439 case Type::STK_FixedPoint: 6440 Diag(Src.get()->getExprLoc(), 6441 diag::err_unimplemented_conversion_with_fixed_point_type) 6442 << SrcTy; 6443 return CK_IntegralCast; 6444 } 6445 llvm_unreachable("Should have returned before this"); 6446 6447 case Type::STK_IntegralComplex: 6448 switch (DestTy->getScalarTypeKind()) { 6449 case Type::STK_FloatingComplex: 6450 return CK_IntegralComplexToFloatingComplex; 6451 case Type::STK_IntegralComplex: 6452 return CK_IntegralComplexCast; 6453 case Type::STK_Integral: { 6454 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 6455 if (Context.hasSameType(ET, DestTy)) 6456 return CK_IntegralComplexToReal; 6457 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 6458 return CK_IntegralCast; 6459 } 6460 case Type::STK_Bool: 6461 return CK_IntegralComplexToBoolean; 6462 case Type::STK_Floating: 6463 Src = ImpCastExprToType(Src.get(), 6464 SrcTy->castAs<ComplexType>()->getElementType(), 6465 CK_IntegralComplexToReal); 6466 return CK_IntegralToFloating; 6467 case Type::STK_CPointer: 6468 case Type::STK_ObjCObjectPointer: 6469 case Type::STK_BlockPointer: 6470 llvm_unreachable("valid complex int->pointer cast?"); 6471 case Type::STK_MemberPointer: 6472 llvm_unreachable("member pointer type in C"); 6473 case Type::STK_FixedPoint: 6474 Diag(Src.get()->getExprLoc(), 6475 diag::err_unimplemented_conversion_with_fixed_point_type) 6476 << SrcTy; 6477 return CK_IntegralCast; 6478 } 6479 llvm_unreachable("Should have returned before this"); 6480 } 6481 6482 llvm_unreachable("Unhandled scalar cast"); 6483 } 6484 6485 static bool breakDownVectorType(QualType type, uint64_t &len, 6486 QualType &eltType) { 6487 // Vectors are simple. 6488 if (const VectorType *vecType = type->getAs<VectorType>()) { 6489 len = vecType->getNumElements(); 6490 eltType = vecType->getElementType(); 6491 assert(eltType->isScalarType()); 6492 return true; 6493 } 6494 6495 // We allow lax conversion to and from non-vector types, but only if 6496 // they're real types (i.e. non-complex, non-pointer scalar types). 6497 if (!type->isRealType()) return false; 6498 6499 len = 1; 6500 eltType = type; 6501 return true; 6502 } 6503 6504 /// Are the two types lax-compatible vector types? That is, given 6505 /// that one of them is a vector, do they have equal storage sizes, 6506 /// where the storage size is the number of elements times the element 6507 /// size? 6508 /// 6509 /// This will also return false if either of the types is neither a 6510 /// vector nor a real type. 6511 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 6512 assert(destTy->isVectorType() || srcTy->isVectorType()); 6513 6514 // Disallow lax conversions between scalars and ExtVectors (these 6515 // conversions are allowed for other vector types because common headers 6516 // depend on them). Most scalar OP ExtVector cases are handled by the 6517 // splat path anyway, which does what we want (convert, not bitcast). 6518 // What this rules out for ExtVectors is crazy things like char4*float. 6519 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 6520 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 6521 6522 uint64_t srcLen, destLen; 6523 QualType srcEltTy, destEltTy; 6524 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 6525 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 6526 6527 // ASTContext::getTypeSize will return the size rounded up to a 6528 // power of 2, so instead of using that, we need to use the raw 6529 // element size multiplied by the element count. 6530 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 6531 uint64_t destEltSize = Context.getTypeSize(destEltTy); 6532 6533 return (srcLen * srcEltSize == destLen * destEltSize); 6534 } 6535 6536 /// Is this a legal conversion between two types, one of which is 6537 /// known to be a vector type? 6538 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 6539 assert(destTy->isVectorType() || srcTy->isVectorType()); 6540 6541 switch (Context.getLangOpts().getLaxVectorConversions()) { 6542 case LangOptions::LaxVectorConversionKind::None: 6543 return false; 6544 6545 case LangOptions::LaxVectorConversionKind::Integer: 6546 if (!srcTy->isIntegralOrEnumerationType()) { 6547 auto *Vec = srcTy->getAs<VectorType>(); 6548 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 6549 return false; 6550 } 6551 if (!destTy->isIntegralOrEnumerationType()) { 6552 auto *Vec = destTy->getAs<VectorType>(); 6553 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 6554 return false; 6555 } 6556 // OK, integer (vector) -> integer (vector) bitcast. 6557 break; 6558 6559 case LangOptions::LaxVectorConversionKind::All: 6560 break; 6561 } 6562 6563 return areLaxCompatibleVectorTypes(srcTy, destTy); 6564 } 6565 6566 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 6567 CastKind &Kind) { 6568 assert(VectorTy->isVectorType() && "Not a vector type!"); 6569 6570 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 6571 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 6572 return Diag(R.getBegin(), 6573 Ty->isVectorType() ? 6574 diag::err_invalid_conversion_between_vectors : 6575 diag::err_invalid_conversion_between_vector_and_integer) 6576 << VectorTy << Ty << R; 6577 } else 6578 return Diag(R.getBegin(), 6579 diag::err_invalid_conversion_between_vector_and_scalar) 6580 << VectorTy << Ty << R; 6581 6582 Kind = CK_BitCast; 6583 return false; 6584 } 6585 6586 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 6587 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 6588 6589 if (DestElemTy == SplattedExpr->getType()) 6590 return SplattedExpr; 6591 6592 assert(DestElemTy->isFloatingType() || 6593 DestElemTy->isIntegralOrEnumerationType()); 6594 6595 CastKind CK; 6596 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 6597 // OpenCL requires that we convert `true` boolean expressions to -1, but 6598 // only when splatting vectors. 6599 if (DestElemTy->isFloatingType()) { 6600 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 6601 // in two steps: boolean to signed integral, then to floating. 6602 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 6603 CK_BooleanToSignedIntegral); 6604 SplattedExpr = CastExprRes.get(); 6605 CK = CK_IntegralToFloating; 6606 } else { 6607 CK = CK_BooleanToSignedIntegral; 6608 } 6609 } else { 6610 ExprResult CastExprRes = SplattedExpr; 6611 CK = PrepareScalarCast(CastExprRes, DestElemTy); 6612 if (CastExprRes.isInvalid()) 6613 return ExprError(); 6614 SplattedExpr = CastExprRes.get(); 6615 } 6616 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 6617 } 6618 6619 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 6620 Expr *CastExpr, CastKind &Kind) { 6621 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 6622 6623 QualType SrcTy = CastExpr->getType(); 6624 6625 // If SrcTy is a VectorType, the total size must match to explicitly cast to 6626 // an ExtVectorType. 6627 // In OpenCL, casts between vectors of different types are not allowed. 6628 // (See OpenCL 6.2). 6629 if (SrcTy->isVectorType()) { 6630 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 6631 (getLangOpts().OpenCL && 6632 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 6633 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 6634 << DestTy << SrcTy << R; 6635 return ExprError(); 6636 } 6637 Kind = CK_BitCast; 6638 return CastExpr; 6639 } 6640 6641 // All non-pointer scalars can be cast to ExtVector type. The appropriate 6642 // conversion will take place first from scalar to elt type, and then 6643 // splat from elt type to vector. 6644 if (SrcTy->isPointerType()) 6645 return Diag(R.getBegin(), 6646 diag::err_invalid_conversion_between_vector_and_scalar) 6647 << DestTy << SrcTy << R; 6648 6649 Kind = CK_VectorSplat; 6650 return prepareVectorSplat(DestTy, CastExpr); 6651 } 6652 6653 ExprResult 6654 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 6655 Declarator &D, ParsedType &Ty, 6656 SourceLocation RParenLoc, Expr *CastExpr) { 6657 assert(!D.isInvalidType() && (CastExpr != nullptr) && 6658 "ActOnCastExpr(): missing type or expr"); 6659 6660 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 6661 if (D.isInvalidType()) 6662 return ExprError(); 6663 6664 if (getLangOpts().CPlusPlus) { 6665 // Check that there are no default arguments (C++ only). 6666 CheckExtraCXXDefaultArguments(D); 6667 } else { 6668 // Make sure any TypoExprs have been dealt with. 6669 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 6670 if (!Res.isUsable()) 6671 return ExprError(); 6672 CastExpr = Res.get(); 6673 } 6674 6675 checkUnusedDeclAttributes(D); 6676 6677 QualType castType = castTInfo->getType(); 6678 Ty = CreateParsedType(castType, castTInfo); 6679 6680 bool isVectorLiteral = false; 6681 6682 // Check for an altivec or OpenCL literal, 6683 // i.e. all the elements are integer constants. 6684 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 6685 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 6686 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 6687 && castType->isVectorType() && (PE || PLE)) { 6688 if (PLE && PLE->getNumExprs() == 0) { 6689 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 6690 return ExprError(); 6691 } 6692 if (PE || PLE->getNumExprs() == 1) { 6693 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 6694 if (!E->getType()->isVectorType()) 6695 isVectorLiteral = true; 6696 } 6697 else 6698 isVectorLiteral = true; 6699 } 6700 6701 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 6702 // then handle it as such. 6703 if (isVectorLiteral) 6704 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 6705 6706 // If the Expr being casted is a ParenListExpr, handle it specially. 6707 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 6708 // sequence of BinOp comma operators. 6709 if (isa<ParenListExpr>(CastExpr)) { 6710 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 6711 if (Result.isInvalid()) return ExprError(); 6712 CastExpr = Result.get(); 6713 } 6714 6715 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6716 !getSourceManager().isInSystemMacro(LParenLoc)) 6717 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6718 6719 CheckTollFreeBridgeCast(castType, CastExpr); 6720 6721 CheckObjCBridgeRelatedCast(castType, CastExpr); 6722 6723 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 6724 6725 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6726 } 6727 6728 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6729 SourceLocation RParenLoc, Expr *E, 6730 TypeSourceInfo *TInfo) { 6731 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6732 "Expected paren or paren list expression"); 6733 6734 Expr **exprs; 6735 unsigned numExprs; 6736 Expr *subExpr; 6737 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6738 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6739 LiteralLParenLoc = PE->getLParenLoc(); 6740 LiteralRParenLoc = PE->getRParenLoc(); 6741 exprs = PE->getExprs(); 6742 numExprs = PE->getNumExprs(); 6743 } else { // isa<ParenExpr> by assertion at function entrance 6744 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6745 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6746 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6747 exprs = &subExpr; 6748 numExprs = 1; 6749 } 6750 6751 QualType Ty = TInfo->getType(); 6752 assert(Ty->isVectorType() && "Expected vector type"); 6753 6754 SmallVector<Expr *, 8> initExprs; 6755 const VectorType *VTy = Ty->castAs<VectorType>(); 6756 unsigned numElems = VTy->getNumElements(); 6757 6758 // '(...)' form of vector initialization in AltiVec: the number of 6759 // initializers must be one or must match the size of the vector. 6760 // If a single value is specified in the initializer then it will be 6761 // replicated to all the components of the vector 6762 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6763 // The number of initializers must be one or must match the size of the 6764 // vector. If a single value is specified in the initializer then it will 6765 // be replicated to all the components of the vector 6766 if (numExprs == 1) { 6767 QualType ElemTy = VTy->getElementType(); 6768 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6769 if (Literal.isInvalid()) 6770 return ExprError(); 6771 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6772 PrepareScalarCast(Literal, ElemTy)); 6773 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6774 } 6775 else if (numExprs < numElems) { 6776 Diag(E->getExprLoc(), 6777 diag::err_incorrect_number_of_vector_initializers); 6778 return ExprError(); 6779 } 6780 else 6781 initExprs.append(exprs, exprs + numExprs); 6782 } 6783 else { 6784 // For OpenCL, when the number of initializers is a single value, 6785 // it will be replicated to all components of the vector. 6786 if (getLangOpts().OpenCL && 6787 VTy->getVectorKind() == VectorType::GenericVector && 6788 numExprs == 1) { 6789 QualType ElemTy = VTy->getElementType(); 6790 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6791 if (Literal.isInvalid()) 6792 return ExprError(); 6793 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6794 PrepareScalarCast(Literal, ElemTy)); 6795 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6796 } 6797 6798 initExprs.append(exprs, exprs + numExprs); 6799 } 6800 // FIXME: This means that pretty-printing the final AST will produce curly 6801 // braces instead of the original commas. 6802 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6803 initExprs, LiteralRParenLoc); 6804 initE->setType(Ty); 6805 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6806 } 6807 6808 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6809 /// the ParenListExpr into a sequence of comma binary operators. 6810 ExprResult 6811 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6812 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6813 if (!E) 6814 return OrigExpr; 6815 6816 ExprResult Result(E->getExpr(0)); 6817 6818 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6819 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6820 E->getExpr(i)); 6821 6822 if (Result.isInvalid()) return ExprError(); 6823 6824 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6825 } 6826 6827 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6828 SourceLocation R, 6829 MultiExprArg Val) { 6830 return ParenListExpr::Create(Context, L, Val, R); 6831 } 6832 6833 /// Emit a specialized diagnostic when one expression is a null pointer 6834 /// constant and the other is not a pointer. Returns true if a diagnostic is 6835 /// emitted. 6836 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6837 SourceLocation QuestionLoc) { 6838 Expr *NullExpr = LHSExpr; 6839 Expr *NonPointerExpr = RHSExpr; 6840 Expr::NullPointerConstantKind NullKind = 6841 NullExpr->isNullPointerConstant(Context, 6842 Expr::NPC_ValueDependentIsNotNull); 6843 6844 if (NullKind == Expr::NPCK_NotNull) { 6845 NullExpr = RHSExpr; 6846 NonPointerExpr = LHSExpr; 6847 NullKind = 6848 NullExpr->isNullPointerConstant(Context, 6849 Expr::NPC_ValueDependentIsNotNull); 6850 } 6851 6852 if (NullKind == Expr::NPCK_NotNull) 6853 return false; 6854 6855 if (NullKind == Expr::NPCK_ZeroExpression) 6856 return false; 6857 6858 if (NullKind == Expr::NPCK_ZeroLiteral) { 6859 // In this case, check to make sure that we got here from a "NULL" 6860 // string in the source code. 6861 NullExpr = NullExpr->IgnoreParenImpCasts(); 6862 SourceLocation loc = NullExpr->getExprLoc(); 6863 if (!findMacroSpelling(loc, "NULL")) 6864 return false; 6865 } 6866 6867 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6868 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6869 << NonPointerExpr->getType() << DiagType 6870 << NonPointerExpr->getSourceRange(); 6871 return true; 6872 } 6873 6874 /// Return false if the condition expression is valid, true otherwise. 6875 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6876 QualType CondTy = Cond->getType(); 6877 6878 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6879 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6880 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6881 << CondTy << Cond->getSourceRange(); 6882 return true; 6883 } 6884 6885 // C99 6.5.15p2 6886 if (CondTy->isScalarType()) return false; 6887 6888 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6889 << CondTy << Cond->getSourceRange(); 6890 return true; 6891 } 6892 6893 /// Handle when one or both operands are void type. 6894 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6895 ExprResult &RHS) { 6896 Expr *LHSExpr = LHS.get(); 6897 Expr *RHSExpr = RHS.get(); 6898 6899 if (!LHSExpr->getType()->isVoidType()) 6900 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 6901 << RHSExpr->getSourceRange(); 6902 if (!RHSExpr->getType()->isVoidType()) 6903 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 6904 << LHSExpr->getSourceRange(); 6905 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6906 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6907 return S.Context.VoidTy; 6908 } 6909 6910 /// Return false if the NullExpr can be promoted to PointerTy, 6911 /// true otherwise. 6912 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6913 QualType PointerTy) { 6914 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6915 !NullExpr.get()->isNullPointerConstant(S.Context, 6916 Expr::NPC_ValueDependentIsNull)) 6917 return true; 6918 6919 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6920 return false; 6921 } 6922 6923 /// Checks compatibility between two pointers and return the resulting 6924 /// type. 6925 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6926 ExprResult &RHS, 6927 SourceLocation Loc) { 6928 QualType LHSTy = LHS.get()->getType(); 6929 QualType RHSTy = RHS.get()->getType(); 6930 6931 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6932 // Two identical pointers types are always compatible. 6933 return LHSTy; 6934 } 6935 6936 QualType lhptee, rhptee; 6937 6938 // Get the pointee types. 6939 bool IsBlockPointer = false; 6940 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6941 lhptee = LHSBTy->getPointeeType(); 6942 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6943 IsBlockPointer = true; 6944 } else { 6945 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6946 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6947 } 6948 6949 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6950 // differently qualified versions of compatible types, the result type is 6951 // a pointer to an appropriately qualified version of the composite 6952 // type. 6953 6954 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6955 // clause doesn't make sense for our extensions. E.g. address space 2 should 6956 // be incompatible with address space 3: they may live on different devices or 6957 // anything. 6958 Qualifiers lhQual = lhptee.getQualifiers(); 6959 Qualifiers rhQual = rhptee.getQualifiers(); 6960 6961 LangAS ResultAddrSpace = LangAS::Default; 6962 LangAS LAddrSpace = lhQual.getAddressSpace(); 6963 LangAS RAddrSpace = rhQual.getAddressSpace(); 6964 6965 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 6966 // spaces is disallowed. 6967 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 6968 ResultAddrSpace = LAddrSpace; 6969 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 6970 ResultAddrSpace = RAddrSpace; 6971 else { 6972 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 6973 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 6974 << RHS.get()->getSourceRange(); 6975 return QualType(); 6976 } 6977 6978 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6979 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 6980 lhQual.removeCVRQualifiers(); 6981 rhQual.removeCVRQualifiers(); 6982 6983 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 6984 // (C99 6.7.3) for address spaces. We assume that the check should behave in 6985 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 6986 // qual types are compatible iff 6987 // * corresponded types are compatible 6988 // * CVR qualifiers are equal 6989 // * address spaces are equal 6990 // Thus for conditional operator we merge CVR and address space unqualified 6991 // pointees and if there is a composite type we return a pointer to it with 6992 // merged qualifiers. 6993 LHSCastKind = 6994 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 6995 RHSCastKind = 6996 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 6997 lhQual.removeAddressSpace(); 6998 rhQual.removeAddressSpace(); 6999 7000 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 7001 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 7002 7003 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 7004 7005 if (CompositeTy.isNull()) { 7006 // In this situation, we assume void* type. No especially good 7007 // reason, but this is what gcc does, and we do have to pick 7008 // to get a consistent AST. 7009 QualType incompatTy; 7010 incompatTy = S.Context.getPointerType( 7011 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 7012 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 7013 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 7014 7015 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 7016 // for casts between types with incompatible address space qualifiers. 7017 // For the following code the compiler produces casts between global and 7018 // local address spaces of the corresponded innermost pointees: 7019 // local int *global *a; 7020 // global int *global *b; 7021 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 7022 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 7023 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7024 << RHS.get()->getSourceRange(); 7025 7026 return incompatTy; 7027 } 7028 7029 // The pointer types are compatible. 7030 // In case of OpenCL ResultTy should have the address space qualifier 7031 // which is a superset of address spaces of both the 2nd and the 3rd 7032 // operands of the conditional operator. 7033 QualType ResultTy = [&, ResultAddrSpace]() { 7034 if (S.getLangOpts().OpenCL) { 7035 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 7036 CompositeQuals.setAddressSpace(ResultAddrSpace); 7037 return S.Context 7038 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 7039 .withCVRQualifiers(MergedCVRQual); 7040 } 7041 return CompositeTy.withCVRQualifiers(MergedCVRQual); 7042 }(); 7043 if (IsBlockPointer) 7044 ResultTy = S.Context.getBlockPointerType(ResultTy); 7045 else 7046 ResultTy = S.Context.getPointerType(ResultTy); 7047 7048 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 7049 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 7050 return ResultTy; 7051 } 7052 7053 /// Return the resulting type when the operands are both block pointers. 7054 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 7055 ExprResult &LHS, 7056 ExprResult &RHS, 7057 SourceLocation Loc) { 7058 QualType LHSTy = LHS.get()->getType(); 7059 QualType RHSTy = RHS.get()->getType(); 7060 7061 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 7062 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 7063 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 7064 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7065 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7066 return destType; 7067 } 7068 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 7069 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7070 << RHS.get()->getSourceRange(); 7071 return QualType(); 7072 } 7073 7074 // We have 2 block pointer types. 7075 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7076 } 7077 7078 /// Return the resulting type when the operands are both pointers. 7079 static QualType 7080 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 7081 ExprResult &RHS, 7082 SourceLocation Loc) { 7083 // get the pointer types 7084 QualType LHSTy = LHS.get()->getType(); 7085 QualType RHSTy = RHS.get()->getType(); 7086 7087 // get the "pointed to" types 7088 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7089 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7090 7091 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 7092 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 7093 // Figure out necessary qualifiers (C99 6.5.15p6) 7094 QualType destPointee 7095 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7096 QualType destType = S.Context.getPointerType(destPointee); 7097 // Add qualifiers if necessary. 7098 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7099 // Promote to void*. 7100 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7101 return destType; 7102 } 7103 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 7104 QualType destPointee 7105 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7106 QualType destType = S.Context.getPointerType(destPointee); 7107 // Add qualifiers if necessary. 7108 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7109 // Promote to void*. 7110 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7111 return destType; 7112 } 7113 7114 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7115 } 7116 7117 /// Return false if the first expression is not an integer and the second 7118 /// expression is not a pointer, true otherwise. 7119 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 7120 Expr* PointerExpr, SourceLocation Loc, 7121 bool IsIntFirstExpr) { 7122 if (!PointerExpr->getType()->isPointerType() || 7123 !Int.get()->getType()->isIntegerType()) 7124 return false; 7125 7126 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 7127 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 7128 7129 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 7130 << Expr1->getType() << Expr2->getType() 7131 << Expr1->getSourceRange() << Expr2->getSourceRange(); 7132 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 7133 CK_IntegralToPointer); 7134 return true; 7135 } 7136 7137 /// Simple conversion between integer and floating point types. 7138 /// 7139 /// Used when handling the OpenCL conditional operator where the 7140 /// condition is a vector while the other operands are scalar. 7141 /// 7142 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 7143 /// types are either integer or floating type. Between the two 7144 /// operands, the type with the higher rank is defined as the "result 7145 /// type". The other operand needs to be promoted to the same type. No 7146 /// other type promotion is allowed. We cannot use 7147 /// UsualArithmeticConversions() for this purpose, since it always 7148 /// promotes promotable types. 7149 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 7150 ExprResult &RHS, 7151 SourceLocation QuestionLoc) { 7152 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 7153 if (LHS.isInvalid()) 7154 return QualType(); 7155 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 7156 if (RHS.isInvalid()) 7157 return QualType(); 7158 7159 // For conversion purposes, we ignore any qualifiers. 7160 // For example, "const float" and "float" are equivalent. 7161 QualType LHSType = 7162 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 7163 QualType RHSType = 7164 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 7165 7166 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 7167 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7168 << LHSType << LHS.get()->getSourceRange(); 7169 return QualType(); 7170 } 7171 7172 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 7173 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7174 << RHSType << RHS.get()->getSourceRange(); 7175 return QualType(); 7176 } 7177 7178 // If both types are identical, no conversion is needed. 7179 if (LHSType == RHSType) 7180 return LHSType; 7181 7182 // Now handle "real" floating types (i.e. float, double, long double). 7183 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 7184 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 7185 /*IsCompAssign = */ false); 7186 7187 // Finally, we have two differing integer types. 7188 return handleIntegerConversion<doIntegralCast, doIntegralCast> 7189 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 7190 } 7191 7192 /// Convert scalar operands to a vector that matches the 7193 /// condition in length. 7194 /// 7195 /// Used when handling the OpenCL conditional operator where the 7196 /// condition is a vector while the other operands are scalar. 7197 /// 7198 /// We first compute the "result type" for the scalar operands 7199 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 7200 /// into a vector of that type where the length matches the condition 7201 /// vector type. s6.11.6 requires that the element types of the result 7202 /// and the condition must have the same number of bits. 7203 static QualType 7204 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 7205 QualType CondTy, SourceLocation QuestionLoc) { 7206 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 7207 if (ResTy.isNull()) return QualType(); 7208 7209 const VectorType *CV = CondTy->getAs<VectorType>(); 7210 assert(CV); 7211 7212 // Determine the vector result type 7213 unsigned NumElements = CV->getNumElements(); 7214 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 7215 7216 // Ensure that all types have the same number of bits 7217 if (S.Context.getTypeSize(CV->getElementType()) 7218 != S.Context.getTypeSize(ResTy)) { 7219 // Since VectorTy is created internally, it does not pretty print 7220 // with an OpenCL name. Instead, we just print a description. 7221 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 7222 SmallString<64> Str; 7223 llvm::raw_svector_ostream OS(Str); 7224 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 7225 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 7226 << CondTy << OS.str(); 7227 return QualType(); 7228 } 7229 7230 // Convert operands to the vector result type 7231 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 7232 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 7233 7234 return VectorTy; 7235 } 7236 7237 /// Return false if this is a valid OpenCL condition vector 7238 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 7239 SourceLocation QuestionLoc) { 7240 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 7241 // integral type. 7242 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 7243 assert(CondTy); 7244 QualType EleTy = CondTy->getElementType(); 7245 if (EleTy->isIntegerType()) return false; 7246 7247 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7248 << Cond->getType() << Cond->getSourceRange(); 7249 return true; 7250 } 7251 7252 /// Return false if the vector condition type and the vector 7253 /// result type are compatible. 7254 /// 7255 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 7256 /// number of elements, and their element types have the same number 7257 /// of bits. 7258 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 7259 SourceLocation QuestionLoc) { 7260 const VectorType *CV = CondTy->getAs<VectorType>(); 7261 const VectorType *RV = VecResTy->getAs<VectorType>(); 7262 assert(CV && RV); 7263 7264 if (CV->getNumElements() != RV->getNumElements()) { 7265 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 7266 << CondTy << VecResTy; 7267 return true; 7268 } 7269 7270 QualType CVE = CV->getElementType(); 7271 QualType RVE = RV->getElementType(); 7272 7273 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 7274 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 7275 << CondTy << VecResTy; 7276 return true; 7277 } 7278 7279 return false; 7280 } 7281 7282 /// Return the resulting type for the conditional operator in 7283 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 7284 /// s6.3.i) when the condition is a vector type. 7285 static QualType 7286 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 7287 ExprResult &LHS, ExprResult &RHS, 7288 SourceLocation QuestionLoc) { 7289 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 7290 if (Cond.isInvalid()) 7291 return QualType(); 7292 QualType CondTy = Cond.get()->getType(); 7293 7294 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 7295 return QualType(); 7296 7297 // If either operand is a vector then find the vector type of the 7298 // result as specified in OpenCL v1.1 s6.3.i. 7299 if (LHS.get()->getType()->isVectorType() || 7300 RHS.get()->getType()->isVectorType()) { 7301 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 7302 /*isCompAssign*/false, 7303 /*AllowBothBool*/true, 7304 /*AllowBoolConversions*/false); 7305 if (VecResTy.isNull()) return QualType(); 7306 // The result type must match the condition type as specified in 7307 // OpenCL v1.1 s6.11.6. 7308 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 7309 return QualType(); 7310 return VecResTy; 7311 } 7312 7313 // Both operands are scalar. 7314 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 7315 } 7316 7317 /// Return true if the Expr is block type 7318 static bool checkBlockType(Sema &S, const Expr *E) { 7319 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 7320 QualType Ty = CE->getCallee()->getType(); 7321 if (Ty->isBlockPointerType()) { 7322 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 7323 return true; 7324 } 7325 } 7326 return false; 7327 } 7328 7329 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 7330 /// In that case, LHS = cond. 7331 /// C99 6.5.15 7332 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 7333 ExprResult &RHS, ExprValueKind &VK, 7334 ExprObjectKind &OK, 7335 SourceLocation QuestionLoc) { 7336 7337 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 7338 if (!LHSResult.isUsable()) return QualType(); 7339 LHS = LHSResult; 7340 7341 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 7342 if (!RHSResult.isUsable()) return QualType(); 7343 RHS = RHSResult; 7344 7345 // C++ is sufficiently different to merit its own checker. 7346 if (getLangOpts().CPlusPlus) 7347 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 7348 7349 VK = VK_RValue; 7350 OK = OK_Ordinary; 7351 7352 // The OpenCL operator with a vector condition is sufficiently 7353 // different to merit its own checker. 7354 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 7355 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 7356 7357 // First, check the condition. 7358 Cond = UsualUnaryConversions(Cond.get()); 7359 if (Cond.isInvalid()) 7360 return QualType(); 7361 if (checkCondition(*this, Cond.get(), QuestionLoc)) 7362 return QualType(); 7363 7364 // Now check the two expressions. 7365 if (LHS.get()->getType()->isVectorType() || 7366 RHS.get()->getType()->isVectorType()) 7367 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 7368 /*AllowBothBool*/true, 7369 /*AllowBoolConversions*/false); 7370 7371 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 7372 if (LHS.isInvalid() || RHS.isInvalid()) 7373 return QualType(); 7374 7375 QualType LHSTy = LHS.get()->getType(); 7376 QualType RHSTy = RHS.get()->getType(); 7377 7378 // Diagnose attempts to convert between __float128 and long double where 7379 // such conversions currently can't be handled. 7380 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 7381 Diag(QuestionLoc, 7382 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 7383 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7384 return QualType(); 7385 } 7386 7387 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 7388 // selection operator (?:). 7389 if (getLangOpts().OpenCL && 7390 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 7391 return QualType(); 7392 } 7393 7394 // If both operands have arithmetic type, do the usual arithmetic conversions 7395 // to find a common type: C99 6.5.15p3,5. 7396 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 7397 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 7398 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 7399 7400 return ResTy; 7401 } 7402 7403 // If both operands are the same structure or union type, the result is that 7404 // type. 7405 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 7406 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 7407 if (LHSRT->getDecl() == RHSRT->getDecl()) 7408 // "If both the operands have structure or union type, the result has 7409 // that type." This implies that CV qualifiers are dropped. 7410 return LHSTy.getUnqualifiedType(); 7411 // FIXME: Type of conditional expression must be complete in C mode. 7412 } 7413 7414 // C99 6.5.15p5: "If both operands have void type, the result has void type." 7415 // The following || allows only one side to be void (a GCC-ism). 7416 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 7417 return checkConditionalVoidType(*this, LHS, RHS); 7418 } 7419 7420 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 7421 // the type of the other operand." 7422 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 7423 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 7424 7425 // All objective-c pointer type analysis is done here. 7426 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 7427 QuestionLoc); 7428 if (LHS.isInvalid() || RHS.isInvalid()) 7429 return QualType(); 7430 if (!compositeType.isNull()) 7431 return compositeType; 7432 7433 7434 // Handle block pointer types. 7435 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 7436 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 7437 QuestionLoc); 7438 7439 // Check constraints for C object pointers types (C99 6.5.15p3,6). 7440 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 7441 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 7442 QuestionLoc); 7443 7444 // GCC compatibility: soften pointer/integer mismatch. Note that 7445 // null pointers have been filtered out by this point. 7446 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 7447 /*IsIntFirstExpr=*/true)) 7448 return RHSTy; 7449 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 7450 /*IsIntFirstExpr=*/false)) 7451 return LHSTy; 7452 7453 // Emit a better diagnostic if one of the expressions is a null pointer 7454 // constant and the other is not a pointer type. In this case, the user most 7455 // likely forgot to take the address of the other expression. 7456 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 7457 return QualType(); 7458 7459 // Otherwise, the operands are not compatible. 7460 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 7461 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7462 << RHS.get()->getSourceRange(); 7463 return QualType(); 7464 } 7465 7466 /// FindCompositeObjCPointerType - Helper method to find composite type of 7467 /// two objective-c pointer types of the two input expressions. 7468 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 7469 SourceLocation QuestionLoc) { 7470 QualType LHSTy = LHS.get()->getType(); 7471 QualType RHSTy = RHS.get()->getType(); 7472 7473 // Handle things like Class and struct objc_class*. Here we case the result 7474 // to the pseudo-builtin, because that will be implicitly cast back to the 7475 // redefinition type if an attempt is made to access its fields. 7476 if (LHSTy->isObjCClassType() && 7477 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 7478 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 7479 return LHSTy; 7480 } 7481 if (RHSTy->isObjCClassType() && 7482 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 7483 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 7484 return RHSTy; 7485 } 7486 // And the same for struct objc_object* / id 7487 if (LHSTy->isObjCIdType() && 7488 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 7489 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 7490 return LHSTy; 7491 } 7492 if (RHSTy->isObjCIdType() && 7493 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 7494 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 7495 return RHSTy; 7496 } 7497 // And the same for struct objc_selector* / SEL 7498 if (Context.isObjCSelType(LHSTy) && 7499 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 7500 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 7501 return LHSTy; 7502 } 7503 if (Context.isObjCSelType(RHSTy) && 7504 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 7505 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 7506 return RHSTy; 7507 } 7508 // Check constraints for Objective-C object pointers types. 7509 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 7510 7511 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 7512 // Two identical object pointer types are always compatible. 7513 return LHSTy; 7514 } 7515 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 7516 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 7517 QualType compositeType = LHSTy; 7518 7519 // If both operands are interfaces and either operand can be 7520 // assigned to the other, use that type as the composite 7521 // type. This allows 7522 // xxx ? (A*) a : (B*) b 7523 // where B is a subclass of A. 7524 // 7525 // Additionally, as for assignment, if either type is 'id' 7526 // allow silent coercion. Finally, if the types are 7527 // incompatible then make sure to use 'id' as the composite 7528 // type so the result is acceptable for sending messages to. 7529 7530 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 7531 // It could return the composite type. 7532 if (!(compositeType = 7533 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 7534 // Nothing more to do. 7535 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 7536 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 7537 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 7538 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 7539 } else if ((LHSOPT->isObjCQualifiedIdType() || 7540 RHSOPT->isObjCQualifiedIdType()) && 7541 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 7542 true)) { 7543 // Need to handle "id<xx>" explicitly. 7544 // GCC allows qualified id and any Objective-C type to devolve to 7545 // id. Currently localizing to here until clear this should be 7546 // part of ObjCQualifiedIdTypesAreCompatible. 7547 compositeType = Context.getObjCIdType(); 7548 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 7549 compositeType = Context.getObjCIdType(); 7550 } else { 7551 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 7552 << LHSTy << RHSTy 7553 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7554 QualType incompatTy = Context.getObjCIdType(); 7555 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 7556 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 7557 return incompatTy; 7558 } 7559 // The object pointer types are compatible. 7560 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 7561 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 7562 return compositeType; 7563 } 7564 // Check Objective-C object pointer types and 'void *' 7565 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 7566 if (getLangOpts().ObjCAutoRefCount) { 7567 // ARC forbids the implicit conversion of object pointers to 'void *', 7568 // so these types are not compatible. 7569 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7570 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7571 LHS = RHS = true; 7572 return QualType(); 7573 } 7574 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7575 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 7576 QualType destPointee 7577 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7578 QualType destType = Context.getPointerType(destPointee); 7579 // Add qualifiers if necessary. 7580 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7581 // Promote to void*. 7582 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7583 return destType; 7584 } 7585 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 7586 if (getLangOpts().ObjCAutoRefCount) { 7587 // ARC forbids the implicit conversion of object pointers to 'void *', 7588 // so these types are not compatible. 7589 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7590 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7591 LHS = RHS = true; 7592 return QualType(); 7593 } 7594 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 7595 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7596 QualType destPointee 7597 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7598 QualType destType = Context.getPointerType(destPointee); 7599 // Add qualifiers if necessary. 7600 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7601 // Promote to void*. 7602 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7603 return destType; 7604 } 7605 return QualType(); 7606 } 7607 7608 /// SuggestParentheses - Emit a note with a fixit hint that wraps 7609 /// ParenRange in parentheses. 7610 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 7611 const PartialDiagnostic &Note, 7612 SourceRange ParenRange) { 7613 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 7614 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 7615 EndLoc.isValid()) { 7616 Self.Diag(Loc, Note) 7617 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 7618 << FixItHint::CreateInsertion(EndLoc, ")"); 7619 } else { 7620 // We can't display the parentheses, so just show the bare note. 7621 Self.Diag(Loc, Note) << ParenRange; 7622 } 7623 } 7624 7625 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 7626 return BinaryOperator::isAdditiveOp(Opc) || 7627 BinaryOperator::isMultiplicativeOp(Opc) || 7628 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 7629 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 7630 // not any of the logical operators. Bitwise-xor is commonly used as a 7631 // logical-xor because there is no logical-xor operator. The logical 7632 // operators, including uses of xor, have a high false positive rate for 7633 // precedence warnings. 7634 } 7635 7636 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 7637 /// expression, either using a built-in or overloaded operator, 7638 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 7639 /// expression. 7640 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 7641 Expr **RHSExprs) { 7642 // Don't strip parenthesis: we should not warn if E is in parenthesis. 7643 E = E->IgnoreImpCasts(); 7644 E = E->IgnoreConversionOperator(); 7645 E = E->IgnoreImpCasts(); 7646 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 7647 E = MTE->GetTemporaryExpr(); 7648 E = E->IgnoreImpCasts(); 7649 } 7650 7651 // Built-in binary operator. 7652 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 7653 if (IsArithmeticOp(OP->getOpcode())) { 7654 *Opcode = OP->getOpcode(); 7655 *RHSExprs = OP->getRHS(); 7656 return true; 7657 } 7658 } 7659 7660 // Overloaded operator. 7661 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 7662 if (Call->getNumArgs() != 2) 7663 return false; 7664 7665 // Make sure this is really a binary operator that is safe to pass into 7666 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 7667 OverloadedOperatorKind OO = Call->getOperator(); 7668 if (OO < OO_Plus || OO > OO_Arrow || 7669 OO == OO_PlusPlus || OO == OO_MinusMinus) 7670 return false; 7671 7672 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 7673 if (IsArithmeticOp(OpKind)) { 7674 *Opcode = OpKind; 7675 *RHSExprs = Call->getArg(1); 7676 return true; 7677 } 7678 } 7679 7680 return false; 7681 } 7682 7683 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 7684 /// or is a logical expression such as (x==y) which has int type, but is 7685 /// commonly interpreted as boolean. 7686 static bool ExprLooksBoolean(Expr *E) { 7687 E = E->IgnoreParenImpCasts(); 7688 7689 if (E->getType()->isBooleanType()) 7690 return true; 7691 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 7692 return OP->isComparisonOp() || OP->isLogicalOp(); 7693 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 7694 return OP->getOpcode() == UO_LNot; 7695 if (E->getType()->isPointerType()) 7696 return true; 7697 // FIXME: What about overloaded operator calls returning "unspecified boolean 7698 // type"s (commonly pointer-to-members)? 7699 7700 return false; 7701 } 7702 7703 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 7704 /// and binary operator are mixed in a way that suggests the programmer assumed 7705 /// the conditional operator has higher precedence, for example: 7706 /// "int x = a + someBinaryCondition ? 1 : 2". 7707 static void DiagnoseConditionalPrecedence(Sema &Self, 7708 SourceLocation OpLoc, 7709 Expr *Condition, 7710 Expr *LHSExpr, 7711 Expr *RHSExpr) { 7712 BinaryOperatorKind CondOpcode; 7713 Expr *CondRHS; 7714 7715 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 7716 return; 7717 if (!ExprLooksBoolean(CondRHS)) 7718 return; 7719 7720 // The condition is an arithmetic binary expression, with a right- 7721 // hand side that looks boolean, so warn. 7722 7723 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 7724 ? diag::warn_precedence_bitwise_conditional 7725 : diag::warn_precedence_conditional; 7726 7727 Self.Diag(OpLoc, DiagID) 7728 << Condition->getSourceRange() 7729 << BinaryOperator::getOpcodeStr(CondOpcode); 7730 7731 SuggestParentheses( 7732 Self, OpLoc, 7733 Self.PDiag(diag::note_precedence_silence) 7734 << BinaryOperator::getOpcodeStr(CondOpcode), 7735 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 7736 7737 SuggestParentheses(Self, OpLoc, 7738 Self.PDiag(diag::note_precedence_conditional_first), 7739 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 7740 } 7741 7742 /// Compute the nullability of a conditional expression. 7743 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 7744 QualType LHSTy, QualType RHSTy, 7745 ASTContext &Ctx) { 7746 if (!ResTy->isAnyPointerType()) 7747 return ResTy; 7748 7749 auto GetNullability = [&Ctx](QualType Ty) { 7750 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 7751 if (Kind) 7752 return *Kind; 7753 return NullabilityKind::Unspecified; 7754 }; 7755 7756 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 7757 NullabilityKind MergedKind; 7758 7759 // Compute nullability of a binary conditional expression. 7760 if (IsBin) { 7761 if (LHSKind == NullabilityKind::NonNull) 7762 MergedKind = NullabilityKind::NonNull; 7763 else 7764 MergedKind = RHSKind; 7765 // Compute nullability of a normal conditional expression. 7766 } else { 7767 if (LHSKind == NullabilityKind::Nullable || 7768 RHSKind == NullabilityKind::Nullable) 7769 MergedKind = NullabilityKind::Nullable; 7770 else if (LHSKind == NullabilityKind::NonNull) 7771 MergedKind = RHSKind; 7772 else if (RHSKind == NullabilityKind::NonNull) 7773 MergedKind = LHSKind; 7774 else 7775 MergedKind = NullabilityKind::Unspecified; 7776 } 7777 7778 // Return if ResTy already has the correct nullability. 7779 if (GetNullability(ResTy) == MergedKind) 7780 return ResTy; 7781 7782 // Strip all nullability from ResTy. 7783 while (ResTy->getNullability(Ctx)) 7784 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 7785 7786 // Create a new AttributedType with the new nullability kind. 7787 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 7788 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 7789 } 7790 7791 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7792 /// in the case of a the GNU conditional expr extension. 7793 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7794 SourceLocation ColonLoc, 7795 Expr *CondExpr, Expr *LHSExpr, 7796 Expr *RHSExpr) { 7797 if (!getLangOpts().CPlusPlus) { 7798 // C cannot handle TypoExpr nodes in the condition because it 7799 // doesn't handle dependent types properly, so make sure any TypoExprs have 7800 // been dealt with before checking the operands. 7801 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7802 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7803 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7804 7805 if (!CondResult.isUsable()) 7806 return ExprError(); 7807 7808 if (LHSExpr) { 7809 if (!LHSResult.isUsable()) 7810 return ExprError(); 7811 } 7812 7813 if (!RHSResult.isUsable()) 7814 return ExprError(); 7815 7816 CondExpr = CondResult.get(); 7817 LHSExpr = LHSResult.get(); 7818 RHSExpr = RHSResult.get(); 7819 } 7820 7821 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7822 // was the condition. 7823 OpaqueValueExpr *opaqueValue = nullptr; 7824 Expr *commonExpr = nullptr; 7825 if (!LHSExpr) { 7826 commonExpr = CondExpr; 7827 // Lower out placeholder types first. This is important so that we don't 7828 // try to capture a placeholder. This happens in few cases in C++; such 7829 // as Objective-C++'s dictionary subscripting syntax. 7830 if (commonExpr->hasPlaceholderType()) { 7831 ExprResult result = CheckPlaceholderExpr(commonExpr); 7832 if (!result.isUsable()) return ExprError(); 7833 commonExpr = result.get(); 7834 } 7835 // We usually want to apply unary conversions *before* saving, except 7836 // in the special case of a C++ l-value conditional. 7837 if (!(getLangOpts().CPlusPlus 7838 && !commonExpr->isTypeDependent() 7839 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7840 && commonExpr->isGLValue() 7841 && commonExpr->isOrdinaryOrBitFieldObject() 7842 && RHSExpr->isOrdinaryOrBitFieldObject() 7843 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7844 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7845 if (commonRes.isInvalid()) 7846 return ExprError(); 7847 commonExpr = commonRes.get(); 7848 } 7849 7850 // If the common expression is a class or array prvalue, materialize it 7851 // so that we can safely refer to it multiple times. 7852 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 7853 commonExpr->getType()->isArrayType())) { 7854 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 7855 if (MatExpr.isInvalid()) 7856 return ExprError(); 7857 commonExpr = MatExpr.get(); 7858 } 7859 7860 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7861 commonExpr->getType(), 7862 commonExpr->getValueKind(), 7863 commonExpr->getObjectKind(), 7864 commonExpr); 7865 LHSExpr = CondExpr = opaqueValue; 7866 } 7867 7868 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 7869 ExprValueKind VK = VK_RValue; 7870 ExprObjectKind OK = OK_Ordinary; 7871 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7872 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7873 VK, OK, QuestionLoc); 7874 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7875 RHS.isInvalid()) 7876 return ExprError(); 7877 7878 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7879 RHS.get()); 7880 7881 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 7882 7883 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 7884 Context); 7885 7886 if (!commonExpr) 7887 return new (Context) 7888 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 7889 RHS.get(), result, VK, OK); 7890 7891 return new (Context) BinaryConditionalOperator( 7892 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 7893 ColonLoc, result, VK, OK); 7894 } 7895 7896 // checkPointerTypesForAssignment - This is a very tricky routine (despite 7897 // being closely modeled after the C99 spec:-). The odd characteristic of this 7898 // routine is it effectively iqnores the qualifiers on the top level pointee. 7899 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 7900 // FIXME: add a couple examples in this comment. 7901 static Sema::AssignConvertType 7902 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 7903 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7904 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7905 7906 // get the "pointed to" type (ignoring qualifiers at the top level) 7907 const Type *lhptee, *rhptee; 7908 Qualifiers lhq, rhq; 7909 std::tie(lhptee, lhq) = 7910 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 7911 std::tie(rhptee, rhq) = 7912 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 7913 7914 Sema::AssignConvertType ConvTy = Sema::Compatible; 7915 7916 // C99 6.5.16.1p1: This following citation is common to constraints 7917 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 7918 // qualifiers of the type *pointed to* by the right; 7919 7920 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 7921 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 7922 lhq.compatiblyIncludesObjCLifetime(rhq)) { 7923 // Ignore lifetime for further calculation. 7924 lhq.removeObjCLifetime(); 7925 rhq.removeObjCLifetime(); 7926 } 7927 7928 if (!lhq.compatiblyIncludes(rhq)) { 7929 // Treat address-space mismatches as fatal. 7930 if (!lhq.isAddressSpaceSupersetOf(rhq)) 7931 return Sema::IncompatiblePointerDiscardsQualifiers; 7932 7933 // It's okay to add or remove GC or lifetime qualifiers when converting to 7934 // and from void*. 7935 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 7936 .compatiblyIncludes( 7937 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 7938 && (lhptee->isVoidType() || rhptee->isVoidType())) 7939 ; // keep old 7940 7941 // Treat lifetime mismatches as fatal. 7942 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 7943 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7944 7945 // For GCC/MS compatibility, other qualifier mismatches are treated 7946 // as still compatible in C. 7947 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7948 } 7949 7950 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 7951 // incomplete type and the other is a pointer to a qualified or unqualified 7952 // version of void... 7953 if (lhptee->isVoidType()) { 7954 if (rhptee->isIncompleteOrObjectType()) 7955 return ConvTy; 7956 7957 // As an extension, we allow cast to/from void* to function pointer. 7958 assert(rhptee->isFunctionType()); 7959 return Sema::FunctionVoidPointer; 7960 } 7961 7962 if (rhptee->isVoidType()) { 7963 if (lhptee->isIncompleteOrObjectType()) 7964 return ConvTy; 7965 7966 // As an extension, we allow cast to/from void* to function pointer. 7967 assert(lhptee->isFunctionType()); 7968 return Sema::FunctionVoidPointer; 7969 } 7970 7971 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7972 // unqualified versions of compatible types, ... 7973 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7974 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7975 // Check if the pointee types are compatible ignoring the sign. 7976 // We explicitly check for char so that we catch "char" vs 7977 // "unsigned char" on systems where "char" is unsigned. 7978 if (lhptee->isCharType()) 7979 ltrans = S.Context.UnsignedCharTy; 7980 else if (lhptee->hasSignedIntegerRepresentation()) 7981 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7982 7983 if (rhptee->isCharType()) 7984 rtrans = S.Context.UnsignedCharTy; 7985 else if (rhptee->hasSignedIntegerRepresentation()) 7986 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 7987 7988 if (ltrans == rtrans) { 7989 // Types are compatible ignoring the sign. Qualifier incompatibility 7990 // takes priority over sign incompatibility because the sign 7991 // warning can be disabled. 7992 if (ConvTy != Sema::Compatible) 7993 return ConvTy; 7994 7995 return Sema::IncompatiblePointerSign; 7996 } 7997 7998 // If we are a multi-level pointer, it's possible that our issue is simply 7999 // one of qualification - e.g. char ** -> const char ** is not allowed. If 8000 // the eventual target type is the same and the pointers have the same 8001 // level of indirection, this must be the issue. 8002 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 8003 do { 8004 std::tie(lhptee, lhq) = 8005 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 8006 std::tie(rhptee, rhq) = 8007 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 8008 8009 // Inconsistent address spaces at this point is invalid, even if the 8010 // address spaces would be compatible. 8011 // FIXME: This doesn't catch address space mismatches for pointers of 8012 // different nesting levels, like: 8013 // __local int *** a; 8014 // int ** b = a; 8015 // It's not clear how to actually determine when such pointers are 8016 // invalidly incompatible. 8017 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 8018 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 8019 8020 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 8021 8022 if (lhptee == rhptee) 8023 return Sema::IncompatibleNestedPointerQualifiers; 8024 } 8025 8026 // General pointer incompatibility takes priority over qualifiers. 8027 return Sema::IncompatiblePointer; 8028 } 8029 if (!S.getLangOpts().CPlusPlus && 8030 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 8031 return Sema::IncompatiblePointer; 8032 return ConvTy; 8033 } 8034 8035 /// checkBlockPointerTypesForAssignment - This routine determines whether two 8036 /// block pointer types are compatible or whether a block and normal pointer 8037 /// are compatible. It is more restrict than comparing two function pointer 8038 // types. 8039 static Sema::AssignConvertType 8040 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 8041 QualType RHSType) { 8042 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8043 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8044 8045 QualType lhptee, rhptee; 8046 8047 // get the "pointed to" type (ignoring qualifiers at the top level) 8048 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 8049 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 8050 8051 // In C++, the types have to match exactly. 8052 if (S.getLangOpts().CPlusPlus) 8053 return Sema::IncompatibleBlockPointer; 8054 8055 Sema::AssignConvertType ConvTy = Sema::Compatible; 8056 8057 // For blocks we enforce that qualifiers are identical. 8058 Qualifiers LQuals = lhptee.getLocalQualifiers(); 8059 Qualifiers RQuals = rhptee.getLocalQualifiers(); 8060 if (S.getLangOpts().OpenCL) { 8061 LQuals.removeAddressSpace(); 8062 RQuals.removeAddressSpace(); 8063 } 8064 if (LQuals != RQuals) 8065 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8066 8067 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 8068 // assignment. 8069 // The current behavior is similar to C++ lambdas. A block might be 8070 // assigned to a variable iff its return type and parameters are compatible 8071 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 8072 // an assignment. Presumably it should behave in way that a function pointer 8073 // assignment does in C, so for each parameter and return type: 8074 // * CVR and address space of LHS should be a superset of CVR and address 8075 // space of RHS. 8076 // * unqualified types should be compatible. 8077 if (S.getLangOpts().OpenCL) { 8078 if (!S.Context.typesAreBlockPointerCompatible( 8079 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 8080 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 8081 return Sema::IncompatibleBlockPointer; 8082 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 8083 return Sema::IncompatibleBlockPointer; 8084 8085 return ConvTy; 8086 } 8087 8088 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 8089 /// for assignment compatibility. 8090 static Sema::AssignConvertType 8091 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 8092 QualType RHSType) { 8093 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 8094 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 8095 8096 if (LHSType->isObjCBuiltinType()) { 8097 // Class is not compatible with ObjC object pointers. 8098 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 8099 !RHSType->isObjCQualifiedClassType()) 8100 return Sema::IncompatiblePointer; 8101 return Sema::Compatible; 8102 } 8103 if (RHSType->isObjCBuiltinType()) { 8104 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 8105 !LHSType->isObjCQualifiedClassType()) 8106 return Sema::IncompatiblePointer; 8107 return Sema::Compatible; 8108 } 8109 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8110 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8111 8112 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 8113 // make an exception for id<P> 8114 !LHSType->isObjCQualifiedIdType()) 8115 return Sema::CompatiblePointerDiscardsQualifiers; 8116 8117 if (S.Context.typesAreCompatible(LHSType, RHSType)) 8118 return Sema::Compatible; 8119 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 8120 return Sema::IncompatibleObjCQualifiedId; 8121 return Sema::IncompatiblePointer; 8122 } 8123 8124 Sema::AssignConvertType 8125 Sema::CheckAssignmentConstraints(SourceLocation Loc, 8126 QualType LHSType, QualType RHSType) { 8127 // Fake up an opaque expression. We don't actually care about what 8128 // cast operations are required, so if CheckAssignmentConstraints 8129 // adds casts to this they'll be wasted, but fortunately that doesn't 8130 // usually happen on valid code. 8131 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 8132 ExprResult RHSPtr = &RHSExpr; 8133 CastKind K; 8134 8135 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 8136 } 8137 8138 /// This helper function returns true if QT is a vector type that has element 8139 /// type ElementType. 8140 static bool isVector(QualType QT, QualType ElementType) { 8141 if (const VectorType *VT = QT->getAs<VectorType>()) 8142 return VT->getElementType() == ElementType; 8143 return false; 8144 } 8145 8146 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 8147 /// has code to accommodate several GCC extensions when type checking 8148 /// pointers. Here are some objectionable examples that GCC considers warnings: 8149 /// 8150 /// int a, *pint; 8151 /// short *pshort; 8152 /// struct foo *pfoo; 8153 /// 8154 /// pint = pshort; // warning: assignment from incompatible pointer type 8155 /// a = pint; // warning: assignment makes integer from pointer without a cast 8156 /// pint = a; // warning: assignment makes pointer from integer without a cast 8157 /// pint = pfoo; // warning: assignment from incompatible pointer type 8158 /// 8159 /// As a result, the code for dealing with pointers is more complex than the 8160 /// C99 spec dictates. 8161 /// 8162 /// Sets 'Kind' for any result kind except Incompatible. 8163 Sema::AssignConvertType 8164 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 8165 CastKind &Kind, bool ConvertRHS) { 8166 QualType RHSType = RHS.get()->getType(); 8167 QualType OrigLHSType = LHSType; 8168 8169 // Get canonical types. We're not formatting these types, just comparing 8170 // them. 8171 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 8172 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 8173 8174 // Common case: no conversion required. 8175 if (LHSType == RHSType) { 8176 Kind = CK_NoOp; 8177 return Compatible; 8178 } 8179 8180 // If we have an atomic type, try a non-atomic assignment, then just add an 8181 // atomic qualification step. 8182 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 8183 Sema::AssignConvertType result = 8184 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 8185 if (result != Compatible) 8186 return result; 8187 if (Kind != CK_NoOp && ConvertRHS) 8188 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 8189 Kind = CK_NonAtomicToAtomic; 8190 return Compatible; 8191 } 8192 8193 // If the left-hand side is a reference type, then we are in a 8194 // (rare!) case where we've allowed the use of references in C, 8195 // e.g., as a parameter type in a built-in function. In this case, 8196 // just make sure that the type referenced is compatible with the 8197 // right-hand side type. The caller is responsible for adjusting 8198 // LHSType so that the resulting expression does not have reference 8199 // type. 8200 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 8201 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 8202 Kind = CK_LValueBitCast; 8203 return Compatible; 8204 } 8205 return Incompatible; 8206 } 8207 8208 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 8209 // to the same ExtVector type. 8210 if (LHSType->isExtVectorType()) { 8211 if (RHSType->isExtVectorType()) 8212 return Incompatible; 8213 if (RHSType->isArithmeticType()) { 8214 // CK_VectorSplat does T -> vector T, so first cast to the element type. 8215 if (ConvertRHS) 8216 RHS = prepareVectorSplat(LHSType, RHS.get()); 8217 Kind = CK_VectorSplat; 8218 return Compatible; 8219 } 8220 } 8221 8222 // Conversions to or from vector type. 8223 if (LHSType->isVectorType() || RHSType->isVectorType()) { 8224 if (LHSType->isVectorType() && RHSType->isVectorType()) { 8225 // Allow assignments of an AltiVec vector type to an equivalent GCC 8226 // vector type and vice versa 8227 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8228 Kind = CK_BitCast; 8229 return Compatible; 8230 } 8231 8232 // If we are allowing lax vector conversions, and LHS and RHS are both 8233 // vectors, the total size only needs to be the same. This is a bitcast; 8234 // no bits are changed but the result type is different. 8235 if (isLaxVectorConversion(RHSType, LHSType)) { 8236 Kind = CK_BitCast; 8237 return IncompatibleVectors; 8238 } 8239 } 8240 8241 // When the RHS comes from another lax conversion (e.g. binops between 8242 // scalars and vectors) the result is canonicalized as a vector. When the 8243 // LHS is also a vector, the lax is allowed by the condition above. Handle 8244 // the case where LHS is a scalar. 8245 if (LHSType->isScalarType()) { 8246 const VectorType *VecType = RHSType->getAs<VectorType>(); 8247 if (VecType && VecType->getNumElements() == 1 && 8248 isLaxVectorConversion(RHSType, LHSType)) { 8249 ExprResult *VecExpr = &RHS; 8250 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 8251 Kind = CK_BitCast; 8252 return Compatible; 8253 } 8254 } 8255 8256 return Incompatible; 8257 } 8258 8259 // Diagnose attempts to convert between __float128 and long double where 8260 // such conversions currently can't be handled. 8261 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 8262 return Incompatible; 8263 8264 // Disallow assigning a _Complex to a real type in C++ mode since it simply 8265 // discards the imaginary part. 8266 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 8267 !LHSType->getAs<ComplexType>()) 8268 return Incompatible; 8269 8270 // Arithmetic conversions. 8271 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 8272 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 8273 if (ConvertRHS) 8274 Kind = PrepareScalarCast(RHS, LHSType); 8275 return Compatible; 8276 } 8277 8278 // Conversions to normal pointers. 8279 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 8280 // U* -> T* 8281 if (isa<PointerType>(RHSType)) { 8282 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 8283 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 8284 if (AddrSpaceL != AddrSpaceR) 8285 Kind = CK_AddressSpaceConversion; 8286 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 8287 Kind = CK_NoOp; 8288 else 8289 Kind = CK_BitCast; 8290 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 8291 } 8292 8293 // int -> T* 8294 if (RHSType->isIntegerType()) { 8295 Kind = CK_IntegralToPointer; // FIXME: null? 8296 return IntToPointer; 8297 } 8298 8299 // C pointers are not compatible with ObjC object pointers, 8300 // with two exceptions: 8301 if (isa<ObjCObjectPointerType>(RHSType)) { 8302 // - conversions to void* 8303 if (LHSPointer->getPointeeType()->isVoidType()) { 8304 Kind = CK_BitCast; 8305 return Compatible; 8306 } 8307 8308 // - conversions from 'Class' to the redefinition type 8309 if (RHSType->isObjCClassType() && 8310 Context.hasSameType(LHSType, 8311 Context.getObjCClassRedefinitionType())) { 8312 Kind = CK_BitCast; 8313 return Compatible; 8314 } 8315 8316 Kind = CK_BitCast; 8317 return IncompatiblePointer; 8318 } 8319 8320 // U^ -> void* 8321 if (RHSType->getAs<BlockPointerType>()) { 8322 if (LHSPointer->getPointeeType()->isVoidType()) { 8323 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 8324 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 8325 ->getPointeeType() 8326 .getAddressSpace(); 8327 Kind = 8328 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 8329 return Compatible; 8330 } 8331 } 8332 8333 return Incompatible; 8334 } 8335 8336 // Conversions to block pointers. 8337 if (isa<BlockPointerType>(LHSType)) { 8338 // U^ -> T^ 8339 if (RHSType->isBlockPointerType()) { 8340 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 8341 ->getPointeeType() 8342 .getAddressSpace(); 8343 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 8344 ->getPointeeType() 8345 .getAddressSpace(); 8346 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 8347 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 8348 } 8349 8350 // int or null -> T^ 8351 if (RHSType->isIntegerType()) { 8352 Kind = CK_IntegralToPointer; // FIXME: null 8353 return IntToBlockPointer; 8354 } 8355 8356 // id -> T^ 8357 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 8358 Kind = CK_AnyPointerToBlockPointerCast; 8359 return Compatible; 8360 } 8361 8362 // void* -> T^ 8363 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 8364 if (RHSPT->getPointeeType()->isVoidType()) { 8365 Kind = CK_AnyPointerToBlockPointerCast; 8366 return Compatible; 8367 } 8368 8369 return Incompatible; 8370 } 8371 8372 // Conversions to Objective-C pointers. 8373 if (isa<ObjCObjectPointerType>(LHSType)) { 8374 // A* -> B* 8375 if (RHSType->isObjCObjectPointerType()) { 8376 Kind = CK_BitCast; 8377 Sema::AssignConvertType result = 8378 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 8379 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8380 result == Compatible && 8381 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 8382 result = IncompatibleObjCWeakRef; 8383 return result; 8384 } 8385 8386 // int or null -> A* 8387 if (RHSType->isIntegerType()) { 8388 Kind = CK_IntegralToPointer; // FIXME: null 8389 return IntToPointer; 8390 } 8391 8392 // In general, C pointers are not compatible with ObjC object pointers, 8393 // with two exceptions: 8394 if (isa<PointerType>(RHSType)) { 8395 Kind = CK_CPointerToObjCPointerCast; 8396 8397 // - conversions from 'void*' 8398 if (RHSType->isVoidPointerType()) { 8399 return Compatible; 8400 } 8401 8402 // - conversions to 'Class' from its redefinition type 8403 if (LHSType->isObjCClassType() && 8404 Context.hasSameType(RHSType, 8405 Context.getObjCClassRedefinitionType())) { 8406 return Compatible; 8407 } 8408 8409 return IncompatiblePointer; 8410 } 8411 8412 // Only under strict condition T^ is compatible with an Objective-C pointer. 8413 if (RHSType->isBlockPointerType() && 8414 LHSType->isBlockCompatibleObjCPointerType(Context)) { 8415 if (ConvertRHS) 8416 maybeExtendBlockObject(RHS); 8417 Kind = CK_BlockPointerToObjCPointerCast; 8418 return Compatible; 8419 } 8420 8421 return Incompatible; 8422 } 8423 8424 // Conversions from pointers that are not covered by the above. 8425 if (isa<PointerType>(RHSType)) { 8426 // T* -> _Bool 8427 if (LHSType == Context.BoolTy) { 8428 Kind = CK_PointerToBoolean; 8429 return Compatible; 8430 } 8431 8432 // T* -> int 8433 if (LHSType->isIntegerType()) { 8434 Kind = CK_PointerToIntegral; 8435 return PointerToInt; 8436 } 8437 8438 return Incompatible; 8439 } 8440 8441 // Conversions from Objective-C pointers that are not covered by the above. 8442 if (isa<ObjCObjectPointerType>(RHSType)) { 8443 // T* -> _Bool 8444 if (LHSType == Context.BoolTy) { 8445 Kind = CK_PointerToBoolean; 8446 return Compatible; 8447 } 8448 8449 // T* -> int 8450 if (LHSType->isIntegerType()) { 8451 Kind = CK_PointerToIntegral; 8452 return PointerToInt; 8453 } 8454 8455 return Incompatible; 8456 } 8457 8458 // struct A -> struct B 8459 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 8460 if (Context.typesAreCompatible(LHSType, RHSType)) { 8461 Kind = CK_NoOp; 8462 return Compatible; 8463 } 8464 } 8465 8466 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 8467 Kind = CK_IntToOCLSampler; 8468 return Compatible; 8469 } 8470 8471 return Incompatible; 8472 } 8473 8474 /// Constructs a transparent union from an expression that is 8475 /// used to initialize the transparent union. 8476 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 8477 ExprResult &EResult, QualType UnionType, 8478 FieldDecl *Field) { 8479 // Build an initializer list that designates the appropriate member 8480 // of the transparent union. 8481 Expr *E = EResult.get(); 8482 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 8483 E, SourceLocation()); 8484 Initializer->setType(UnionType); 8485 Initializer->setInitializedFieldInUnion(Field); 8486 8487 // Build a compound literal constructing a value of the transparent 8488 // union type from this initializer list. 8489 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 8490 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 8491 VK_RValue, Initializer, false); 8492 } 8493 8494 Sema::AssignConvertType 8495 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 8496 ExprResult &RHS) { 8497 QualType RHSType = RHS.get()->getType(); 8498 8499 // If the ArgType is a Union type, we want to handle a potential 8500 // transparent_union GCC extension. 8501 const RecordType *UT = ArgType->getAsUnionType(); 8502 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 8503 return Incompatible; 8504 8505 // The field to initialize within the transparent union. 8506 RecordDecl *UD = UT->getDecl(); 8507 FieldDecl *InitField = nullptr; 8508 // It's compatible if the expression matches any of the fields. 8509 for (auto *it : UD->fields()) { 8510 if (it->getType()->isPointerType()) { 8511 // If the transparent union contains a pointer type, we allow: 8512 // 1) void pointer 8513 // 2) null pointer constant 8514 if (RHSType->isPointerType()) 8515 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 8516 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 8517 InitField = it; 8518 break; 8519 } 8520 8521 if (RHS.get()->isNullPointerConstant(Context, 8522 Expr::NPC_ValueDependentIsNull)) { 8523 RHS = ImpCastExprToType(RHS.get(), it->getType(), 8524 CK_NullToPointer); 8525 InitField = it; 8526 break; 8527 } 8528 } 8529 8530 CastKind Kind; 8531 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 8532 == Compatible) { 8533 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 8534 InitField = it; 8535 break; 8536 } 8537 } 8538 8539 if (!InitField) 8540 return Incompatible; 8541 8542 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 8543 return Compatible; 8544 } 8545 8546 Sema::AssignConvertType 8547 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 8548 bool Diagnose, 8549 bool DiagnoseCFAudited, 8550 bool ConvertRHS) { 8551 // We need to be able to tell the caller whether we diagnosed a problem, if 8552 // they ask us to issue diagnostics. 8553 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 8554 8555 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 8556 // we can't avoid *all* modifications at the moment, so we need some somewhere 8557 // to put the updated value. 8558 ExprResult LocalRHS = CallerRHS; 8559 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 8560 8561 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 8562 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 8563 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 8564 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 8565 Diag(RHS.get()->getExprLoc(), 8566 diag::warn_noderef_to_dereferenceable_pointer) 8567 << RHS.get()->getSourceRange(); 8568 } 8569 } 8570 } 8571 8572 if (getLangOpts().CPlusPlus) { 8573 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 8574 // C++ 5.17p3: If the left operand is not of class type, the 8575 // expression is implicitly converted (C++ 4) to the 8576 // cv-unqualified type of the left operand. 8577 QualType RHSType = RHS.get()->getType(); 8578 if (Diagnose) { 8579 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8580 AA_Assigning); 8581 } else { 8582 ImplicitConversionSequence ICS = 8583 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8584 /*SuppressUserConversions=*/false, 8585 /*AllowExplicit=*/false, 8586 /*InOverloadResolution=*/false, 8587 /*CStyle=*/false, 8588 /*AllowObjCWritebackConversion=*/false); 8589 if (ICS.isFailure()) 8590 return Incompatible; 8591 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8592 ICS, AA_Assigning); 8593 } 8594 if (RHS.isInvalid()) 8595 return Incompatible; 8596 Sema::AssignConvertType result = Compatible; 8597 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8598 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 8599 result = IncompatibleObjCWeakRef; 8600 return result; 8601 } 8602 8603 // FIXME: Currently, we fall through and treat C++ classes like C 8604 // structures. 8605 // FIXME: We also fall through for atomics; not sure what should 8606 // happen there, though. 8607 } else if (RHS.get()->getType() == Context.OverloadTy) { 8608 // As a set of extensions to C, we support overloading on functions. These 8609 // functions need to be resolved here. 8610 DeclAccessPair DAP; 8611 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 8612 RHS.get(), LHSType, /*Complain=*/false, DAP)) 8613 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 8614 else 8615 return Incompatible; 8616 } 8617 8618 // C99 6.5.16.1p1: the left operand is a pointer and the right is 8619 // a null pointer constant. 8620 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 8621 LHSType->isBlockPointerType()) && 8622 RHS.get()->isNullPointerConstant(Context, 8623 Expr::NPC_ValueDependentIsNull)) { 8624 if (Diagnose || ConvertRHS) { 8625 CastKind Kind; 8626 CXXCastPath Path; 8627 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 8628 /*IgnoreBaseAccess=*/false, Diagnose); 8629 if (ConvertRHS) 8630 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 8631 } 8632 return Compatible; 8633 } 8634 8635 // OpenCL queue_t type assignment. 8636 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 8637 Context, Expr::NPC_ValueDependentIsNull)) { 8638 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 8639 return Compatible; 8640 } 8641 8642 // This check seems unnatural, however it is necessary to ensure the proper 8643 // conversion of functions/arrays. If the conversion were done for all 8644 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 8645 // expressions that suppress this implicit conversion (&, sizeof). 8646 // 8647 // Suppress this for references: C++ 8.5.3p5. 8648 if (!LHSType->isReferenceType()) { 8649 // FIXME: We potentially allocate here even if ConvertRHS is false. 8650 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 8651 if (RHS.isInvalid()) 8652 return Incompatible; 8653 } 8654 CastKind Kind; 8655 Sema::AssignConvertType result = 8656 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 8657 8658 // C99 6.5.16.1p2: The value of the right operand is converted to the 8659 // type of the assignment expression. 8660 // CheckAssignmentConstraints allows the left-hand side to be a reference, 8661 // so that we can use references in built-in functions even in C. 8662 // The getNonReferenceType() call makes sure that the resulting expression 8663 // does not have reference type. 8664 if (result != Incompatible && RHS.get()->getType() != LHSType) { 8665 QualType Ty = LHSType.getNonLValueExprType(Context); 8666 Expr *E = RHS.get(); 8667 8668 // Check for various Objective-C errors. If we are not reporting 8669 // diagnostics and just checking for errors, e.g., during overload 8670 // resolution, return Incompatible to indicate the failure. 8671 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8672 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 8673 Diagnose, DiagnoseCFAudited) != ACR_okay) { 8674 if (!Diagnose) 8675 return Incompatible; 8676 } 8677 if (getLangOpts().ObjC && 8678 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 8679 E->getType(), E, Diagnose) || 8680 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 8681 if (!Diagnose) 8682 return Incompatible; 8683 // Replace the expression with a corrected version and continue so we 8684 // can find further errors. 8685 RHS = E; 8686 return Compatible; 8687 } 8688 8689 if (ConvertRHS) 8690 RHS = ImpCastExprToType(E, Ty, Kind); 8691 } 8692 8693 return result; 8694 } 8695 8696 namespace { 8697 /// The original operand to an operator, prior to the application of the usual 8698 /// arithmetic conversions and converting the arguments of a builtin operator 8699 /// candidate. 8700 struct OriginalOperand { 8701 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 8702 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 8703 Op = MTE->GetTemporaryExpr(); 8704 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 8705 Op = BTE->getSubExpr(); 8706 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 8707 Orig = ICE->getSubExprAsWritten(); 8708 Conversion = ICE->getConversionFunction(); 8709 } 8710 } 8711 8712 QualType getType() const { return Orig->getType(); } 8713 8714 Expr *Orig; 8715 NamedDecl *Conversion; 8716 }; 8717 } 8718 8719 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 8720 ExprResult &RHS) { 8721 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 8722 8723 Diag(Loc, diag::err_typecheck_invalid_operands) 8724 << OrigLHS.getType() << OrigRHS.getType() 8725 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8726 8727 // If a user-defined conversion was applied to either of the operands prior 8728 // to applying the built-in operator rules, tell the user about it. 8729 if (OrigLHS.Conversion) { 8730 Diag(OrigLHS.Conversion->getLocation(), 8731 diag::note_typecheck_invalid_operands_converted) 8732 << 0 << LHS.get()->getType(); 8733 } 8734 if (OrigRHS.Conversion) { 8735 Diag(OrigRHS.Conversion->getLocation(), 8736 diag::note_typecheck_invalid_operands_converted) 8737 << 1 << RHS.get()->getType(); 8738 } 8739 8740 return QualType(); 8741 } 8742 8743 // Diagnose cases where a scalar was implicitly converted to a vector and 8744 // diagnose the underlying types. Otherwise, diagnose the error 8745 // as invalid vector logical operands for non-C++ cases. 8746 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 8747 ExprResult &RHS) { 8748 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 8749 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 8750 8751 bool LHSNatVec = LHSType->isVectorType(); 8752 bool RHSNatVec = RHSType->isVectorType(); 8753 8754 if (!(LHSNatVec && RHSNatVec)) { 8755 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 8756 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 8757 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8758 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 8759 << Vector->getSourceRange(); 8760 return QualType(); 8761 } 8762 8763 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8764 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 8765 << RHS.get()->getSourceRange(); 8766 8767 return QualType(); 8768 } 8769 8770 /// Try to convert a value of non-vector type to a vector type by converting 8771 /// the type to the element type of the vector and then performing a splat. 8772 /// If the language is OpenCL, we only use conversions that promote scalar 8773 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 8774 /// for float->int. 8775 /// 8776 /// OpenCL V2.0 6.2.6.p2: 8777 /// An error shall occur if any scalar operand type has greater rank 8778 /// than the type of the vector element. 8779 /// 8780 /// \param scalar - if non-null, actually perform the conversions 8781 /// \return true if the operation fails (but without diagnosing the failure) 8782 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 8783 QualType scalarTy, 8784 QualType vectorEltTy, 8785 QualType vectorTy, 8786 unsigned &DiagID) { 8787 // The conversion to apply to the scalar before splatting it, 8788 // if necessary. 8789 CastKind scalarCast = CK_NoOp; 8790 8791 if (vectorEltTy->isIntegralType(S.Context)) { 8792 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 8793 (scalarTy->isIntegerType() && 8794 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 8795 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8796 return true; 8797 } 8798 if (!scalarTy->isIntegralType(S.Context)) 8799 return true; 8800 scalarCast = CK_IntegralCast; 8801 } else if (vectorEltTy->isRealFloatingType()) { 8802 if (scalarTy->isRealFloatingType()) { 8803 if (S.getLangOpts().OpenCL && 8804 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 8805 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8806 return true; 8807 } 8808 scalarCast = CK_FloatingCast; 8809 } 8810 else if (scalarTy->isIntegralType(S.Context)) 8811 scalarCast = CK_IntegralToFloating; 8812 else 8813 return true; 8814 } else { 8815 return true; 8816 } 8817 8818 // Adjust scalar if desired. 8819 if (scalar) { 8820 if (scalarCast != CK_NoOp) 8821 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 8822 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 8823 } 8824 return false; 8825 } 8826 8827 /// Convert vector E to a vector with the same number of elements but different 8828 /// element type. 8829 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 8830 const auto *VecTy = E->getType()->getAs<VectorType>(); 8831 assert(VecTy && "Expression E must be a vector"); 8832 QualType NewVecTy = S.Context.getVectorType(ElementType, 8833 VecTy->getNumElements(), 8834 VecTy->getVectorKind()); 8835 8836 // Look through the implicit cast. Return the subexpression if its type is 8837 // NewVecTy. 8838 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 8839 if (ICE->getSubExpr()->getType() == NewVecTy) 8840 return ICE->getSubExpr(); 8841 8842 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 8843 return S.ImpCastExprToType(E, NewVecTy, Cast); 8844 } 8845 8846 /// Test if a (constant) integer Int can be casted to another integer type 8847 /// IntTy without losing precision. 8848 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 8849 QualType OtherIntTy) { 8850 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8851 8852 // Reject cases where the value of the Int is unknown as that would 8853 // possibly cause truncation, but accept cases where the scalar can be 8854 // demoted without loss of precision. 8855 Expr::EvalResult EVResult; 8856 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 8857 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 8858 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 8859 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 8860 8861 if (CstInt) { 8862 // If the scalar is constant and is of a higher order and has more active 8863 // bits that the vector element type, reject it. 8864 llvm::APSInt Result = EVResult.Val.getInt(); 8865 unsigned NumBits = IntSigned 8866 ? (Result.isNegative() ? Result.getMinSignedBits() 8867 : Result.getActiveBits()) 8868 : Result.getActiveBits(); 8869 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 8870 return true; 8871 8872 // If the signedness of the scalar type and the vector element type 8873 // differs and the number of bits is greater than that of the vector 8874 // element reject it. 8875 return (IntSigned != OtherIntSigned && 8876 NumBits > S.Context.getIntWidth(OtherIntTy)); 8877 } 8878 8879 // Reject cases where the value of the scalar is not constant and it's 8880 // order is greater than that of the vector element type. 8881 return (Order < 0); 8882 } 8883 8884 /// Test if a (constant) integer Int can be casted to floating point type 8885 /// FloatTy without losing precision. 8886 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 8887 QualType FloatTy) { 8888 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8889 8890 // Determine if the integer constant can be expressed as a floating point 8891 // number of the appropriate type. 8892 Expr::EvalResult EVResult; 8893 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 8894 8895 uint64_t Bits = 0; 8896 if (CstInt) { 8897 // Reject constants that would be truncated if they were converted to 8898 // the floating point type. Test by simple to/from conversion. 8899 // FIXME: Ideally the conversion to an APFloat and from an APFloat 8900 // could be avoided if there was a convertFromAPInt method 8901 // which could signal back if implicit truncation occurred. 8902 llvm::APSInt Result = EVResult.Val.getInt(); 8903 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 8904 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 8905 llvm::APFloat::rmTowardZero); 8906 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 8907 !IntTy->hasSignedIntegerRepresentation()); 8908 bool Ignored = false; 8909 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 8910 &Ignored); 8911 if (Result != ConvertBack) 8912 return true; 8913 } else { 8914 // Reject types that cannot be fully encoded into the mantissa of 8915 // the float. 8916 Bits = S.Context.getTypeSize(IntTy); 8917 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 8918 S.Context.getFloatTypeSemantics(FloatTy)); 8919 if (Bits > FloatPrec) 8920 return true; 8921 } 8922 8923 return false; 8924 } 8925 8926 /// Attempt to convert and splat Scalar into a vector whose types matches 8927 /// Vector following GCC conversion rules. The rule is that implicit 8928 /// conversion can occur when Scalar can be casted to match Vector's element 8929 /// type without causing truncation of Scalar. 8930 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 8931 ExprResult *Vector) { 8932 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 8933 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 8934 const VectorType *VT = VectorTy->getAs<VectorType>(); 8935 8936 assert(!isa<ExtVectorType>(VT) && 8937 "ExtVectorTypes should not be handled here!"); 8938 8939 QualType VectorEltTy = VT->getElementType(); 8940 8941 // Reject cases where the vector element type or the scalar element type are 8942 // not integral or floating point types. 8943 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 8944 return true; 8945 8946 // The conversion to apply to the scalar before splatting it, 8947 // if necessary. 8948 CastKind ScalarCast = CK_NoOp; 8949 8950 // Accept cases where the vector elements are integers and the scalar is 8951 // an integer. 8952 // FIXME: Notionally if the scalar was a floating point value with a precise 8953 // integral representation, we could cast it to an appropriate integer 8954 // type and then perform the rest of the checks here. GCC will perform 8955 // this conversion in some cases as determined by the input language. 8956 // We should accept it on a language independent basis. 8957 if (VectorEltTy->isIntegralType(S.Context) && 8958 ScalarTy->isIntegralType(S.Context) && 8959 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 8960 8961 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 8962 return true; 8963 8964 ScalarCast = CK_IntegralCast; 8965 } else if (VectorEltTy->isRealFloatingType()) { 8966 if (ScalarTy->isRealFloatingType()) { 8967 8968 // Reject cases where the scalar type is not a constant and has a higher 8969 // Order than the vector element type. 8970 llvm::APFloat Result(0.0); 8971 bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context); 8972 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 8973 if (!CstScalar && Order < 0) 8974 return true; 8975 8976 // If the scalar cannot be safely casted to the vector element type, 8977 // reject it. 8978 if (CstScalar) { 8979 bool Truncated = false; 8980 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 8981 llvm::APFloat::rmNearestTiesToEven, &Truncated); 8982 if (Truncated) 8983 return true; 8984 } 8985 8986 ScalarCast = CK_FloatingCast; 8987 } else if (ScalarTy->isIntegralType(S.Context)) { 8988 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 8989 return true; 8990 8991 ScalarCast = CK_IntegralToFloating; 8992 } else 8993 return true; 8994 } 8995 8996 // Adjust scalar if desired. 8997 if (Scalar) { 8998 if (ScalarCast != CK_NoOp) 8999 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 9000 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 9001 } 9002 return false; 9003 } 9004 9005 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 9006 SourceLocation Loc, bool IsCompAssign, 9007 bool AllowBothBool, 9008 bool AllowBoolConversions) { 9009 if (!IsCompAssign) { 9010 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 9011 if (LHS.isInvalid()) 9012 return QualType(); 9013 } 9014 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 9015 if (RHS.isInvalid()) 9016 return QualType(); 9017 9018 // For conversion purposes, we ignore any qualifiers. 9019 // For example, "const float" and "float" are equivalent. 9020 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 9021 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 9022 9023 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 9024 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 9025 assert(LHSVecType || RHSVecType); 9026 9027 // AltiVec-style "vector bool op vector bool" combinations are allowed 9028 // for some operators but not others. 9029 if (!AllowBothBool && 9030 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9031 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9032 return InvalidOperands(Loc, LHS, RHS); 9033 9034 // If the vector types are identical, return. 9035 if (Context.hasSameType(LHSType, RHSType)) 9036 return LHSType; 9037 9038 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 9039 if (LHSVecType && RHSVecType && 9040 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9041 if (isa<ExtVectorType>(LHSVecType)) { 9042 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9043 return LHSType; 9044 } 9045 9046 if (!IsCompAssign) 9047 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9048 return RHSType; 9049 } 9050 9051 // AllowBoolConversions says that bool and non-bool AltiVec vectors 9052 // can be mixed, with the result being the non-bool type. The non-bool 9053 // operand must have integer element type. 9054 if (AllowBoolConversions && LHSVecType && RHSVecType && 9055 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 9056 (Context.getTypeSize(LHSVecType->getElementType()) == 9057 Context.getTypeSize(RHSVecType->getElementType()))) { 9058 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 9059 LHSVecType->getElementType()->isIntegerType() && 9060 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 9061 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9062 return LHSType; 9063 } 9064 if (!IsCompAssign && 9065 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9066 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 9067 RHSVecType->getElementType()->isIntegerType()) { 9068 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9069 return RHSType; 9070 } 9071 } 9072 9073 // If there's a vector type and a scalar, try to convert the scalar to 9074 // the vector element type and splat. 9075 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 9076 if (!RHSVecType) { 9077 if (isa<ExtVectorType>(LHSVecType)) { 9078 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 9079 LHSVecType->getElementType(), LHSType, 9080 DiagID)) 9081 return LHSType; 9082 } else { 9083 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 9084 return LHSType; 9085 } 9086 } 9087 if (!LHSVecType) { 9088 if (isa<ExtVectorType>(RHSVecType)) { 9089 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 9090 LHSType, RHSVecType->getElementType(), 9091 RHSType, DiagID)) 9092 return RHSType; 9093 } else { 9094 if (LHS.get()->getValueKind() == VK_LValue || 9095 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 9096 return RHSType; 9097 } 9098 } 9099 9100 // FIXME: The code below also handles conversion between vectors and 9101 // non-scalars, we should break this down into fine grained specific checks 9102 // and emit proper diagnostics. 9103 QualType VecType = LHSVecType ? LHSType : RHSType; 9104 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 9105 QualType OtherType = LHSVecType ? RHSType : LHSType; 9106 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 9107 if (isLaxVectorConversion(OtherType, VecType)) { 9108 // If we're allowing lax vector conversions, only the total (data) size 9109 // needs to be the same. For non compound assignment, if one of the types is 9110 // scalar, the result is always the vector type. 9111 if (!IsCompAssign) { 9112 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 9113 return VecType; 9114 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 9115 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 9116 // type. Note that this is already done by non-compound assignments in 9117 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 9118 // <1 x T> -> T. The result is also a vector type. 9119 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 9120 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 9121 ExprResult *RHSExpr = &RHS; 9122 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 9123 return VecType; 9124 } 9125 } 9126 9127 // Okay, the expression is invalid. 9128 9129 // If there's a non-vector, non-real operand, diagnose that. 9130 if ((!RHSVecType && !RHSType->isRealType()) || 9131 (!LHSVecType && !LHSType->isRealType())) { 9132 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 9133 << LHSType << RHSType 9134 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9135 return QualType(); 9136 } 9137 9138 // OpenCL V1.1 6.2.6.p1: 9139 // If the operands are of more than one vector type, then an error shall 9140 // occur. Implicit conversions between vector types are not permitted, per 9141 // section 6.2.1. 9142 if (getLangOpts().OpenCL && 9143 RHSVecType && isa<ExtVectorType>(RHSVecType) && 9144 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 9145 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 9146 << RHSType; 9147 return QualType(); 9148 } 9149 9150 9151 // If there is a vector type that is not a ExtVector and a scalar, we reach 9152 // this point if scalar could not be converted to the vector's element type 9153 // without truncation. 9154 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 9155 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 9156 QualType Scalar = LHSVecType ? RHSType : LHSType; 9157 QualType Vector = LHSVecType ? LHSType : RHSType; 9158 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 9159 Diag(Loc, 9160 diag::err_typecheck_vector_not_convertable_implict_truncation) 9161 << ScalarOrVector << Scalar << Vector; 9162 9163 return QualType(); 9164 } 9165 9166 // Otherwise, use the generic diagnostic. 9167 Diag(Loc, DiagID) 9168 << LHSType << RHSType 9169 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9170 return QualType(); 9171 } 9172 9173 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 9174 // expression. These are mainly cases where the null pointer is used as an 9175 // integer instead of a pointer. 9176 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 9177 SourceLocation Loc, bool IsCompare) { 9178 // The canonical way to check for a GNU null is with isNullPointerConstant, 9179 // but we use a bit of a hack here for speed; this is a relatively 9180 // hot path, and isNullPointerConstant is slow. 9181 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 9182 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 9183 9184 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 9185 9186 // Avoid analyzing cases where the result will either be invalid (and 9187 // diagnosed as such) or entirely valid and not something to warn about. 9188 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 9189 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 9190 return; 9191 9192 // Comparison operations would not make sense with a null pointer no matter 9193 // what the other expression is. 9194 if (!IsCompare) { 9195 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 9196 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 9197 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 9198 return; 9199 } 9200 9201 // The rest of the operations only make sense with a null pointer 9202 // if the other expression is a pointer. 9203 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 9204 NonNullType->canDecayToPointerType()) 9205 return; 9206 9207 S.Diag(Loc, diag::warn_null_in_comparison_operation) 9208 << LHSNull /* LHS is NULL */ << NonNullType 9209 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9210 } 9211 9212 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 9213 SourceLocation Loc) { 9214 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 9215 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 9216 if (!LUE || !RUE) 9217 return; 9218 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 9219 RUE->getKind() != UETT_SizeOf) 9220 return; 9221 9222 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 9223 QualType LHSTy = LHSArg->getType(); 9224 QualType RHSTy; 9225 9226 if (RUE->isArgumentType()) 9227 RHSTy = RUE->getArgumentType(); 9228 else 9229 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 9230 9231 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 9232 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 9233 return; 9234 9235 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 9236 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 9237 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 9238 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 9239 << LHSArgDecl; 9240 } 9241 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 9242 QualType ArrayElemTy = ArrayTy->getElementType(); 9243 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 9244 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 9245 ArrayElemTy->isCharType() || 9246 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 9247 return; 9248 S.Diag(Loc, diag::warn_division_sizeof_array) 9249 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 9250 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 9251 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 9252 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 9253 << LHSArgDecl; 9254 } 9255 9256 S.Diag(Loc, diag::note_precedence_silence) << RHS; 9257 } 9258 } 9259 9260 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 9261 ExprResult &RHS, 9262 SourceLocation Loc, bool IsDiv) { 9263 // Check for division/remainder by zero. 9264 Expr::EvalResult RHSValue; 9265 if (!RHS.get()->isValueDependent() && 9266 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 9267 RHSValue.Val.getInt() == 0) 9268 S.DiagRuntimeBehavior(Loc, RHS.get(), 9269 S.PDiag(diag::warn_remainder_division_by_zero) 9270 << IsDiv << RHS.get()->getSourceRange()); 9271 } 9272 9273 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 9274 SourceLocation Loc, 9275 bool IsCompAssign, bool IsDiv) { 9276 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9277 9278 if (LHS.get()->getType()->isVectorType() || 9279 RHS.get()->getType()->isVectorType()) 9280 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9281 /*AllowBothBool*/getLangOpts().AltiVec, 9282 /*AllowBoolConversions*/false); 9283 9284 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 9285 if (LHS.isInvalid() || RHS.isInvalid()) 9286 return QualType(); 9287 9288 9289 if (compType.isNull() || !compType->isArithmeticType()) 9290 return InvalidOperands(Loc, LHS, RHS); 9291 if (IsDiv) { 9292 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 9293 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 9294 } 9295 return compType; 9296 } 9297 9298 QualType Sema::CheckRemainderOperands( 9299 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 9300 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9301 9302 if (LHS.get()->getType()->isVectorType() || 9303 RHS.get()->getType()->isVectorType()) { 9304 if (LHS.get()->getType()->hasIntegerRepresentation() && 9305 RHS.get()->getType()->hasIntegerRepresentation()) 9306 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9307 /*AllowBothBool*/getLangOpts().AltiVec, 9308 /*AllowBoolConversions*/false); 9309 return InvalidOperands(Loc, LHS, RHS); 9310 } 9311 9312 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 9313 if (LHS.isInvalid() || RHS.isInvalid()) 9314 return QualType(); 9315 9316 if (compType.isNull() || !compType->isIntegerType()) 9317 return InvalidOperands(Loc, LHS, RHS); 9318 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 9319 return compType; 9320 } 9321 9322 /// Diagnose invalid arithmetic on two void pointers. 9323 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 9324 Expr *LHSExpr, Expr *RHSExpr) { 9325 S.Diag(Loc, S.getLangOpts().CPlusPlus 9326 ? diag::err_typecheck_pointer_arith_void_type 9327 : diag::ext_gnu_void_ptr) 9328 << 1 /* two pointers */ << LHSExpr->getSourceRange() 9329 << RHSExpr->getSourceRange(); 9330 } 9331 9332 /// Diagnose invalid arithmetic on a void pointer. 9333 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 9334 Expr *Pointer) { 9335 S.Diag(Loc, S.getLangOpts().CPlusPlus 9336 ? diag::err_typecheck_pointer_arith_void_type 9337 : diag::ext_gnu_void_ptr) 9338 << 0 /* one pointer */ << Pointer->getSourceRange(); 9339 } 9340 9341 /// Diagnose invalid arithmetic on a null pointer. 9342 /// 9343 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 9344 /// idiom, which we recognize as a GNU extension. 9345 /// 9346 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 9347 Expr *Pointer, bool IsGNUIdiom) { 9348 if (IsGNUIdiom) 9349 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 9350 << Pointer->getSourceRange(); 9351 else 9352 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 9353 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 9354 } 9355 9356 /// Diagnose invalid arithmetic on two function pointers. 9357 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 9358 Expr *LHS, Expr *RHS) { 9359 assert(LHS->getType()->isAnyPointerType()); 9360 assert(RHS->getType()->isAnyPointerType()); 9361 S.Diag(Loc, S.getLangOpts().CPlusPlus 9362 ? diag::err_typecheck_pointer_arith_function_type 9363 : diag::ext_gnu_ptr_func_arith) 9364 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 9365 // We only show the second type if it differs from the first. 9366 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 9367 RHS->getType()) 9368 << RHS->getType()->getPointeeType() 9369 << LHS->getSourceRange() << RHS->getSourceRange(); 9370 } 9371 9372 /// Diagnose invalid arithmetic on a function pointer. 9373 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 9374 Expr *Pointer) { 9375 assert(Pointer->getType()->isAnyPointerType()); 9376 S.Diag(Loc, S.getLangOpts().CPlusPlus 9377 ? diag::err_typecheck_pointer_arith_function_type 9378 : diag::ext_gnu_ptr_func_arith) 9379 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 9380 << 0 /* one pointer, so only one type */ 9381 << Pointer->getSourceRange(); 9382 } 9383 9384 /// Emit error if Operand is incomplete pointer type 9385 /// 9386 /// \returns True if pointer has incomplete type 9387 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 9388 Expr *Operand) { 9389 QualType ResType = Operand->getType(); 9390 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 9391 ResType = ResAtomicType->getValueType(); 9392 9393 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 9394 QualType PointeeTy = ResType->getPointeeType(); 9395 return S.RequireCompleteType(Loc, PointeeTy, 9396 diag::err_typecheck_arithmetic_incomplete_type, 9397 PointeeTy, Operand->getSourceRange()); 9398 } 9399 9400 /// Check the validity of an arithmetic pointer operand. 9401 /// 9402 /// If the operand has pointer type, this code will check for pointer types 9403 /// which are invalid in arithmetic operations. These will be diagnosed 9404 /// appropriately, including whether or not the use is supported as an 9405 /// extension. 9406 /// 9407 /// \returns True when the operand is valid to use (even if as an extension). 9408 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 9409 Expr *Operand) { 9410 QualType ResType = Operand->getType(); 9411 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 9412 ResType = ResAtomicType->getValueType(); 9413 9414 if (!ResType->isAnyPointerType()) return true; 9415 9416 QualType PointeeTy = ResType->getPointeeType(); 9417 if (PointeeTy->isVoidType()) { 9418 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 9419 return !S.getLangOpts().CPlusPlus; 9420 } 9421 if (PointeeTy->isFunctionType()) { 9422 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 9423 return !S.getLangOpts().CPlusPlus; 9424 } 9425 9426 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 9427 9428 return true; 9429 } 9430 9431 /// Check the validity of a binary arithmetic operation w.r.t. pointer 9432 /// operands. 9433 /// 9434 /// This routine will diagnose any invalid arithmetic on pointer operands much 9435 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 9436 /// for emitting a single diagnostic even for operations where both LHS and RHS 9437 /// are (potentially problematic) pointers. 9438 /// 9439 /// \returns True when the operand is valid to use (even if as an extension). 9440 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 9441 Expr *LHSExpr, Expr *RHSExpr) { 9442 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 9443 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 9444 if (!isLHSPointer && !isRHSPointer) return true; 9445 9446 QualType LHSPointeeTy, RHSPointeeTy; 9447 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 9448 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 9449 9450 // if both are pointers check if operation is valid wrt address spaces 9451 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 9452 const PointerType *lhsPtr = LHSExpr->getType()->castAs<PointerType>(); 9453 const PointerType *rhsPtr = RHSExpr->getType()->castAs<PointerType>(); 9454 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 9455 S.Diag(Loc, 9456 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 9457 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 9458 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 9459 return false; 9460 } 9461 } 9462 9463 // Check for arithmetic on pointers to incomplete types. 9464 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 9465 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 9466 if (isLHSVoidPtr || isRHSVoidPtr) { 9467 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 9468 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 9469 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 9470 9471 return !S.getLangOpts().CPlusPlus; 9472 } 9473 9474 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 9475 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 9476 if (isLHSFuncPtr || isRHSFuncPtr) { 9477 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 9478 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 9479 RHSExpr); 9480 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 9481 9482 return !S.getLangOpts().CPlusPlus; 9483 } 9484 9485 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 9486 return false; 9487 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 9488 return false; 9489 9490 return true; 9491 } 9492 9493 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 9494 /// literal. 9495 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 9496 Expr *LHSExpr, Expr *RHSExpr) { 9497 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 9498 Expr* IndexExpr = RHSExpr; 9499 if (!StrExpr) { 9500 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 9501 IndexExpr = LHSExpr; 9502 } 9503 9504 bool IsStringPlusInt = StrExpr && 9505 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 9506 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 9507 return; 9508 9509 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 9510 Self.Diag(OpLoc, diag::warn_string_plus_int) 9511 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 9512 9513 // Only print a fixit for "str" + int, not for int + "str". 9514 if (IndexExpr == RHSExpr) { 9515 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 9516 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 9517 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 9518 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 9519 << FixItHint::CreateInsertion(EndLoc, "]"); 9520 } else 9521 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 9522 } 9523 9524 /// Emit a warning when adding a char literal to a string. 9525 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 9526 Expr *LHSExpr, Expr *RHSExpr) { 9527 const Expr *StringRefExpr = LHSExpr; 9528 const CharacterLiteral *CharExpr = 9529 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 9530 9531 if (!CharExpr) { 9532 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 9533 StringRefExpr = RHSExpr; 9534 } 9535 9536 if (!CharExpr || !StringRefExpr) 9537 return; 9538 9539 const QualType StringType = StringRefExpr->getType(); 9540 9541 // Return if not a PointerType. 9542 if (!StringType->isAnyPointerType()) 9543 return; 9544 9545 // Return if not a CharacterType. 9546 if (!StringType->getPointeeType()->isAnyCharacterType()) 9547 return; 9548 9549 ASTContext &Ctx = Self.getASTContext(); 9550 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 9551 9552 const QualType CharType = CharExpr->getType(); 9553 if (!CharType->isAnyCharacterType() && 9554 CharType->isIntegerType() && 9555 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 9556 Self.Diag(OpLoc, diag::warn_string_plus_char) 9557 << DiagRange << Ctx.CharTy; 9558 } else { 9559 Self.Diag(OpLoc, diag::warn_string_plus_char) 9560 << DiagRange << CharExpr->getType(); 9561 } 9562 9563 // Only print a fixit for str + char, not for char + str. 9564 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 9565 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 9566 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 9567 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 9568 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 9569 << FixItHint::CreateInsertion(EndLoc, "]"); 9570 } else { 9571 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 9572 } 9573 } 9574 9575 /// Emit error when two pointers are incompatible. 9576 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 9577 Expr *LHSExpr, Expr *RHSExpr) { 9578 assert(LHSExpr->getType()->isAnyPointerType()); 9579 assert(RHSExpr->getType()->isAnyPointerType()); 9580 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 9581 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 9582 << RHSExpr->getSourceRange(); 9583 } 9584 9585 // C99 6.5.6 9586 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 9587 SourceLocation Loc, BinaryOperatorKind Opc, 9588 QualType* CompLHSTy) { 9589 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9590 9591 if (LHS.get()->getType()->isVectorType() || 9592 RHS.get()->getType()->isVectorType()) { 9593 QualType compType = CheckVectorOperands( 9594 LHS, RHS, Loc, CompLHSTy, 9595 /*AllowBothBool*/getLangOpts().AltiVec, 9596 /*AllowBoolConversions*/getLangOpts().ZVector); 9597 if (CompLHSTy) *CompLHSTy = compType; 9598 return compType; 9599 } 9600 9601 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 9602 if (LHS.isInvalid() || RHS.isInvalid()) 9603 return QualType(); 9604 9605 // Diagnose "string literal" '+' int and string '+' "char literal". 9606 if (Opc == BO_Add) { 9607 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 9608 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 9609 } 9610 9611 // handle the common case first (both operands are arithmetic). 9612 if (!compType.isNull() && compType->isArithmeticType()) { 9613 if (CompLHSTy) *CompLHSTy = compType; 9614 return compType; 9615 } 9616 9617 // Type-checking. Ultimately the pointer's going to be in PExp; 9618 // note that we bias towards the LHS being the pointer. 9619 Expr *PExp = LHS.get(), *IExp = RHS.get(); 9620 9621 bool isObjCPointer; 9622 if (PExp->getType()->isPointerType()) { 9623 isObjCPointer = false; 9624 } else if (PExp->getType()->isObjCObjectPointerType()) { 9625 isObjCPointer = true; 9626 } else { 9627 std::swap(PExp, IExp); 9628 if (PExp->getType()->isPointerType()) { 9629 isObjCPointer = false; 9630 } else if (PExp->getType()->isObjCObjectPointerType()) { 9631 isObjCPointer = true; 9632 } else { 9633 return InvalidOperands(Loc, LHS, RHS); 9634 } 9635 } 9636 assert(PExp->getType()->isAnyPointerType()); 9637 9638 if (!IExp->getType()->isIntegerType()) 9639 return InvalidOperands(Loc, LHS, RHS); 9640 9641 // Adding to a null pointer results in undefined behavior. 9642 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 9643 Context, Expr::NPC_ValueDependentIsNotNull)) { 9644 // In C++ adding zero to a null pointer is defined. 9645 Expr::EvalResult KnownVal; 9646 if (!getLangOpts().CPlusPlus || 9647 (!IExp->isValueDependent() && 9648 (!IExp->EvaluateAsInt(KnownVal, Context) || 9649 KnownVal.Val.getInt() != 0))) { 9650 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 9651 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 9652 Context, BO_Add, PExp, IExp); 9653 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 9654 } 9655 } 9656 9657 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 9658 return QualType(); 9659 9660 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 9661 return QualType(); 9662 9663 // Check array bounds for pointer arithemtic 9664 CheckArrayAccess(PExp, IExp); 9665 9666 if (CompLHSTy) { 9667 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 9668 if (LHSTy.isNull()) { 9669 LHSTy = LHS.get()->getType(); 9670 if (LHSTy->isPromotableIntegerType()) 9671 LHSTy = Context.getPromotedIntegerType(LHSTy); 9672 } 9673 *CompLHSTy = LHSTy; 9674 } 9675 9676 return PExp->getType(); 9677 } 9678 9679 // C99 6.5.6 9680 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 9681 SourceLocation Loc, 9682 QualType* CompLHSTy) { 9683 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9684 9685 if (LHS.get()->getType()->isVectorType() || 9686 RHS.get()->getType()->isVectorType()) { 9687 QualType compType = CheckVectorOperands( 9688 LHS, RHS, Loc, CompLHSTy, 9689 /*AllowBothBool*/getLangOpts().AltiVec, 9690 /*AllowBoolConversions*/getLangOpts().ZVector); 9691 if (CompLHSTy) *CompLHSTy = compType; 9692 return compType; 9693 } 9694 9695 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 9696 if (LHS.isInvalid() || RHS.isInvalid()) 9697 return QualType(); 9698 9699 // Enforce type constraints: C99 6.5.6p3. 9700 9701 // Handle the common case first (both operands are arithmetic). 9702 if (!compType.isNull() && compType->isArithmeticType()) { 9703 if (CompLHSTy) *CompLHSTy = compType; 9704 return compType; 9705 } 9706 9707 // Either ptr - int or ptr - ptr. 9708 if (LHS.get()->getType()->isAnyPointerType()) { 9709 QualType lpointee = LHS.get()->getType()->getPointeeType(); 9710 9711 // Diagnose bad cases where we step over interface counts. 9712 if (LHS.get()->getType()->isObjCObjectPointerType() && 9713 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 9714 return QualType(); 9715 9716 // The result type of a pointer-int computation is the pointer type. 9717 if (RHS.get()->getType()->isIntegerType()) { 9718 // Subtracting from a null pointer should produce a warning. 9719 // The last argument to the diagnose call says this doesn't match the 9720 // GNU int-to-pointer idiom. 9721 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 9722 Expr::NPC_ValueDependentIsNotNull)) { 9723 // In C++ adding zero to a null pointer is defined. 9724 Expr::EvalResult KnownVal; 9725 if (!getLangOpts().CPlusPlus || 9726 (!RHS.get()->isValueDependent() && 9727 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 9728 KnownVal.Val.getInt() != 0))) { 9729 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 9730 } 9731 } 9732 9733 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 9734 return QualType(); 9735 9736 // Check array bounds for pointer arithemtic 9737 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 9738 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 9739 9740 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9741 return LHS.get()->getType(); 9742 } 9743 9744 // Handle pointer-pointer subtractions. 9745 if (const PointerType *RHSPTy 9746 = RHS.get()->getType()->getAs<PointerType>()) { 9747 QualType rpointee = RHSPTy->getPointeeType(); 9748 9749 if (getLangOpts().CPlusPlus) { 9750 // Pointee types must be the same: C++ [expr.add] 9751 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 9752 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9753 } 9754 } else { 9755 // Pointee types must be compatible C99 6.5.6p3 9756 if (!Context.typesAreCompatible( 9757 Context.getCanonicalType(lpointee).getUnqualifiedType(), 9758 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 9759 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9760 return QualType(); 9761 } 9762 } 9763 9764 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 9765 LHS.get(), RHS.get())) 9766 return QualType(); 9767 9768 // FIXME: Add warnings for nullptr - ptr. 9769 9770 // The pointee type may have zero size. As an extension, a structure or 9771 // union may have zero size or an array may have zero length. In this 9772 // case subtraction does not make sense. 9773 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 9774 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 9775 if (ElementSize.isZero()) { 9776 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 9777 << rpointee.getUnqualifiedType() 9778 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9779 } 9780 } 9781 9782 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9783 return Context.getPointerDiffType(); 9784 } 9785 } 9786 9787 return InvalidOperands(Loc, LHS, RHS); 9788 } 9789 9790 static bool isScopedEnumerationType(QualType T) { 9791 if (const EnumType *ET = T->getAs<EnumType>()) 9792 return ET->getDecl()->isScoped(); 9793 return false; 9794 } 9795 9796 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 9797 SourceLocation Loc, BinaryOperatorKind Opc, 9798 QualType LHSType) { 9799 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 9800 // so skip remaining warnings as we don't want to modify values within Sema. 9801 if (S.getLangOpts().OpenCL) 9802 return; 9803 9804 // Check right/shifter operand 9805 Expr::EvalResult RHSResult; 9806 if (RHS.get()->isValueDependent() || 9807 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 9808 return; 9809 llvm::APSInt Right = RHSResult.Val.getInt(); 9810 9811 if (Right.isNegative()) { 9812 S.DiagRuntimeBehavior(Loc, RHS.get(), 9813 S.PDiag(diag::warn_shift_negative) 9814 << RHS.get()->getSourceRange()); 9815 return; 9816 } 9817 llvm::APInt LeftBits(Right.getBitWidth(), 9818 S.Context.getTypeSize(LHS.get()->getType())); 9819 if (Right.uge(LeftBits)) { 9820 S.DiagRuntimeBehavior(Loc, RHS.get(), 9821 S.PDiag(diag::warn_shift_gt_typewidth) 9822 << RHS.get()->getSourceRange()); 9823 return; 9824 } 9825 if (Opc != BO_Shl) 9826 return; 9827 9828 // When left shifting an ICE which is signed, we can check for overflow which 9829 // according to C++ standards prior to C++2a has undefined behavior 9830 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 9831 // more than the maximum value representable in the result type, so never 9832 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 9833 // expression is still probably a bug.) 9834 Expr::EvalResult LHSResult; 9835 if (LHS.get()->isValueDependent() || 9836 LHSType->hasUnsignedIntegerRepresentation() || 9837 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 9838 return; 9839 llvm::APSInt Left = LHSResult.Val.getInt(); 9840 9841 // If LHS does not have a signed type and non-negative value 9842 // then, the behavior is undefined before C++2a. Warn about it. 9843 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 9844 !S.getLangOpts().CPlusPlus2a) { 9845 S.DiagRuntimeBehavior(Loc, LHS.get(), 9846 S.PDiag(diag::warn_shift_lhs_negative) 9847 << LHS.get()->getSourceRange()); 9848 return; 9849 } 9850 9851 llvm::APInt ResultBits = 9852 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 9853 if (LeftBits.uge(ResultBits)) 9854 return; 9855 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 9856 Result = Result.shl(Right); 9857 9858 // Print the bit representation of the signed integer as an unsigned 9859 // hexadecimal number. 9860 SmallString<40> HexResult; 9861 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 9862 9863 // If we are only missing a sign bit, this is less likely to result in actual 9864 // bugs -- if the result is cast back to an unsigned type, it will have the 9865 // expected value. Thus we place this behind a different warning that can be 9866 // turned off separately if needed. 9867 if (LeftBits == ResultBits - 1) { 9868 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 9869 << HexResult << LHSType 9870 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9871 return; 9872 } 9873 9874 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 9875 << HexResult.str() << Result.getMinSignedBits() << LHSType 9876 << Left.getBitWidth() << LHS.get()->getSourceRange() 9877 << RHS.get()->getSourceRange(); 9878 } 9879 9880 /// Return the resulting type when a vector is shifted 9881 /// by a scalar or vector shift amount. 9882 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 9883 SourceLocation Loc, bool IsCompAssign) { 9884 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 9885 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 9886 !LHS.get()->getType()->isVectorType()) { 9887 S.Diag(Loc, diag::err_shift_rhs_only_vector) 9888 << RHS.get()->getType() << LHS.get()->getType() 9889 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9890 return QualType(); 9891 } 9892 9893 if (!IsCompAssign) { 9894 LHS = S.UsualUnaryConversions(LHS.get()); 9895 if (LHS.isInvalid()) return QualType(); 9896 } 9897 9898 RHS = S.UsualUnaryConversions(RHS.get()); 9899 if (RHS.isInvalid()) return QualType(); 9900 9901 QualType LHSType = LHS.get()->getType(); 9902 // Note that LHS might be a scalar because the routine calls not only in 9903 // OpenCL case. 9904 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 9905 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 9906 9907 // Note that RHS might not be a vector. 9908 QualType RHSType = RHS.get()->getType(); 9909 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 9910 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 9911 9912 // The operands need to be integers. 9913 if (!LHSEleType->isIntegerType()) { 9914 S.Diag(Loc, diag::err_typecheck_expect_int) 9915 << LHS.get()->getType() << LHS.get()->getSourceRange(); 9916 return QualType(); 9917 } 9918 9919 if (!RHSEleType->isIntegerType()) { 9920 S.Diag(Loc, diag::err_typecheck_expect_int) 9921 << RHS.get()->getType() << RHS.get()->getSourceRange(); 9922 return QualType(); 9923 } 9924 9925 if (!LHSVecTy) { 9926 assert(RHSVecTy); 9927 if (IsCompAssign) 9928 return RHSType; 9929 if (LHSEleType != RHSEleType) { 9930 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 9931 LHSEleType = RHSEleType; 9932 } 9933 QualType VecTy = 9934 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 9935 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 9936 LHSType = VecTy; 9937 } else if (RHSVecTy) { 9938 // OpenCL v1.1 s6.3.j says that for vector types, the operators 9939 // are applied component-wise. So if RHS is a vector, then ensure 9940 // that the number of elements is the same as LHS... 9941 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 9942 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 9943 << LHS.get()->getType() << RHS.get()->getType() 9944 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9945 return QualType(); 9946 } 9947 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 9948 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 9949 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 9950 if (LHSBT != RHSBT && 9951 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 9952 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 9953 << LHS.get()->getType() << RHS.get()->getType() 9954 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9955 } 9956 } 9957 } else { 9958 // ...else expand RHS to match the number of elements in LHS. 9959 QualType VecTy = 9960 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 9961 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 9962 } 9963 9964 return LHSType; 9965 } 9966 9967 // C99 6.5.7 9968 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 9969 SourceLocation Loc, BinaryOperatorKind Opc, 9970 bool IsCompAssign) { 9971 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9972 9973 // Vector shifts promote their scalar inputs to vector type. 9974 if (LHS.get()->getType()->isVectorType() || 9975 RHS.get()->getType()->isVectorType()) { 9976 if (LangOpts.ZVector) { 9977 // The shift operators for the z vector extensions work basically 9978 // like general shifts, except that neither the LHS nor the RHS is 9979 // allowed to be a "vector bool". 9980 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 9981 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 9982 return InvalidOperands(Loc, LHS, RHS); 9983 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 9984 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9985 return InvalidOperands(Loc, LHS, RHS); 9986 } 9987 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 9988 } 9989 9990 // Shifts don't perform usual arithmetic conversions, they just do integer 9991 // promotions on each operand. C99 6.5.7p3 9992 9993 // For the LHS, do usual unary conversions, but then reset them away 9994 // if this is a compound assignment. 9995 ExprResult OldLHS = LHS; 9996 LHS = UsualUnaryConversions(LHS.get()); 9997 if (LHS.isInvalid()) 9998 return QualType(); 9999 QualType LHSType = LHS.get()->getType(); 10000 if (IsCompAssign) LHS = OldLHS; 10001 10002 // The RHS is simpler. 10003 RHS = UsualUnaryConversions(RHS.get()); 10004 if (RHS.isInvalid()) 10005 return QualType(); 10006 QualType RHSType = RHS.get()->getType(); 10007 10008 // C99 6.5.7p2: Each of the operands shall have integer type. 10009 if (!LHSType->hasIntegerRepresentation() || 10010 !RHSType->hasIntegerRepresentation()) 10011 return InvalidOperands(Loc, LHS, RHS); 10012 10013 // C++0x: Don't allow scoped enums. FIXME: Use something better than 10014 // hasIntegerRepresentation() above instead of this. 10015 if (isScopedEnumerationType(LHSType) || 10016 isScopedEnumerationType(RHSType)) { 10017 return InvalidOperands(Loc, LHS, RHS); 10018 } 10019 // Sanity-check shift operands 10020 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 10021 10022 // "The type of the result is that of the promoted left operand." 10023 return LHSType; 10024 } 10025 10026 /// If two different enums are compared, raise a warning. 10027 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 10028 Expr *RHS) { 10029 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 10030 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 10031 10032 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 10033 if (!LHSEnumType) 10034 return; 10035 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 10036 if (!RHSEnumType) 10037 return; 10038 10039 // Ignore anonymous enums. 10040 if (!LHSEnumType->getDecl()->getIdentifier() && 10041 !LHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 10042 return; 10043 if (!RHSEnumType->getDecl()->getIdentifier() && 10044 !RHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 10045 return; 10046 10047 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 10048 return; 10049 10050 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 10051 << LHSStrippedType << RHSStrippedType 10052 << LHS->getSourceRange() << RHS->getSourceRange(); 10053 } 10054 10055 /// Diagnose bad pointer comparisons. 10056 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 10057 ExprResult &LHS, ExprResult &RHS, 10058 bool IsError) { 10059 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 10060 : diag::ext_typecheck_comparison_of_distinct_pointers) 10061 << LHS.get()->getType() << RHS.get()->getType() 10062 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10063 } 10064 10065 /// Returns false if the pointers are converted to a composite type, 10066 /// true otherwise. 10067 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 10068 ExprResult &LHS, ExprResult &RHS) { 10069 // C++ [expr.rel]p2: 10070 // [...] Pointer conversions (4.10) and qualification 10071 // conversions (4.4) are performed on pointer operands (or on 10072 // a pointer operand and a null pointer constant) to bring 10073 // them to their composite pointer type. [...] 10074 // 10075 // C++ [expr.eq]p1 uses the same notion for (in)equality 10076 // comparisons of pointers. 10077 10078 QualType LHSType = LHS.get()->getType(); 10079 QualType RHSType = RHS.get()->getType(); 10080 assert(LHSType->isPointerType() || RHSType->isPointerType() || 10081 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 10082 10083 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 10084 if (T.isNull()) { 10085 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 10086 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 10087 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 10088 else 10089 S.InvalidOperands(Loc, LHS, RHS); 10090 return true; 10091 } 10092 10093 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 10094 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 10095 return false; 10096 } 10097 10098 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 10099 ExprResult &LHS, 10100 ExprResult &RHS, 10101 bool IsError) { 10102 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 10103 : diag::ext_typecheck_comparison_of_fptr_to_void) 10104 << LHS.get()->getType() << RHS.get()->getType() 10105 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10106 } 10107 10108 static bool isObjCObjectLiteral(ExprResult &E) { 10109 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 10110 case Stmt::ObjCArrayLiteralClass: 10111 case Stmt::ObjCDictionaryLiteralClass: 10112 case Stmt::ObjCStringLiteralClass: 10113 case Stmt::ObjCBoxedExprClass: 10114 return true; 10115 default: 10116 // Note that ObjCBoolLiteral is NOT an object literal! 10117 return false; 10118 } 10119 } 10120 10121 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 10122 const ObjCObjectPointerType *Type = 10123 LHS->getType()->getAs<ObjCObjectPointerType>(); 10124 10125 // If this is not actually an Objective-C object, bail out. 10126 if (!Type) 10127 return false; 10128 10129 // Get the LHS object's interface type. 10130 QualType InterfaceType = Type->getPointeeType(); 10131 10132 // If the RHS isn't an Objective-C object, bail out. 10133 if (!RHS->getType()->isObjCObjectPointerType()) 10134 return false; 10135 10136 // Try to find the -isEqual: method. 10137 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 10138 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 10139 InterfaceType, 10140 /*IsInstance=*/true); 10141 if (!Method) { 10142 if (Type->isObjCIdType()) { 10143 // For 'id', just check the global pool. 10144 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 10145 /*receiverId=*/true); 10146 } else { 10147 // Check protocols. 10148 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 10149 /*IsInstance=*/true); 10150 } 10151 } 10152 10153 if (!Method) 10154 return false; 10155 10156 QualType T = Method->parameters()[0]->getType(); 10157 if (!T->isObjCObjectPointerType()) 10158 return false; 10159 10160 QualType R = Method->getReturnType(); 10161 if (!R->isScalarType()) 10162 return false; 10163 10164 return true; 10165 } 10166 10167 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 10168 FromE = FromE->IgnoreParenImpCasts(); 10169 switch (FromE->getStmtClass()) { 10170 default: 10171 break; 10172 case Stmt::ObjCStringLiteralClass: 10173 // "string literal" 10174 return LK_String; 10175 case Stmt::ObjCArrayLiteralClass: 10176 // "array literal" 10177 return LK_Array; 10178 case Stmt::ObjCDictionaryLiteralClass: 10179 // "dictionary literal" 10180 return LK_Dictionary; 10181 case Stmt::BlockExprClass: 10182 return LK_Block; 10183 case Stmt::ObjCBoxedExprClass: { 10184 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 10185 switch (Inner->getStmtClass()) { 10186 case Stmt::IntegerLiteralClass: 10187 case Stmt::FloatingLiteralClass: 10188 case Stmt::CharacterLiteralClass: 10189 case Stmt::ObjCBoolLiteralExprClass: 10190 case Stmt::CXXBoolLiteralExprClass: 10191 // "numeric literal" 10192 return LK_Numeric; 10193 case Stmt::ImplicitCastExprClass: { 10194 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 10195 // Boolean literals can be represented by implicit casts. 10196 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 10197 return LK_Numeric; 10198 break; 10199 } 10200 default: 10201 break; 10202 } 10203 return LK_Boxed; 10204 } 10205 } 10206 return LK_None; 10207 } 10208 10209 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 10210 ExprResult &LHS, ExprResult &RHS, 10211 BinaryOperator::Opcode Opc){ 10212 Expr *Literal; 10213 Expr *Other; 10214 if (isObjCObjectLiteral(LHS)) { 10215 Literal = LHS.get(); 10216 Other = RHS.get(); 10217 } else { 10218 Literal = RHS.get(); 10219 Other = LHS.get(); 10220 } 10221 10222 // Don't warn on comparisons against nil. 10223 Other = Other->IgnoreParenCasts(); 10224 if (Other->isNullPointerConstant(S.getASTContext(), 10225 Expr::NPC_ValueDependentIsNotNull)) 10226 return; 10227 10228 // This should be kept in sync with warn_objc_literal_comparison. 10229 // LK_String should always be after the other literals, since it has its own 10230 // warning flag. 10231 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 10232 assert(LiteralKind != Sema::LK_Block); 10233 if (LiteralKind == Sema::LK_None) { 10234 llvm_unreachable("Unknown Objective-C object literal kind"); 10235 } 10236 10237 if (LiteralKind == Sema::LK_String) 10238 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 10239 << Literal->getSourceRange(); 10240 else 10241 S.Diag(Loc, diag::warn_objc_literal_comparison) 10242 << LiteralKind << Literal->getSourceRange(); 10243 10244 if (BinaryOperator::isEqualityOp(Opc) && 10245 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 10246 SourceLocation Start = LHS.get()->getBeginLoc(); 10247 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 10248 CharSourceRange OpRange = 10249 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 10250 10251 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 10252 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 10253 << FixItHint::CreateReplacement(OpRange, " isEqual:") 10254 << FixItHint::CreateInsertion(End, "]"); 10255 } 10256 } 10257 10258 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 10259 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 10260 ExprResult &RHS, SourceLocation Loc, 10261 BinaryOperatorKind Opc) { 10262 // Check that left hand side is !something. 10263 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 10264 if (!UO || UO->getOpcode() != UO_LNot) return; 10265 10266 // Only check if the right hand side is non-bool arithmetic type. 10267 if (RHS.get()->isKnownToHaveBooleanValue()) return; 10268 10269 // Make sure that the something in !something is not bool. 10270 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 10271 if (SubExpr->isKnownToHaveBooleanValue()) return; 10272 10273 // Emit warning. 10274 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 10275 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 10276 << Loc << IsBitwiseOp; 10277 10278 // First note suggest !(x < y) 10279 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 10280 SourceLocation FirstClose = RHS.get()->getEndLoc(); 10281 FirstClose = S.getLocForEndOfToken(FirstClose); 10282 if (FirstClose.isInvalid()) 10283 FirstOpen = SourceLocation(); 10284 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 10285 << IsBitwiseOp 10286 << FixItHint::CreateInsertion(FirstOpen, "(") 10287 << FixItHint::CreateInsertion(FirstClose, ")"); 10288 10289 // Second note suggests (!x) < y 10290 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 10291 SourceLocation SecondClose = LHS.get()->getEndLoc(); 10292 SecondClose = S.getLocForEndOfToken(SecondClose); 10293 if (SecondClose.isInvalid()) 10294 SecondOpen = SourceLocation(); 10295 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 10296 << FixItHint::CreateInsertion(SecondOpen, "(") 10297 << FixItHint::CreateInsertion(SecondClose, ")"); 10298 } 10299 10300 // Returns true if E refers to a non-weak array. 10301 static bool checkForArray(const Expr *E) { 10302 const ValueDecl *D = nullptr; 10303 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 10304 D = DR->getDecl(); 10305 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 10306 if (Mem->isImplicitAccess()) 10307 D = Mem->getMemberDecl(); 10308 } 10309 if (!D) 10310 return false; 10311 return D->getType()->isArrayType() && !D->isWeak(); 10312 } 10313 10314 /// Diagnose some forms of syntactically-obvious tautological comparison. 10315 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 10316 Expr *LHS, Expr *RHS, 10317 BinaryOperatorKind Opc) { 10318 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 10319 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 10320 10321 QualType LHSType = LHS->getType(); 10322 QualType RHSType = RHS->getType(); 10323 if (LHSType->hasFloatingRepresentation() || 10324 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 10325 LHS->getBeginLoc().isMacroID() || RHS->getBeginLoc().isMacroID() || 10326 S.inTemplateInstantiation()) 10327 return; 10328 10329 // Comparisons between two array types are ill-formed for operator<=>, so 10330 // we shouldn't emit any additional warnings about it. 10331 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 10332 return; 10333 10334 // For non-floating point types, check for self-comparisons of the form 10335 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 10336 // often indicate logic errors in the program. 10337 // 10338 // NOTE: Don't warn about comparison expressions resulting from macro 10339 // expansion. Also don't warn about comparisons which are only self 10340 // comparisons within a template instantiation. The warnings should catch 10341 // obvious cases in the definition of the template anyways. The idea is to 10342 // warn when the typed comparison operator will always evaluate to the same 10343 // result. 10344 10345 // Used for indexing into %select in warn_comparison_always 10346 enum { 10347 AlwaysConstant, 10348 AlwaysTrue, 10349 AlwaysFalse, 10350 AlwaysEqual, // std::strong_ordering::equal from operator<=> 10351 }; 10352 10353 if (Expr::isSameComparisonOperand(LHS, RHS)) { 10354 unsigned Result; 10355 switch (Opc) { 10356 case BO_EQ: case BO_LE: case BO_GE: 10357 Result = AlwaysTrue; 10358 break; 10359 case BO_NE: case BO_LT: case BO_GT: 10360 Result = AlwaysFalse; 10361 break; 10362 case BO_Cmp: 10363 Result = AlwaysEqual; 10364 break; 10365 default: 10366 Result = AlwaysConstant; 10367 break; 10368 } 10369 S.DiagRuntimeBehavior(Loc, nullptr, 10370 S.PDiag(diag::warn_comparison_always) 10371 << 0 /*self-comparison*/ 10372 << Result); 10373 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 10374 // What is it always going to evaluate to? 10375 unsigned Result; 10376 switch(Opc) { 10377 case BO_EQ: // e.g. array1 == array2 10378 Result = AlwaysFalse; 10379 break; 10380 case BO_NE: // e.g. array1 != array2 10381 Result = AlwaysTrue; 10382 break; 10383 default: // e.g. array1 <= array2 10384 // The best we can say is 'a constant' 10385 Result = AlwaysConstant; 10386 break; 10387 } 10388 S.DiagRuntimeBehavior(Loc, nullptr, 10389 S.PDiag(diag::warn_comparison_always) 10390 << 1 /*array comparison*/ 10391 << Result); 10392 } 10393 10394 if (isa<CastExpr>(LHSStripped)) 10395 LHSStripped = LHSStripped->IgnoreParenCasts(); 10396 if (isa<CastExpr>(RHSStripped)) 10397 RHSStripped = RHSStripped->IgnoreParenCasts(); 10398 10399 // Warn about comparisons against a string constant (unless the other 10400 // operand is null); the user probably wants strcmp. 10401 Expr *LiteralString = nullptr; 10402 Expr *LiteralStringStripped = nullptr; 10403 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 10404 !RHSStripped->isNullPointerConstant(S.Context, 10405 Expr::NPC_ValueDependentIsNull)) { 10406 LiteralString = LHS; 10407 LiteralStringStripped = LHSStripped; 10408 } else if ((isa<StringLiteral>(RHSStripped) || 10409 isa<ObjCEncodeExpr>(RHSStripped)) && 10410 !LHSStripped->isNullPointerConstant(S.Context, 10411 Expr::NPC_ValueDependentIsNull)) { 10412 LiteralString = RHS; 10413 LiteralStringStripped = RHSStripped; 10414 } 10415 10416 if (LiteralString) { 10417 S.DiagRuntimeBehavior(Loc, nullptr, 10418 S.PDiag(diag::warn_stringcompare) 10419 << isa<ObjCEncodeExpr>(LiteralStringStripped) 10420 << LiteralString->getSourceRange()); 10421 } 10422 } 10423 10424 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 10425 switch (CK) { 10426 default: { 10427 #ifndef NDEBUG 10428 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 10429 << "\n"; 10430 #endif 10431 llvm_unreachable("unhandled cast kind"); 10432 } 10433 case CK_UserDefinedConversion: 10434 return ICK_Identity; 10435 case CK_LValueToRValue: 10436 return ICK_Lvalue_To_Rvalue; 10437 case CK_ArrayToPointerDecay: 10438 return ICK_Array_To_Pointer; 10439 case CK_FunctionToPointerDecay: 10440 return ICK_Function_To_Pointer; 10441 case CK_IntegralCast: 10442 return ICK_Integral_Conversion; 10443 case CK_FloatingCast: 10444 return ICK_Floating_Conversion; 10445 case CK_IntegralToFloating: 10446 case CK_FloatingToIntegral: 10447 return ICK_Floating_Integral; 10448 case CK_IntegralComplexCast: 10449 case CK_FloatingComplexCast: 10450 case CK_FloatingComplexToIntegralComplex: 10451 case CK_IntegralComplexToFloatingComplex: 10452 return ICK_Complex_Conversion; 10453 case CK_FloatingComplexToReal: 10454 case CK_FloatingRealToComplex: 10455 case CK_IntegralComplexToReal: 10456 case CK_IntegralRealToComplex: 10457 return ICK_Complex_Real; 10458 } 10459 } 10460 10461 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 10462 QualType FromType, 10463 SourceLocation Loc) { 10464 // Check for a narrowing implicit conversion. 10465 StandardConversionSequence SCS; 10466 SCS.setAsIdentityConversion(); 10467 SCS.setToType(0, FromType); 10468 SCS.setToType(1, ToType); 10469 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 10470 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 10471 10472 APValue PreNarrowingValue; 10473 QualType PreNarrowingType; 10474 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 10475 PreNarrowingType, 10476 /*IgnoreFloatToIntegralConversion*/ true)) { 10477 case NK_Dependent_Narrowing: 10478 // Implicit conversion to a narrower type, but the expression is 10479 // value-dependent so we can't tell whether it's actually narrowing. 10480 case NK_Not_Narrowing: 10481 return false; 10482 10483 case NK_Constant_Narrowing: 10484 // Implicit conversion to a narrower type, and the value is not a constant 10485 // expression. 10486 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 10487 << /*Constant*/ 1 10488 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 10489 return true; 10490 10491 case NK_Variable_Narrowing: 10492 // Implicit conversion to a narrower type, and the value is not a constant 10493 // expression. 10494 case NK_Type_Narrowing: 10495 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 10496 << /*Constant*/ 0 << FromType << ToType; 10497 // TODO: It's not a constant expression, but what if the user intended it 10498 // to be? Can we produce notes to help them figure out why it isn't? 10499 return true; 10500 } 10501 llvm_unreachable("unhandled case in switch"); 10502 } 10503 10504 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 10505 ExprResult &LHS, 10506 ExprResult &RHS, 10507 SourceLocation Loc) { 10508 using CCT = ComparisonCategoryType; 10509 10510 QualType LHSType = LHS.get()->getType(); 10511 QualType RHSType = RHS.get()->getType(); 10512 // Dig out the original argument type and expression before implicit casts 10513 // were applied. These are the types/expressions we need to check the 10514 // [expr.spaceship] requirements against. 10515 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 10516 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 10517 QualType LHSStrippedType = LHSStripped.get()->getType(); 10518 QualType RHSStrippedType = RHSStripped.get()->getType(); 10519 10520 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 10521 // other is not, the program is ill-formed. 10522 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 10523 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 10524 return QualType(); 10525 } 10526 10527 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 10528 RHSStrippedType->isEnumeralType(); 10529 if (NumEnumArgs == 1) { 10530 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 10531 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 10532 if (OtherTy->hasFloatingRepresentation()) { 10533 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 10534 return QualType(); 10535 } 10536 } 10537 if (NumEnumArgs == 2) { 10538 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 10539 // type E, the operator yields the result of converting the operands 10540 // to the underlying type of E and applying <=> to the converted operands. 10541 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 10542 S.InvalidOperands(Loc, LHS, RHS); 10543 return QualType(); 10544 } 10545 QualType IntType = 10546 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 10547 assert(IntType->isArithmeticType()); 10548 10549 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 10550 // promote the boolean type, and all other promotable integer types, to 10551 // avoid this. 10552 if (IntType->isPromotableIntegerType()) 10553 IntType = S.Context.getPromotedIntegerType(IntType); 10554 10555 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 10556 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 10557 LHSType = RHSType = IntType; 10558 } 10559 10560 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 10561 // usual arithmetic conversions are applied to the operands. 10562 QualType Type = S.UsualArithmeticConversions(LHS, RHS); 10563 if (LHS.isInvalid() || RHS.isInvalid()) 10564 return QualType(); 10565 if (Type.isNull()) 10566 return S.InvalidOperands(Loc, LHS, RHS); 10567 assert(Type->isArithmeticType() || Type->isEnumeralType()); 10568 10569 bool HasNarrowing = checkThreeWayNarrowingConversion( 10570 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 10571 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 10572 RHS.get()->getBeginLoc()); 10573 if (HasNarrowing) 10574 return QualType(); 10575 10576 assert(!Type.isNull() && "composite type for <=> has not been set"); 10577 10578 auto TypeKind = [&]() { 10579 if (const ComplexType *CT = Type->getAs<ComplexType>()) { 10580 if (CT->getElementType()->hasFloatingRepresentation()) 10581 return CCT::WeakEquality; 10582 return CCT::StrongEquality; 10583 } 10584 if (Type->isIntegralOrEnumerationType()) 10585 return CCT::StrongOrdering; 10586 if (Type->hasFloatingRepresentation()) 10587 return CCT::PartialOrdering; 10588 llvm_unreachable("other types are unimplemented"); 10589 }(); 10590 10591 return S.CheckComparisonCategoryType(TypeKind, Loc); 10592 } 10593 10594 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 10595 ExprResult &RHS, 10596 SourceLocation Loc, 10597 BinaryOperatorKind Opc) { 10598 if (Opc == BO_Cmp) 10599 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 10600 10601 // C99 6.5.8p3 / C99 6.5.9p4 10602 QualType Type = S.UsualArithmeticConversions(LHS, RHS); 10603 if (LHS.isInvalid() || RHS.isInvalid()) 10604 return QualType(); 10605 if (Type.isNull()) 10606 return S.InvalidOperands(Loc, LHS, RHS); 10607 assert(Type->isArithmeticType() || Type->isEnumeralType()); 10608 10609 checkEnumComparison(S, Loc, LHS.get(), RHS.get()); 10610 10611 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 10612 return S.InvalidOperands(Loc, LHS, RHS); 10613 10614 // Check for comparisons of floating point operands using != and ==. 10615 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 10616 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 10617 10618 // The result of comparisons is 'bool' in C++, 'int' in C. 10619 return S.Context.getLogicalOperationType(); 10620 } 10621 10622 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 10623 if (!NullE.get()->getType()->isAnyPointerType()) 10624 return; 10625 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 10626 if (!E.get()->getType()->isAnyPointerType() && 10627 E.get()->isNullPointerConstant(Context, 10628 Expr::NPC_ValueDependentIsNotNull) == 10629 Expr::NPCK_ZeroExpression) { 10630 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 10631 if (CL->getValue() == 0) 10632 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 10633 << NullValue 10634 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 10635 NullValue ? "NULL" : "(void *)0"); 10636 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 10637 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 10638 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 10639 if (T == Context.CharTy) 10640 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 10641 << NullValue 10642 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 10643 NullValue ? "NULL" : "(void *)0"); 10644 } 10645 } 10646 } 10647 10648 // C99 6.5.8, C++ [expr.rel] 10649 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 10650 SourceLocation Loc, 10651 BinaryOperatorKind Opc) { 10652 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 10653 bool IsThreeWay = Opc == BO_Cmp; 10654 auto IsAnyPointerType = [](ExprResult E) { 10655 QualType Ty = E.get()->getType(); 10656 return Ty->isPointerType() || Ty->isMemberPointerType(); 10657 }; 10658 10659 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 10660 // type, array-to-pointer, ..., conversions are performed on both operands to 10661 // bring them to their composite type. 10662 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 10663 // any type-related checks. 10664 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 10665 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10666 if (LHS.isInvalid()) 10667 return QualType(); 10668 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10669 if (RHS.isInvalid()) 10670 return QualType(); 10671 } else { 10672 LHS = DefaultLvalueConversion(LHS.get()); 10673 if (LHS.isInvalid()) 10674 return QualType(); 10675 RHS = DefaultLvalueConversion(RHS.get()); 10676 if (RHS.isInvalid()) 10677 return QualType(); 10678 } 10679 10680 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 10681 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 10682 CheckPtrComparisonWithNullChar(LHS, RHS); 10683 CheckPtrComparisonWithNullChar(RHS, LHS); 10684 } 10685 10686 // Handle vector comparisons separately. 10687 if (LHS.get()->getType()->isVectorType() || 10688 RHS.get()->getType()->isVectorType()) 10689 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 10690 10691 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 10692 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 10693 10694 QualType LHSType = LHS.get()->getType(); 10695 QualType RHSType = RHS.get()->getType(); 10696 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 10697 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 10698 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 10699 10700 const Expr::NullPointerConstantKind LHSNullKind = 10701 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 10702 const Expr::NullPointerConstantKind RHSNullKind = 10703 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 10704 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 10705 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 10706 10707 auto computeResultTy = [&]() { 10708 if (Opc != BO_Cmp) 10709 return Context.getLogicalOperationType(); 10710 assert(getLangOpts().CPlusPlus); 10711 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 10712 10713 QualType CompositeTy = LHS.get()->getType(); 10714 assert(!CompositeTy->isReferenceType()); 10715 10716 auto buildResultTy = [&](ComparisonCategoryType Kind) { 10717 return CheckComparisonCategoryType(Kind, Loc); 10718 }; 10719 10720 // C++2a [expr.spaceship]p7: If the composite pointer type is a function 10721 // pointer type, a pointer-to-member type, or std::nullptr_t, the 10722 // result is of type std::strong_equality 10723 if (CompositeTy->isFunctionPointerType() || 10724 CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType()) 10725 // FIXME: consider making the function pointer case produce 10726 // strong_ordering not strong_equality, per P0946R0-Jax18 discussion 10727 // and direction polls 10728 return buildResultTy(ComparisonCategoryType::StrongEquality); 10729 10730 // C++2a [expr.spaceship]p8: If the composite pointer type is an object 10731 // pointer type, p <=> q is of type std::strong_ordering. 10732 if (CompositeTy->isPointerType()) { 10733 // P0946R0: Comparisons between a null pointer constant and an object 10734 // pointer result in std::strong_equality 10735 if (LHSIsNull != RHSIsNull) 10736 return buildResultTy(ComparisonCategoryType::StrongEquality); 10737 return buildResultTy(ComparisonCategoryType::StrongOrdering); 10738 } 10739 // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed. 10740 // TODO: Extend support for operator<=> to ObjC types. 10741 return InvalidOperands(Loc, LHS, RHS); 10742 }; 10743 10744 10745 if (!IsRelational && LHSIsNull != RHSIsNull) { 10746 bool IsEquality = Opc == BO_EQ; 10747 if (RHSIsNull) 10748 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 10749 RHS.get()->getSourceRange()); 10750 else 10751 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 10752 LHS.get()->getSourceRange()); 10753 } 10754 10755 if ((LHSType->isIntegerType() && !LHSIsNull) || 10756 (RHSType->isIntegerType() && !RHSIsNull)) { 10757 // Skip normal pointer conversion checks in this case; we have better 10758 // diagnostics for this below. 10759 } else if (getLangOpts().CPlusPlus) { 10760 // Equality comparison of a function pointer to a void pointer is invalid, 10761 // but we allow it as an extension. 10762 // FIXME: If we really want to allow this, should it be part of composite 10763 // pointer type computation so it works in conditionals too? 10764 if (!IsRelational && 10765 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 10766 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 10767 // This is a gcc extension compatibility comparison. 10768 // In a SFINAE context, we treat this as a hard error to maintain 10769 // conformance with the C++ standard. 10770 diagnoseFunctionPointerToVoidComparison( 10771 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 10772 10773 if (isSFINAEContext()) 10774 return QualType(); 10775 10776 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10777 return computeResultTy(); 10778 } 10779 10780 // C++ [expr.eq]p2: 10781 // If at least one operand is a pointer [...] bring them to their 10782 // composite pointer type. 10783 // C++ [expr.spaceship]p6 10784 // If at least one of the operands is of pointer type, [...] bring them 10785 // to their composite pointer type. 10786 // C++ [expr.rel]p2: 10787 // If both operands are pointers, [...] bring them to their composite 10788 // pointer type. 10789 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 10790 (IsRelational ? 2 : 1) && 10791 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 10792 RHSType->isObjCObjectPointerType()))) { 10793 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 10794 return QualType(); 10795 return computeResultTy(); 10796 } 10797 } else if (LHSType->isPointerType() && 10798 RHSType->isPointerType()) { // C99 6.5.8p2 10799 // All of the following pointer-related warnings are GCC extensions, except 10800 // when handling null pointer constants. 10801 QualType LCanPointeeTy = 10802 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 10803 QualType RCanPointeeTy = 10804 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 10805 10806 // C99 6.5.9p2 and C99 6.5.8p2 10807 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 10808 RCanPointeeTy.getUnqualifiedType())) { 10809 // Valid unless a relational comparison of function pointers 10810 if (IsRelational && LCanPointeeTy->isFunctionType()) { 10811 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 10812 << LHSType << RHSType << LHS.get()->getSourceRange() 10813 << RHS.get()->getSourceRange(); 10814 } 10815 } else if (!IsRelational && 10816 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 10817 // Valid unless comparison between non-null pointer and function pointer 10818 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 10819 && !LHSIsNull && !RHSIsNull) 10820 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 10821 /*isError*/false); 10822 } else { 10823 // Invalid 10824 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 10825 } 10826 if (LCanPointeeTy != RCanPointeeTy) { 10827 // Treat NULL constant as a special case in OpenCL. 10828 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 10829 const PointerType *LHSPtr = LHSType->castAs<PointerType>(); 10830 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->castAs<PointerType>())) { 10831 Diag(Loc, 10832 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10833 << LHSType << RHSType << 0 /* comparison */ 10834 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10835 } 10836 } 10837 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 10838 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 10839 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 10840 : CK_BitCast; 10841 if (LHSIsNull && !RHSIsNull) 10842 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 10843 else 10844 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 10845 } 10846 return computeResultTy(); 10847 } 10848 10849 if (getLangOpts().CPlusPlus) { 10850 // C++ [expr.eq]p4: 10851 // Two operands of type std::nullptr_t or one operand of type 10852 // std::nullptr_t and the other a null pointer constant compare equal. 10853 if (!IsRelational && LHSIsNull && RHSIsNull) { 10854 if (LHSType->isNullPtrType()) { 10855 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10856 return computeResultTy(); 10857 } 10858 if (RHSType->isNullPtrType()) { 10859 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10860 return computeResultTy(); 10861 } 10862 } 10863 10864 // Comparison of Objective-C pointers and block pointers against nullptr_t. 10865 // These aren't covered by the composite pointer type rules. 10866 if (!IsRelational && RHSType->isNullPtrType() && 10867 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 10868 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10869 return computeResultTy(); 10870 } 10871 if (!IsRelational && LHSType->isNullPtrType() && 10872 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 10873 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10874 return computeResultTy(); 10875 } 10876 10877 if (IsRelational && 10878 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 10879 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 10880 // HACK: Relational comparison of nullptr_t against a pointer type is 10881 // invalid per DR583, but we allow it within std::less<> and friends, 10882 // since otherwise common uses of it break. 10883 // FIXME: Consider removing this hack once LWG fixes std::less<> and 10884 // friends to have std::nullptr_t overload candidates. 10885 DeclContext *DC = CurContext; 10886 if (isa<FunctionDecl>(DC)) 10887 DC = DC->getParent(); 10888 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 10889 if (CTSD->isInStdNamespace() && 10890 llvm::StringSwitch<bool>(CTSD->getName()) 10891 .Cases("less", "less_equal", "greater", "greater_equal", true) 10892 .Default(false)) { 10893 if (RHSType->isNullPtrType()) 10894 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10895 else 10896 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10897 return computeResultTy(); 10898 } 10899 } 10900 } 10901 10902 // C++ [expr.eq]p2: 10903 // If at least one operand is a pointer to member, [...] bring them to 10904 // their composite pointer type. 10905 if (!IsRelational && 10906 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 10907 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 10908 return QualType(); 10909 else 10910 return computeResultTy(); 10911 } 10912 } 10913 10914 // Handle block pointer types. 10915 if (!IsRelational && LHSType->isBlockPointerType() && 10916 RHSType->isBlockPointerType()) { 10917 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 10918 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 10919 10920 if (!LHSIsNull && !RHSIsNull && 10921 !Context.typesAreCompatible(lpointee, rpointee)) { 10922 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 10923 << LHSType << RHSType << LHS.get()->getSourceRange() 10924 << RHS.get()->getSourceRange(); 10925 } 10926 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10927 return computeResultTy(); 10928 } 10929 10930 // Allow block pointers to be compared with null pointer constants. 10931 if (!IsRelational 10932 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 10933 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 10934 if (!LHSIsNull && !RHSIsNull) { 10935 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 10936 ->getPointeeType()->isVoidType()) 10937 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 10938 ->getPointeeType()->isVoidType()))) 10939 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 10940 << LHSType << RHSType << LHS.get()->getSourceRange() 10941 << RHS.get()->getSourceRange(); 10942 } 10943 if (LHSIsNull && !RHSIsNull) 10944 LHS = ImpCastExprToType(LHS.get(), RHSType, 10945 RHSType->isPointerType() ? CK_BitCast 10946 : CK_AnyPointerToBlockPointerCast); 10947 else 10948 RHS = ImpCastExprToType(RHS.get(), LHSType, 10949 LHSType->isPointerType() ? CK_BitCast 10950 : CK_AnyPointerToBlockPointerCast); 10951 return computeResultTy(); 10952 } 10953 10954 if (LHSType->isObjCObjectPointerType() || 10955 RHSType->isObjCObjectPointerType()) { 10956 const PointerType *LPT = LHSType->getAs<PointerType>(); 10957 const PointerType *RPT = RHSType->getAs<PointerType>(); 10958 if (LPT || RPT) { 10959 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 10960 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 10961 10962 if (!LPtrToVoid && !RPtrToVoid && 10963 !Context.typesAreCompatible(LHSType, RHSType)) { 10964 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 10965 /*isError*/false); 10966 } 10967 if (LHSIsNull && !RHSIsNull) { 10968 Expr *E = LHS.get(); 10969 if (getLangOpts().ObjCAutoRefCount) 10970 CheckObjCConversion(SourceRange(), RHSType, E, 10971 CCK_ImplicitConversion); 10972 LHS = ImpCastExprToType(E, RHSType, 10973 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 10974 } 10975 else { 10976 Expr *E = RHS.get(); 10977 if (getLangOpts().ObjCAutoRefCount) 10978 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 10979 /*Diagnose=*/true, 10980 /*DiagnoseCFAudited=*/false, Opc); 10981 RHS = ImpCastExprToType(E, LHSType, 10982 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 10983 } 10984 return computeResultTy(); 10985 } 10986 if (LHSType->isObjCObjectPointerType() && 10987 RHSType->isObjCObjectPointerType()) { 10988 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 10989 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 10990 /*isError*/false); 10991 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 10992 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 10993 10994 if (LHSIsNull && !RHSIsNull) 10995 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10996 else 10997 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10998 return computeResultTy(); 10999 } 11000 11001 if (!IsRelational && LHSType->isBlockPointerType() && 11002 RHSType->isBlockCompatibleObjCPointerType(Context)) { 11003 LHS = ImpCastExprToType(LHS.get(), RHSType, 11004 CK_BlockPointerToObjCPointerCast); 11005 return computeResultTy(); 11006 } else if (!IsRelational && 11007 LHSType->isBlockCompatibleObjCPointerType(Context) && 11008 RHSType->isBlockPointerType()) { 11009 RHS = ImpCastExprToType(RHS.get(), LHSType, 11010 CK_BlockPointerToObjCPointerCast); 11011 return computeResultTy(); 11012 } 11013 } 11014 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 11015 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 11016 unsigned DiagID = 0; 11017 bool isError = false; 11018 if (LangOpts.DebuggerSupport) { 11019 // Under a debugger, allow the comparison of pointers to integers, 11020 // since users tend to want to compare addresses. 11021 } else if ((LHSIsNull && LHSType->isIntegerType()) || 11022 (RHSIsNull && RHSType->isIntegerType())) { 11023 if (IsRelational) { 11024 isError = getLangOpts().CPlusPlus; 11025 DiagID = 11026 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 11027 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 11028 } 11029 } else if (getLangOpts().CPlusPlus) { 11030 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 11031 isError = true; 11032 } else if (IsRelational) 11033 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 11034 else 11035 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 11036 11037 if (DiagID) { 11038 Diag(Loc, DiagID) 11039 << LHSType << RHSType << LHS.get()->getSourceRange() 11040 << RHS.get()->getSourceRange(); 11041 if (isError) 11042 return QualType(); 11043 } 11044 11045 if (LHSType->isIntegerType()) 11046 LHS = ImpCastExprToType(LHS.get(), RHSType, 11047 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11048 else 11049 RHS = ImpCastExprToType(RHS.get(), LHSType, 11050 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11051 return computeResultTy(); 11052 } 11053 11054 // Handle block pointers. 11055 if (!IsRelational && RHSIsNull 11056 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 11057 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11058 return computeResultTy(); 11059 } 11060 if (!IsRelational && LHSIsNull 11061 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 11062 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11063 return computeResultTy(); 11064 } 11065 11066 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 11067 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 11068 return computeResultTy(); 11069 } 11070 11071 if (LHSType->isQueueT() && RHSType->isQueueT()) { 11072 return computeResultTy(); 11073 } 11074 11075 if (LHSIsNull && RHSType->isQueueT()) { 11076 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11077 return computeResultTy(); 11078 } 11079 11080 if (LHSType->isQueueT() && RHSIsNull) { 11081 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11082 return computeResultTy(); 11083 } 11084 } 11085 11086 return InvalidOperands(Loc, LHS, RHS); 11087 } 11088 11089 // Return a signed ext_vector_type that is of identical size and number of 11090 // elements. For floating point vectors, return an integer type of identical 11091 // size and number of elements. In the non ext_vector_type case, search from 11092 // the largest type to the smallest type to avoid cases where long long == long, 11093 // where long gets picked over long long. 11094 QualType Sema::GetSignedVectorType(QualType V) { 11095 const VectorType *VTy = V->castAs<VectorType>(); 11096 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 11097 11098 if (isa<ExtVectorType>(VTy)) { 11099 if (TypeSize == Context.getTypeSize(Context.CharTy)) 11100 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 11101 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 11102 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 11103 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 11104 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 11105 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 11106 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 11107 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 11108 "Unhandled vector element size in vector compare"); 11109 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 11110 } 11111 11112 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 11113 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 11114 VectorType::GenericVector); 11115 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 11116 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 11117 VectorType::GenericVector); 11118 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 11119 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 11120 VectorType::GenericVector); 11121 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 11122 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 11123 VectorType::GenericVector); 11124 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 11125 "Unhandled vector element size in vector compare"); 11126 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 11127 VectorType::GenericVector); 11128 } 11129 11130 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 11131 /// operates on extended vector types. Instead of producing an IntTy result, 11132 /// like a scalar comparison, a vector comparison produces a vector of integer 11133 /// types. 11134 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 11135 SourceLocation Loc, 11136 BinaryOperatorKind Opc) { 11137 // Check to make sure we're operating on vectors of the same type and width, 11138 // Allowing one side to be a scalar of element type. 11139 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 11140 /*AllowBothBool*/true, 11141 /*AllowBoolConversions*/getLangOpts().ZVector); 11142 if (vType.isNull()) 11143 return vType; 11144 11145 QualType LHSType = LHS.get()->getType(); 11146 11147 // If AltiVec, the comparison results in a numeric type, i.e. 11148 // bool for C++, int for C 11149 if (getLangOpts().AltiVec && 11150 vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 11151 return Context.getLogicalOperationType(); 11152 11153 // For non-floating point types, check for self-comparisons of the form 11154 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11155 // often indicate logic errors in the program. 11156 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11157 11158 // Check for comparisons of floating point operands using != and ==. 11159 if (BinaryOperator::isEqualityOp(Opc) && 11160 LHSType->hasFloatingRepresentation()) { 11161 assert(RHS.get()->getType()->hasFloatingRepresentation()); 11162 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11163 } 11164 11165 // Return a signed type for the vector. 11166 return GetSignedVectorType(vType); 11167 } 11168 11169 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 11170 const ExprResult &XorRHS, 11171 const SourceLocation Loc) { 11172 // Do not diagnose macros. 11173 if (Loc.isMacroID()) 11174 return; 11175 11176 bool Negative = false; 11177 bool ExplicitPlus = false; 11178 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 11179 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 11180 11181 if (!LHSInt) 11182 return; 11183 if (!RHSInt) { 11184 // Check negative literals. 11185 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 11186 UnaryOperatorKind Opc = UO->getOpcode(); 11187 if (Opc != UO_Minus && Opc != UO_Plus) 11188 return; 11189 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 11190 if (!RHSInt) 11191 return; 11192 Negative = (Opc == UO_Minus); 11193 ExplicitPlus = !Negative; 11194 } else { 11195 return; 11196 } 11197 } 11198 11199 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 11200 llvm::APInt RightSideValue = RHSInt->getValue(); 11201 if (LeftSideValue != 2 && LeftSideValue != 10) 11202 return; 11203 11204 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 11205 return; 11206 11207 CharSourceRange ExprRange = CharSourceRange::getCharRange( 11208 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 11209 llvm::StringRef ExprStr = 11210 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 11211 11212 CharSourceRange XorRange = 11213 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11214 llvm::StringRef XorStr = 11215 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 11216 // Do not diagnose if xor keyword/macro is used. 11217 if (XorStr == "xor") 11218 return; 11219 11220 std::string LHSStr = Lexer::getSourceText( 11221 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 11222 S.getSourceManager(), S.getLangOpts()); 11223 std::string RHSStr = Lexer::getSourceText( 11224 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 11225 S.getSourceManager(), S.getLangOpts()); 11226 11227 if (Negative) { 11228 RightSideValue = -RightSideValue; 11229 RHSStr = "-" + RHSStr; 11230 } else if (ExplicitPlus) { 11231 RHSStr = "+" + RHSStr; 11232 } 11233 11234 StringRef LHSStrRef = LHSStr; 11235 StringRef RHSStrRef = RHSStr; 11236 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 11237 // literals. 11238 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 11239 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 11240 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 11241 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 11242 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 11243 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 11244 LHSStrRef.find('\'') != StringRef::npos || 11245 RHSStrRef.find('\'') != StringRef::npos) 11246 return; 11247 11248 bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 11249 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 11250 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 11251 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 11252 std::string SuggestedExpr = "1 << " + RHSStr; 11253 bool Overflow = false; 11254 llvm::APInt One = (LeftSideValue - 1); 11255 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 11256 if (Overflow) { 11257 if (RightSideIntValue < 64) 11258 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 11259 << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr) 11260 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 11261 else if (RightSideIntValue == 64) 11262 S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true); 11263 else 11264 return; 11265 } else { 11266 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 11267 << ExprStr << XorValue.toString(10, true) << SuggestedExpr 11268 << PowValue.toString(10, true) 11269 << FixItHint::CreateReplacement( 11270 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 11271 } 11272 11273 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor; 11274 } else if (LeftSideValue == 10) { 11275 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 11276 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 11277 << ExprStr << XorValue.toString(10, true) << SuggestedValue 11278 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 11279 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor; 11280 } 11281 } 11282 11283 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 11284 SourceLocation Loc) { 11285 // Ensure that either both operands are of the same vector type, or 11286 // one operand is of a vector type and the other is of its element type. 11287 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 11288 /*AllowBothBool*/true, 11289 /*AllowBoolConversions*/false); 11290 if (vType.isNull()) 11291 return InvalidOperands(Loc, LHS, RHS); 11292 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 11293 !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation()) 11294 return InvalidOperands(Loc, LHS, RHS); 11295 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 11296 // usage of the logical operators && and || with vectors in C. This 11297 // check could be notionally dropped. 11298 if (!getLangOpts().CPlusPlus && 11299 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 11300 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 11301 11302 return GetSignedVectorType(LHS.get()->getType()); 11303 } 11304 11305 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 11306 SourceLocation Loc, 11307 BinaryOperatorKind Opc) { 11308 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11309 11310 bool IsCompAssign = 11311 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 11312 11313 if (LHS.get()->getType()->isVectorType() || 11314 RHS.get()->getType()->isVectorType()) { 11315 if (LHS.get()->getType()->hasIntegerRepresentation() && 11316 RHS.get()->getType()->hasIntegerRepresentation()) 11317 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 11318 /*AllowBothBool*/true, 11319 /*AllowBoolConversions*/getLangOpts().ZVector); 11320 return InvalidOperands(Loc, LHS, RHS); 11321 } 11322 11323 if (Opc == BO_And) 11324 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11325 11326 ExprResult LHSResult = LHS, RHSResult = RHS; 11327 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 11328 IsCompAssign); 11329 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 11330 return QualType(); 11331 LHS = LHSResult.get(); 11332 RHS = RHSResult.get(); 11333 11334 if (Opc == BO_Xor) 11335 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 11336 11337 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 11338 return compType; 11339 return InvalidOperands(Loc, LHS, RHS); 11340 } 11341 11342 // C99 6.5.[13,14] 11343 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 11344 SourceLocation Loc, 11345 BinaryOperatorKind Opc) { 11346 // Check vector operands differently. 11347 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 11348 return CheckVectorLogicalOperands(LHS, RHS, Loc); 11349 11350 bool EnumConstantInBoolContext = false; 11351 for (const ExprResult &HS : {LHS, RHS}) { 11352 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 11353 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 11354 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 11355 EnumConstantInBoolContext = true; 11356 } 11357 } 11358 11359 if (EnumConstantInBoolContext) 11360 Diag(Loc, diag::warn_enum_constant_in_bool_context); 11361 11362 // Diagnose cases where the user write a logical and/or but probably meant a 11363 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 11364 // is a constant. 11365 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 11366 !LHS.get()->getType()->isBooleanType() && 11367 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 11368 // Don't warn in macros or template instantiations. 11369 !Loc.isMacroID() && !inTemplateInstantiation()) { 11370 // If the RHS can be constant folded, and if it constant folds to something 11371 // that isn't 0 or 1 (which indicate a potential logical operation that 11372 // happened to fold to true/false) then warn. 11373 // Parens on the RHS are ignored. 11374 Expr::EvalResult EVResult; 11375 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 11376 llvm::APSInt Result = EVResult.Val.getInt(); 11377 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 11378 !RHS.get()->getExprLoc().isMacroID()) || 11379 (Result != 0 && Result != 1)) { 11380 Diag(Loc, diag::warn_logical_instead_of_bitwise) 11381 << RHS.get()->getSourceRange() 11382 << (Opc == BO_LAnd ? "&&" : "||"); 11383 // Suggest replacing the logical operator with the bitwise version 11384 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 11385 << (Opc == BO_LAnd ? "&" : "|") 11386 << FixItHint::CreateReplacement(SourceRange( 11387 Loc, getLocForEndOfToken(Loc)), 11388 Opc == BO_LAnd ? "&" : "|"); 11389 if (Opc == BO_LAnd) 11390 // Suggest replacing "Foo() && kNonZero" with "Foo()" 11391 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 11392 << FixItHint::CreateRemoval( 11393 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 11394 RHS.get()->getEndLoc())); 11395 } 11396 } 11397 } 11398 11399 if (!Context.getLangOpts().CPlusPlus) { 11400 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 11401 // not operate on the built-in scalar and vector float types. 11402 if (Context.getLangOpts().OpenCL && 11403 Context.getLangOpts().OpenCLVersion < 120) { 11404 if (LHS.get()->getType()->isFloatingType() || 11405 RHS.get()->getType()->isFloatingType()) 11406 return InvalidOperands(Loc, LHS, RHS); 11407 } 11408 11409 LHS = UsualUnaryConversions(LHS.get()); 11410 if (LHS.isInvalid()) 11411 return QualType(); 11412 11413 RHS = UsualUnaryConversions(RHS.get()); 11414 if (RHS.isInvalid()) 11415 return QualType(); 11416 11417 if (!LHS.get()->getType()->isScalarType() || 11418 !RHS.get()->getType()->isScalarType()) 11419 return InvalidOperands(Loc, LHS, RHS); 11420 11421 return Context.IntTy; 11422 } 11423 11424 // The following is safe because we only use this method for 11425 // non-overloadable operands. 11426 11427 // C++ [expr.log.and]p1 11428 // C++ [expr.log.or]p1 11429 // The operands are both contextually converted to type bool. 11430 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 11431 if (LHSRes.isInvalid()) 11432 return InvalidOperands(Loc, LHS, RHS); 11433 LHS = LHSRes; 11434 11435 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 11436 if (RHSRes.isInvalid()) 11437 return InvalidOperands(Loc, LHS, RHS); 11438 RHS = RHSRes; 11439 11440 // C++ [expr.log.and]p2 11441 // C++ [expr.log.or]p2 11442 // The result is a bool. 11443 return Context.BoolTy; 11444 } 11445 11446 static bool IsReadonlyMessage(Expr *E, Sema &S) { 11447 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 11448 if (!ME) return false; 11449 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 11450 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 11451 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 11452 if (!Base) return false; 11453 return Base->getMethodDecl() != nullptr; 11454 } 11455 11456 /// Is the given expression (which must be 'const') a reference to a 11457 /// variable which was originally non-const, but which has become 11458 /// 'const' due to being captured within a block? 11459 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 11460 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 11461 assert(E->isLValue() && E->getType().isConstQualified()); 11462 E = E->IgnoreParens(); 11463 11464 // Must be a reference to a declaration from an enclosing scope. 11465 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 11466 if (!DRE) return NCCK_None; 11467 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 11468 11469 // The declaration must be a variable which is not declared 'const'. 11470 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 11471 if (!var) return NCCK_None; 11472 if (var->getType().isConstQualified()) return NCCK_None; 11473 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 11474 11475 // Decide whether the first capture was for a block or a lambda. 11476 DeclContext *DC = S.CurContext, *Prev = nullptr; 11477 // Decide whether the first capture was for a block or a lambda. 11478 while (DC) { 11479 // For init-capture, it is possible that the variable belongs to the 11480 // template pattern of the current context. 11481 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 11482 if (var->isInitCapture() && 11483 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 11484 break; 11485 if (DC == var->getDeclContext()) 11486 break; 11487 Prev = DC; 11488 DC = DC->getParent(); 11489 } 11490 // Unless we have an init-capture, we've gone one step too far. 11491 if (!var->isInitCapture()) 11492 DC = Prev; 11493 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 11494 } 11495 11496 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 11497 Ty = Ty.getNonReferenceType(); 11498 if (IsDereference && Ty->isPointerType()) 11499 Ty = Ty->getPointeeType(); 11500 return !Ty.isConstQualified(); 11501 } 11502 11503 // Update err_typecheck_assign_const and note_typecheck_assign_const 11504 // when this enum is changed. 11505 enum { 11506 ConstFunction, 11507 ConstVariable, 11508 ConstMember, 11509 ConstMethod, 11510 NestedConstMember, 11511 ConstUnknown, // Keep as last element 11512 }; 11513 11514 /// Emit the "read-only variable not assignable" error and print notes to give 11515 /// more information about why the variable is not assignable, such as pointing 11516 /// to the declaration of a const variable, showing that a method is const, or 11517 /// that the function is returning a const reference. 11518 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 11519 SourceLocation Loc) { 11520 SourceRange ExprRange = E->getSourceRange(); 11521 11522 // Only emit one error on the first const found. All other consts will emit 11523 // a note to the error. 11524 bool DiagnosticEmitted = false; 11525 11526 // Track if the current expression is the result of a dereference, and if the 11527 // next checked expression is the result of a dereference. 11528 bool IsDereference = false; 11529 bool NextIsDereference = false; 11530 11531 // Loop to process MemberExpr chains. 11532 while (true) { 11533 IsDereference = NextIsDereference; 11534 11535 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 11536 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 11537 NextIsDereference = ME->isArrow(); 11538 const ValueDecl *VD = ME->getMemberDecl(); 11539 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 11540 // Mutable fields can be modified even if the class is const. 11541 if (Field->isMutable()) { 11542 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 11543 break; 11544 } 11545 11546 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 11547 if (!DiagnosticEmitted) { 11548 S.Diag(Loc, diag::err_typecheck_assign_const) 11549 << ExprRange << ConstMember << false /*static*/ << Field 11550 << Field->getType(); 11551 DiagnosticEmitted = true; 11552 } 11553 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11554 << ConstMember << false /*static*/ << Field << Field->getType() 11555 << Field->getSourceRange(); 11556 } 11557 E = ME->getBase(); 11558 continue; 11559 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 11560 if (VDecl->getType().isConstQualified()) { 11561 if (!DiagnosticEmitted) { 11562 S.Diag(Loc, diag::err_typecheck_assign_const) 11563 << ExprRange << ConstMember << true /*static*/ << VDecl 11564 << VDecl->getType(); 11565 DiagnosticEmitted = true; 11566 } 11567 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11568 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 11569 << VDecl->getSourceRange(); 11570 } 11571 // Static fields do not inherit constness from parents. 11572 break; 11573 } 11574 break; // End MemberExpr 11575 } else if (const ArraySubscriptExpr *ASE = 11576 dyn_cast<ArraySubscriptExpr>(E)) { 11577 E = ASE->getBase()->IgnoreParenImpCasts(); 11578 continue; 11579 } else if (const ExtVectorElementExpr *EVE = 11580 dyn_cast<ExtVectorElementExpr>(E)) { 11581 E = EVE->getBase()->IgnoreParenImpCasts(); 11582 continue; 11583 } 11584 break; 11585 } 11586 11587 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 11588 // Function calls 11589 const FunctionDecl *FD = CE->getDirectCallee(); 11590 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 11591 if (!DiagnosticEmitted) { 11592 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 11593 << ConstFunction << FD; 11594 DiagnosticEmitted = true; 11595 } 11596 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 11597 diag::note_typecheck_assign_const) 11598 << ConstFunction << FD << FD->getReturnType() 11599 << FD->getReturnTypeSourceRange(); 11600 } 11601 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11602 // Point to variable declaration. 11603 if (const ValueDecl *VD = DRE->getDecl()) { 11604 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 11605 if (!DiagnosticEmitted) { 11606 S.Diag(Loc, diag::err_typecheck_assign_const) 11607 << ExprRange << ConstVariable << VD << VD->getType(); 11608 DiagnosticEmitted = true; 11609 } 11610 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11611 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 11612 } 11613 } 11614 } else if (isa<CXXThisExpr>(E)) { 11615 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 11616 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 11617 if (MD->isConst()) { 11618 if (!DiagnosticEmitted) { 11619 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 11620 << ConstMethod << MD; 11621 DiagnosticEmitted = true; 11622 } 11623 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 11624 << ConstMethod << MD << MD->getSourceRange(); 11625 } 11626 } 11627 } 11628 } 11629 11630 if (DiagnosticEmitted) 11631 return; 11632 11633 // Can't determine a more specific message, so display the generic error. 11634 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 11635 } 11636 11637 enum OriginalExprKind { 11638 OEK_Variable, 11639 OEK_Member, 11640 OEK_LValue 11641 }; 11642 11643 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 11644 const RecordType *Ty, 11645 SourceLocation Loc, SourceRange Range, 11646 OriginalExprKind OEK, 11647 bool &DiagnosticEmitted) { 11648 std::vector<const RecordType *> RecordTypeList; 11649 RecordTypeList.push_back(Ty); 11650 unsigned NextToCheckIndex = 0; 11651 // We walk the record hierarchy breadth-first to ensure that we print 11652 // diagnostics in field nesting order. 11653 while (RecordTypeList.size() > NextToCheckIndex) { 11654 bool IsNested = NextToCheckIndex > 0; 11655 for (const FieldDecl *Field : 11656 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 11657 // First, check every field for constness. 11658 QualType FieldTy = Field->getType(); 11659 if (FieldTy.isConstQualified()) { 11660 if (!DiagnosticEmitted) { 11661 S.Diag(Loc, diag::err_typecheck_assign_const) 11662 << Range << NestedConstMember << OEK << VD 11663 << IsNested << Field; 11664 DiagnosticEmitted = true; 11665 } 11666 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 11667 << NestedConstMember << IsNested << Field 11668 << FieldTy << Field->getSourceRange(); 11669 } 11670 11671 // Then we append it to the list to check next in order. 11672 FieldTy = FieldTy.getCanonicalType(); 11673 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 11674 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) 11675 RecordTypeList.push_back(FieldRecTy); 11676 } 11677 } 11678 ++NextToCheckIndex; 11679 } 11680 } 11681 11682 /// Emit an error for the case where a record we are trying to assign to has a 11683 /// const-qualified field somewhere in its hierarchy. 11684 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 11685 SourceLocation Loc) { 11686 QualType Ty = E->getType(); 11687 assert(Ty->isRecordType() && "lvalue was not record?"); 11688 SourceRange Range = E->getSourceRange(); 11689 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 11690 bool DiagEmitted = false; 11691 11692 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 11693 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 11694 Range, OEK_Member, DiagEmitted); 11695 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11696 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 11697 Range, OEK_Variable, DiagEmitted); 11698 else 11699 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 11700 Range, OEK_LValue, DiagEmitted); 11701 if (!DiagEmitted) 11702 DiagnoseConstAssignment(S, E, Loc); 11703 } 11704 11705 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 11706 /// emit an error and return true. If so, return false. 11707 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 11708 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 11709 11710 S.CheckShadowingDeclModification(E, Loc); 11711 11712 SourceLocation OrigLoc = Loc; 11713 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 11714 &Loc); 11715 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 11716 IsLV = Expr::MLV_InvalidMessageExpression; 11717 if (IsLV == Expr::MLV_Valid) 11718 return false; 11719 11720 unsigned DiagID = 0; 11721 bool NeedType = false; 11722 switch (IsLV) { // C99 6.5.16p2 11723 case Expr::MLV_ConstQualified: 11724 // Use a specialized diagnostic when we're assigning to an object 11725 // from an enclosing function or block. 11726 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 11727 if (NCCK == NCCK_Block) 11728 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 11729 else 11730 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 11731 break; 11732 } 11733 11734 // In ARC, use some specialized diagnostics for occasions where we 11735 // infer 'const'. These are always pseudo-strong variables. 11736 if (S.getLangOpts().ObjCAutoRefCount) { 11737 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 11738 if (declRef && isa<VarDecl>(declRef->getDecl())) { 11739 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 11740 11741 // Use the normal diagnostic if it's pseudo-__strong but the 11742 // user actually wrote 'const'. 11743 if (var->isARCPseudoStrong() && 11744 (!var->getTypeSourceInfo() || 11745 !var->getTypeSourceInfo()->getType().isConstQualified())) { 11746 // There are three pseudo-strong cases: 11747 // - self 11748 ObjCMethodDecl *method = S.getCurMethodDecl(); 11749 if (method && var == method->getSelfDecl()) { 11750 DiagID = method->isClassMethod() 11751 ? diag::err_typecheck_arc_assign_self_class_method 11752 : diag::err_typecheck_arc_assign_self; 11753 11754 // - Objective-C externally_retained attribute. 11755 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 11756 isa<ParmVarDecl>(var)) { 11757 DiagID = diag::err_typecheck_arc_assign_externally_retained; 11758 11759 // - fast enumeration variables 11760 } else { 11761 DiagID = diag::err_typecheck_arr_assign_enumeration; 11762 } 11763 11764 SourceRange Assign; 11765 if (Loc != OrigLoc) 11766 Assign = SourceRange(OrigLoc, OrigLoc); 11767 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 11768 // We need to preserve the AST regardless, so migration tool 11769 // can do its job. 11770 return false; 11771 } 11772 } 11773 } 11774 11775 // If none of the special cases above are triggered, then this is a 11776 // simple const assignment. 11777 if (DiagID == 0) { 11778 DiagnoseConstAssignment(S, E, Loc); 11779 return true; 11780 } 11781 11782 break; 11783 case Expr::MLV_ConstAddrSpace: 11784 DiagnoseConstAssignment(S, E, Loc); 11785 return true; 11786 case Expr::MLV_ConstQualifiedField: 11787 DiagnoseRecursiveConstFields(S, E, Loc); 11788 return true; 11789 case Expr::MLV_ArrayType: 11790 case Expr::MLV_ArrayTemporary: 11791 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 11792 NeedType = true; 11793 break; 11794 case Expr::MLV_NotObjectType: 11795 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 11796 NeedType = true; 11797 break; 11798 case Expr::MLV_LValueCast: 11799 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 11800 break; 11801 case Expr::MLV_Valid: 11802 llvm_unreachable("did not take early return for MLV_Valid"); 11803 case Expr::MLV_InvalidExpression: 11804 case Expr::MLV_MemberFunction: 11805 case Expr::MLV_ClassTemporary: 11806 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 11807 break; 11808 case Expr::MLV_IncompleteType: 11809 case Expr::MLV_IncompleteVoidType: 11810 return S.RequireCompleteType(Loc, E->getType(), 11811 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 11812 case Expr::MLV_DuplicateVectorComponents: 11813 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 11814 break; 11815 case Expr::MLV_NoSetterProperty: 11816 llvm_unreachable("readonly properties should be processed differently"); 11817 case Expr::MLV_InvalidMessageExpression: 11818 DiagID = diag::err_readonly_message_assignment; 11819 break; 11820 case Expr::MLV_SubObjCPropertySetting: 11821 DiagID = diag::err_no_subobject_property_setting; 11822 break; 11823 } 11824 11825 SourceRange Assign; 11826 if (Loc != OrigLoc) 11827 Assign = SourceRange(OrigLoc, OrigLoc); 11828 if (NeedType) 11829 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 11830 else 11831 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 11832 return true; 11833 } 11834 11835 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 11836 SourceLocation Loc, 11837 Sema &Sema) { 11838 if (Sema.inTemplateInstantiation()) 11839 return; 11840 if (Sema.isUnevaluatedContext()) 11841 return; 11842 if (Loc.isInvalid() || Loc.isMacroID()) 11843 return; 11844 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 11845 return; 11846 11847 // C / C++ fields 11848 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 11849 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 11850 if (ML && MR) { 11851 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 11852 return; 11853 const ValueDecl *LHSDecl = 11854 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 11855 const ValueDecl *RHSDecl = 11856 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 11857 if (LHSDecl != RHSDecl) 11858 return; 11859 if (LHSDecl->getType().isVolatileQualified()) 11860 return; 11861 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 11862 if (RefTy->getPointeeType().isVolatileQualified()) 11863 return; 11864 11865 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 11866 } 11867 11868 // Objective-C instance variables 11869 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 11870 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 11871 if (OL && OR && OL->getDecl() == OR->getDecl()) { 11872 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 11873 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 11874 if (RL && RR && RL->getDecl() == RR->getDecl()) 11875 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 11876 } 11877 } 11878 11879 // C99 6.5.16.1 11880 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 11881 SourceLocation Loc, 11882 QualType CompoundType) { 11883 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 11884 11885 // Verify that LHS is a modifiable lvalue, and emit error if not. 11886 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 11887 return QualType(); 11888 11889 QualType LHSType = LHSExpr->getType(); 11890 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 11891 CompoundType; 11892 // OpenCL v1.2 s6.1.1.1 p2: 11893 // The half data type can only be used to declare a pointer to a buffer that 11894 // contains half values 11895 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 11896 LHSType->isHalfType()) { 11897 Diag(Loc, diag::err_opencl_half_load_store) << 1 11898 << LHSType.getUnqualifiedType(); 11899 return QualType(); 11900 } 11901 11902 AssignConvertType ConvTy; 11903 if (CompoundType.isNull()) { 11904 Expr *RHSCheck = RHS.get(); 11905 11906 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 11907 11908 QualType LHSTy(LHSType); 11909 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 11910 if (RHS.isInvalid()) 11911 return QualType(); 11912 // Special case of NSObject attributes on c-style pointer types. 11913 if (ConvTy == IncompatiblePointer && 11914 ((Context.isObjCNSObjectType(LHSType) && 11915 RHSType->isObjCObjectPointerType()) || 11916 (Context.isObjCNSObjectType(RHSType) && 11917 LHSType->isObjCObjectPointerType()))) 11918 ConvTy = Compatible; 11919 11920 if (ConvTy == Compatible && 11921 LHSType->isObjCObjectType()) 11922 Diag(Loc, diag::err_objc_object_assignment) 11923 << LHSType; 11924 11925 // If the RHS is a unary plus or minus, check to see if they = and + are 11926 // right next to each other. If so, the user may have typo'd "x =+ 4" 11927 // instead of "x += 4". 11928 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 11929 RHSCheck = ICE->getSubExpr(); 11930 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 11931 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 11932 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 11933 // Only if the two operators are exactly adjacent. 11934 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 11935 // And there is a space or other character before the subexpr of the 11936 // unary +/-. We don't want to warn on "x=-1". 11937 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 11938 UO->getSubExpr()->getBeginLoc().isFileID()) { 11939 Diag(Loc, diag::warn_not_compound_assign) 11940 << (UO->getOpcode() == UO_Plus ? "+" : "-") 11941 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 11942 } 11943 } 11944 11945 if (ConvTy == Compatible) { 11946 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 11947 // Warn about retain cycles where a block captures the LHS, but 11948 // not if the LHS is a simple variable into which the block is 11949 // being stored...unless that variable can be captured by reference! 11950 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 11951 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 11952 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 11953 checkRetainCycles(LHSExpr, RHS.get()); 11954 } 11955 11956 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 11957 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 11958 // It is safe to assign a weak reference into a strong variable. 11959 // Although this code can still have problems: 11960 // id x = self.weakProp; 11961 // id y = self.weakProp; 11962 // we do not warn to warn spuriously when 'x' and 'y' are on separate 11963 // paths through the function. This should be revisited if 11964 // -Wrepeated-use-of-weak is made flow-sensitive. 11965 // For ObjCWeak only, we do not warn if the assign is to a non-weak 11966 // variable, which will be valid for the current autorelease scope. 11967 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 11968 RHS.get()->getBeginLoc())) 11969 getCurFunction()->markSafeWeakUse(RHS.get()); 11970 11971 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 11972 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 11973 } 11974 } 11975 } else { 11976 // Compound assignment "x += y" 11977 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 11978 } 11979 11980 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 11981 RHS.get(), AA_Assigning)) 11982 return QualType(); 11983 11984 CheckForNullPointerDereference(*this, LHSExpr); 11985 11986 if (getLangOpts().CPlusPlus2a && LHSType.isVolatileQualified()) { 11987 if (CompoundType.isNull()) { 11988 // C++2a [expr.ass]p5: 11989 // A simple-assignment whose left operand is of a volatile-qualified 11990 // type is deprecated unless the assignment is either a discarded-value 11991 // expression or an unevaluated operand 11992 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 11993 } else { 11994 // C++2a [expr.ass]p6: 11995 // [Compound-assignment] expressions are deprecated if E1 has 11996 // volatile-qualified type 11997 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 11998 } 11999 } 12000 12001 // C99 6.5.16p3: The type of an assignment expression is the type of the 12002 // left operand unless the left operand has qualified type, in which case 12003 // it is the unqualified version of the type of the left operand. 12004 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 12005 // is converted to the type of the assignment expression (above). 12006 // C++ 5.17p1: the type of the assignment expression is that of its left 12007 // operand. 12008 return (getLangOpts().CPlusPlus 12009 ? LHSType : LHSType.getUnqualifiedType()); 12010 } 12011 12012 // Only ignore explicit casts to void. 12013 static bool IgnoreCommaOperand(const Expr *E) { 12014 E = E->IgnoreParens(); 12015 12016 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 12017 if (CE->getCastKind() == CK_ToVoid) { 12018 return true; 12019 } 12020 12021 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 12022 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 12023 CE->getSubExpr()->getType()->isDependentType()) { 12024 return true; 12025 } 12026 } 12027 12028 return false; 12029 } 12030 12031 // Look for instances where it is likely the comma operator is confused with 12032 // another operator. There is a whitelist of acceptable expressions for the 12033 // left hand side of the comma operator, otherwise emit a warning. 12034 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 12035 // No warnings in macros 12036 if (Loc.isMacroID()) 12037 return; 12038 12039 // Don't warn in template instantiations. 12040 if (inTemplateInstantiation()) 12041 return; 12042 12043 // Scope isn't fine-grained enough to whitelist the specific cases, so 12044 // instead, skip more than needed, then call back into here with the 12045 // CommaVisitor in SemaStmt.cpp. 12046 // The whitelisted locations are the initialization and increment portions 12047 // of a for loop. The additional checks are on the condition of 12048 // if statements, do/while loops, and for loops. 12049 // Differences in scope flags for C89 mode requires the extra logic. 12050 const unsigned ForIncrementFlags = 12051 getLangOpts().C99 || getLangOpts().CPlusPlus 12052 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 12053 : Scope::ContinueScope | Scope::BreakScope; 12054 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 12055 const unsigned ScopeFlags = getCurScope()->getFlags(); 12056 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 12057 (ScopeFlags & ForInitFlags) == ForInitFlags) 12058 return; 12059 12060 // If there are multiple comma operators used together, get the RHS of the 12061 // of the comma operator as the LHS. 12062 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 12063 if (BO->getOpcode() != BO_Comma) 12064 break; 12065 LHS = BO->getRHS(); 12066 } 12067 12068 // Only allow some expressions on LHS to not warn. 12069 if (IgnoreCommaOperand(LHS)) 12070 return; 12071 12072 Diag(Loc, diag::warn_comma_operator); 12073 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 12074 << LHS->getSourceRange() 12075 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 12076 LangOpts.CPlusPlus ? "static_cast<void>(" 12077 : "(void)(") 12078 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 12079 ")"); 12080 } 12081 12082 // C99 6.5.17 12083 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 12084 SourceLocation Loc) { 12085 LHS = S.CheckPlaceholderExpr(LHS.get()); 12086 RHS = S.CheckPlaceholderExpr(RHS.get()); 12087 if (LHS.isInvalid() || RHS.isInvalid()) 12088 return QualType(); 12089 12090 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 12091 // operands, but not unary promotions. 12092 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 12093 12094 // So we treat the LHS as a ignored value, and in C++ we allow the 12095 // containing site to determine what should be done with the RHS. 12096 LHS = S.IgnoredValueConversions(LHS.get()); 12097 if (LHS.isInvalid()) 12098 return QualType(); 12099 12100 S.DiagnoseUnusedExprResult(LHS.get()); 12101 12102 if (!S.getLangOpts().CPlusPlus) { 12103 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 12104 if (RHS.isInvalid()) 12105 return QualType(); 12106 if (!RHS.get()->getType()->isVoidType()) 12107 S.RequireCompleteType(Loc, RHS.get()->getType(), 12108 diag::err_incomplete_type); 12109 } 12110 12111 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 12112 S.DiagnoseCommaOperator(LHS.get(), Loc); 12113 12114 return RHS.get()->getType(); 12115 } 12116 12117 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 12118 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 12119 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 12120 ExprValueKind &VK, 12121 ExprObjectKind &OK, 12122 SourceLocation OpLoc, 12123 bool IsInc, bool IsPrefix) { 12124 if (Op->isTypeDependent()) 12125 return S.Context.DependentTy; 12126 12127 QualType ResType = Op->getType(); 12128 // Atomic types can be used for increment / decrement where the non-atomic 12129 // versions can, so ignore the _Atomic() specifier for the purpose of 12130 // checking. 12131 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 12132 ResType = ResAtomicType->getValueType(); 12133 12134 assert(!ResType.isNull() && "no type for increment/decrement expression"); 12135 12136 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 12137 // Decrement of bool is not allowed. 12138 if (!IsInc) { 12139 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 12140 return QualType(); 12141 } 12142 // Increment of bool sets it to true, but is deprecated. 12143 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 12144 : diag::warn_increment_bool) 12145 << Op->getSourceRange(); 12146 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 12147 // Error on enum increments and decrements in C++ mode 12148 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 12149 return QualType(); 12150 } else if (ResType->isRealType()) { 12151 // OK! 12152 } else if (ResType->isPointerType()) { 12153 // C99 6.5.2.4p2, 6.5.6p2 12154 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 12155 return QualType(); 12156 } else if (ResType->isObjCObjectPointerType()) { 12157 // On modern runtimes, ObjC pointer arithmetic is forbidden. 12158 // Otherwise, we just need a complete type. 12159 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 12160 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 12161 return QualType(); 12162 } else if (ResType->isAnyComplexType()) { 12163 // C99 does not support ++/-- on complex types, we allow as an extension. 12164 S.Diag(OpLoc, diag::ext_integer_increment_complex) 12165 << ResType << Op->getSourceRange(); 12166 } else if (ResType->isPlaceholderType()) { 12167 ExprResult PR = S.CheckPlaceholderExpr(Op); 12168 if (PR.isInvalid()) return QualType(); 12169 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 12170 IsInc, IsPrefix); 12171 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 12172 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 12173 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 12174 (ResType->castAs<VectorType>()->getVectorKind() != 12175 VectorType::AltiVecBool)) { 12176 // The z vector extensions allow ++ and -- for non-bool vectors. 12177 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 12178 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 12179 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 12180 } else { 12181 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 12182 << ResType << int(IsInc) << Op->getSourceRange(); 12183 return QualType(); 12184 } 12185 // At this point, we know we have a real, complex or pointer type. 12186 // Now make sure the operand is a modifiable lvalue. 12187 if (CheckForModifiableLvalue(Op, OpLoc, S)) 12188 return QualType(); 12189 if (S.getLangOpts().CPlusPlus2a && ResType.isVolatileQualified()) { 12190 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 12191 // An operand with volatile-qualified type is deprecated 12192 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 12193 << IsInc << ResType; 12194 } 12195 // In C++, a prefix increment is the same type as the operand. Otherwise 12196 // (in C or with postfix), the increment is the unqualified type of the 12197 // operand. 12198 if (IsPrefix && S.getLangOpts().CPlusPlus) { 12199 VK = VK_LValue; 12200 OK = Op->getObjectKind(); 12201 return ResType; 12202 } else { 12203 VK = VK_RValue; 12204 return ResType.getUnqualifiedType(); 12205 } 12206 } 12207 12208 12209 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 12210 /// This routine allows us to typecheck complex/recursive expressions 12211 /// where the declaration is needed for type checking. We only need to 12212 /// handle cases when the expression references a function designator 12213 /// or is an lvalue. Here are some examples: 12214 /// - &(x) => x 12215 /// - &*****f => f for f a function designator. 12216 /// - &s.xx => s 12217 /// - &s.zz[1].yy -> s, if zz is an array 12218 /// - *(x + 1) -> x, if x is an array 12219 /// - &"123"[2] -> 0 12220 /// - & __real__ x -> x 12221 static ValueDecl *getPrimaryDecl(Expr *E) { 12222 switch (E->getStmtClass()) { 12223 case Stmt::DeclRefExprClass: 12224 return cast<DeclRefExpr>(E)->getDecl(); 12225 case Stmt::MemberExprClass: 12226 // If this is an arrow operator, the address is an offset from 12227 // the base's value, so the object the base refers to is 12228 // irrelevant. 12229 if (cast<MemberExpr>(E)->isArrow()) 12230 return nullptr; 12231 // Otherwise, the expression refers to a part of the base 12232 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 12233 case Stmt::ArraySubscriptExprClass: { 12234 // FIXME: This code shouldn't be necessary! We should catch the implicit 12235 // promotion of register arrays earlier. 12236 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 12237 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 12238 if (ICE->getSubExpr()->getType()->isArrayType()) 12239 return getPrimaryDecl(ICE->getSubExpr()); 12240 } 12241 return nullptr; 12242 } 12243 case Stmt::UnaryOperatorClass: { 12244 UnaryOperator *UO = cast<UnaryOperator>(E); 12245 12246 switch(UO->getOpcode()) { 12247 case UO_Real: 12248 case UO_Imag: 12249 case UO_Extension: 12250 return getPrimaryDecl(UO->getSubExpr()); 12251 default: 12252 return nullptr; 12253 } 12254 } 12255 case Stmt::ParenExprClass: 12256 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 12257 case Stmt::ImplicitCastExprClass: 12258 // If the result of an implicit cast is an l-value, we care about 12259 // the sub-expression; otherwise, the result here doesn't matter. 12260 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 12261 default: 12262 return nullptr; 12263 } 12264 } 12265 12266 namespace { 12267 enum { 12268 AO_Bit_Field = 0, 12269 AO_Vector_Element = 1, 12270 AO_Property_Expansion = 2, 12271 AO_Register_Variable = 3, 12272 AO_No_Error = 4 12273 }; 12274 } 12275 /// Diagnose invalid operand for address of operations. 12276 /// 12277 /// \param Type The type of operand which cannot have its address taken. 12278 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 12279 Expr *E, unsigned Type) { 12280 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 12281 } 12282 12283 /// CheckAddressOfOperand - The operand of & must be either a function 12284 /// designator or an lvalue designating an object. If it is an lvalue, the 12285 /// object cannot be declared with storage class register or be a bit field. 12286 /// Note: The usual conversions are *not* applied to the operand of the & 12287 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 12288 /// In C++, the operand might be an overloaded function name, in which case 12289 /// we allow the '&' but retain the overloaded-function type. 12290 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 12291 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 12292 if (PTy->getKind() == BuiltinType::Overload) { 12293 Expr *E = OrigOp.get()->IgnoreParens(); 12294 if (!isa<OverloadExpr>(E)) { 12295 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 12296 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 12297 << OrigOp.get()->getSourceRange(); 12298 return QualType(); 12299 } 12300 12301 OverloadExpr *Ovl = cast<OverloadExpr>(E); 12302 if (isa<UnresolvedMemberExpr>(Ovl)) 12303 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 12304 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 12305 << OrigOp.get()->getSourceRange(); 12306 return QualType(); 12307 } 12308 12309 return Context.OverloadTy; 12310 } 12311 12312 if (PTy->getKind() == BuiltinType::UnknownAny) 12313 return Context.UnknownAnyTy; 12314 12315 if (PTy->getKind() == BuiltinType::BoundMember) { 12316 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 12317 << OrigOp.get()->getSourceRange(); 12318 return QualType(); 12319 } 12320 12321 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 12322 if (OrigOp.isInvalid()) return QualType(); 12323 } 12324 12325 if (OrigOp.get()->isTypeDependent()) 12326 return Context.DependentTy; 12327 12328 assert(!OrigOp.get()->getType()->isPlaceholderType()); 12329 12330 // Make sure to ignore parentheses in subsequent checks 12331 Expr *op = OrigOp.get()->IgnoreParens(); 12332 12333 // In OpenCL captures for blocks called as lambda functions 12334 // are located in the private address space. Blocks used in 12335 // enqueue_kernel can be located in a different address space 12336 // depending on a vendor implementation. Thus preventing 12337 // taking an address of the capture to avoid invalid AS casts. 12338 if (LangOpts.OpenCL) { 12339 auto* VarRef = dyn_cast<DeclRefExpr>(op); 12340 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 12341 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 12342 return QualType(); 12343 } 12344 } 12345 12346 if (getLangOpts().C99) { 12347 // Implement C99-only parts of addressof rules. 12348 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 12349 if (uOp->getOpcode() == UO_Deref) 12350 // Per C99 6.5.3.2, the address of a deref always returns a valid result 12351 // (assuming the deref expression is valid). 12352 return uOp->getSubExpr()->getType(); 12353 } 12354 // Technically, there should be a check for array subscript 12355 // expressions here, but the result of one is always an lvalue anyway. 12356 } 12357 ValueDecl *dcl = getPrimaryDecl(op); 12358 12359 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 12360 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 12361 op->getBeginLoc())) 12362 return QualType(); 12363 12364 Expr::LValueClassification lval = op->ClassifyLValue(Context); 12365 unsigned AddressOfError = AO_No_Error; 12366 12367 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 12368 bool sfinae = (bool)isSFINAEContext(); 12369 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 12370 : diag::ext_typecheck_addrof_temporary) 12371 << op->getType() << op->getSourceRange(); 12372 if (sfinae) 12373 return QualType(); 12374 // Materialize the temporary as an lvalue so that we can take its address. 12375 OrigOp = op = 12376 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 12377 } else if (isa<ObjCSelectorExpr>(op)) { 12378 return Context.getPointerType(op->getType()); 12379 } else if (lval == Expr::LV_MemberFunction) { 12380 // If it's an instance method, make a member pointer. 12381 // The expression must have exactly the form &A::foo. 12382 12383 // If the underlying expression isn't a decl ref, give up. 12384 if (!isa<DeclRefExpr>(op)) { 12385 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 12386 << OrigOp.get()->getSourceRange(); 12387 return QualType(); 12388 } 12389 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 12390 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 12391 12392 // The id-expression was parenthesized. 12393 if (OrigOp.get() != DRE) { 12394 Diag(OpLoc, diag::err_parens_pointer_member_function) 12395 << OrigOp.get()->getSourceRange(); 12396 12397 // The method was named without a qualifier. 12398 } else if (!DRE->getQualifier()) { 12399 if (MD->getParent()->getName().empty()) 12400 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 12401 << op->getSourceRange(); 12402 else { 12403 SmallString<32> Str; 12404 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 12405 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 12406 << op->getSourceRange() 12407 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 12408 } 12409 } 12410 12411 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 12412 if (isa<CXXDestructorDecl>(MD)) 12413 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 12414 12415 QualType MPTy = Context.getMemberPointerType( 12416 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 12417 // Under the MS ABI, lock down the inheritance model now. 12418 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 12419 (void)isCompleteType(OpLoc, MPTy); 12420 return MPTy; 12421 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 12422 // C99 6.5.3.2p1 12423 // The operand must be either an l-value or a function designator 12424 if (!op->getType()->isFunctionType()) { 12425 // Use a special diagnostic for loads from property references. 12426 if (isa<PseudoObjectExpr>(op)) { 12427 AddressOfError = AO_Property_Expansion; 12428 } else { 12429 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 12430 << op->getType() << op->getSourceRange(); 12431 return QualType(); 12432 } 12433 } 12434 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 12435 // The operand cannot be a bit-field 12436 AddressOfError = AO_Bit_Field; 12437 } else if (op->getObjectKind() == OK_VectorComponent) { 12438 // The operand cannot be an element of a vector 12439 AddressOfError = AO_Vector_Element; 12440 } else if (dcl) { // C99 6.5.3.2p1 12441 // We have an lvalue with a decl. Make sure the decl is not declared 12442 // with the register storage-class specifier. 12443 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 12444 // in C++ it is not error to take address of a register 12445 // variable (c++03 7.1.1P3) 12446 if (vd->getStorageClass() == SC_Register && 12447 !getLangOpts().CPlusPlus) { 12448 AddressOfError = AO_Register_Variable; 12449 } 12450 } else if (isa<MSPropertyDecl>(dcl)) { 12451 AddressOfError = AO_Property_Expansion; 12452 } else if (isa<FunctionTemplateDecl>(dcl)) { 12453 return Context.OverloadTy; 12454 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 12455 // Okay: we can take the address of a field. 12456 // Could be a pointer to member, though, if there is an explicit 12457 // scope qualifier for the class. 12458 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 12459 DeclContext *Ctx = dcl->getDeclContext(); 12460 if (Ctx && Ctx->isRecord()) { 12461 if (dcl->getType()->isReferenceType()) { 12462 Diag(OpLoc, 12463 diag::err_cannot_form_pointer_to_member_of_reference_type) 12464 << dcl->getDeclName() << dcl->getType(); 12465 return QualType(); 12466 } 12467 12468 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 12469 Ctx = Ctx->getParent(); 12470 12471 QualType MPTy = Context.getMemberPointerType( 12472 op->getType(), 12473 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 12474 // Under the MS ABI, lock down the inheritance model now. 12475 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 12476 (void)isCompleteType(OpLoc, MPTy); 12477 return MPTy; 12478 } 12479 } 12480 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 12481 !isa<BindingDecl>(dcl)) 12482 llvm_unreachable("Unknown/unexpected decl type"); 12483 } 12484 12485 if (AddressOfError != AO_No_Error) { 12486 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 12487 return QualType(); 12488 } 12489 12490 if (lval == Expr::LV_IncompleteVoidType) { 12491 // Taking the address of a void variable is technically illegal, but we 12492 // allow it in cases which are otherwise valid. 12493 // Example: "extern void x; void* y = &x;". 12494 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 12495 } 12496 12497 // If the operand has type "type", the result has type "pointer to type". 12498 if (op->getType()->isObjCObjectType()) 12499 return Context.getObjCObjectPointerType(op->getType()); 12500 12501 CheckAddressOfPackedMember(op); 12502 12503 return Context.getPointerType(op->getType()); 12504 } 12505 12506 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 12507 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 12508 if (!DRE) 12509 return; 12510 const Decl *D = DRE->getDecl(); 12511 if (!D) 12512 return; 12513 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 12514 if (!Param) 12515 return; 12516 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 12517 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 12518 return; 12519 if (FunctionScopeInfo *FD = S.getCurFunction()) 12520 if (!FD->ModifiedNonNullParams.count(Param)) 12521 FD->ModifiedNonNullParams.insert(Param); 12522 } 12523 12524 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 12525 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 12526 SourceLocation OpLoc) { 12527 if (Op->isTypeDependent()) 12528 return S.Context.DependentTy; 12529 12530 ExprResult ConvResult = S.UsualUnaryConversions(Op); 12531 if (ConvResult.isInvalid()) 12532 return QualType(); 12533 Op = ConvResult.get(); 12534 QualType OpTy = Op->getType(); 12535 QualType Result; 12536 12537 if (isa<CXXReinterpretCastExpr>(Op)) { 12538 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 12539 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 12540 Op->getSourceRange()); 12541 } 12542 12543 if (const PointerType *PT = OpTy->getAs<PointerType>()) 12544 { 12545 Result = PT->getPointeeType(); 12546 } 12547 else if (const ObjCObjectPointerType *OPT = 12548 OpTy->getAs<ObjCObjectPointerType>()) 12549 Result = OPT->getPointeeType(); 12550 else { 12551 ExprResult PR = S.CheckPlaceholderExpr(Op); 12552 if (PR.isInvalid()) return QualType(); 12553 if (PR.get() != Op) 12554 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 12555 } 12556 12557 if (Result.isNull()) { 12558 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 12559 << OpTy << Op->getSourceRange(); 12560 return QualType(); 12561 } 12562 12563 // Note that per both C89 and C99, indirection is always legal, even if Result 12564 // is an incomplete type or void. It would be possible to warn about 12565 // dereferencing a void pointer, but it's completely well-defined, and such a 12566 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 12567 // for pointers to 'void' but is fine for any other pointer type: 12568 // 12569 // C++ [expr.unary.op]p1: 12570 // [...] the expression to which [the unary * operator] is applied shall 12571 // be a pointer to an object type, or a pointer to a function type 12572 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 12573 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 12574 << OpTy << Op->getSourceRange(); 12575 12576 // Dereferences are usually l-values... 12577 VK = VK_LValue; 12578 12579 // ...except that certain expressions are never l-values in C. 12580 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 12581 VK = VK_RValue; 12582 12583 return Result; 12584 } 12585 12586 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 12587 BinaryOperatorKind Opc; 12588 switch (Kind) { 12589 default: llvm_unreachable("Unknown binop!"); 12590 case tok::periodstar: Opc = BO_PtrMemD; break; 12591 case tok::arrowstar: Opc = BO_PtrMemI; break; 12592 case tok::star: Opc = BO_Mul; break; 12593 case tok::slash: Opc = BO_Div; break; 12594 case tok::percent: Opc = BO_Rem; break; 12595 case tok::plus: Opc = BO_Add; break; 12596 case tok::minus: Opc = BO_Sub; break; 12597 case tok::lessless: Opc = BO_Shl; break; 12598 case tok::greatergreater: Opc = BO_Shr; break; 12599 case tok::lessequal: Opc = BO_LE; break; 12600 case tok::less: Opc = BO_LT; break; 12601 case tok::greaterequal: Opc = BO_GE; break; 12602 case tok::greater: Opc = BO_GT; break; 12603 case tok::exclaimequal: Opc = BO_NE; break; 12604 case tok::equalequal: Opc = BO_EQ; break; 12605 case tok::spaceship: Opc = BO_Cmp; break; 12606 case tok::amp: Opc = BO_And; break; 12607 case tok::caret: Opc = BO_Xor; break; 12608 case tok::pipe: Opc = BO_Or; break; 12609 case tok::ampamp: Opc = BO_LAnd; break; 12610 case tok::pipepipe: Opc = BO_LOr; break; 12611 case tok::equal: Opc = BO_Assign; break; 12612 case tok::starequal: Opc = BO_MulAssign; break; 12613 case tok::slashequal: Opc = BO_DivAssign; break; 12614 case tok::percentequal: Opc = BO_RemAssign; break; 12615 case tok::plusequal: Opc = BO_AddAssign; break; 12616 case tok::minusequal: Opc = BO_SubAssign; break; 12617 case tok::lesslessequal: Opc = BO_ShlAssign; break; 12618 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 12619 case tok::ampequal: Opc = BO_AndAssign; break; 12620 case tok::caretequal: Opc = BO_XorAssign; break; 12621 case tok::pipeequal: Opc = BO_OrAssign; break; 12622 case tok::comma: Opc = BO_Comma; break; 12623 } 12624 return Opc; 12625 } 12626 12627 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 12628 tok::TokenKind Kind) { 12629 UnaryOperatorKind Opc; 12630 switch (Kind) { 12631 default: llvm_unreachable("Unknown unary op!"); 12632 case tok::plusplus: Opc = UO_PreInc; break; 12633 case tok::minusminus: Opc = UO_PreDec; break; 12634 case tok::amp: Opc = UO_AddrOf; break; 12635 case tok::star: Opc = UO_Deref; break; 12636 case tok::plus: Opc = UO_Plus; break; 12637 case tok::minus: Opc = UO_Minus; break; 12638 case tok::tilde: Opc = UO_Not; break; 12639 case tok::exclaim: Opc = UO_LNot; break; 12640 case tok::kw___real: Opc = UO_Real; break; 12641 case tok::kw___imag: Opc = UO_Imag; break; 12642 case tok::kw___extension__: Opc = UO_Extension; break; 12643 } 12644 return Opc; 12645 } 12646 12647 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 12648 /// This warning suppressed in the event of macro expansions. 12649 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 12650 SourceLocation OpLoc, bool IsBuiltin) { 12651 if (S.inTemplateInstantiation()) 12652 return; 12653 if (S.isUnevaluatedContext()) 12654 return; 12655 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 12656 return; 12657 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 12658 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 12659 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 12660 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 12661 if (!LHSDeclRef || !RHSDeclRef || 12662 LHSDeclRef->getLocation().isMacroID() || 12663 RHSDeclRef->getLocation().isMacroID()) 12664 return; 12665 const ValueDecl *LHSDecl = 12666 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 12667 const ValueDecl *RHSDecl = 12668 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 12669 if (LHSDecl != RHSDecl) 12670 return; 12671 if (LHSDecl->getType().isVolatileQualified()) 12672 return; 12673 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 12674 if (RefTy->getPointeeType().isVolatileQualified()) 12675 return; 12676 12677 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 12678 : diag::warn_self_assignment_overloaded) 12679 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 12680 << RHSExpr->getSourceRange(); 12681 } 12682 12683 /// Check if a bitwise-& is performed on an Objective-C pointer. This 12684 /// is usually indicative of introspection within the Objective-C pointer. 12685 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 12686 SourceLocation OpLoc) { 12687 if (!S.getLangOpts().ObjC) 12688 return; 12689 12690 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 12691 const Expr *LHS = L.get(); 12692 const Expr *RHS = R.get(); 12693 12694 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 12695 ObjCPointerExpr = LHS; 12696 OtherExpr = RHS; 12697 } 12698 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 12699 ObjCPointerExpr = RHS; 12700 OtherExpr = LHS; 12701 } 12702 12703 // This warning is deliberately made very specific to reduce false 12704 // positives with logic that uses '&' for hashing. This logic mainly 12705 // looks for code trying to introspect into tagged pointers, which 12706 // code should generally never do. 12707 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 12708 unsigned Diag = diag::warn_objc_pointer_masking; 12709 // Determine if we are introspecting the result of performSelectorXXX. 12710 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 12711 // Special case messages to -performSelector and friends, which 12712 // can return non-pointer values boxed in a pointer value. 12713 // Some clients may wish to silence warnings in this subcase. 12714 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 12715 Selector S = ME->getSelector(); 12716 StringRef SelArg0 = S.getNameForSlot(0); 12717 if (SelArg0.startswith("performSelector")) 12718 Diag = diag::warn_objc_pointer_masking_performSelector; 12719 } 12720 12721 S.Diag(OpLoc, Diag) 12722 << ObjCPointerExpr->getSourceRange(); 12723 } 12724 } 12725 12726 static NamedDecl *getDeclFromExpr(Expr *E) { 12727 if (!E) 12728 return nullptr; 12729 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 12730 return DRE->getDecl(); 12731 if (auto *ME = dyn_cast<MemberExpr>(E)) 12732 return ME->getMemberDecl(); 12733 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 12734 return IRE->getDecl(); 12735 return nullptr; 12736 } 12737 12738 // This helper function promotes a binary operator's operands (which are of a 12739 // half vector type) to a vector of floats and then truncates the result to 12740 // a vector of either half or short. 12741 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 12742 BinaryOperatorKind Opc, QualType ResultTy, 12743 ExprValueKind VK, ExprObjectKind OK, 12744 bool IsCompAssign, SourceLocation OpLoc, 12745 FPOptions FPFeatures) { 12746 auto &Context = S.getASTContext(); 12747 assert((isVector(ResultTy, Context.HalfTy) || 12748 isVector(ResultTy, Context.ShortTy)) && 12749 "Result must be a vector of half or short"); 12750 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 12751 isVector(RHS.get()->getType(), Context.HalfTy) && 12752 "both operands expected to be a half vector"); 12753 12754 RHS = convertVector(RHS.get(), Context.FloatTy, S); 12755 QualType BinOpResTy = RHS.get()->getType(); 12756 12757 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 12758 // change BinOpResTy to a vector of ints. 12759 if (isVector(ResultTy, Context.ShortTy)) 12760 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 12761 12762 if (IsCompAssign) 12763 return new (Context) CompoundAssignOperator( 12764 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy, 12765 OpLoc, FPFeatures); 12766 12767 LHS = convertVector(LHS.get(), Context.FloatTy, S); 12768 auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy, 12769 VK, OK, OpLoc, FPFeatures); 12770 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 12771 } 12772 12773 static std::pair<ExprResult, ExprResult> 12774 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 12775 Expr *RHSExpr) { 12776 ExprResult LHS = LHSExpr, RHS = RHSExpr; 12777 if (!S.getLangOpts().CPlusPlus) { 12778 // C cannot handle TypoExpr nodes on either side of a binop because it 12779 // doesn't handle dependent types properly, so make sure any TypoExprs have 12780 // been dealt with before checking the operands. 12781 LHS = S.CorrectDelayedTyposInExpr(LHS); 12782 RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) { 12783 if (Opc != BO_Assign) 12784 return ExprResult(E); 12785 // Avoid correcting the RHS to the same Expr as the LHS. 12786 Decl *D = getDeclFromExpr(E); 12787 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 12788 }); 12789 } 12790 return std::make_pair(LHS, RHS); 12791 } 12792 12793 /// Returns true if conversion between vectors of halfs and vectors of floats 12794 /// is needed. 12795 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 12796 QualType SrcType) { 12797 return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType && 12798 !Ctx.getTargetInfo().useFP16ConversionIntrinsics() && 12799 isVector(SrcType, Ctx.HalfTy); 12800 } 12801 12802 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 12803 /// operator @p Opc at location @c TokLoc. This routine only supports 12804 /// built-in operations; ActOnBinOp handles overloaded operators. 12805 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 12806 BinaryOperatorKind Opc, 12807 Expr *LHSExpr, Expr *RHSExpr) { 12808 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 12809 // The syntax only allows initializer lists on the RHS of assignment, 12810 // so we don't need to worry about accepting invalid code for 12811 // non-assignment operators. 12812 // C++11 5.17p9: 12813 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 12814 // of x = {} is x = T(). 12815 InitializationKind Kind = InitializationKind::CreateDirectList( 12816 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 12817 InitializedEntity Entity = 12818 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 12819 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 12820 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 12821 if (Init.isInvalid()) 12822 return Init; 12823 RHSExpr = Init.get(); 12824 } 12825 12826 ExprResult LHS = LHSExpr, RHS = RHSExpr; 12827 QualType ResultTy; // Result type of the binary operator. 12828 // The following two variables are used for compound assignment operators 12829 QualType CompLHSTy; // Type of LHS after promotions for computation 12830 QualType CompResultTy; // Type of computation result 12831 ExprValueKind VK = VK_RValue; 12832 ExprObjectKind OK = OK_Ordinary; 12833 bool ConvertHalfVec = false; 12834 12835 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 12836 if (!LHS.isUsable() || !RHS.isUsable()) 12837 return ExprError(); 12838 12839 if (getLangOpts().OpenCL) { 12840 QualType LHSTy = LHSExpr->getType(); 12841 QualType RHSTy = RHSExpr->getType(); 12842 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 12843 // the ATOMIC_VAR_INIT macro. 12844 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 12845 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 12846 if (BO_Assign == Opc) 12847 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 12848 else 12849 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 12850 return ExprError(); 12851 } 12852 12853 // OpenCL special types - image, sampler, pipe, and blocks are to be used 12854 // only with a builtin functions and therefore should be disallowed here. 12855 if (LHSTy->isImageType() || RHSTy->isImageType() || 12856 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 12857 LHSTy->isPipeType() || RHSTy->isPipeType() || 12858 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 12859 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 12860 return ExprError(); 12861 } 12862 } 12863 12864 // Diagnose operations on the unsupported types for OpenMP device compilation. 12865 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) { 12866 if (Opc != BO_Assign && Opc != BO_Comma) { 12867 checkOpenMPDeviceExpr(LHSExpr); 12868 checkOpenMPDeviceExpr(RHSExpr); 12869 } 12870 } 12871 12872 switch (Opc) { 12873 case BO_Assign: 12874 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 12875 if (getLangOpts().CPlusPlus && 12876 LHS.get()->getObjectKind() != OK_ObjCProperty) { 12877 VK = LHS.get()->getValueKind(); 12878 OK = LHS.get()->getObjectKind(); 12879 } 12880 if (!ResultTy.isNull()) { 12881 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 12882 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 12883 12884 // Avoid copying a block to the heap if the block is assigned to a local 12885 // auto variable that is declared in the same scope as the block. This 12886 // optimization is unsafe if the local variable is declared in an outer 12887 // scope. For example: 12888 // 12889 // BlockTy b; 12890 // { 12891 // b = ^{...}; 12892 // } 12893 // // It is unsafe to invoke the block here if it wasn't copied to the 12894 // // heap. 12895 // b(); 12896 12897 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 12898 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 12899 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 12900 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 12901 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 12902 12903 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 12904 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 12905 NTCUC_Assignment, NTCUK_Copy); 12906 } 12907 RecordModifiableNonNullParam(*this, LHS.get()); 12908 break; 12909 case BO_PtrMemD: 12910 case BO_PtrMemI: 12911 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 12912 Opc == BO_PtrMemI); 12913 break; 12914 case BO_Mul: 12915 case BO_Div: 12916 ConvertHalfVec = true; 12917 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 12918 Opc == BO_Div); 12919 break; 12920 case BO_Rem: 12921 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 12922 break; 12923 case BO_Add: 12924 ConvertHalfVec = true; 12925 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 12926 break; 12927 case BO_Sub: 12928 ConvertHalfVec = true; 12929 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 12930 break; 12931 case BO_Shl: 12932 case BO_Shr: 12933 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 12934 break; 12935 case BO_LE: 12936 case BO_LT: 12937 case BO_GE: 12938 case BO_GT: 12939 ConvertHalfVec = true; 12940 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12941 break; 12942 case BO_EQ: 12943 case BO_NE: 12944 ConvertHalfVec = true; 12945 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12946 break; 12947 case BO_Cmp: 12948 ConvertHalfVec = true; 12949 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12950 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 12951 break; 12952 case BO_And: 12953 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 12954 LLVM_FALLTHROUGH; 12955 case BO_Xor: 12956 case BO_Or: 12957 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 12958 break; 12959 case BO_LAnd: 12960 case BO_LOr: 12961 ConvertHalfVec = true; 12962 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 12963 break; 12964 case BO_MulAssign: 12965 case BO_DivAssign: 12966 ConvertHalfVec = true; 12967 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 12968 Opc == BO_DivAssign); 12969 CompLHSTy = CompResultTy; 12970 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12971 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12972 break; 12973 case BO_RemAssign: 12974 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 12975 CompLHSTy = CompResultTy; 12976 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12977 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12978 break; 12979 case BO_AddAssign: 12980 ConvertHalfVec = true; 12981 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 12982 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12983 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12984 break; 12985 case BO_SubAssign: 12986 ConvertHalfVec = true; 12987 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 12988 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12989 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12990 break; 12991 case BO_ShlAssign: 12992 case BO_ShrAssign: 12993 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 12994 CompLHSTy = CompResultTy; 12995 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12996 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12997 break; 12998 case BO_AndAssign: 12999 case BO_OrAssign: // fallthrough 13000 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 13001 LLVM_FALLTHROUGH; 13002 case BO_XorAssign: 13003 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 13004 CompLHSTy = CompResultTy; 13005 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13006 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13007 break; 13008 case BO_Comma: 13009 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 13010 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 13011 VK = RHS.get()->getValueKind(); 13012 OK = RHS.get()->getObjectKind(); 13013 } 13014 break; 13015 } 13016 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 13017 return ExprError(); 13018 13019 // Some of the binary operations require promoting operands of half vector to 13020 // float vectors and truncating the result back to half vector. For now, we do 13021 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 13022 // arm64). 13023 assert(isVector(RHS.get()->getType(), Context.HalfTy) == 13024 isVector(LHS.get()->getType(), Context.HalfTy) && 13025 "both sides are half vectors or neither sides are"); 13026 ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context, 13027 LHS.get()->getType()); 13028 13029 // Check for array bounds violations for both sides of the BinaryOperator 13030 CheckArrayAccess(LHS.get()); 13031 CheckArrayAccess(RHS.get()); 13032 13033 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 13034 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 13035 &Context.Idents.get("object_setClass"), 13036 SourceLocation(), LookupOrdinaryName); 13037 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 13038 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 13039 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 13040 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 13041 "object_setClass(") 13042 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 13043 ",") 13044 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 13045 } 13046 else 13047 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 13048 } 13049 else if (const ObjCIvarRefExpr *OIRE = 13050 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 13051 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 13052 13053 // Opc is not a compound assignment if CompResultTy is null. 13054 if (CompResultTy.isNull()) { 13055 if (ConvertHalfVec) 13056 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 13057 OpLoc, FPFeatures); 13058 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 13059 OK, OpLoc, FPFeatures); 13060 } 13061 13062 // Handle compound assignments. 13063 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 13064 OK_ObjCProperty) { 13065 VK = VK_LValue; 13066 OK = LHS.get()->getObjectKind(); 13067 } 13068 13069 if (ConvertHalfVec) 13070 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 13071 OpLoc, FPFeatures); 13072 13073 return new (Context) CompoundAssignOperator( 13074 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 13075 OpLoc, FPFeatures); 13076 } 13077 13078 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 13079 /// operators are mixed in a way that suggests that the programmer forgot that 13080 /// comparison operators have higher precedence. The most typical example of 13081 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 13082 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 13083 SourceLocation OpLoc, Expr *LHSExpr, 13084 Expr *RHSExpr) { 13085 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 13086 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 13087 13088 // Check that one of the sides is a comparison operator and the other isn't. 13089 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 13090 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 13091 if (isLeftComp == isRightComp) 13092 return; 13093 13094 // Bitwise operations are sometimes used as eager logical ops. 13095 // Don't diagnose this. 13096 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 13097 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 13098 if (isLeftBitwise || isRightBitwise) 13099 return; 13100 13101 SourceRange DiagRange = isLeftComp 13102 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 13103 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 13104 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 13105 SourceRange ParensRange = 13106 isLeftComp 13107 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 13108 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 13109 13110 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 13111 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 13112 SuggestParentheses(Self, OpLoc, 13113 Self.PDiag(diag::note_precedence_silence) << OpStr, 13114 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 13115 SuggestParentheses(Self, OpLoc, 13116 Self.PDiag(diag::note_precedence_bitwise_first) 13117 << BinaryOperator::getOpcodeStr(Opc), 13118 ParensRange); 13119 } 13120 13121 /// It accepts a '&&' expr that is inside a '||' one. 13122 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 13123 /// in parentheses. 13124 static void 13125 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 13126 BinaryOperator *Bop) { 13127 assert(Bop->getOpcode() == BO_LAnd); 13128 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 13129 << Bop->getSourceRange() << OpLoc; 13130 SuggestParentheses(Self, Bop->getOperatorLoc(), 13131 Self.PDiag(diag::note_precedence_silence) 13132 << Bop->getOpcodeStr(), 13133 Bop->getSourceRange()); 13134 } 13135 13136 /// Returns true if the given expression can be evaluated as a constant 13137 /// 'true'. 13138 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 13139 bool Res; 13140 return !E->isValueDependent() && 13141 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 13142 } 13143 13144 /// Returns true if the given expression can be evaluated as a constant 13145 /// 'false'. 13146 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 13147 bool Res; 13148 return !E->isValueDependent() && 13149 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 13150 } 13151 13152 /// Look for '&&' in the left hand of a '||' expr. 13153 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 13154 Expr *LHSExpr, Expr *RHSExpr) { 13155 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 13156 if (Bop->getOpcode() == BO_LAnd) { 13157 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 13158 if (EvaluatesAsFalse(S, RHSExpr)) 13159 return; 13160 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 13161 if (!EvaluatesAsTrue(S, Bop->getLHS())) 13162 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 13163 } else if (Bop->getOpcode() == BO_LOr) { 13164 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 13165 // If it's "a || b && 1 || c" we didn't warn earlier for 13166 // "a || b && 1", but warn now. 13167 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 13168 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 13169 } 13170 } 13171 } 13172 } 13173 13174 /// Look for '&&' in the right hand of a '||' expr. 13175 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 13176 Expr *LHSExpr, Expr *RHSExpr) { 13177 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 13178 if (Bop->getOpcode() == BO_LAnd) { 13179 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 13180 if (EvaluatesAsFalse(S, LHSExpr)) 13181 return; 13182 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 13183 if (!EvaluatesAsTrue(S, Bop->getRHS())) 13184 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 13185 } 13186 } 13187 } 13188 13189 /// Look for bitwise op in the left or right hand of a bitwise op with 13190 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 13191 /// the '&' expression in parentheses. 13192 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 13193 SourceLocation OpLoc, Expr *SubExpr) { 13194 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 13195 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 13196 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 13197 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 13198 << Bop->getSourceRange() << OpLoc; 13199 SuggestParentheses(S, Bop->getOperatorLoc(), 13200 S.PDiag(diag::note_precedence_silence) 13201 << Bop->getOpcodeStr(), 13202 Bop->getSourceRange()); 13203 } 13204 } 13205 } 13206 13207 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 13208 Expr *SubExpr, StringRef Shift) { 13209 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 13210 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 13211 StringRef Op = Bop->getOpcodeStr(); 13212 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 13213 << Bop->getSourceRange() << OpLoc << Shift << Op; 13214 SuggestParentheses(S, Bop->getOperatorLoc(), 13215 S.PDiag(diag::note_precedence_silence) << Op, 13216 Bop->getSourceRange()); 13217 } 13218 } 13219 } 13220 13221 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 13222 Expr *LHSExpr, Expr *RHSExpr) { 13223 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 13224 if (!OCE) 13225 return; 13226 13227 FunctionDecl *FD = OCE->getDirectCallee(); 13228 if (!FD || !FD->isOverloadedOperator()) 13229 return; 13230 13231 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 13232 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 13233 return; 13234 13235 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 13236 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 13237 << (Kind == OO_LessLess); 13238 SuggestParentheses(S, OCE->getOperatorLoc(), 13239 S.PDiag(diag::note_precedence_silence) 13240 << (Kind == OO_LessLess ? "<<" : ">>"), 13241 OCE->getSourceRange()); 13242 SuggestParentheses( 13243 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 13244 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 13245 } 13246 13247 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 13248 /// precedence. 13249 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 13250 SourceLocation OpLoc, Expr *LHSExpr, 13251 Expr *RHSExpr){ 13252 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 13253 if (BinaryOperator::isBitwiseOp(Opc)) 13254 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 13255 13256 // Diagnose "arg1 & arg2 | arg3" 13257 if ((Opc == BO_Or || Opc == BO_Xor) && 13258 !OpLoc.isMacroID()/* Don't warn in macros. */) { 13259 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 13260 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 13261 } 13262 13263 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 13264 // We don't warn for 'assert(a || b && "bad")' since this is safe. 13265 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 13266 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 13267 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 13268 } 13269 13270 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 13271 || Opc == BO_Shr) { 13272 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 13273 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 13274 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 13275 } 13276 13277 // Warn on overloaded shift operators and comparisons, such as: 13278 // cout << 5 == 4; 13279 if (BinaryOperator::isComparisonOp(Opc)) 13280 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 13281 } 13282 13283 // Binary Operators. 'Tok' is the token for the operator. 13284 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 13285 tok::TokenKind Kind, 13286 Expr *LHSExpr, Expr *RHSExpr) { 13287 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 13288 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 13289 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 13290 13291 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 13292 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 13293 13294 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 13295 } 13296 13297 /// Build an overloaded binary operator expression in the given scope. 13298 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 13299 BinaryOperatorKind Opc, 13300 Expr *LHS, Expr *RHS) { 13301 switch (Opc) { 13302 case BO_Assign: 13303 case BO_DivAssign: 13304 case BO_RemAssign: 13305 case BO_SubAssign: 13306 case BO_AndAssign: 13307 case BO_OrAssign: 13308 case BO_XorAssign: 13309 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 13310 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 13311 break; 13312 default: 13313 break; 13314 } 13315 13316 // Find all of the overloaded operators visible from this 13317 // point. We perform both an operator-name lookup from the local 13318 // scope and an argument-dependent lookup based on the types of 13319 // the arguments. 13320 UnresolvedSet<16> Functions; 13321 OverloadedOperatorKind OverOp 13322 = BinaryOperator::getOverloadedOperator(Opc); 13323 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 13324 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 13325 RHS->getType(), Functions); 13326 13327 // In C++20 onwards, we may have a second operator to look up. 13328 if (S.getLangOpts().CPlusPlus2a) { 13329 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 13330 S.LookupOverloadedOperatorName(ExtraOp, Sc, LHS->getType(), 13331 RHS->getType(), Functions); 13332 } 13333 13334 // Build the (potentially-overloaded, potentially-dependent) 13335 // binary operation. 13336 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 13337 } 13338 13339 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 13340 BinaryOperatorKind Opc, 13341 Expr *LHSExpr, Expr *RHSExpr) { 13342 ExprResult LHS, RHS; 13343 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 13344 if (!LHS.isUsable() || !RHS.isUsable()) 13345 return ExprError(); 13346 LHSExpr = LHS.get(); 13347 RHSExpr = RHS.get(); 13348 13349 // We want to end up calling one of checkPseudoObjectAssignment 13350 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 13351 // both expressions are overloadable or either is type-dependent), 13352 // or CreateBuiltinBinOp (in any other case). We also want to get 13353 // any placeholder types out of the way. 13354 13355 // Handle pseudo-objects in the LHS. 13356 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 13357 // Assignments with a pseudo-object l-value need special analysis. 13358 if (pty->getKind() == BuiltinType::PseudoObject && 13359 BinaryOperator::isAssignmentOp(Opc)) 13360 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 13361 13362 // Don't resolve overloads if the other type is overloadable. 13363 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 13364 // We can't actually test that if we still have a placeholder, 13365 // though. Fortunately, none of the exceptions we see in that 13366 // code below are valid when the LHS is an overload set. Note 13367 // that an overload set can be dependently-typed, but it never 13368 // instantiates to having an overloadable type. 13369 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 13370 if (resolvedRHS.isInvalid()) return ExprError(); 13371 RHSExpr = resolvedRHS.get(); 13372 13373 if (RHSExpr->isTypeDependent() || 13374 RHSExpr->getType()->isOverloadableType()) 13375 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13376 } 13377 13378 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 13379 // template, diagnose the missing 'template' keyword instead of diagnosing 13380 // an invalid use of a bound member function. 13381 // 13382 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 13383 // to C++1z [over.over]/1.4, but we already checked for that case above. 13384 if (Opc == BO_LT && inTemplateInstantiation() && 13385 (pty->getKind() == BuiltinType::BoundMember || 13386 pty->getKind() == BuiltinType::Overload)) { 13387 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 13388 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 13389 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 13390 return isa<FunctionTemplateDecl>(ND); 13391 })) { 13392 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 13393 : OE->getNameLoc(), 13394 diag::err_template_kw_missing) 13395 << OE->getName().getAsString() << ""; 13396 return ExprError(); 13397 } 13398 } 13399 13400 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 13401 if (LHS.isInvalid()) return ExprError(); 13402 LHSExpr = LHS.get(); 13403 } 13404 13405 // Handle pseudo-objects in the RHS. 13406 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 13407 // An overload in the RHS can potentially be resolved by the type 13408 // being assigned to. 13409 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 13410 if (getLangOpts().CPlusPlus && 13411 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 13412 LHSExpr->getType()->isOverloadableType())) 13413 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13414 13415 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 13416 } 13417 13418 // Don't resolve overloads if the other type is overloadable. 13419 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 13420 LHSExpr->getType()->isOverloadableType()) 13421 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13422 13423 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 13424 if (!resolvedRHS.isUsable()) return ExprError(); 13425 RHSExpr = resolvedRHS.get(); 13426 } 13427 13428 if (getLangOpts().CPlusPlus) { 13429 // If either expression is type-dependent, always build an 13430 // overloaded op. 13431 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 13432 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13433 13434 // Otherwise, build an overloaded op if either expression has an 13435 // overloadable type. 13436 if (LHSExpr->getType()->isOverloadableType() || 13437 RHSExpr->getType()->isOverloadableType()) 13438 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13439 } 13440 13441 // Build a built-in binary operation. 13442 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 13443 } 13444 13445 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 13446 if (T.isNull() || T->isDependentType()) 13447 return false; 13448 13449 if (!T->isPromotableIntegerType()) 13450 return true; 13451 13452 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 13453 } 13454 13455 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 13456 UnaryOperatorKind Opc, 13457 Expr *InputExpr) { 13458 ExprResult Input = InputExpr; 13459 ExprValueKind VK = VK_RValue; 13460 ExprObjectKind OK = OK_Ordinary; 13461 QualType resultType; 13462 bool CanOverflow = false; 13463 13464 bool ConvertHalfVec = false; 13465 if (getLangOpts().OpenCL) { 13466 QualType Ty = InputExpr->getType(); 13467 // The only legal unary operation for atomics is '&'. 13468 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 13469 // OpenCL special types - image, sampler, pipe, and blocks are to be used 13470 // only with a builtin functions and therefore should be disallowed here. 13471 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 13472 || Ty->isBlockPointerType())) { 13473 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13474 << InputExpr->getType() 13475 << Input.get()->getSourceRange()); 13476 } 13477 } 13478 // Diagnose operations on the unsupported types for OpenMP device compilation. 13479 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) { 13480 if (UnaryOperator::isIncrementDecrementOp(Opc) || 13481 UnaryOperator::isArithmeticOp(Opc)) 13482 checkOpenMPDeviceExpr(InputExpr); 13483 } 13484 13485 switch (Opc) { 13486 case UO_PreInc: 13487 case UO_PreDec: 13488 case UO_PostInc: 13489 case UO_PostDec: 13490 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 13491 OpLoc, 13492 Opc == UO_PreInc || 13493 Opc == UO_PostInc, 13494 Opc == UO_PreInc || 13495 Opc == UO_PreDec); 13496 CanOverflow = isOverflowingIntegerType(Context, resultType); 13497 break; 13498 case UO_AddrOf: 13499 resultType = CheckAddressOfOperand(Input, OpLoc); 13500 CheckAddressOfNoDeref(InputExpr); 13501 RecordModifiableNonNullParam(*this, InputExpr); 13502 break; 13503 case UO_Deref: { 13504 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 13505 if (Input.isInvalid()) return ExprError(); 13506 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 13507 break; 13508 } 13509 case UO_Plus: 13510 case UO_Minus: 13511 CanOverflow = Opc == UO_Minus && 13512 isOverflowingIntegerType(Context, Input.get()->getType()); 13513 Input = UsualUnaryConversions(Input.get()); 13514 if (Input.isInvalid()) return ExprError(); 13515 // Unary plus and minus require promoting an operand of half vector to a 13516 // float vector and truncating the result back to a half vector. For now, we 13517 // do this only when HalfArgsAndReturns is set (that is, when the target is 13518 // arm or arm64). 13519 ConvertHalfVec = 13520 needsConversionOfHalfVec(true, Context, Input.get()->getType()); 13521 13522 // If the operand is a half vector, promote it to a float vector. 13523 if (ConvertHalfVec) 13524 Input = convertVector(Input.get(), Context.FloatTy, *this); 13525 resultType = Input.get()->getType(); 13526 if (resultType->isDependentType()) 13527 break; 13528 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 13529 break; 13530 else if (resultType->isVectorType() && 13531 // The z vector extensions don't allow + or - with bool vectors. 13532 (!Context.getLangOpts().ZVector || 13533 resultType->castAs<VectorType>()->getVectorKind() != 13534 VectorType::AltiVecBool)) 13535 break; 13536 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 13537 Opc == UO_Plus && 13538 resultType->isPointerType()) 13539 break; 13540 13541 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13542 << resultType << Input.get()->getSourceRange()); 13543 13544 case UO_Not: // bitwise complement 13545 Input = UsualUnaryConversions(Input.get()); 13546 if (Input.isInvalid()) 13547 return ExprError(); 13548 resultType = Input.get()->getType(); 13549 if (resultType->isDependentType()) 13550 break; 13551 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 13552 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 13553 // C99 does not support '~' for complex conjugation. 13554 Diag(OpLoc, diag::ext_integer_complement_complex) 13555 << resultType << Input.get()->getSourceRange(); 13556 else if (resultType->hasIntegerRepresentation()) 13557 break; 13558 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 13559 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 13560 // on vector float types. 13561 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 13562 if (!T->isIntegerType()) 13563 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13564 << resultType << Input.get()->getSourceRange()); 13565 } else { 13566 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13567 << resultType << Input.get()->getSourceRange()); 13568 } 13569 break; 13570 13571 case UO_LNot: // logical negation 13572 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 13573 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 13574 if (Input.isInvalid()) return ExprError(); 13575 resultType = Input.get()->getType(); 13576 13577 // Though we still have to promote half FP to float... 13578 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 13579 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 13580 resultType = Context.FloatTy; 13581 } 13582 13583 if (resultType->isDependentType()) 13584 break; 13585 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 13586 // C99 6.5.3.3p1: ok, fallthrough; 13587 if (Context.getLangOpts().CPlusPlus) { 13588 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 13589 // operand contextually converted to bool. 13590 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 13591 ScalarTypeToBooleanCastKind(resultType)); 13592 } else if (Context.getLangOpts().OpenCL && 13593 Context.getLangOpts().OpenCLVersion < 120) { 13594 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 13595 // operate on scalar float types. 13596 if (!resultType->isIntegerType() && !resultType->isPointerType()) 13597 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13598 << resultType << Input.get()->getSourceRange()); 13599 } 13600 } else if (resultType->isExtVectorType()) { 13601 if (Context.getLangOpts().OpenCL && 13602 Context.getLangOpts().OpenCLVersion < 120 && 13603 !Context.getLangOpts().OpenCLCPlusPlus) { 13604 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 13605 // operate on vector float types. 13606 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 13607 if (!T->isIntegerType()) 13608 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13609 << resultType << Input.get()->getSourceRange()); 13610 } 13611 // Vector logical not returns the signed variant of the operand type. 13612 resultType = GetSignedVectorType(resultType); 13613 break; 13614 } else { 13615 // FIXME: GCC's vector extension permits the usage of '!' with a vector 13616 // type in C++. We should allow that here too. 13617 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13618 << resultType << Input.get()->getSourceRange()); 13619 } 13620 13621 // LNot always has type int. C99 6.5.3.3p5. 13622 // In C++, it's bool. C++ 5.3.1p8 13623 resultType = Context.getLogicalOperationType(); 13624 break; 13625 case UO_Real: 13626 case UO_Imag: 13627 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 13628 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 13629 // complex l-values to ordinary l-values and all other values to r-values. 13630 if (Input.isInvalid()) return ExprError(); 13631 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 13632 if (Input.get()->getValueKind() != VK_RValue && 13633 Input.get()->getObjectKind() == OK_Ordinary) 13634 VK = Input.get()->getValueKind(); 13635 } else if (!getLangOpts().CPlusPlus) { 13636 // In C, a volatile scalar is read by __imag. In C++, it is not. 13637 Input = DefaultLvalueConversion(Input.get()); 13638 } 13639 break; 13640 case UO_Extension: 13641 resultType = Input.get()->getType(); 13642 VK = Input.get()->getValueKind(); 13643 OK = Input.get()->getObjectKind(); 13644 break; 13645 case UO_Coawait: 13646 // It's unnecessary to represent the pass-through operator co_await in the 13647 // AST; just return the input expression instead. 13648 assert(!Input.get()->getType()->isDependentType() && 13649 "the co_await expression must be non-dependant before " 13650 "building operator co_await"); 13651 return Input; 13652 } 13653 if (resultType.isNull() || Input.isInvalid()) 13654 return ExprError(); 13655 13656 // Check for array bounds violations in the operand of the UnaryOperator, 13657 // except for the '*' and '&' operators that have to be handled specially 13658 // by CheckArrayAccess (as there are special cases like &array[arraysize] 13659 // that are explicitly defined as valid by the standard). 13660 if (Opc != UO_AddrOf && Opc != UO_Deref) 13661 CheckArrayAccess(Input.get()); 13662 13663 auto *UO = new (Context) 13664 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow); 13665 13666 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 13667 !isa<ArrayType>(UO->getType().getDesugaredType(Context))) 13668 ExprEvalContexts.back().PossibleDerefs.insert(UO); 13669 13670 // Convert the result back to a half vector. 13671 if (ConvertHalfVec) 13672 return convertVector(UO, Context.HalfTy, *this); 13673 return UO; 13674 } 13675 13676 /// Determine whether the given expression is a qualified member 13677 /// access expression, of a form that could be turned into a pointer to member 13678 /// with the address-of operator. 13679 bool Sema::isQualifiedMemberAccess(Expr *E) { 13680 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13681 if (!DRE->getQualifier()) 13682 return false; 13683 13684 ValueDecl *VD = DRE->getDecl(); 13685 if (!VD->isCXXClassMember()) 13686 return false; 13687 13688 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 13689 return true; 13690 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 13691 return Method->isInstance(); 13692 13693 return false; 13694 } 13695 13696 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 13697 if (!ULE->getQualifier()) 13698 return false; 13699 13700 for (NamedDecl *D : ULE->decls()) { 13701 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 13702 if (Method->isInstance()) 13703 return true; 13704 } else { 13705 // Overload set does not contain methods. 13706 break; 13707 } 13708 } 13709 13710 return false; 13711 } 13712 13713 return false; 13714 } 13715 13716 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 13717 UnaryOperatorKind Opc, Expr *Input) { 13718 // First things first: handle placeholders so that the 13719 // overloaded-operator check considers the right type. 13720 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 13721 // Increment and decrement of pseudo-object references. 13722 if (pty->getKind() == BuiltinType::PseudoObject && 13723 UnaryOperator::isIncrementDecrementOp(Opc)) 13724 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 13725 13726 // extension is always a builtin operator. 13727 if (Opc == UO_Extension) 13728 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13729 13730 // & gets special logic for several kinds of placeholder. 13731 // The builtin code knows what to do. 13732 if (Opc == UO_AddrOf && 13733 (pty->getKind() == BuiltinType::Overload || 13734 pty->getKind() == BuiltinType::UnknownAny || 13735 pty->getKind() == BuiltinType::BoundMember)) 13736 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13737 13738 // Anything else needs to be handled now. 13739 ExprResult Result = CheckPlaceholderExpr(Input); 13740 if (Result.isInvalid()) return ExprError(); 13741 Input = Result.get(); 13742 } 13743 13744 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 13745 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 13746 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 13747 // Find all of the overloaded operators visible from this 13748 // point. We perform both an operator-name lookup from the local 13749 // scope and an argument-dependent lookup based on the types of 13750 // the arguments. 13751 UnresolvedSet<16> Functions; 13752 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 13753 if (S && OverOp != OO_None) 13754 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 13755 Functions); 13756 13757 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 13758 } 13759 13760 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13761 } 13762 13763 // Unary Operators. 'Tok' is the token for the operator. 13764 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 13765 tok::TokenKind Op, Expr *Input) { 13766 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 13767 } 13768 13769 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 13770 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 13771 LabelDecl *TheDecl) { 13772 TheDecl->markUsed(Context); 13773 // Create the AST node. The address of a label always has type 'void*'. 13774 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 13775 Context.getPointerType(Context.VoidTy)); 13776 } 13777 13778 void Sema::ActOnStartStmtExpr() { 13779 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 13780 } 13781 13782 void Sema::ActOnStmtExprError() { 13783 // Note that function is also called by TreeTransform when leaving a 13784 // StmtExpr scope without rebuilding anything. 13785 13786 DiscardCleanupsInEvaluationContext(); 13787 PopExpressionEvaluationContext(); 13788 } 13789 13790 ExprResult 13791 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 13792 SourceLocation RPLoc) { // "({..})" 13793 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 13794 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 13795 13796 if (hasAnyUnrecoverableErrorsInThisFunction()) 13797 DiscardCleanupsInEvaluationContext(); 13798 assert(!Cleanup.exprNeedsCleanups() && 13799 "cleanups within StmtExpr not correctly bound!"); 13800 PopExpressionEvaluationContext(); 13801 13802 // FIXME: there are a variety of strange constraints to enforce here, for 13803 // example, it is not possible to goto into a stmt expression apparently. 13804 // More semantic analysis is needed. 13805 13806 // If there are sub-stmts in the compound stmt, take the type of the last one 13807 // as the type of the stmtexpr. 13808 QualType Ty = Context.VoidTy; 13809 bool StmtExprMayBindToTemp = false; 13810 if (!Compound->body_empty()) { 13811 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 13812 if (const auto *LastStmt = 13813 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 13814 if (const Expr *Value = LastStmt->getExprStmt()) { 13815 StmtExprMayBindToTemp = true; 13816 Ty = Value->getType(); 13817 } 13818 } 13819 } 13820 13821 // FIXME: Check that expression type is complete/non-abstract; statement 13822 // expressions are not lvalues. 13823 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 13824 if (StmtExprMayBindToTemp) 13825 return MaybeBindToTemporary(ResStmtExpr); 13826 return ResStmtExpr; 13827 } 13828 13829 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 13830 if (ER.isInvalid()) 13831 return ExprError(); 13832 13833 // Do function/array conversion on the last expression, but not 13834 // lvalue-to-rvalue. However, initialize an unqualified type. 13835 ER = DefaultFunctionArrayConversion(ER.get()); 13836 if (ER.isInvalid()) 13837 return ExprError(); 13838 Expr *E = ER.get(); 13839 13840 if (E->isTypeDependent()) 13841 return E; 13842 13843 // In ARC, if the final expression ends in a consume, splice 13844 // the consume out and bind it later. In the alternate case 13845 // (when dealing with a retainable type), the result 13846 // initialization will create a produce. In both cases the 13847 // result will be +1, and we'll need to balance that out with 13848 // a bind. 13849 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 13850 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 13851 return Cast->getSubExpr(); 13852 13853 // FIXME: Provide a better location for the initialization. 13854 return PerformCopyInitialization( 13855 InitializedEntity::InitializeStmtExprResult( 13856 E->getBeginLoc(), E->getType().getUnqualifiedType()), 13857 SourceLocation(), E); 13858 } 13859 13860 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 13861 TypeSourceInfo *TInfo, 13862 ArrayRef<OffsetOfComponent> Components, 13863 SourceLocation RParenLoc) { 13864 QualType ArgTy = TInfo->getType(); 13865 bool Dependent = ArgTy->isDependentType(); 13866 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 13867 13868 // We must have at least one component that refers to the type, and the first 13869 // one is known to be a field designator. Verify that the ArgTy represents 13870 // a struct/union/class. 13871 if (!Dependent && !ArgTy->isRecordType()) 13872 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 13873 << ArgTy << TypeRange); 13874 13875 // Type must be complete per C99 7.17p3 because a declaring a variable 13876 // with an incomplete type would be ill-formed. 13877 if (!Dependent 13878 && RequireCompleteType(BuiltinLoc, ArgTy, 13879 diag::err_offsetof_incomplete_type, TypeRange)) 13880 return ExprError(); 13881 13882 bool DidWarnAboutNonPOD = false; 13883 QualType CurrentType = ArgTy; 13884 SmallVector<OffsetOfNode, 4> Comps; 13885 SmallVector<Expr*, 4> Exprs; 13886 for (const OffsetOfComponent &OC : Components) { 13887 if (OC.isBrackets) { 13888 // Offset of an array sub-field. TODO: Should we allow vector elements? 13889 if (!CurrentType->isDependentType()) { 13890 const ArrayType *AT = Context.getAsArrayType(CurrentType); 13891 if(!AT) 13892 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 13893 << CurrentType); 13894 CurrentType = AT->getElementType(); 13895 } else 13896 CurrentType = Context.DependentTy; 13897 13898 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 13899 if (IdxRval.isInvalid()) 13900 return ExprError(); 13901 Expr *Idx = IdxRval.get(); 13902 13903 // The expression must be an integral expression. 13904 // FIXME: An integral constant expression? 13905 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 13906 !Idx->getType()->isIntegerType()) 13907 return ExprError( 13908 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 13909 << Idx->getSourceRange()); 13910 13911 // Record this array index. 13912 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 13913 Exprs.push_back(Idx); 13914 continue; 13915 } 13916 13917 // Offset of a field. 13918 if (CurrentType->isDependentType()) { 13919 // We have the offset of a field, but we can't look into the dependent 13920 // type. Just record the identifier of the field. 13921 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 13922 CurrentType = Context.DependentTy; 13923 continue; 13924 } 13925 13926 // We need to have a complete type to look into. 13927 if (RequireCompleteType(OC.LocStart, CurrentType, 13928 diag::err_offsetof_incomplete_type)) 13929 return ExprError(); 13930 13931 // Look for the designated field. 13932 const RecordType *RC = CurrentType->getAs<RecordType>(); 13933 if (!RC) 13934 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 13935 << CurrentType); 13936 RecordDecl *RD = RC->getDecl(); 13937 13938 // C++ [lib.support.types]p5: 13939 // The macro offsetof accepts a restricted set of type arguments in this 13940 // International Standard. type shall be a POD structure or a POD union 13941 // (clause 9). 13942 // C++11 [support.types]p4: 13943 // If type is not a standard-layout class (Clause 9), the results are 13944 // undefined. 13945 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 13946 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 13947 unsigned DiagID = 13948 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 13949 : diag::ext_offsetof_non_pod_type; 13950 13951 if (!IsSafe && !DidWarnAboutNonPOD && 13952 DiagRuntimeBehavior(BuiltinLoc, nullptr, 13953 PDiag(DiagID) 13954 << SourceRange(Components[0].LocStart, OC.LocEnd) 13955 << CurrentType)) 13956 DidWarnAboutNonPOD = true; 13957 } 13958 13959 // Look for the field. 13960 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 13961 LookupQualifiedName(R, RD); 13962 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 13963 IndirectFieldDecl *IndirectMemberDecl = nullptr; 13964 if (!MemberDecl) { 13965 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 13966 MemberDecl = IndirectMemberDecl->getAnonField(); 13967 } 13968 13969 if (!MemberDecl) 13970 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 13971 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 13972 OC.LocEnd)); 13973 13974 // C99 7.17p3: 13975 // (If the specified member is a bit-field, the behavior is undefined.) 13976 // 13977 // We diagnose this as an error. 13978 if (MemberDecl->isBitField()) { 13979 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 13980 << MemberDecl->getDeclName() 13981 << SourceRange(BuiltinLoc, RParenLoc); 13982 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 13983 return ExprError(); 13984 } 13985 13986 RecordDecl *Parent = MemberDecl->getParent(); 13987 if (IndirectMemberDecl) 13988 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 13989 13990 // If the member was found in a base class, introduce OffsetOfNodes for 13991 // the base class indirections. 13992 CXXBasePaths Paths; 13993 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 13994 Paths)) { 13995 if (Paths.getDetectedVirtual()) { 13996 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 13997 << MemberDecl->getDeclName() 13998 << SourceRange(BuiltinLoc, RParenLoc); 13999 return ExprError(); 14000 } 14001 14002 CXXBasePath &Path = Paths.front(); 14003 for (const CXXBasePathElement &B : Path) 14004 Comps.push_back(OffsetOfNode(B.Base)); 14005 } 14006 14007 if (IndirectMemberDecl) { 14008 for (auto *FI : IndirectMemberDecl->chain()) { 14009 assert(isa<FieldDecl>(FI)); 14010 Comps.push_back(OffsetOfNode(OC.LocStart, 14011 cast<FieldDecl>(FI), OC.LocEnd)); 14012 } 14013 } else 14014 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 14015 14016 CurrentType = MemberDecl->getType().getNonReferenceType(); 14017 } 14018 14019 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 14020 Comps, Exprs, RParenLoc); 14021 } 14022 14023 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 14024 SourceLocation BuiltinLoc, 14025 SourceLocation TypeLoc, 14026 ParsedType ParsedArgTy, 14027 ArrayRef<OffsetOfComponent> Components, 14028 SourceLocation RParenLoc) { 14029 14030 TypeSourceInfo *ArgTInfo; 14031 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 14032 if (ArgTy.isNull()) 14033 return ExprError(); 14034 14035 if (!ArgTInfo) 14036 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 14037 14038 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 14039 } 14040 14041 14042 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 14043 Expr *CondExpr, 14044 Expr *LHSExpr, Expr *RHSExpr, 14045 SourceLocation RPLoc) { 14046 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 14047 14048 ExprValueKind VK = VK_RValue; 14049 ExprObjectKind OK = OK_Ordinary; 14050 QualType resType; 14051 bool ValueDependent = false; 14052 bool CondIsTrue = false; 14053 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 14054 resType = Context.DependentTy; 14055 ValueDependent = true; 14056 } else { 14057 // The conditional expression is required to be a constant expression. 14058 llvm::APSInt condEval(32); 14059 ExprResult CondICE 14060 = VerifyIntegerConstantExpression(CondExpr, &condEval, 14061 diag::err_typecheck_choose_expr_requires_constant, false); 14062 if (CondICE.isInvalid()) 14063 return ExprError(); 14064 CondExpr = CondICE.get(); 14065 CondIsTrue = condEval.getZExtValue(); 14066 14067 // If the condition is > zero, then the AST type is the same as the LHSExpr. 14068 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 14069 14070 resType = ActiveExpr->getType(); 14071 ValueDependent = ActiveExpr->isValueDependent(); 14072 VK = ActiveExpr->getValueKind(); 14073 OK = ActiveExpr->getObjectKind(); 14074 } 14075 14076 return new (Context) 14077 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 14078 CondIsTrue, resType->isDependentType(), ValueDependent); 14079 } 14080 14081 //===----------------------------------------------------------------------===// 14082 // Clang Extensions. 14083 //===----------------------------------------------------------------------===// 14084 14085 /// ActOnBlockStart - This callback is invoked when a block literal is started. 14086 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 14087 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 14088 14089 if (LangOpts.CPlusPlus) { 14090 MangleNumberingContext *MCtx; 14091 Decl *ManglingContextDecl; 14092 std::tie(MCtx, ManglingContextDecl) = 14093 getCurrentMangleNumberContext(Block->getDeclContext()); 14094 if (MCtx) { 14095 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 14096 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 14097 } 14098 } 14099 14100 PushBlockScope(CurScope, Block); 14101 CurContext->addDecl(Block); 14102 if (CurScope) 14103 PushDeclContext(CurScope, Block); 14104 else 14105 CurContext = Block; 14106 14107 getCurBlock()->HasImplicitReturnType = true; 14108 14109 // Enter a new evaluation context to insulate the block from any 14110 // cleanups from the enclosing full-expression. 14111 PushExpressionEvaluationContext( 14112 ExpressionEvaluationContext::PotentiallyEvaluated); 14113 } 14114 14115 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 14116 Scope *CurScope) { 14117 assert(ParamInfo.getIdentifier() == nullptr && 14118 "block-id should have no identifier!"); 14119 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext); 14120 BlockScopeInfo *CurBlock = getCurBlock(); 14121 14122 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 14123 QualType T = Sig->getType(); 14124 14125 // FIXME: We should allow unexpanded parameter packs here, but that would, 14126 // in turn, make the block expression contain unexpanded parameter packs. 14127 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 14128 // Drop the parameters. 14129 FunctionProtoType::ExtProtoInfo EPI; 14130 EPI.HasTrailingReturn = false; 14131 EPI.TypeQuals.addConst(); 14132 T = Context.getFunctionType(Context.DependentTy, None, EPI); 14133 Sig = Context.getTrivialTypeSourceInfo(T); 14134 } 14135 14136 // GetTypeForDeclarator always produces a function type for a block 14137 // literal signature. Furthermore, it is always a FunctionProtoType 14138 // unless the function was written with a typedef. 14139 assert(T->isFunctionType() && 14140 "GetTypeForDeclarator made a non-function block signature"); 14141 14142 // Look for an explicit signature in that function type. 14143 FunctionProtoTypeLoc ExplicitSignature; 14144 14145 if ((ExplicitSignature = Sig->getTypeLoc() 14146 .getAsAdjusted<FunctionProtoTypeLoc>())) { 14147 14148 // Check whether that explicit signature was synthesized by 14149 // GetTypeForDeclarator. If so, don't save that as part of the 14150 // written signature. 14151 if (ExplicitSignature.getLocalRangeBegin() == 14152 ExplicitSignature.getLocalRangeEnd()) { 14153 // This would be much cheaper if we stored TypeLocs instead of 14154 // TypeSourceInfos. 14155 TypeLoc Result = ExplicitSignature.getReturnLoc(); 14156 unsigned Size = Result.getFullDataSize(); 14157 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 14158 Sig->getTypeLoc().initializeFullCopy(Result, Size); 14159 14160 ExplicitSignature = FunctionProtoTypeLoc(); 14161 } 14162 } 14163 14164 CurBlock->TheDecl->setSignatureAsWritten(Sig); 14165 CurBlock->FunctionType = T; 14166 14167 const FunctionType *Fn = T->getAs<FunctionType>(); 14168 QualType RetTy = Fn->getReturnType(); 14169 bool isVariadic = 14170 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 14171 14172 CurBlock->TheDecl->setIsVariadic(isVariadic); 14173 14174 // Context.DependentTy is used as a placeholder for a missing block 14175 // return type. TODO: what should we do with declarators like: 14176 // ^ * { ... } 14177 // If the answer is "apply template argument deduction".... 14178 if (RetTy != Context.DependentTy) { 14179 CurBlock->ReturnType = RetTy; 14180 CurBlock->TheDecl->setBlockMissingReturnType(false); 14181 CurBlock->HasImplicitReturnType = false; 14182 } 14183 14184 // Push block parameters from the declarator if we had them. 14185 SmallVector<ParmVarDecl*, 8> Params; 14186 if (ExplicitSignature) { 14187 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 14188 ParmVarDecl *Param = ExplicitSignature.getParam(I); 14189 if (Param->getIdentifier() == nullptr && 14190 !Param->isImplicit() && 14191 !Param->isInvalidDecl() && 14192 !getLangOpts().CPlusPlus) 14193 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 14194 Params.push_back(Param); 14195 } 14196 14197 // Fake up parameter variables if we have a typedef, like 14198 // ^ fntype { ... } 14199 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 14200 for (const auto &I : Fn->param_types()) { 14201 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 14202 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 14203 Params.push_back(Param); 14204 } 14205 } 14206 14207 // Set the parameters on the block decl. 14208 if (!Params.empty()) { 14209 CurBlock->TheDecl->setParams(Params); 14210 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 14211 /*CheckParameterNames=*/false); 14212 } 14213 14214 // Finally we can process decl attributes. 14215 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 14216 14217 // Put the parameter variables in scope. 14218 for (auto AI : CurBlock->TheDecl->parameters()) { 14219 AI->setOwningFunction(CurBlock->TheDecl); 14220 14221 // If this has an identifier, add it to the scope stack. 14222 if (AI->getIdentifier()) { 14223 CheckShadow(CurBlock->TheScope, AI); 14224 14225 PushOnScopeChains(AI, CurBlock->TheScope); 14226 } 14227 } 14228 } 14229 14230 /// ActOnBlockError - If there is an error parsing a block, this callback 14231 /// is invoked to pop the information about the block from the action impl. 14232 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 14233 // Leave the expression-evaluation context. 14234 DiscardCleanupsInEvaluationContext(); 14235 PopExpressionEvaluationContext(); 14236 14237 // Pop off CurBlock, handle nested blocks. 14238 PopDeclContext(); 14239 PopFunctionScopeInfo(); 14240 } 14241 14242 /// ActOnBlockStmtExpr - This is called when the body of a block statement 14243 /// literal was successfully completed. ^(int x){...} 14244 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 14245 Stmt *Body, Scope *CurScope) { 14246 // If blocks are disabled, emit an error. 14247 if (!LangOpts.Blocks) 14248 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 14249 14250 // Leave the expression-evaluation context. 14251 if (hasAnyUnrecoverableErrorsInThisFunction()) 14252 DiscardCleanupsInEvaluationContext(); 14253 assert(!Cleanup.exprNeedsCleanups() && 14254 "cleanups within block not correctly bound!"); 14255 PopExpressionEvaluationContext(); 14256 14257 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 14258 BlockDecl *BD = BSI->TheDecl; 14259 14260 if (BSI->HasImplicitReturnType) 14261 deduceClosureReturnType(*BSI); 14262 14263 QualType RetTy = Context.VoidTy; 14264 if (!BSI->ReturnType.isNull()) 14265 RetTy = BSI->ReturnType; 14266 14267 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 14268 QualType BlockTy; 14269 14270 // If the user wrote a function type in some form, try to use that. 14271 if (!BSI->FunctionType.isNull()) { 14272 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 14273 14274 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 14275 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 14276 14277 // Turn protoless block types into nullary block types. 14278 if (isa<FunctionNoProtoType>(FTy)) { 14279 FunctionProtoType::ExtProtoInfo EPI; 14280 EPI.ExtInfo = Ext; 14281 BlockTy = Context.getFunctionType(RetTy, None, EPI); 14282 14283 // Otherwise, if we don't need to change anything about the function type, 14284 // preserve its sugar structure. 14285 } else if (FTy->getReturnType() == RetTy && 14286 (!NoReturn || FTy->getNoReturnAttr())) { 14287 BlockTy = BSI->FunctionType; 14288 14289 // Otherwise, make the minimal modifications to the function type. 14290 } else { 14291 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 14292 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 14293 EPI.TypeQuals = Qualifiers(); 14294 EPI.ExtInfo = Ext; 14295 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 14296 } 14297 14298 // If we don't have a function type, just build one from nothing. 14299 } else { 14300 FunctionProtoType::ExtProtoInfo EPI; 14301 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 14302 BlockTy = Context.getFunctionType(RetTy, None, EPI); 14303 } 14304 14305 DiagnoseUnusedParameters(BD->parameters()); 14306 BlockTy = Context.getBlockPointerType(BlockTy); 14307 14308 // If needed, diagnose invalid gotos and switches in the block. 14309 if (getCurFunction()->NeedsScopeChecking() && 14310 !PP.isCodeCompletionEnabled()) 14311 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 14312 14313 BD->setBody(cast<CompoundStmt>(Body)); 14314 14315 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 14316 DiagnoseUnguardedAvailabilityViolations(BD); 14317 14318 // Try to apply the named return value optimization. We have to check again 14319 // if we can do this, though, because blocks keep return statements around 14320 // to deduce an implicit return type. 14321 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 14322 !BD->isDependentContext()) 14323 computeNRVO(Body, BSI); 14324 14325 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 14326 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 14327 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 14328 NTCUK_Destruct|NTCUK_Copy); 14329 14330 PopDeclContext(); 14331 14332 // Pop the block scope now but keep it alive to the end of this function. 14333 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14334 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 14335 14336 // Set the captured variables on the block. 14337 SmallVector<BlockDecl::Capture, 4> Captures; 14338 for (Capture &Cap : BSI->Captures) { 14339 if (Cap.isInvalid() || Cap.isThisCapture()) 14340 continue; 14341 14342 VarDecl *Var = Cap.getVariable(); 14343 Expr *CopyExpr = nullptr; 14344 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 14345 if (const RecordType *Record = 14346 Cap.getCaptureType()->getAs<RecordType>()) { 14347 // The capture logic needs the destructor, so make sure we mark it. 14348 // Usually this is unnecessary because most local variables have 14349 // their destructors marked at declaration time, but parameters are 14350 // an exception because it's technically only the call site that 14351 // actually requires the destructor. 14352 if (isa<ParmVarDecl>(Var)) 14353 FinalizeVarWithDestructor(Var, Record); 14354 14355 // Enter a separate potentially-evaluated context while building block 14356 // initializers to isolate their cleanups from those of the block 14357 // itself. 14358 // FIXME: Is this appropriate even when the block itself occurs in an 14359 // unevaluated operand? 14360 EnterExpressionEvaluationContext EvalContext( 14361 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 14362 14363 SourceLocation Loc = Cap.getLocation(); 14364 14365 ExprResult Result = BuildDeclarationNameExpr( 14366 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 14367 14368 // According to the blocks spec, the capture of a variable from 14369 // the stack requires a const copy constructor. This is not true 14370 // of the copy/move done to move a __block variable to the heap. 14371 if (!Result.isInvalid() && 14372 !Result.get()->getType().isConstQualified()) { 14373 Result = ImpCastExprToType(Result.get(), 14374 Result.get()->getType().withConst(), 14375 CK_NoOp, VK_LValue); 14376 } 14377 14378 if (!Result.isInvalid()) { 14379 Result = PerformCopyInitialization( 14380 InitializedEntity::InitializeBlock(Var->getLocation(), 14381 Cap.getCaptureType(), false), 14382 Loc, Result.get()); 14383 } 14384 14385 // Build a full-expression copy expression if initialization 14386 // succeeded and used a non-trivial constructor. Recover from 14387 // errors by pretending that the copy isn't necessary. 14388 if (!Result.isInvalid() && 14389 !cast<CXXConstructExpr>(Result.get())->getConstructor() 14390 ->isTrivial()) { 14391 Result = MaybeCreateExprWithCleanups(Result); 14392 CopyExpr = Result.get(); 14393 } 14394 } 14395 } 14396 14397 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 14398 CopyExpr); 14399 Captures.push_back(NewCap); 14400 } 14401 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 14402 14403 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 14404 14405 // If the block isn't obviously global, i.e. it captures anything at 14406 // all, then we need to do a few things in the surrounding context: 14407 if (Result->getBlockDecl()->hasCaptures()) { 14408 // First, this expression has a new cleanup object. 14409 ExprCleanupObjects.push_back(Result->getBlockDecl()); 14410 Cleanup.setExprNeedsCleanups(true); 14411 14412 // It also gets a branch-protected scope if any of the captured 14413 // variables needs destruction. 14414 for (const auto &CI : Result->getBlockDecl()->captures()) { 14415 const VarDecl *var = CI.getVariable(); 14416 if (var->getType().isDestructedType() != QualType::DK_none) { 14417 setFunctionHasBranchProtectedScope(); 14418 break; 14419 } 14420 } 14421 } 14422 14423 if (getCurFunction()) 14424 getCurFunction()->addBlock(BD); 14425 14426 return Result; 14427 } 14428 14429 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 14430 SourceLocation RPLoc) { 14431 TypeSourceInfo *TInfo; 14432 GetTypeFromParser(Ty, &TInfo); 14433 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 14434 } 14435 14436 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 14437 Expr *E, TypeSourceInfo *TInfo, 14438 SourceLocation RPLoc) { 14439 Expr *OrigExpr = E; 14440 bool IsMS = false; 14441 14442 // CUDA device code does not support varargs. 14443 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 14444 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 14445 CUDAFunctionTarget T = IdentifyCUDATarget(F); 14446 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 14447 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 14448 } 14449 } 14450 14451 // NVPTX does not support va_arg expression. 14452 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 14453 Context.getTargetInfo().getTriple().isNVPTX()) 14454 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 14455 14456 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 14457 // as Microsoft ABI on an actual Microsoft platform, where 14458 // __builtin_ms_va_list and __builtin_va_list are the same.) 14459 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 14460 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 14461 QualType MSVaListType = Context.getBuiltinMSVaListType(); 14462 if (Context.hasSameType(MSVaListType, E->getType())) { 14463 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 14464 return ExprError(); 14465 IsMS = true; 14466 } 14467 } 14468 14469 // Get the va_list type 14470 QualType VaListType = Context.getBuiltinVaListType(); 14471 if (!IsMS) { 14472 if (VaListType->isArrayType()) { 14473 // Deal with implicit array decay; for example, on x86-64, 14474 // va_list is an array, but it's supposed to decay to 14475 // a pointer for va_arg. 14476 VaListType = Context.getArrayDecayedType(VaListType); 14477 // Make sure the input expression also decays appropriately. 14478 ExprResult Result = UsualUnaryConversions(E); 14479 if (Result.isInvalid()) 14480 return ExprError(); 14481 E = Result.get(); 14482 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 14483 // If va_list is a record type and we are compiling in C++ mode, 14484 // check the argument using reference binding. 14485 InitializedEntity Entity = InitializedEntity::InitializeParameter( 14486 Context, Context.getLValueReferenceType(VaListType), false); 14487 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 14488 if (Init.isInvalid()) 14489 return ExprError(); 14490 E = Init.getAs<Expr>(); 14491 } else { 14492 // Otherwise, the va_list argument must be an l-value because 14493 // it is modified by va_arg. 14494 if (!E->isTypeDependent() && 14495 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 14496 return ExprError(); 14497 } 14498 } 14499 14500 if (!IsMS && !E->isTypeDependent() && 14501 !Context.hasSameType(VaListType, E->getType())) 14502 return ExprError( 14503 Diag(E->getBeginLoc(), 14504 diag::err_first_argument_to_va_arg_not_of_type_va_list) 14505 << OrigExpr->getType() << E->getSourceRange()); 14506 14507 if (!TInfo->getType()->isDependentType()) { 14508 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 14509 diag::err_second_parameter_to_va_arg_incomplete, 14510 TInfo->getTypeLoc())) 14511 return ExprError(); 14512 14513 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 14514 TInfo->getType(), 14515 diag::err_second_parameter_to_va_arg_abstract, 14516 TInfo->getTypeLoc())) 14517 return ExprError(); 14518 14519 if (!TInfo->getType().isPODType(Context)) { 14520 Diag(TInfo->getTypeLoc().getBeginLoc(), 14521 TInfo->getType()->isObjCLifetimeType() 14522 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 14523 : diag::warn_second_parameter_to_va_arg_not_pod) 14524 << TInfo->getType() 14525 << TInfo->getTypeLoc().getSourceRange(); 14526 } 14527 14528 // Check for va_arg where arguments of the given type will be promoted 14529 // (i.e. this va_arg is guaranteed to have undefined behavior). 14530 QualType PromoteType; 14531 if (TInfo->getType()->isPromotableIntegerType()) { 14532 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 14533 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 14534 PromoteType = QualType(); 14535 } 14536 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 14537 PromoteType = Context.DoubleTy; 14538 if (!PromoteType.isNull()) 14539 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 14540 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 14541 << TInfo->getType() 14542 << PromoteType 14543 << TInfo->getTypeLoc().getSourceRange()); 14544 } 14545 14546 QualType T = TInfo->getType().getNonLValueExprType(Context); 14547 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 14548 } 14549 14550 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 14551 // The type of __null will be int or long, depending on the size of 14552 // pointers on the target. 14553 QualType Ty; 14554 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 14555 if (pw == Context.getTargetInfo().getIntWidth()) 14556 Ty = Context.IntTy; 14557 else if (pw == Context.getTargetInfo().getLongWidth()) 14558 Ty = Context.LongTy; 14559 else if (pw == Context.getTargetInfo().getLongLongWidth()) 14560 Ty = Context.LongLongTy; 14561 else { 14562 llvm_unreachable("I don't know size of pointer!"); 14563 } 14564 14565 return new (Context) GNUNullExpr(Ty, TokenLoc); 14566 } 14567 14568 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 14569 SourceLocation BuiltinLoc, 14570 SourceLocation RPLoc) { 14571 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); 14572 } 14573 14574 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 14575 SourceLocation BuiltinLoc, 14576 SourceLocation RPLoc, 14577 DeclContext *ParentContext) { 14578 return new (Context) 14579 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); 14580 } 14581 14582 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 14583 bool Diagnose) { 14584 if (!getLangOpts().ObjC) 14585 return false; 14586 14587 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 14588 if (!PT) 14589 return false; 14590 14591 if (!PT->isObjCIdType()) { 14592 // Check if the destination is the 'NSString' interface. 14593 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 14594 if (!ID || !ID->getIdentifier()->isStr("NSString")) 14595 return false; 14596 } 14597 14598 // Ignore any parens, implicit casts (should only be 14599 // array-to-pointer decays), and not-so-opaque values. The last is 14600 // important for making this trigger for property assignments. 14601 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 14602 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 14603 if (OV->getSourceExpr()) 14604 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 14605 14606 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 14607 if (!SL || !SL->isAscii()) 14608 return false; 14609 if (Diagnose) { 14610 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 14611 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 14612 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 14613 } 14614 return true; 14615 } 14616 14617 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 14618 const Expr *SrcExpr) { 14619 if (!DstType->isFunctionPointerType() || 14620 !SrcExpr->getType()->isFunctionType()) 14621 return false; 14622 14623 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 14624 if (!DRE) 14625 return false; 14626 14627 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 14628 if (!FD) 14629 return false; 14630 14631 return !S.checkAddressOfFunctionIsAvailable(FD, 14632 /*Complain=*/true, 14633 SrcExpr->getBeginLoc()); 14634 } 14635 14636 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 14637 SourceLocation Loc, 14638 QualType DstType, QualType SrcType, 14639 Expr *SrcExpr, AssignmentAction Action, 14640 bool *Complained) { 14641 if (Complained) 14642 *Complained = false; 14643 14644 // Decode the result (notice that AST's are still created for extensions). 14645 bool CheckInferredResultType = false; 14646 bool isInvalid = false; 14647 unsigned DiagKind = 0; 14648 FixItHint Hint; 14649 ConversionFixItGenerator ConvHints; 14650 bool MayHaveConvFixit = false; 14651 bool MayHaveFunctionDiff = false; 14652 const ObjCInterfaceDecl *IFace = nullptr; 14653 const ObjCProtocolDecl *PDecl = nullptr; 14654 14655 switch (ConvTy) { 14656 case Compatible: 14657 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 14658 return false; 14659 14660 case PointerToInt: 14661 DiagKind = diag::ext_typecheck_convert_pointer_int; 14662 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14663 MayHaveConvFixit = true; 14664 break; 14665 case IntToPointer: 14666 DiagKind = diag::ext_typecheck_convert_int_pointer; 14667 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14668 MayHaveConvFixit = true; 14669 break; 14670 case IncompatiblePointer: 14671 if (Action == AA_Passing_CFAudited) 14672 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 14673 else if (SrcType->isFunctionPointerType() && 14674 DstType->isFunctionPointerType()) 14675 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 14676 else 14677 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 14678 14679 CheckInferredResultType = DstType->isObjCObjectPointerType() && 14680 SrcType->isObjCObjectPointerType(); 14681 if (Hint.isNull() && !CheckInferredResultType) { 14682 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14683 } 14684 else if (CheckInferredResultType) { 14685 SrcType = SrcType.getUnqualifiedType(); 14686 DstType = DstType.getUnqualifiedType(); 14687 } 14688 MayHaveConvFixit = true; 14689 break; 14690 case IncompatiblePointerSign: 14691 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 14692 break; 14693 case FunctionVoidPointer: 14694 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 14695 break; 14696 case IncompatiblePointerDiscardsQualifiers: { 14697 // Perform array-to-pointer decay if necessary. 14698 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 14699 14700 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 14701 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 14702 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 14703 DiagKind = diag::err_typecheck_incompatible_address_space; 14704 break; 14705 14706 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 14707 DiagKind = diag::err_typecheck_incompatible_ownership; 14708 break; 14709 } 14710 14711 llvm_unreachable("unknown error case for discarding qualifiers!"); 14712 // fallthrough 14713 } 14714 case CompatiblePointerDiscardsQualifiers: 14715 // If the qualifiers lost were because we were applying the 14716 // (deprecated) C++ conversion from a string literal to a char* 14717 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 14718 // Ideally, this check would be performed in 14719 // checkPointerTypesForAssignment. However, that would require a 14720 // bit of refactoring (so that the second argument is an 14721 // expression, rather than a type), which should be done as part 14722 // of a larger effort to fix checkPointerTypesForAssignment for 14723 // C++ semantics. 14724 if (getLangOpts().CPlusPlus && 14725 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 14726 return false; 14727 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 14728 break; 14729 case IncompatibleNestedPointerQualifiers: 14730 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 14731 break; 14732 case IncompatibleNestedPointerAddressSpaceMismatch: 14733 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 14734 break; 14735 case IntToBlockPointer: 14736 DiagKind = diag::err_int_to_block_pointer; 14737 break; 14738 case IncompatibleBlockPointer: 14739 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 14740 break; 14741 case IncompatibleObjCQualifiedId: { 14742 if (SrcType->isObjCQualifiedIdType()) { 14743 const ObjCObjectPointerType *srcOPT = 14744 SrcType->castAs<ObjCObjectPointerType>(); 14745 for (auto *srcProto : srcOPT->quals()) { 14746 PDecl = srcProto; 14747 break; 14748 } 14749 if (const ObjCInterfaceType *IFaceT = 14750 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 14751 IFace = IFaceT->getDecl(); 14752 } 14753 else if (DstType->isObjCQualifiedIdType()) { 14754 const ObjCObjectPointerType *dstOPT = 14755 DstType->castAs<ObjCObjectPointerType>(); 14756 for (auto *dstProto : dstOPT->quals()) { 14757 PDecl = dstProto; 14758 break; 14759 } 14760 if (const ObjCInterfaceType *IFaceT = 14761 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 14762 IFace = IFaceT->getDecl(); 14763 } 14764 DiagKind = diag::warn_incompatible_qualified_id; 14765 break; 14766 } 14767 case IncompatibleVectors: 14768 DiagKind = diag::warn_incompatible_vectors; 14769 break; 14770 case IncompatibleObjCWeakRef: 14771 DiagKind = diag::err_arc_weak_unavailable_assign; 14772 break; 14773 case Incompatible: 14774 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 14775 if (Complained) 14776 *Complained = true; 14777 return true; 14778 } 14779 14780 DiagKind = diag::err_typecheck_convert_incompatible; 14781 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14782 MayHaveConvFixit = true; 14783 isInvalid = true; 14784 MayHaveFunctionDiff = true; 14785 break; 14786 } 14787 14788 QualType FirstType, SecondType; 14789 switch (Action) { 14790 case AA_Assigning: 14791 case AA_Initializing: 14792 // The destination type comes first. 14793 FirstType = DstType; 14794 SecondType = SrcType; 14795 break; 14796 14797 case AA_Returning: 14798 case AA_Passing: 14799 case AA_Passing_CFAudited: 14800 case AA_Converting: 14801 case AA_Sending: 14802 case AA_Casting: 14803 // The source type comes first. 14804 FirstType = SrcType; 14805 SecondType = DstType; 14806 break; 14807 } 14808 14809 PartialDiagnostic FDiag = PDiag(DiagKind); 14810 if (Action == AA_Passing_CFAudited) 14811 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 14812 else 14813 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 14814 14815 // If we can fix the conversion, suggest the FixIts. 14816 assert(ConvHints.isNull() || Hint.isNull()); 14817 if (!ConvHints.isNull()) { 14818 for (FixItHint &H : ConvHints.Hints) 14819 FDiag << H; 14820 } else { 14821 FDiag << Hint; 14822 } 14823 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 14824 14825 if (MayHaveFunctionDiff) 14826 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 14827 14828 Diag(Loc, FDiag); 14829 if (DiagKind == diag::warn_incompatible_qualified_id && 14830 PDecl && IFace && !IFace->hasDefinition()) 14831 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 14832 << IFace << PDecl; 14833 14834 if (SecondType == Context.OverloadTy) 14835 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 14836 FirstType, /*TakingAddress=*/true); 14837 14838 if (CheckInferredResultType) 14839 EmitRelatedResultTypeNote(SrcExpr); 14840 14841 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 14842 EmitRelatedResultTypeNoteForReturn(DstType); 14843 14844 if (Complained) 14845 *Complained = true; 14846 return isInvalid; 14847 } 14848 14849 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 14850 llvm::APSInt *Result) { 14851 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 14852 public: 14853 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 14854 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 14855 } 14856 } Diagnoser; 14857 14858 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 14859 } 14860 14861 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 14862 llvm::APSInt *Result, 14863 unsigned DiagID, 14864 bool AllowFold) { 14865 class IDDiagnoser : public VerifyICEDiagnoser { 14866 unsigned DiagID; 14867 14868 public: 14869 IDDiagnoser(unsigned DiagID) 14870 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 14871 14872 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 14873 S.Diag(Loc, DiagID) << SR; 14874 } 14875 } Diagnoser(DiagID); 14876 14877 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 14878 } 14879 14880 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 14881 SourceRange SR) { 14882 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 14883 } 14884 14885 ExprResult 14886 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 14887 VerifyICEDiagnoser &Diagnoser, 14888 bool AllowFold) { 14889 SourceLocation DiagLoc = E->getBeginLoc(); 14890 14891 if (getLangOpts().CPlusPlus11) { 14892 // C++11 [expr.const]p5: 14893 // If an expression of literal class type is used in a context where an 14894 // integral constant expression is required, then that class type shall 14895 // have a single non-explicit conversion function to an integral or 14896 // unscoped enumeration type 14897 ExprResult Converted; 14898 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 14899 public: 14900 CXX11ConvertDiagnoser(bool Silent) 14901 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 14902 Silent, true) {} 14903 14904 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 14905 QualType T) override { 14906 return S.Diag(Loc, diag::err_ice_not_integral) << T; 14907 } 14908 14909 SemaDiagnosticBuilder diagnoseIncomplete( 14910 Sema &S, SourceLocation Loc, QualType T) override { 14911 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 14912 } 14913 14914 SemaDiagnosticBuilder diagnoseExplicitConv( 14915 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 14916 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 14917 } 14918 14919 SemaDiagnosticBuilder noteExplicitConv( 14920 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 14921 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 14922 << ConvTy->isEnumeralType() << ConvTy; 14923 } 14924 14925 SemaDiagnosticBuilder diagnoseAmbiguous( 14926 Sema &S, SourceLocation Loc, QualType T) override { 14927 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 14928 } 14929 14930 SemaDiagnosticBuilder noteAmbiguous( 14931 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 14932 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 14933 << ConvTy->isEnumeralType() << ConvTy; 14934 } 14935 14936 SemaDiagnosticBuilder diagnoseConversion( 14937 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 14938 llvm_unreachable("conversion functions are permitted"); 14939 } 14940 } ConvertDiagnoser(Diagnoser.Suppress); 14941 14942 Converted = PerformContextualImplicitConversion(DiagLoc, E, 14943 ConvertDiagnoser); 14944 if (Converted.isInvalid()) 14945 return Converted; 14946 E = Converted.get(); 14947 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 14948 return ExprError(); 14949 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 14950 // An ICE must be of integral or unscoped enumeration type. 14951 if (!Diagnoser.Suppress) 14952 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 14953 return ExprError(); 14954 } 14955 14956 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 14957 // in the non-ICE case. 14958 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 14959 if (Result) 14960 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 14961 if (!isa<ConstantExpr>(E)) 14962 E = ConstantExpr::Create(Context, E); 14963 return E; 14964 } 14965 14966 Expr::EvalResult EvalResult; 14967 SmallVector<PartialDiagnosticAt, 8> Notes; 14968 EvalResult.Diag = &Notes; 14969 14970 // Try to evaluate the expression, and produce diagnostics explaining why it's 14971 // not a constant expression as a side-effect. 14972 bool Folded = 14973 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 14974 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 14975 14976 if (!isa<ConstantExpr>(E)) 14977 E = ConstantExpr::Create(Context, E, EvalResult.Val); 14978 14979 // In C++11, we can rely on diagnostics being produced for any expression 14980 // which is not a constant expression. If no diagnostics were produced, then 14981 // this is a constant expression. 14982 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 14983 if (Result) 14984 *Result = EvalResult.Val.getInt(); 14985 return E; 14986 } 14987 14988 // If our only note is the usual "invalid subexpression" note, just point 14989 // the caret at its location rather than producing an essentially 14990 // redundant note. 14991 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 14992 diag::note_invalid_subexpr_in_const_expr) { 14993 DiagLoc = Notes[0].first; 14994 Notes.clear(); 14995 } 14996 14997 if (!Folded || !AllowFold) { 14998 if (!Diagnoser.Suppress) { 14999 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 15000 for (const PartialDiagnosticAt &Note : Notes) 15001 Diag(Note.first, Note.second); 15002 } 15003 15004 return ExprError(); 15005 } 15006 15007 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 15008 for (const PartialDiagnosticAt &Note : Notes) 15009 Diag(Note.first, Note.second); 15010 15011 if (Result) 15012 *Result = EvalResult.Val.getInt(); 15013 return E; 15014 } 15015 15016 namespace { 15017 // Handle the case where we conclude a expression which we speculatively 15018 // considered to be unevaluated is actually evaluated. 15019 class TransformToPE : public TreeTransform<TransformToPE> { 15020 typedef TreeTransform<TransformToPE> BaseTransform; 15021 15022 public: 15023 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 15024 15025 // Make sure we redo semantic analysis 15026 bool AlwaysRebuild() { return true; } 15027 bool ReplacingOriginal() { return true; } 15028 15029 // We need to special-case DeclRefExprs referring to FieldDecls which 15030 // are not part of a member pointer formation; normal TreeTransforming 15031 // doesn't catch this case because of the way we represent them in the AST. 15032 // FIXME: This is a bit ugly; is it really the best way to handle this 15033 // case? 15034 // 15035 // Error on DeclRefExprs referring to FieldDecls. 15036 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 15037 if (isa<FieldDecl>(E->getDecl()) && 15038 !SemaRef.isUnevaluatedContext()) 15039 return SemaRef.Diag(E->getLocation(), 15040 diag::err_invalid_non_static_member_use) 15041 << E->getDecl() << E->getSourceRange(); 15042 15043 return BaseTransform::TransformDeclRefExpr(E); 15044 } 15045 15046 // Exception: filter out member pointer formation 15047 ExprResult TransformUnaryOperator(UnaryOperator *E) { 15048 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 15049 return E; 15050 15051 return BaseTransform::TransformUnaryOperator(E); 15052 } 15053 15054 // The body of a lambda-expression is in a separate expression evaluation 15055 // context so never needs to be transformed. 15056 // FIXME: Ideally we wouldn't transform the closure type either, and would 15057 // just recreate the capture expressions and lambda expression. 15058 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 15059 return SkipLambdaBody(E, Body); 15060 } 15061 }; 15062 } 15063 15064 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 15065 assert(isUnevaluatedContext() && 15066 "Should only transform unevaluated expressions"); 15067 ExprEvalContexts.back().Context = 15068 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 15069 if (isUnevaluatedContext()) 15070 return E; 15071 return TransformToPE(*this).TransformExpr(E); 15072 } 15073 15074 void 15075 Sema::PushExpressionEvaluationContext( 15076 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 15077 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 15078 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 15079 LambdaContextDecl, ExprContext); 15080 Cleanup.reset(); 15081 if (!MaybeODRUseExprs.empty()) 15082 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 15083 } 15084 15085 void 15086 Sema::PushExpressionEvaluationContext( 15087 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 15088 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 15089 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 15090 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 15091 } 15092 15093 namespace { 15094 15095 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 15096 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 15097 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 15098 if (E->getOpcode() == UO_Deref) 15099 return CheckPossibleDeref(S, E->getSubExpr()); 15100 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 15101 return CheckPossibleDeref(S, E->getBase()); 15102 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 15103 return CheckPossibleDeref(S, E->getBase()); 15104 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 15105 QualType Inner; 15106 QualType Ty = E->getType(); 15107 if (const auto *Ptr = Ty->getAs<PointerType>()) 15108 Inner = Ptr->getPointeeType(); 15109 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 15110 Inner = Arr->getElementType(); 15111 else 15112 return nullptr; 15113 15114 if (Inner->hasAttr(attr::NoDeref)) 15115 return E; 15116 } 15117 return nullptr; 15118 } 15119 15120 } // namespace 15121 15122 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 15123 for (const Expr *E : Rec.PossibleDerefs) { 15124 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 15125 if (DeclRef) { 15126 const ValueDecl *Decl = DeclRef->getDecl(); 15127 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 15128 << Decl->getName() << E->getSourceRange(); 15129 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 15130 } else { 15131 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 15132 << E->getSourceRange(); 15133 } 15134 } 15135 Rec.PossibleDerefs.clear(); 15136 } 15137 15138 /// Check whether E, which is either a discarded-value expression or an 15139 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 15140 /// and if so, remove it from the list of volatile-qualified assignments that 15141 /// we are going to warn are deprecated. 15142 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 15143 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus2a) 15144 return; 15145 15146 // Note: ignoring parens here is not justified by the standard rules, but 15147 // ignoring parentheses seems like a more reasonable approach, and this only 15148 // drives a deprecation warning so doesn't affect conformance. 15149 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 15150 if (BO->getOpcode() == BO_Assign) { 15151 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 15152 LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()), 15153 LHSs.end()); 15154 } 15155 } 15156 } 15157 15158 void Sema::PopExpressionEvaluationContext() { 15159 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 15160 unsigned NumTypos = Rec.NumTypos; 15161 15162 if (!Rec.Lambdas.empty()) { 15163 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 15164 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() || 15165 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) { 15166 unsigned D; 15167 if (Rec.isUnevaluated()) { 15168 // C++11 [expr.prim.lambda]p2: 15169 // A lambda-expression shall not appear in an unevaluated operand 15170 // (Clause 5). 15171 D = diag::err_lambda_unevaluated_operand; 15172 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 15173 // C++1y [expr.const]p2: 15174 // A conditional-expression e is a core constant expression unless the 15175 // evaluation of e, following the rules of the abstract machine, would 15176 // evaluate [...] a lambda-expression. 15177 D = diag::err_lambda_in_constant_expression; 15178 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 15179 // C++17 [expr.prim.lamda]p2: 15180 // A lambda-expression shall not appear [...] in a template-argument. 15181 D = diag::err_lambda_in_invalid_context; 15182 } else 15183 llvm_unreachable("Couldn't infer lambda error message."); 15184 15185 for (const auto *L : Rec.Lambdas) 15186 Diag(L->getBeginLoc(), D); 15187 } 15188 } 15189 15190 WarnOnPendingNoDerefs(Rec); 15191 15192 // Warn on any volatile-qualified simple-assignments that are not discarded- 15193 // value expressions nor unevaluated operands (those cases get removed from 15194 // this list by CheckUnusedVolatileAssignment). 15195 for (auto *BO : Rec.VolatileAssignmentLHSs) 15196 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 15197 << BO->getType(); 15198 15199 // When are coming out of an unevaluated context, clear out any 15200 // temporaries that we may have created as part of the evaluation of 15201 // the expression in that context: they aren't relevant because they 15202 // will never be constructed. 15203 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 15204 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 15205 ExprCleanupObjects.end()); 15206 Cleanup = Rec.ParentCleanup; 15207 CleanupVarDeclMarking(); 15208 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 15209 // Otherwise, merge the contexts together. 15210 } else { 15211 Cleanup.mergeFrom(Rec.ParentCleanup); 15212 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 15213 Rec.SavedMaybeODRUseExprs.end()); 15214 } 15215 15216 // Pop the current expression evaluation context off the stack. 15217 ExprEvalContexts.pop_back(); 15218 15219 // The global expression evaluation context record is never popped. 15220 ExprEvalContexts.back().NumTypos += NumTypos; 15221 } 15222 15223 void Sema::DiscardCleanupsInEvaluationContext() { 15224 ExprCleanupObjects.erase( 15225 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 15226 ExprCleanupObjects.end()); 15227 Cleanup.reset(); 15228 MaybeODRUseExprs.clear(); 15229 } 15230 15231 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 15232 ExprResult Result = CheckPlaceholderExpr(E); 15233 if (Result.isInvalid()) 15234 return ExprError(); 15235 E = Result.get(); 15236 if (!E->getType()->isVariablyModifiedType()) 15237 return E; 15238 return TransformToPotentiallyEvaluated(E); 15239 } 15240 15241 /// Are we in a context that is potentially constant evaluated per C++20 15242 /// [expr.const]p12? 15243 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 15244 /// C++2a [expr.const]p12: 15245 // An expression or conversion is potentially constant evaluated if it is 15246 switch (SemaRef.ExprEvalContexts.back().Context) { 15247 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 15248 // -- a manifestly constant-evaluated expression, 15249 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 15250 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 15251 case Sema::ExpressionEvaluationContext::DiscardedStatement: 15252 // -- a potentially-evaluated expression, 15253 case Sema::ExpressionEvaluationContext::UnevaluatedList: 15254 // -- an immediate subexpression of a braced-init-list, 15255 15256 // -- [FIXME] an expression of the form & cast-expression that occurs 15257 // within a templated entity 15258 // -- a subexpression of one of the above that is not a subexpression of 15259 // a nested unevaluated operand. 15260 return true; 15261 15262 case Sema::ExpressionEvaluationContext::Unevaluated: 15263 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 15264 // Expressions in this context are never evaluated. 15265 return false; 15266 } 15267 llvm_unreachable("Invalid context"); 15268 } 15269 15270 /// Return true if this function has a calling convention that requires mangling 15271 /// in the size of the parameter pack. 15272 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 15273 // These manglings don't do anything on non-Windows or non-x86 platforms, so 15274 // we don't need parameter type sizes. 15275 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 15276 if (!TT.isOSWindows() || (TT.getArch() != llvm::Triple::x86 && 15277 TT.getArch() != llvm::Triple::x86_64)) 15278 return false; 15279 15280 // If this is C++ and this isn't an extern "C" function, parameters do not 15281 // need to be complete. In this case, C++ mangling will apply, which doesn't 15282 // use the size of the parameters. 15283 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 15284 return false; 15285 15286 // Stdcall, fastcall, and vectorcall need this special treatment. 15287 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 15288 switch (CC) { 15289 case CC_X86StdCall: 15290 case CC_X86FastCall: 15291 case CC_X86VectorCall: 15292 return true; 15293 default: 15294 break; 15295 } 15296 return false; 15297 } 15298 15299 /// Require that all of the parameter types of function be complete. Normally, 15300 /// parameter types are only required to be complete when a function is called 15301 /// or defined, but to mangle functions with certain calling conventions, the 15302 /// mangler needs to know the size of the parameter list. In this situation, 15303 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 15304 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 15305 /// result in a linker error. Clang doesn't implement this behavior, and instead 15306 /// attempts to error at compile time. 15307 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 15308 SourceLocation Loc) { 15309 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 15310 FunctionDecl *FD; 15311 ParmVarDecl *Param; 15312 15313 public: 15314 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 15315 : FD(FD), Param(Param) {} 15316 15317 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 15318 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 15319 StringRef CCName; 15320 switch (CC) { 15321 case CC_X86StdCall: 15322 CCName = "stdcall"; 15323 break; 15324 case CC_X86FastCall: 15325 CCName = "fastcall"; 15326 break; 15327 case CC_X86VectorCall: 15328 CCName = "vectorcall"; 15329 break; 15330 default: 15331 llvm_unreachable("CC does not need mangling"); 15332 } 15333 15334 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 15335 << Param->getDeclName() << FD->getDeclName() << CCName; 15336 } 15337 }; 15338 15339 for (ParmVarDecl *Param : FD->parameters()) { 15340 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 15341 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 15342 } 15343 } 15344 15345 namespace { 15346 enum class OdrUseContext { 15347 /// Declarations in this context are not odr-used. 15348 None, 15349 /// Declarations in this context are formally odr-used, but this is a 15350 /// dependent context. 15351 Dependent, 15352 /// Declarations in this context are odr-used but not actually used (yet). 15353 FormallyOdrUsed, 15354 /// Declarations in this context are used. 15355 Used 15356 }; 15357 } 15358 15359 /// Are we within a context in which references to resolved functions or to 15360 /// variables result in odr-use? 15361 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 15362 OdrUseContext Result; 15363 15364 switch (SemaRef.ExprEvalContexts.back().Context) { 15365 case Sema::ExpressionEvaluationContext::Unevaluated: 15366 case Sema::ExpressionEvaluationContext::UnevaluatedList: 15367 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 15368 return OdrUseContext::None; 15369 15370 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 15371 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 15372 Result = OdrUseContext::Used; 15373 break; 15374 15375 case Sema::ExpressionEvaluationContext::DiscardedStatement: 15376 Result = OdrUseContext::FormallyOdrUsed; 15377 break; 15378 15379 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 15380 // A default argument formally results in odr-use, but doesn't actually 15381 // result in a use in any real sense until it itself is used. 15382 Result = OdrUseContext::FormallyOdrUsed; 15383 break; 15384 } 15385 15386 if (SemaRef.CurContext->isDependentContext()) 15387 return OdrUseContext::Dependent; 15388 15389 return Result; 15390 } 15391 15392 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 15393 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 15394 return Func->isConstexpr() && 15395 (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided())); 15396 } 15397 15398 /// Mark a function referenced, and check whether it is odr-used 15399 /// (C++ [basic.def.odr]p2, C99 6.9p3) 15400 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 15401 bool MightBeOdrUse) { 15402 assert(Func && "No function?"); 15403 15404 Func->setReferenced(); 15405 15406 // Recursive functions aren't really used until they're used from some other 15407 // context. 15408 bool IsRecursiveCall = CurContext == Func; 15409 15410 // C++11 [basic.def.odr]p3: 15411 // A function whose name appears as a potentially-evaluated expression is 15412 // odr-used if it is the unique lookup result or the selected member of a 15413 // set of overloaded functions [...]. 15414 // 15415 // We (incorrectly) mark overload resolution as an unevaluated context, so we 15416 // can just check that here. 15417 OdrUseContext OdrUse = 15418 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 15419 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 15420 OdrUse = OdrUseContext::FormallyOdrUsed; 15421 15422 // Trivial default constructors and destructors are never actually used. 15423 // FIXME: What about other special members? 15424 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 15425 OdrUse == OdrUseContext::Used) { 15426 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 15427 if (Constructor->isDefaultConstructor()) 15428 OdrUse = OdrUseContext::FormallyOdrUsed; 15429 if (isa<CXXDestructorDecl>(Func)) 15430 OdrUse = OdrUseContext::FormallyOdrUsed; 15431 } 15432 15433 // C++20 [expr.const]p12: 15434 // A function [...] is needed for constant evaluation if it is [...] a 15435 // constexpr function that is named by an expression that is potentially 15436 // constant evaluated 15437 bool NeededForConstantEvaluation = 15438 isPotentiallyConstantEvaluatedContext(*this) && 15439 isImplicitlyDefinableConstexprFunction(Func); 15440 15441 // Determine whether we require a function definition to exist, per 15442 // C++11 [temp.inst]p3: 15443 // Unless a function template specialization has been explicitly 15444 // instantiated or explicitly specialized, the function template 15445 // specialization is implicitly instantiated when the specialization is 15446 // referenced in a context that requires a function definition to exist. 15447 // C++20 [temp.inst]p7: 15448 // The existence of a definition of a [...] function is considered to 15449 // affect the semantics of the program if the [...] function is needed for 15450 // constant evaluation by an expression 15451 // C++20 [basic.def.odr]p10: 15452 // Every program shall contain exactly one definition of every non-inline 15453 // function or variable that is odr-used in that program outside of a 15454 // discarded statement 15455 // C++20 [special]p1: 15456 // The implementation will implicitly define [defaulted special members] 15457 // if they are odr-used or needed for constant evaluation. 15458 // 15459 // Note that we skip the implicit instantiation of templates that are only 15460 // used in unused default arguments or by recursive calls to themselves. 15461 // This is formally non-conforming, but seems reasonable in practice. 15462 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 15463 NeededForConstantEvaluation); 15464 15465 // C++14 [temp.expl.spec]p6: 15466 // If a template [...] is explicitly specialized then that specialization 15467 // shall be declared before the first use of that specialization that would 15468 // cause an implicit instantiation to take place, in every translation unit 15469 // in which such a use occurs 15470 if (NeedDefinition && 15471 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 15472 Func->getMemberSpecializationInfo())) 15473 checkSpecializationVisibility(Loc, Func); 15474 15475 // C++14 [except.spec]p17: 15476 // An exception-specification is considered to be needed when: 15477 // - the function is odr-used or, if it appears in an unevaluated operand, 15478 // would be odr-used if the expression were potentially-evaluated; 15479 // 15480 // Note, we do this even if MightBeOdrUse is false. That indicates that the 15481 // function is a pure virtual function we're calling, and in that case the 15482 // function was selected by overload resolution and we need to resolve its 15483 // exception specification for a different reason. 15484 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 15485 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 15486 ResolveExceptionSpec(Loc, FPT); 15487 15488 if (getLangOpts().CUDA) 15489 CheckCUDACall(Loc, Func); 15490 15491 // If we need a definition, try to create one. 15492 if (NeedDefinition && !Func->getBody()) { 15493 runWithSufficientStackSpace(Loc, [&] { 15494 if (CXXConstructorDecl *Constructor = 15495 dyn_cast<CXXConstructorDecl>(Func)) { 15496 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 15497 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 15498 if (Constructor->isDefaultConstructor()) { 15499 if (Constructor->isTrivial() && 15500 !Constructor->hasAttr<DLLExportAttr>()) 15501 return; 15502 DefineImplicitDefaultConstructor(Loc, Constructor); 15503 } else if (Constructor->isCopyConstructor()) { 15504 DefineImplicitCopyConstructor(Loc, Constructor); 15505 } else if (Constructor->isMoveConstructor()) { 15506 DefineImplicitMoveConstructor(Loc, Constructor); 15507 } 15508 } else if (Constructor->getInheritedConstructor()) { 15509 DefineInheritingConstructor(Loc, Constructor); 15510 } 15511 } else if (CXXDestructorDecl *Destructor = 15512 dyn_cast<CXXDestructorDecl>(Func)) { 15513 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 15514 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 15515 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 15516 return; 15517 DefineImplicitDestructor(Loc, Destructor); 15518 } 15519 if (Destructor->isVirtual() && getLangOpts().AppleKext) 15520 MarkVTableUsed(Loc, Destructor->getParent()); 15521 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 15522 if (MethodDecl->isOverloadedOperator() && 15523 MethodDecl->getOverloadedOperator() == OO_Equal) { 15524 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 15525 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 15526 if (MethodDecl->isCopyAssignmentOperator()) 15527 DefineImplicitCopyAssignment(Loc, MethodDecl); 15528 else if (MethodDecl->isMoveAssignmentOperator()) 15529 DefineImplicitMoveAssignment(Loc, MethodDecl); 15530 } 15531 } else if (isa<CXXConversionDecl>(MethodDecl) && 15532 MethodDecl->getParent()->isLambda()) { 15533 CXXConversionDecl *Conversion = 15534 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 15535 if (Conversion->isLambdaToBlockPointerConversion()) 15536 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 15537 else 15538 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 15539 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 15540 MarkVTableUsed(Loc, MethodDecl->getParent()); 15541 } 15542 15543 // Implicit instantiation of function templates and member functions of 15544 // class templates. 15545 if (Func->isImplicitlyInstantiable()) { 15546 TemplateSpecializationKind TSK = 15547 Func->getTemplateSpecializationKindForInstantiation(); 15548 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 15549 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 15550 if (FirstInstantiation) { 15551 PointOfInstantiation = Loc; 15552 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 15553 } else if (TSK != TSK_ImplicitInstantiation) { 15554 // Use the point of use as the point of instantiation, instead of the 15555 // point of explicit instantiation (which we track as the actual point 15556 // of instantiation). This gives better backtraces in diagnostics. 15557 PointOfInstantiation = Loc; 15558 } 15559 15560 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 15561 Func->isConstexpr()) { 15562 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 15563 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 15564 CodeSynthesisContexts.size()) 15565 PendingLocalImplicitInstantiations.push_back( 15566 std::make_pair(Func, PointOfInstantiation)); 15567 else if (Func->isConstexpr()) 15568 // Do not defer instantiations of constexpr functions, to avoid the 15569 // expression evaluator needing to call back into Sema if it sees a 15570 // call to such a function. 15571 InstantiateFunctionDefinition(PointOfInstantiation, Func); 15572 else { 15573 Func->setInstantiationIsPending(true); 15574 PendingInstantiations.push_back( 15575 std::make_pair(Func, PointOfInstantiation)); 15576 // Notify the consumer that a function was implicitly instantiated. 15577 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 15578 } 15579 } 15580 } else { 15581 // Walk redefinitions, as some of them may be instantiable. 15582 for (auto i : Func->redecls()) { 15583 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 15584 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 15585 } 15586 } 15587 }); 15588 } 15589 15590 // If this is the first "real" use, act on that. 15591 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 15592 // Keep track of used but undefined functions. 15593 if (!Func->isDefined()) { 15594 if (mightHaveNonExternalLinkage(Func)) 15595 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 15596 else if (Func->getMostRecentDecl()->isInlined() && 15597 !LangOpts.GNUInline && 15598 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 15599 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 15600 else if (isExternalWithNoLinkageType(Func)) 15601 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 15602 } 15603 15604 // Some x86 Windows calling conventions mangle the size of the parameter 15605 // pack into the name. Computing the size of the parameters requires the 15606 // parameter types to be complete. Check that now. 15607 if (funcHasParameterSizeMangling(*this, Func)) 15608 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 15609 15610 Func->markUsed(Context); 15611 } 15612 15613 if (LangOpts.OpenMP) { 15614 markOpenMPDeclareVariantFuncsReferenced(Loc, Func, MightBeOdrUse); 15615 if (LangOpts.OpenMPIsDevice) 15616 checkOpenMPDeviceFunction(Loc, Func); 15617 else 15618 checkOpenMPHostFunction(Loc, Func); 15619 } 15620 } 15621 15622 /// Directly mark a variable odr-used. Given a choice, prefer to use 15623 /// MarkVariableReferenced since it does additional checks and then 15624 /// calls MarkVarDeclODRUsed. 15625 /// If the variable must be captured: 15626 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 15627 /// - else capture it in the DeclContext that maps to the 15628 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 15629 static void 15630 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 15631 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 15632 // Keep track of used but undefined variables. 15633 // FIXME: We shouldn't suppress this warning for static data members. 15634 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 15635 (!Var->isExternallyVisible() || Var->isInline() || 15636 SemaRef.isExternalWithNoLinkageType(Var)) && 15637 !(Var->isStaticDataMember() && Var->hasInit())) { 15638 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 15639 if (old.isInvalid()) 15640 old = Loc; 15641 } 15642 QualType CaptureType, DeclRefType; 15643 if (SemaRef.LangOpts.OpenMP) 15644 SemaRef.tryCaptureOpenMPLambdas(Var); 15645 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 15646 /*EllipsisLoc*/ SourceLocation(), 15647 /*BuildAndDiagnose*/ true, 15648 CaptureType, DeclRefType, 15649 FunctionScopeIndexToStopAt); 15650 15651 Var->markUsed(SemaRef.Context); 15652 } 15653 15654 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 15655 SourceLocation Loc, 15656 unsigned CapturingScopeIndex) { 15657 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 15658 } 15659 15660 static void 15661 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 15662 ValueDecl *var, DeclContext *DC) { 15663 DeclContext *VarDC = var->getDeclContext(); 15664 15665 // If the parameter still belongs to the translation unit, then 15666 // we're actually just using one parameter in the declaration of 15667 // the next. 15668 if (isa<ParmVarDecl>(var) && 15669 isa<TranslationUnitDecl>(VarDC)) 15670 return; 15671 15672 // For C code, don't diagnose about capture if we're not actually in code 15673 // right now; it's impossible to write a non-constant expression outside of 15674 // function context, so we'll get other (more useful) diagnostics later. 15675 // 15676 // For C++, things get a bit more nasty... it would be nice to suppress this 15677 // diagnostic for certain cases like using a local variable in an array bound 15678 // for a member of a local class, but the correct predicate is not obvious. 15679 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 15680 return; 15681 15682 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 15683 unsigned ContextKind = 3; // unknown 15684 if (isa<CXXMethodDecl>(VarDC) && 15685 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 15686 ContextKind = 2; 15687 } else if (isa<FunctionDecl>(VarDC)) { 15688 ContextKind = 0; 15689 } else if (isa<BlockDecl>(VarDC)) { 15690 ContextKind = 1; 15691 } 15692 15693 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 15694 << var << ValueKind << ContextKind << VarDC; 15695 S.Diag(var->getLocation(), diag::note_entity_declared_at) 15696 << var; 15697 15698 // FIXME: Add additional diagnostic info about class etc. which prevents 15699 // capture. 15700 } 15701 15702 15703 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 15704 bool &SubCapturesAreNested, 15705 QualType &CaptureType, 15706 QualType &DeclRefType) { 15707 // Check whether we've already captured it. 15708 if (CSI->CaptureMap.count(Var)) { 15709 // If we found a capture, any subcaptures are nested. 15710 SubCapturesAreNested = true; 15711 15712 // Retrieve the capture type for this variable. 15713 CaptureType = CSI->getCapture(Var).getCaptureType(); 15714 15715 // Compute the type of an expression that refers to this variable. 15716 DeclRefType = CaptureType.getNonReferenceType(); 15717 15718 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 15719 // are mutable in the sense that user can change their value - they are 15720 // private instances of the captured declarations. 15721 const Capture &Cap = CSI->getCapture(Var); 15722 if (Cap.isCopyCapture() && 15723 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 15724 !(isa<CapturedRegionScopeInfo>(CSI) && 15725 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 15726 DeclRefType.addConst(); 15727 return true; 15728 } 15729 return false; 15730 } 15731 15732 // Only block literals, captured statements, and lambda expressions can 15733 // capture; other scopes don't work. 15734 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 15735 SourceLocation Loc, 15736 const bool Diagnose, Sema &S) { 15737 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 15738 return getLambdaAwareParentOfDeclContext(DC); 15739 else if (Var->hasLocalStorage()) { 15740 if (Diagnose) 15741 diagnoseUncapturableValueReference(S, Loc, Var, DC); 15742 } 15743 return nullptr; 15744 } 15745 15746 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 15747 // certain types of variables (unnamed, variably modified types etc.) 15748 // so check for eligibility. 15749 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 15750 SourceLocation Loc, 15751 const bool Diagnose, Sema &S) { 15752 15753 bool IsBlock = isa<BlockScopeInfo>(CSI); 15754 bool IsLambda = isa<LambdaScopeInfo>(CSI); 15755 15756 // Lambdas are not allowed to capture unnamed variables 15757 // (e.g. anonymous unions). 15758 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 15759 // assuming that's the intent. 15760 if (IsLambda && !Var->getDeclName()) { 15761 if (Diagnose) { 15762 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 15763 S.Diag(Var->getLocation(), diag::note_declared_at); 15764 } 15765 return false; 15766 } 15767 15768 // Prohibit variably-modified types in blocks; they're difficult to deal with. 15769 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 15770 if (Diagnose) { 15771 S.Diag(Loc, diag::err_ref_vm_type); 15772 S.Diag(Var->getLocation(), diag::note_previous_decl) 15773 << Var->getDeclName(); 15774 } 15775 return false; 15776 } 15777 // Prohibit structs with flexible array members too. 15778 // We cannot capture what is in the tail end of the struct. 15779 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 15780 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 15781 if (Diagnose) { 15782 if (IsBlock) 15783 S.Diag(Loc, diag::err_ref_flexarray_type); 15784 else 15785 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 15786 << Var->getDeclName(); 15787 S.Diag(Var->getLocation(), diag::note_previous_decl) 15788 << Var->getDeclName(); 15789 } 15790 return false; 15791 } 15792 } 15793 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 15794 // Lambdas and captured statements are not allowed to capture __block 15795 // variables; they don't support the expected semantics. 15796 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 15797 if (Diagnose) { 15798 S.Diag(Loc, diag::err_capture_block_variable) 15799 << Var->getDeclName() << !IsLambda; 15800 S.Diag(Var->getLocation(), diag::note_previous_decl) 15801 << Var->getDeclName(); 15802 } 15803 return false; 15804 } 15805 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 15806 if (S.getLangOpts().OpenCL && IsBlock && 15807 Var->getType()->isBlockPointerType()) { 15808 if (Diagnose) 15809 S.Diag(Loc, diag::err_opencl_block_ref_block); 15810 return false; 15811 } 15812 15813 return true; 15814 } 15815 15816 // Returns true if the capture by block was successful. 15817 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 15818 SourceLocation Loc, 15819 const bool BuildAndDiagnose, 15820 QualType &CaptureType, 15821 QualType &DeclRefType, 15822 const bool Nested, 15823 Sema &S, bool Invalid) { 15824 bool ByRef = false; 15825 15826 // Blocks are not allowed to capture arrays, excepting OpenCL. 15827 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 15828 // (decayed to pointers). 15829 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 15830 if (BuildAndDiagnose) { 15831 S.Diag(Loc, diag::err_ref_array_type); 15832 S.Diag(Var->getLocation(), diag::note_previous_decl) 15833 << Var->getDeclName(); 15834 Invalid = true; 15835 } else { 15836 return false; 15837 } 15838 } 15839 15840 // Forbid the block-capture of autoreleasing variables. 15841 if (!Invalid && 15842 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 15843 if (BuildAndDiagnose) { 15844 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 15845 << /*block*/ 0; 15846 S.Diag(Var->getLocation(), diag::note_previous_decl) 15847 << Var->getDeclName(); 15848 Invalid = true; 15849 } else { 15850 return false; 15851 } 15852 } 15853 15854 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 15855 if (const auto *PT = CaptureType->getAs<PointerType>()) { 15856 QualType PointeeTy = PT->getPointeeType(); 15857 15858 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 15859 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 15860 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 15861 if (BuildAndDiagnose) { 15862 SourceLocation VarLoc = Var->getLocation(); 15863 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 15864 S.Diag(VarLoc, diag::note_declare_parameter_strong); 15865 } 15866 } 15867 } 15868 15869 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 15870 if (HasBlocksAttr || CaptureType->isReferenceType() || 15871 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 15872 // Block capture by reference does not change the capture or 15873 // declaration reference types. 15874 ByRef = true; 15875 } else { 15876 // Block capture by copy introduces 'const'. 15877 CaptureType = CaptureType.getNonReferenceType().withConst(); 15878 DeclRefType = CaptureType; 15879 } 15880 15881 // Actually capture the variable. 15882 if (BuildAndDiagnose) 15883 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 15884 CaptureType, Invalid); 15885 15886 return !Invalid; 15887 } 15888 15889 15890 /// Capture the given variable in the captured region. 15891 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 15892 VarDecl *Var, 15893 SourceLocation Loc, 15894 const bool BuildAndDiagnose, 15895 QualType &CaptureType, 15896 QualType &DeclRefType, 15897 const bool RefersToCapturedVariable, 15898 Sema &S, bool Invalid) { 15899 // By default, capture variables by reference. 15900 bool ByRef = true; 15901 // Using an LValue reference type is consistent with Lambdas (see below). 15902 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 15903 if (S.isOpenMPCapturedDecl(Var)) { 15904 bool HasConst = DeclRefType.isConstQualified(); 15905 DeclRefType = DeclRefType.getUnqualifiedType(); 15906 // Don't lose diagnostics about assignments to const. 15907 if (HasConst) 15908 DeclRefType.addConst(); 15909 } 15910 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 15911 RSI->OpenMPCaptureLevel); 15912 } 15913 15914 if (ByRef) 15915 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 15916 else 15917 CaptureType = DeclRefType; 15918 15919 // Actually capture the variable. 15920 if (BuildAndDiagnose) 15921 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 15922 Loc, SourceLocation(), CaptureType, Invalid); 15923 15924 return !Invalid; 15925 } 15926 15927 /// Capture the given variable in the lambda. 15928 static bool captureInLambda(LambdaScopeInfo *LSI, 15929 VarDecl *Var, 15930 SourceLocation Loc, 15931 const bool BuildAndDiagnose, 15932 QualType &CaptureType, 15933 QualType &DeclRefType, 15934 const bool RefersToCapturedVariable, 15935 const Sema::TryCaptureKind Kind, 15936 SourceLocation EllipsisLoc, 15937 const bool IsTopScope, 15938 Sema &S, bool Invalid) { 15939 // Determine whether we are capturing by reference or by value. 15940 bool ByRef = false; 15941 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 15942 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 15943 } else { 15944 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 15945 } 15946 15947 // Compute the type of the field that will capture this variable. 15948 if (ByRef) { 15949 // C++11 [expr.prim.lambda]p15: 15950 // An entity is captured by reference if it is implicitly or 15951 // explicitly captured but not captured by copy. It is 15952 // unspecified whether additional unnamed non-static data 15953 // members are declared in the closure type for entities 15954 // captured by reference. 15955 // 15956 // FIXME: It is not clear whether we want to build an lvalue reference 15957 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 15958 // to do the former, while EDG does the latter. Core issue 1249 will 15959 // clarify, but for now we follow GCC because it's a more permissive and 15960 // easily defensible position. 15961 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 15962 } else { 15963 // C++11 [expr.prim.lambda]p14: 15964 // For each entity captured by copy, an unnamed non-static 15965 // data member is declared in the closure type. The 15966 // declaration order of these members is unspecified. The type 15967 // of such a data member is the type of the corresponding 15968 // captured entity if the entity is not a reference to an 15969 // object, or the referenced type otherwise. [Note: If the 15970 // captured entity is a reference to a function, the 15971 // corresponding data member is also a reference to a 15972 // function. - end note ] 15973 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 15974 if (!RefType->getPointeeType()->isFunctionType()) 15975 CaptureType = RefType->getPointeeType(); 15976 } 15977 15978 // Forbid the lambda copy-capture of autoreleasing variables. 15979 if (!Invalid && 15980 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 15981 if (BuildAndDiagnose) { 15982 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 15983 S.Diag(Var->getLocation(), diag::note_previous_decl) 15984 << Var->getDeclName(); 15985 Invalid = true; 15986 } else { 15987 return false; 15988 } 15989 } 15990 15991 // Make sure that by-copy captures are of a complete and non-abstract type. 15992 if (!Invalid && BuildAndDiagnose) { 15993 if (!CaptureType->isDependentType() && 15994 S.RequireCompleteType(Loc, CaptureType, 15995 diag::err_capture_of_incomplete_type, 15996 Var->getDeclName())) 15997 Invalid = true; 15998 else if (S.RequireNonAbstractType(Loc, CaptureType, 15999 diag::err_capture_of_abstract_type)) 16000 Invalid = true; 16001 } 16002 } 16003 16004 // Compute the type of a reference to this captured variable. 16005 if (ByRef) 16006 DeclRefType = CaptureType.getNonReferenceType(); 16007 else { 16008 // C++ [expr.prim.lambda]p5: 16009 // The closure type for a lambda-expression has a public inline 16010 // function call operator [...]. This function call operator is 16011 // declared const (9.3.1) if and only if the lambda-expression's 16012 // parameter-declaration-clause is not followed by mutable. 16013 DeclRefType = CaptureType.getNonReferenceType(); 16014 if (!LSI->Mutable && !CaptureType->isReferenceType()) 16015 DeclRefType.addConst(); 16016 } 16017 16018 // Add the capture. 16019 if (BuildAndDiagnose) 16020 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 16021 Loc, EllipsisLoc, CaptureType, Invalid); 16022 16023 return !Invalid; 16024 } 16025 16026 bool Sema::tryCaptureVariable( 16027 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 16028 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 16029 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 16030 // An init-capture is notionally from the context surrounding its 16031 // declaration, but its parent DC is the lambda class. 16032 DeclContext *VarDC = Var->getDeclContext(); 16033 if (Var->isInitCapture()) 16034 VarDC = VarDC->getParent(); 16035 16036 DeclContext *DC = CurContext; 16037 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 16038 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 16039 // We need to sync up the Declaration Context with the 16040 // FunctionScopeIndexToStopAt 16041 if (FunctionScopeIndexToStopAt) { 16042 unsigned FSIndex = FunctionScopes.size() - 1; 16043 while (FSIndex != MaxFunctionScopesIndex) { 16044 DC = getLambdaAwareParentOfDeclContext(DC); 16045 --FSIndex; 16046 } 16047 } 16048 16049 16050 // If the variable is declared in the current context, there is no need to 16051 // capture it. 16052 if (VarDC == DC) return true; 16053 16054 // Capture global variables if it is required to use private copy of this 16055 // variable. 16056 bool IsGlobal = !Var->hasLocalStorage(); 16057 if (IsGlobal && 16058 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 16059 MaxFunctionScopesIndex))) 16060 return true; 16061 Var = Var->getCanonicalDecl(); 16062 16063 // Walk up the stack to determine whether we can capture the variable, 16064 // performing the "simple" checks that don't depend on type. We stop when 16065 // we've either hit the declared scope of the variable or find an existing 16066 // capture of that variable. We start from the innermost capturing-entity 16067 // (the DC) and ensure that all intervening capturing-entities 16068 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 16069 // declcontext can either capture the variable or have already captured 16070 // the variable. 16071 CaptureType = Var->getType(); 16072 DeclRefType = CaptureType.getNonReferenceType(); 16073 bool Nested = false; 16074 bool Explicit = (Kind != TryCapture_Implicit); 16075 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 16076 do { 16077 // Only block literals, captured statements, and lambda expressions can 16078 // capture; other scopes don't work. 16079 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 16080 ExprLoc, 16081 BuildAndDiagnose, 16082 *this); 16083 // We need to check for the parent *first* because, if we *have* 16084 // private-captured a global variable, we need to recursively capture it in 16085 // intermediate blocks, lambdas, etc. 16086 if (!ParentDC) { 16087 if (IsGlobal) { 16088 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 16089 break; 16090 } 16091 return true; 16092 } 16093 16094 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 16095 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 16096 16097 16098 // Check whether we've already captured it. 16099 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 16100 DeclRefType)) { 16101 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 16102 break; 16103 } 16104 // If we are instantiating a generic lambda call operator body, 16105 // we do not want to capture new variables. What was captured 16106 // during either a lambdas transformation or initial parsing 16107 // should be used. 16108 if (isGenericLambdaCallOperatorSpecialization(DC)) { 16109 if (BuildAndDiagnose) { 16110 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 16111 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 16112 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 16113 Diag(Var->getLocation(), diag::note_previous_decl) 16114 << Var->getDeclName(); 16115 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 16116 } else 16117 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 16118 } 16119 return true; 16120 } 16121 16122 // Try to capture variable-length arrays types. 16123 if (Var->getType()->isVariablyModifiedType()) { 16124 // We're going to walk down into the type and look for VLA 16125 // expressions. 16126 QualType QTy = Var->getType(); 16127 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 16128 QTy = PVD->getOriginalType(); 16129 captureVariablyModifiedType(Context, QTy, CSI); 16130 } 16131 16132 if (getLangOpts().OpenMP) { 16133 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 16134 // OpenMP private variables should not be captured in outer scope, so 16135 // just break here. Similarly, global variables that are captured in a 16136 // target region should not be captured outside the scope of the region. 16137 if (RSI->CapRegionKind == CR_OpenMP) { 16138 bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel); 16139 // If the variable is private (i.e. not captured) and has variably 16140 // modified type, we still need to capture the type for correct 16141 // codegen in all regions, associated with the construct. Currently, 16142 // it is captured in the innermost captured region only. 16143 if (IsOpenMPPrivateDecl && Var->getType()->isVariablyModifiedType()) { 16144 QualType QTy = Var->getType(); 16145 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 16146 QTy = PVD->getOriginalType(); 16147 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 16148 I < E; ++I) { 16149 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 16150 FunctionScopes[FunctionScopesIndex - I]); 16151 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 16152 "Wrong number of captured regions associated with the " 16153 "OpenMP construct."); 16154 captureVariablyModifiedType(Context, QTy, OuterRSI); 16155 } 16156 } 16157 bool IsTargetCap = !IsOpenMPPrivateDecl && 16158 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 16159 // When we detect target captures we are looking from inside the 16160 // target region, therefore we need to propagate the capture from the 16161 // enclosing region. Therefore, the capture is not initially nested. 16162 if (IsTargetCap) 16163 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 16164 16165 if (IsTargetCap || IsOpenMPPrivateDecl) { 16166 Nested = !IsTargetCap; 16167 DeclRefType = DeclRefType.getUnqualifiedType(); 16168 CaptureType = Context.getLValueReferenceType(DeclRefType); 16169 break; 16170 } 16171 } 16172 } 16173 } 16174 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 16175 // No capture-default, and this is not an explicit capture 16176 // so cannot capture this variable. 16177 if (BuildAndDiagnose) { 16178 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 16179 Diag(Var->getLocation(), diag::note_previous_decl) 16180 << Var->getDeclName(); 16181 if (cast<LambdaScopeInfo>(CSI)->Lambda) 16182 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(), 16183 diag::note_lambda_decl); 16184 // FIXME: If we error out because an outer lambda can not implicitly 16185 // capture a variable that an inner lambda explicitly captures, we 16186 // should have the inner lambda do the explicit capture - because 16187 // it makes for cleaner diagnostics later. This would purely be done 16188 // so that the diagnostic does not misleadingly claim that a variable 16189 // can not be captured by a lambda implicitly even though it is captured 16190 // explicitly. Suggestion: 16191 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 16192 // at the function head 16193 // - cache the StartingDeclContext - this must be a lambda 16194 // - captureInLambda in the innermost lambda the variable. 16195 } 16196 return true; 16197 } 16198 16199 FunctionScopesIndex--; 16200 DC = ParentDC; 16201 Explicit = false; 16202 } while (!VarDC->Equals(DC)); 16203 16204 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 16205 // computing the type of the capture at each step, checking type-specific 16206 // requirements, and adding captures if requested. 16207 // If the variable had already been captured previously, we start capturing 16208 // at the lambda nested within that one. 16209 bool Invalid = false; 16210 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 16211 ++I) { 16212 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 16213 16214 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 16215 // certain types of variables (unnamed, variably modified types etc.) 16216 // so check for eligibility. 16217 if (!Invalid) 16218 Invalid = 16219 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 16220 16221 // After encountering an error, if we're actually supposed to capture, keep 16222 // capturing in nested contexts to suppress any follow-on diagnostics. 16223 if (Invalid && !BuildAndDiagnose) 16224 return true; 16225 16226 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 16227 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 16228 DeclRefType, Nested, *this, Invalid); 16229 Nested = true; 16230 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 16231 Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose, 16232 CaptureType, DeclRefType, Nested, 16233 *this, Invalid); 16234 Nested = true; 16235 } else { 16236 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 16237 Invalid = 16238 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 16239 DeclRefType, Nested, Kind, EllipsisLoc, 16240 /*IsTopScope*/ I == N - 1, *this, Invalid); 16241 Nested = true; 16242 } 16243 16244 if (Invalid && !BuildAndDiagnose) 16245 return true; 16246 } 16247 return Invalid; 16248 } 16249 16250 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 16251 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 16252 QualType CaptureType; 16253 QualType DeclRefType; 16254 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 16255 /*BuildAndDiagnose=*/true, CaptureType, 16256 DeclRefType, nullptr); 16257 } 16258 16259 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 16260 QualType CaptureType; 16261 QualType DeclRefType; 16262 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 16263 /*BuildAndDiagnose=*/false, CaptureType, 16264 DeclRefType, nullptr); 16265 } 16266 16267 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 16268 QualType CaptureType; 16269 QualType DeclRefType; 16270 16271 // Determine whether we can capture this variable. 16272 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 16273 /*BuildAndDiagnose=*/false, CaptureType, 16274 DeclRefType, nullptr)) 16275 return QualType(); 16276 16277 return DeclRefType; 16278 } 16279 16280 namespace { 16281 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 16282 // The produced TemplateArgumentListInfo* points to data stored within this 16283 // object, so should only be used in contexts where the pointer will not be 16284 // used after the CopiedTemplateArgs object is destroyed. 16285 class CopiedTemplateArgs { 16286 bool HasArgs; 16287 TemplateArgumentListInfo TemplateArgStorage; 16288 public: 16289 template<typename RefExpr> 16290 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 16291 if (HasArgs) 16292 E->copyTemplateArgumentsInto(TemplateArgStorage); 16293 } 16294 operator TemplateArgumentListInfo*() 16295 #ifdef __has_cpp_attribute 16296 #if __has_cpp_attribute(clang::lifetimebound) 16297 [[clang::lifetimebound]] 16298 #endif 16299 #endif 16300 { 16301 return HasArgs ? &TemplateArgStorage : nullptr; 16302 } 16303 }; 16304 } 16305 16306 /// Walk the set of potential results of an expression and mark them all as 16307 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 16308 /// 16309 /// \return A new expression if we found any potential results, ExprEmpty() if 16310 /// not, and ExprError() if we diagnosed an error. 16311 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 16312 NonOdrUseReason NOUR) { 16313 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 16314 // an object that satisfies the requirements for appearing in a 16315 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 16316 // is immediately applied." This function handles the lvalue-to-rvalue 16317 // conversion part. 16318 // 16319 // If we encounter a node that claims to be an odr-use but shouldn't be, we 16320 // transform it into the relevant kind of non-odr-use node and rebuild the 16321 // tree of nodes leading to it. 16322 // 16323 // This is a mini-TreeTransform that only transforms a restricted subset of 16324 // nodes (and only certain operands of them). 16325 16326 // Rebuild a subexpression. 16327 auto Rebuild = [&](Expr *Sub) { 16328 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 16329 }; 16330 16331 // Check whether a potential result satisfies the requirements of NOUR. 16332 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 16333 // Any entity other than a VarDecl is always odr-used whenever it's named 16334 // in a potentially-evaluated expression. 16335 auto *VD = dyn_cast<VarDecl>(D); 16336 if (!VD) 16337 return true; 16338 16339 // C++2a [basic.def.odr]p4: 16340 // A variable x whose name appears as a potentially-evalauted expression 16341 // e is odr-used by e unless 16342 // -- x is a reference that is usable in constant expressions, or 16343 // -- x is a variable of non-reference type that is usable in constant 16344 // expressions and has no mutable subobjects, and e is an element of 16345 // the set of potential results of an expression of 16346 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 16347 // conversion is applied, or 16348 // -- x is a variable of non-reference type, and e is an element of the 16349 // set of potential results of a discarded-value expression to which 16350 // the lvalue-to-rvalue conversion is not applied 16351 // 16352 // We check the first bullet and the "potentially-evaluated" condition in 16353 // BuildDeclRefExpr. We check the type requirements in the second bullet 16354 // in CheckLValueToRValueConversionOperand below. 16355 switch (NOUR) { 16356 case NOUR_None: 16357 case NOUR_Unevaluated: 16358 llvm_unreachable("unexpected non-odr-use-reason"); 16359 16360 case NOUR_Constant: 16361 // Constant references were handled when they were built. 16362 if (VD->getType()->isReferenceType()) 16363 return true; 16364 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 16365 if (RD->hasMutableFields()) 16366 return true; 16367 if (!VD->isUsableInConstantExpressions(S.Context)) 16368 return true; 16369 break; 16370 16371 case NOUR_Discarded: 16372 if (VD->getType()->isReferenceType()) 16373 return true; 16374 break; 16375 } 16376 return false; 16377 }; 16378 16379 // Mark that this expression does not constitute an odr-use. 16380 auto MarkNotOdrUsed = [&] { 16381 S.MaybeODRUseExprs.erase(E); 16382 if (LambdaScopeInfo *LSI = S.getCurLambda()) 16383 LSI->markVariableExprAsNonODRUsed(E); 16384 }; 16385 16386 // C++2a [basic.def.odr]p2: 16387 // The set of potential results of an expression e is defined as follows: 16388 switch (E->getStmtClass()) { 16389 // -- If e is an id-expression, ... 16390 case Expr::DeclRefExprClass: { 16391 auto *DRE = cast<DeclRefExpr>(E); 16392 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 16393 break; 16394 16395 // Rebuild as a non-odr-use DeclRefExpr. 16396 MarkNotOdrUsed(); 16397 return DeclRefExpr::Create( 16398 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 16399 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 16400 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 16401 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 16402 } 16403 16404 case Expr::FunctionParmPackExprClass: { 16405 auto *FPPE = cast<FunctionParmPackExpr>(E); 16406 // If any of the declarations in the pack is odr-used, then the expression 16407 // as a whole constitutes an odr-use. 16408 for (VarDecl *D : *FPPE) 16409 if (IsPotentialResultOdrUsed(D)) 16410 return ExprEmpty(); 16411 16412 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 16413 // nothing cares about whether we marked this as an odr-use, but it might 16414 // be useful for non-compiler tools. 16415 MarkNotOdrUsed(); 16416 break; 16417 } 16418 16419 // -- If e is a subscripting operation with an array operand... 16420 case Expr::ArraySubscriptExprClass: { 16421 auto *ASE = cast<ArraySubscriptExpr>(E); 16422 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 16423 if (!OldBase->getType()->isArrayType()) 16424 break; 16425 ExprResult Base = Rebuild(OldBase); 16426 if (!Base.isUsable()) 16427 return Base; 16428 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 16429 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 16430 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 16431 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 16432 ASE->getRBracketLoc()); 16433 } 16434 16435 case Expr::MemberExprClass: { 16436 auto *ME = cast<MemberExpr>(E); 16437 // -- If e is a class member access expression [...] naming a non-static 16438 // data member... 16439 if (isa<FieldDecl>(ME->getMemberDecl())) { 16440 ExprResult Base = Rebuild(ME->getBase()); 16441 if (!Base.isUsable()) 16442 return Base; 16443 return MemberExpr::Create( 16444 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 16445 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 16446 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 16447 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 16448 ME->getObjectKind(), ME->isNonOdrUse()); 16449 } 16450 16451 if (ME->getMemberDecl()->isCXXInstanceMember()) 16452 break; 16453 16454 // -- If e is a class member access expression naming a static data member, 16455 // ... 16456 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 16457 break; 16458 16459 // Rebuild as a non-odr-use MemberExpr. 16460 MarkNotOdrUsed(); 16461 return MemberExpr::Create( 16462 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 16463 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 16464 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 16465 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 16466 return ExprEmpty(); 16467 } 16468 16469 case Expr::BinaryOperatorClass: { 16470 auto *BO = cast<BinaryOperator>(E); 16471 Expr *LHS = BO->getLHS(); 16472 Expr *RHS = BO->getRHS(); 16473 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 16474 if (BO->getOpcode() == BO_PtrMemD) { 16475 ExprResult Sub = Rebuild(LHS); 16476 if (!Sub.isUsable()) 16477 return Sub; 16478 LHS = Sub.get(); 16479 // -- If e is a comma expression, ... 16480 } else if (BO->getOpcode() == BO_Comma) { 16481 ExprResult Sub = Rebuild(RHS); 16482 if (!Sub.isUsable()) 16483 return Sub; 16484 RHS = Sub.get(); 16485 } else { 16486 break; 16487 } 16488 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 16489 LHS, RHS); 16490 } 16491 16492 // -- If e has the form (e1)... 16493 case Expr::ParenExprClass: { 16494 auto *PE = cast<ParenExpr>(E); 16495 ExprResult Sub = Rebuild(PE->getSubExpr()); 16496 if (!Sub.isUsable()) 16497 return Sub; 16498 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 16499 } 16500 16501 // -- If e is a glvalue conditional expression, ... 16502 // We don't apply this to a binary conditional operator. FIXME: Should we? 16503 case Expr::ConditionalOperatorClass: { 16504 auto *CO = cast<ConditionalOperator>(E); 16505 ExprResult LHS = Rebuild(CO->getLHS()); 16506 if (LHS.isInvalid()) 16507 return ExprError(); 16508 ExprResult RHS = Rebuild(CO->getRHS()); 16509 if (RHS.isInvalid()) 16510 return ExprError(); 16511 if (!LHS.isUsable() && !RHS.isUsable()) 16512 return ExprEmpty(); 16513 if (!LHS.isUsable()) 16514 LHS = CO->getLHS(); 16515 if (!RHS.isUsable()) 16516 RHS = CO->getRHS(); 16517 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 16518 CO->getCond(), LHS.get(), RHS.get()); 16519 } 16520 16521 // [Clang extension] 16522 // -- If e has the form __extension__ e1... 16523 case Expr::UnaryOperatorClass: { 16524 auto *UO = cast<UnaryOperator>(E); 16525 if (UO->getOpcode() != UO_Extension) 16526 break; 16527 ExprResult Sub = Rebuild(UO->getSubExpr()); 16528 if (!Sub.isUsable()) 16529 return Sub; 16530 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 16531 Sub.get()); 16532 } 16533 16534 // [Clang extension] 16535 // -- If e has the form _Generic(...), the set of potential results is the 16536 // union of the sets of potential results of the associated expressions. 16537 case Expr::GenericSelectionExprClass: { 16538 auto *GSE = cast<GenericSelectionExpr>(E); 16539 16540 SmallVector<Expr *, 4> AssocExprs; 16541 bool AnyChanged = false; 16542 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 16543 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 16544 if (AssocExpr.isInvalid()) 16545 return ExprError(); 16546 if (AssocExpr.isUsable()) { 16547 AssocExprs.push_back(AssocExpr.get()); 16548 AnyChanged = true; 16549 } else { 16550 AssocExprs.push_back(OrigAssocExpr); 16551 } 16552 } 16553 16554 return AnyChanged ? S.CreateGenericSelectionExpr( 16555 GSE->getGenericLoc(), GSE->getDefaultLoc(), 16556 GSE->getRParenLoc(), GSE->getControllingExpr(), 16557 GSE->getAssocTypeSourceInfos(), AssocExprs) 16558 : ExprEmpty(); 16559 } 16560 16561 // [Clang extension] 16562 // -- If e has the form __builtin_choose_expr(...), the set of potential 16563 // results is the union of the sets of potential results of the 16564 // second and third subexpressions. 16565 case Expr::ChooseExprClass: { 16566 auto *CE = cast<ChooseExpr>(E); 16567 16568 ExprResult LHS = Rebuild(CE->getLHS()); 16569 if (LHS.isInvalid()) 16570 return ExprError(); 16571 16572 ExprResult RHS = Rebuild(CE->getLHS()); 16573 if (RHS.isInvalid()) 16574 return ExprError(); 16575 16576 if (!LHS.get() && !RHS.get()) 16577 return ExprEmpty(); 16578 if (!LHS.isUsable()) 16579 LHS = CE->getLHS(); 16580 if (!RHS.isUsable()) 16581 RHS = CE->getRHS(); 16582 16583 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 16584 RHS.get(), CE->getRParenLoc()); 16585 } 16586 16587 // Step through non-syntactic nodes. 16588 case Expr::ConstantExprClass: { 16589 auto *CE = cast<ConstantExpr>(E); 16590 ExprResult Sub = Rebuild(CE->getSubExpr()); 16591 if (!Sub.isUsable()) 16592 return Sub; 16593 return ConstantExpr::Create(S.Context, Sub.get()); 16594 } 16595 16596 // We could mostly rely on the recursive rebuilding to rebuild implicit 16597 // casts, but not at the top level, so rebuild them here. 16598 case Expr::ImplicitCastExprClass: { 16599 auto *ICE = cast<ImplicitCastExpr>(E); 16600 // Only step through the narrow set of cast kinds we expect to encounter. 16601 // Anything else suggests we've left the region in which potential results 16602 // can be found. 16603 switch (ICE->getCastKind()) { 16604 case CK_NoOp: 16605 case CK_DerivedToBase: 16606 case CK_UncheckedDerivedToBase: { 16607 ExprResult Sub = Rebuild(ICE->getSubExpr()); 16608 if (!Sub.isUsable()) 16609 return Sub; 16610 CXXCastPath Path(ICE->path()); 16611 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 16612 ICE->getValueKind(), &Path); 16613 } 16614 16615 default: 16616 break; 16617 } 16618 break; 16619 } 16620 16621 default: 16622 break; 16623 } 16624 16625 // Can't traverse through this node. Nothing to do. 16626 return ExprEmpty(); 16627 } 16628 16629 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 16630 // Check whether the operand is or contains an object of non-trivial C union 16631 // type. 16632 if (E->getType().isVolatileQualified() && 16633 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 16634 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 16635 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 16636 Sema::NTCUC_LValueToRValueVolatile, 16637 NTCUK_Destruct|NTCUK_Copy); 16638 16639 // C++2a [basic.def.odr]p4: 16640 // [...] an expression of non-volatile-qualified non-class type to which 16641 // the lvalue-to-rvalue conversion is applied [...] 16642 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 16643 return E; 16644 16645 ExprResult Result = 16646 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 16647 if (Result.isInvalid()) 16648 return ExprError(); 16649 return Result.get() ? Result : E; 16650 } 16651 16652 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 16653 Res = CorrectDelayedTyposInExpr(Res); 16654 16655 if (!Res.isUsable()) 16656 return Res; 16657 16658 // If a constant-expression is a reference to a variable where we delay 16659 // deciding whether it is an odr-use, just assume we will apply the 16660 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 16661 // (a non-type template argument), we have special handling anyway. 16662 return CheckLValueToRValueConversionOperand(Res.get()); 16663 } 16664 16665 void Sema::CleanupVarDeclMarking() { 16666 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 16667 // call. 16668 MaybeODRUseExprSet LocalMaybeODRUseExprs; 16669 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 16670 16671 for (Expr *E : LocalMaybeODRUseExprs) { 16672 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 16673 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 16674 DRE->getLocation(), *this); 16675 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 16676 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 16677 *this); 16678 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 16679 for (VarDecl *VD : *FP) 16680 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 16681 } else { 16682 llvm_unreachable("Unexpected expression"); 16683 } 16684 } 16685 16686 assert(MaybeODRUseExprs.empty() && 16687 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 16688 } 16689 16690 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 16691 VarDecl *Var, Expr *E) { 16692 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 16693 isa<FunctionParmPackExpr>(E)) && 16694 "Invalid Expr argument to DoMarkVarDeclReferenced"); 16695 Var->setReferenced(); 16696 16697 if (Var->isInvalidDecl()) 16698 return; 16699 16700 auto *MSI = Var->getMemberSpecializationInfo(); 16701 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 16702 : Var->getTemplateSpecializationKind(); 16703 16704 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 16705 bool UsableInConstantExpr = 16706 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 16707 16708 // C++20 [expr.const]p12: 16709 // A variable [...] is needed for constant evaluation if it is [...] a 16710 // variable whose name appears as a potentially constant evaluated 16711 // expression that is either a contexpr variable or is of non-volatile 16712 // const-qualified integral type or of reference type 16713 bool NeededForConstantEvaluation = 16714 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 16715 16716 bool NeedDefinition = 16717 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 16718 16719 VarTemplateSpecializationDecl *VarSpec = 16720 dyn_cast<VarTemplateSpecializationDecl>(Var); 16721 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 16722 "Can't instantiate a partial template specialization."); 16723 16724 // If this might be a member specialization of a static data member, check 16725 // the specialization is visible. We already did the checks for variable 16726 // template specializations when we created them. 16727 if (NeedDefinition && TSK != TSK_Undeclared && 16728 !isa<VarTemplateSpecializationDecl>(Var)) 16729 SemaRef.checkSpecializationVisibility(Loc, Var); 16730 16731 // Perform implicit instantiation of static data members, static data member 16732 // templates of class templates, and variable template specializations. Delay 16733 // instantiations of variable templates, except for those that could be used 16734 // in a constant expression. 16735 if (NeedDefinition && isTemplateInstantiation(TSK)) { 16736 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 16737 // instantiation declaration if a variable is usable in a constant 16738 // expression (among other cases). 16739 bool TryInstantiating = 16740 TSK == TSK_ImplicitInstantiation || 16741 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 16742 16743 if (TryInstantiating) { 16744 SourceLocation PointOfInstantiation = 16745 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 16746 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 16747 if (FirstInstantiation) { 16748 PointOfInstantiation = Loc; 16749 if (MSI) 16750 MSI->setPointOfInstantiation(PointOfInstantiation); 16751 else 16752 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 16753 } 16754 16755 bool InstantiationDependent = false; 16756 bool IsNonDependent = 16757 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 16758 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 16759 : true; 16760 16761 // Do not instantiate specializations that are still type-dependent. 16762 if (IsNonDependent) { 16763 if (UsableInConstantExpr) { 16764 // Do not defer instantiations of variables that could be used in a 16765 // constant expression. 16766 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 16767 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 16768 }); 16769 } else if (FirstInstantiation || 16770 isa<VarTemplateSpecializationDecl>(Var)) { 16771 // FIXME: For a specialization of a variable template, we don't 16772 // distinguish between "declaration and type implicitly instantiated" 16773 // and "implicit instantiation of definition requested", so we have 16774 // no direct way to avoid enqueueing the pending instantiation 16775 // multiple times. 16776 SemaRef.PendingInstantiations 16777 .push_back(std::make_pair(Var, PointOfInstantiation)); 16778 } 16779 } 16780 } 16781 } 16782 16783 // C++2a [basic.def.odr]p4: 16784 // A variable x whose name appears as a potentially-evaluated expression e 16785 // is odr-used by e unless 16786 // -- x is a reference that is usable in constant expressions 16787 // -- x is a variable of non-reference type that is usable in constant 16788 // expressions and has no mutable subobjects [FIXME], and e is an 16789 // element of the set of potential results of an expression of 16790 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 16791 // conversion is applied 16792 // -- x is a variable of non-reference type, and e is an element of the set 16793 // of potential results of a discarded-value expression to which the 16794 // lvalue-to-rvalue conversion is not applied [FIXME] 16795 // 16796 // We check the first part of the second bullet here, and 16797 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 16798 // FIXME: To get the third bullet right, we need to delay this even for 16799 // variables that are not usable in constant expressions. 16800 16801 // If we already know this isn't an odr-use, there's nothing more to do. 16802 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 16803 if (DRE->isNonOdrUse()) 16804 return; 16805 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 16806 if (ME->isNonOdrUse()) 16807 return; 16808 16809 switch (OdrUse) { 16810 case OdrUseContext::None: 16811 assert((!E || isa<FunctionParmPackExpr>(E)) && 16812 "missing non-odr-use marking for unevaluated decl ref"); 16813 break; 16814 16815 case OdrUseContext::FormallyOdrUsed: 16816 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 16817 // behavior. 16818 break; 16819 16820 case OdrUseContext::Used: 16821 // If we might later find that this expression isn't actually an odr-use, 16822 // delay the marking. 16823 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 16824 SemaRef.MaybeODRUseExprs.insert(E); 16825 else 16826 MarkVarDeclODRUsed(Var, Loc, SemaRef); 16827 break; 16828 16829 case OdrUseContext::Dependent: 16830 // If this is a dependent context, we don't need to mark variables as 16831 // odr-used, but we may still need to track them for lambda capture. 16832 // FIXME: Do we also need to do this inside dependent typeid expressions 16833 // (which are modeled as unevaluated at this point)? 16834 const bool RefersToEnclosingScope = 16835 (SemaRef.CurContext != Var->getDeclContext() && 16836 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 16837 if (RefersToEnclosingScope) { 16838 LambdaScopeInfo *const LSI = 16839 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 16840 if (LSI && (!LSI->CallOperator || 16841 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 16842 // If a variable could potentially be odr-used, defer marking it so 16843 // until we finish analyzing the full expression for any 16844 // lvalue-to-rvalue 16845 // or discarded value conversions that would obviate odr-use. 16846 // Add it to the list of potential captures that will be analyzed 16847 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 16848 // unless the variable is a reference that was initialized by a constant 16849 // expression (this will never need to be captured or odr-used). 16850 // 16851 // FIXME: We can simplify this a lot after implementing P0588R1. 16852 assert(E && "Capture variable should be used in an expression."); 16853 if (!Var->getType()->isReferenceType() || 16854 !Var->isUsableInConstantExpressions(SemaRef.Context)) 16855 LSI->addPotentialCapture(E->IgnoreParens()); 16856 } 16857 } 16858 break; 16859 } 16860 } 16861 16862 /// Mark a variable referenced, and check whether it is odr-used 16863 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 16864 /// used directly for normal expressions referring to VarDecl. 16865 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 16866 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 16867 } 16868 16869 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 16870 Decl *D, Expr *E, bool MightBeOdrUse) { 16871 if (SemaRef.isInOpenMPDeclareTargetContext()) 16872 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 16873 16874 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 16875 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 16876 return; 16877 } 16878 16879 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 16880 16881 // If this is a call to a method via a cast, also mark the method in the 16882 // derived class used in case codegen can devirtualize the call. 16883 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 16884 if (!ME) 16885 return; 16886 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 16887 if (!MD) 16888 return; 16889 // Only attempt to devirtualize if this is truly a virtual call. 16890 bool IsVirtualCall = MD->isVirtual() && 16891 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 16892 if (!IsVirtualCall) 16893 return; 16894 16895 // If it's possible to devirtualize the call, mark the called function 16896 // referenced. 16897 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 16898 ME->getBase(), SemaRef.getLangOpts().AppleKext); 16899 if (DM) 16900 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 16901 } 16902 16903 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 16904 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 16905 // TODO: update this with DR# once a defect report is filed. 16906 // C++11 defect. The address of a pure member should not be an ODR use, even 16907 // if it's a qualified reference. 16908 bool OdrUse = true; 16909 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 16910 if (Method->isVirtual() && 16911 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 16912 OdrUse = false; 16913 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 16914 } 16915 16916 /// Perform reference-marking and odr-use handling for a MemberExpr. 16917 void Sema::MarkMemberReferenced(MemberExpr *E) { 16918 // C++11 [basic.def.odr]p2: 16919 // A non-overloaded function whose name appears as a potentially-evaluated 16920 // expression or a member of a set of candidate functions, if selected by 16921 // overload resolution when referred to from a potentially-evaluated 16922 // expression, is odr-used, unless it is a pure virtual function and its 16923 // name is not explicitly qualified. 16924 bool MightBeOdrUse = true; 16925 if (E->performsVirtualDispatch(getLangOpts())) { 16926 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 16927 if (Method->isPure()) 16928 MightBeOdrUse = false; 16929 } 16930 SourceLocation Loc = 16931 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 16932 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 16933 } 16934 16935 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 16936 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 16937 for (VarDecl *VD : *E) 16938 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true); 16939 } 16940 16941 /// Perform marking for a reference to an arbitrary declaration. It 16942 /// marks the declaration referenced, and performs odr-use checking for 16943 /// functions and variables. This method should not be used when building a 16944 /// normal expression which refers to a variable. 16945 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 16946 bool MightBeOdrUse) { 16947 if (MightBeOdrUse) { 16948 if (auto *VD = dyn_cast<VarDecl>(D)) { 16949 MarkVariableReferenced(Loc, VD); 16950 return; 16951 } 16952 } 16953 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 16954 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 16955 return; 16956 } 16957 D->setReferenced(); 16958 } 16959 16960 namespace { 16961 // Mark all of the declarations used by a type as referenced. 16962 // FIXME: Not fully implemented yet! We need to have a better understanding 16963 // of when we're entering a context we should not recurse into. 16964 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 16965 // TreeTransforms rebuilding the type in a new context. Rather than 16966 // duplicating the TreeTransform logic, we should consider reusing it here. 16967 // Currently that causes problems when rebuilding LambdaExprs. 16968 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 16969 Sema &S; 16970 SourceLocation Loc; 16971 16972 public: 16973 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 16974 16975 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 16976 16977 bool TraverseTemplateArgument(const TemplateArgument &Arg); 16978 }; 16979 } 16980 16981 bool MarkReferencedDecls::TraverseTemplateArgument( 16982 const TemplateArgument &Arg) { 16983 { 16984 // A non-type template argument is a constant-evaluated context. 16985 EnterExpressionEvaluationContext Evaluated( 16986 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 16987 if (Arg.getKind() == TemplateArgument::Declaration) { 16988 if (Decl *D = Arg.getAsDecl()) 16989 S.MarkAnyDeclReferenced(Loc, D, true); 16990 } else if (Arg.getKind() == TemplateArgument::Expression) { 16991 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 16992 } 16993 } 16994 16995 return Inherited::TraverseTemplateArgument(Arg); 16996 } 16997 16998 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 16999 MarkReferencedDecls Marker(*this, Loc); 17000 Marker.TraverseType(T); 17001 } 17002 17003 namespace { 17004 /// Helper class that marks all of the declarations referenced by 17005 /// potentially-evaluated subexpressions as "referenced". 17006 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 17007 Sema &S; 17008 bool SkipLocalVariables; 17009 17010 public: 17011 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 17012 17013 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 17014 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 17015 17016 void VisitDeclRefExpr(DeclRefExpr *E) { 17017 // If we were asked not to visit local variables, don't. 17018 if (SkipLocalVariables) { 17019 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 17020 if (VD->hasLocalStorage()) 17021 return; 17022 } 17023 17024 S.MarkDeclRefReferenced(E); 17025 } 17026 17027 void VisitMemberExpr(MemberExpr *E) { 17028 S.MarkMemberReferenced(E); 17029 Inherited::VisitMemberExpr(E); 17030 } 17031 17032 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 17033 S.MarkFunctionReferenced( 17034 E->getBeginLoc(), 17035 const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor())); 17036 Visit(E->getSubExpr()); 17037 } 17038 17039 void VisitCXXNewExpr(CXXNewExpr *E) { 17040 if (E->getOperatorNew()) 17041 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew()); 17042 if (E->getOperatorDelete()) 17043 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete()); 17044 Inherited::VisitCXXNewExpr(E); 17045 } 17046 17047 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 17048 if (E->getOperatorDelete()) 17049 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete()); 17050 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 17051 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 17052 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 17053 S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record)); 17054 } 17055 17056 Inherited::VisitCXXDeleteExpr(E); 17057 } 17058 17059 void VisitCXXConstructExpr(CXXConstructExpr *E) { 17060 S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor()); 17061 Inherited::VisitCXXConstructExpr(E); 17062 } 17063 17064 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 17065 Visit(E->getExpr()); 17066 } 17067 }; 17068 } 17069 17070 /// Mark any declarations that appear within this expression or any 17071 /// potentially-evaluated subexpressions as "referenced". 17072 /// 17073 /// \param SkipLocalVariables If true, don't mark local variables as 17074 /// 'referenced'. 17075 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 17076 bool SkipLocalVariables) { 17077 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 17078 } 17079 17080 /// Emit a diagnostic that describes an effect on the run-time behavior 17081 /// of the program being compiled. 17082 /// 17083 /// This routine emits the given diagnostic when the code currently being 17084 /// type-checked is "potentially evaluated", meaning that there is a 17085 /// possibility that the code will actually be executable. Code in sizeof() 17086 /// expressions, code used only during overload resolution, etc., are not 17087 /// potentially evaluated. This routine will suppress such diagnostics or, 17088 /// in the absolutely nutty case of potentially potentially evaluated 17089 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 17090 /// later. 17091 /// 17092 /// This routine should be used for all diagnostics that describe the run-time 17093 /// behavior of a program, such as passing a non-POD value through an ellipsis. 17094 /// Failure to do so will likely result in spurious diagnostics or failures 17095 /// during overload resolution or within sizeof/alignof/typeof/typeid. 17096 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 17097 const PartialDiagnostic &PD) { 17098 switch (ExprEvalContexts.back().Context) { 17099 case ExpressionEvaluationContext::Unevaluated: 17100 case ExpressionEvaluationContext::UnevaluatedList: 17101 case ExpressionEvaluationContext::UnevaluatedAbstract: 17102 case ExpressionEvaluationContext::DiscardedStatement: 17103 // The argument will never be evaluated, so don't complain. 17104 break; 17105 17106 case ExpressionEvaluationContext::ConstantEvaluated: 17107 // Relevant diagnostics should be produced by constant evaluation. 17108 break; 17109 17110 case ExpressionEvaluationContext::PotentiallyEvaluated: 17111 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 17112 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 17113 FunctionScopes.back()->PossiblyUnreachableDiags. 17114 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 17115 return true; 17116 } 17117 17118 // The initializer of a constexpr variable or of the first declaration of a 17119 // static data member is not syntactically a constant evaluated constant, 17120 // but nonetheless is always required to be a constant expression, so we 17121 // can skip diagnosing. 17122 // FIXME: Using the mangling context here is a hack. 17123 if (auto *VD = dyn_cast_or_null<VarDecl>( 17124 ExprEvalContexts.back().ManglingContextDecl)) { 17125 if (VD->isConstexpr() || 17126 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 17127 break; 17128 // FIXME: For any other kind of variable, we should build a CFG for its 17129 // initializer and check whether the context in question is reachable. 17130 } 17131 17132 Diag(Loc, PD); 17133 return true; 17134 } 17135 17136 return false; 17137 } 17138 17139 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 17140 const PartialDiagnostic &PD) { 17141 return DiagRuntimeBehavior( 17142 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 17143 } 17144 17145 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 17146 CallExpr *CE, FunctionDecl *FD) { 17147 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 17148 return false; 17149 17150 // If we're inside a decltype's expression, don't check for a valid return 17151 // type or construct temporaries until we know whether this is the last call. 17152 if (ExprEvalContexts.back().ExprContext == 17153 ExpressionEvaluationContextRecord::EK_Decltype) { 17154 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 17155 return false; 17156 } 17157 17158 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 17159 FunctionDecl *FD; 17160 CallExpr *CE; 17161 17162 public: 17163 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 17164 : FD(FD), CE(CE) { } 17165 17166 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 17167 if (!FD) { 17168 S.Diag(Loc, diag::err_call_incomplete_return) 17169 << T << CE->getSourceRange(); 17170 return; 17171 } 17172 17173 S.Diag(Loc, diag::err_call_function_incomplete_return) 17174 << CE->getSourceRange() << FD->getDeclName() << T; 17175 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 17176 << FD->getDeclName(); 17177 } 17178 } Diagnoser(FD, CE); 17179 17180 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 17181 return true; 17182 17183 return false; 17184 } 17185 17186 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 17187 // will prevent this condition from triggering, which is what we want. 17188 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 17189 SourceLocation Loc; 17190 17191 unsigned diagnostic = diag::warn_condition_is_assignment; 17192 bool IsOrAssign = false; 17193 17194 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 17195 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 17196 return; 17197 17198 IsOrAssign = Op->getOpcode() == BO_OrAssign; 17199 17200 // Greylist some idioms by putting them into a warning subcategory. 17201 if (ObjCMessageExpr *ME 17202 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 17203 Selector Sel = ME->getSelector(); 17204 17205 // self = [<foo> init...] 17206 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 17207 diagnostic = diag::warn_condition_is_idiomatic_assignment; 17208 17209 // <foo> = [<bar> nextObject] 17210 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 17211 diagnostic = diag::warn_condition_is_idiomatic_assignment; 17212 } 17213 17214 Loc = Op->getOperatorLoc(); 17215 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 17216 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 17217 return; 17218 17219 IsOrAssign = Op->getOperator() == OO_PipeEqual; 17220 Loc = Op->getOperatorLoc(); 17221 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 17222 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 17223 else { 17224 // Not an assignment. 17225 return; 17226 } 17227 17228 Diag(Loc, diagnostic) << E->getSourceRange(); 17229 17230 SourceLocation Open = E->getBeginLoc(); 17231 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 17232 Diag(Loc, diag::note_condition_assign_silence) 17233 << FixItHint::CreateInsertion(Open, "(") 17234 << FixItHint::CreateInsertion(Close, ")"); 17235 17236 if (IsOrAssign) 17237 Diag(Loc, diag::note_condition_or_assign_to_comparison) 17238 << FixItHint::CreateReplacement(Loc, "!="); 17239 else 17240 Diag(Loc, diag::note_condition_assign_to_comparison) 17241 << FixItHint::CreateReplacement(Loc, "=="); 17242 } 17243 17244 /// Redundant parentheses over an equality comparison can indicate 17245 /// that the user intended an assignment used as condition. 17246 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 17247 // Don't warn if the parens came from a macro. 17248 SourceLocation parenLoc = ParenE->getBeginLoc(); 17249 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 17250 return; 17251 // Don't warn for dependent expressions. 17252 if (ParenE->isTypeDependent()) 17253 return; 17254 17255 Expr *E = ParenE->IgnoreParens(); 17256 17257 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 17258 if (opE->getOpcode() == BO_EQ && 17259 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 17260 == Expr::MLV_Valid) { 17261 SourceLocation Loc = opE->getOperatorLoc(); 17262 17263 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 17264 SourceRange ParenERange = ParenE->getSourceRange(); 17265 Diag(Loc, diag::note_equality_comparison_silence) 17266 << FixItHint::CreateRemoval(ParenERange.getBegin()) 17267 << FixItHint::CreateRemoval(ParenERange.getEnd()); 17268 Diag(Loc, diag::note_equality_comparison_to_assign) 17269 << FixItHint::CreateReplacement(Loc, "="); 17270 } 17271 } 17272 17273 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 17274 bool IsConstexpr) { 17275 DiagnoseAssignmentAsCondition(E); 17276 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 17277 DiagnoseEqualityWithExtraParens(parenE); 17278 17279 ExprResult result = CheckPlaceholderExpr(E); 17280 if (result.isInvalid()) return ExprError(); 17281 E = result.get(); 17282 17283 if (!E->isTypeDependent()) { 17284 if (getLangOpts().CPlusPlus) 17285 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 17286 17287 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 17288 if (ERes.isInvalid()) 17289 return ExprError(); 17290 E = ERes.get(); 17291 17292 QualType T = E->getType(); 17293 if (!T->isScalarType()) { // C99 6.8.4.1p1 17294 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 17295 << T << E->getSourceRange(); 17296 return ExprError(); 17297 } 17298 CheckBoolLikeConversion(E, Loc); 17299 } 17300 17301 return E; 17302 } 17303 17304 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 17305 Expr *SubExpr, ConditionKind CK) { 17306 // Empty conditions are valid in for-statements. 17307 if (!SubExpr) 17308 return ConditionResult(); 17309 17310 ExprResult Cond; 17311 switch (CK) { 17312 case ConditionKind::Boolean: 17313 Cond = CheckBooleanCondition(Loc, SubExpr); 17314 break; 17315 17316 case ConditionKind::ConstexprIf: 17317 Cond = CheckBooleanCondition(Loc, SubExpr, true); 17318 break; 17319 17320 case ConditionKind::Switch: 17321 Cond = CheckSwitchCondition(Loc, SubExpr); 17322 break; 17323 } 17324 if (Cond.isInvalid()) 17325 return ConditionError(); 17326 17327 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 17328 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 17329 if (!FullExpr.get()) 17330 return ConditionError(); 17331 17332 return ConditionResult(*this, nullptr, FullExpr, 17333 CK == ConditionKind::ConstexprIf); 17334 } 17335 17336 namespace { 17337 /// A visitor for rebuilding a call to an __unknown_any expression 17338 /// to have an appropriate type. 17339 struct RebuildUnknownAnyFunction 17340 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 17341 17342 Sema &S; 17343 17344 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 17345 17346 ExprResult VisitStmt(Stmt *S) { 17347 llvm_unreachable("unexpected statement!"); 17348 } 17349 17350 ExprResult VisitExpr(Expr *E) { 17351 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 17352 << E->getSourceRange(); 17353 return ExprError(); 17354 } 17355 17356 /// Rebuild an expression which simply semantically wraps another 17357 /// expression which it shares the type and value kind of. 17358 template <class T> ExprResult rebuildSugarExpr(T *E) { 17359 ExprResult SubResult = Visit(E->getSubExpr()); 17360 if (SubResult.isInvalid()) return ExprError(); 17361 17362 Expr *SubExpr = SubResult.get(); 17363 E->setSubExpr(SubExpr); 17364 E->setType(SubExpr->getType()); 17365 E->setValueKind(SubExpr->getValueKind()); 17366 assert(E->getObjectKind() == OK_Ordinary); 17367 return E; 17368 } 17369 17370 ExprResult VisitParenExpr(ParenExpr *E) { 17371 return rebuildSugarExpr(E); 17372 } 17373 17374 ExprResult VisitUnaryExtension(UnaryOperator *E) { 17375 return rebuildSugarExpr(E); 17376 } 17377 17378 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 17379 ExprResult SubResult = Visit(E->getSubExpr()); 17380 if (SubResult.isInvalid()) return ExprError(); 17381 17382 Expr *SubExpr = SubResult.get(); 17383 E->setSubExpr(SubExpr); 17384 E->setType(S.Context.getPointerType(SubExpr->getType())); 17385 assert(E->getValueKind() == VK_RValue); 17386 assert(E->getObjectKind() == OK_Ordinary); 17387 return E; 17388 } 17389 17390 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 17391 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 17392 17393 E->setType(VD->getType()); 17394 17395 assert(E->getValueKind() == VK_RValue); 17396 if (S.getLangOpts().CPlusPlus && 17397 !(isa<CXXMethodDecl>(VD) && 17398 cast<CXXMethodDecl>(VD)->isInstance())) 17399 E->setValueKind(VK_LValue); 17400 17401 return E; 17402 } 17403 17404 ExprResult VisitMemberExpr(MemberExpr *E) { 17405 return resolveDecl(E, E->getMemberDecl()); 17406 } 17407 17408 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 17409 return resolveDecl(E, E->getDecl()); 17410 } 17411 }; 17412 } 17413 17414 /// Given a function expression of unknown-any type, try to rebuild it 17415 /// to have a function type. 17416 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 17417 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 17418 if (Result.isInvalid()) return ExprError(); 17419 return S.DefaultFunctionArrayConversion(Result.get()); 17420 } 17421 17422 namespace { 17423 /// A visitor for rebuilding an expression of type __unknown_anytype 17424 /// into one which resolves the type directly on the referring 17425 /// expression. Strict preservation of the original source 17426 /// structure is not a goal. 17427 struct RebuildUnknownAnyExpr 17428 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 17429 17430 Sema &S; 17431 17432 /// The current destination type. 17433 QualType DestType; 17434 17435 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 17436 : S(S), DestType(CastType) {} 17437 17438 ExprResult VisitStmt(Stmt *S) { 17439 llvm_unreachable("unexpected statement!"); 17440 } 17441 17442 ExprResult VisitExpr(Expr *E) { 17443 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 17444 << E->getSourceRange(); 17445 return ExprError(); 17446 } 17447 17448 ExprResult VisitCallExpr(CallExpr *E); 17449 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 17450 17451 /// Rebuild an expression which simply semantically wraps another 17452 /// expression which it shares the type and value kind of. 17453 template <class T> ExprResult rebuildSugarExpr(T *E) { 17454 ExprResult SubResult = Visit(E->getSubExpr()); 17455 if (SubResult.isInvalid()) return ExprError(); 17456 Expr *SubExpr = SubResult.get(); 17457 E->setSubExpr(SubExpr); 17458 E->setType(SubExpr->getType()); 17459 E->setValueKind(SubExpr->getValueKind()); 17460 assert(E->getObjectKind() == OK_Ordinary); 17461 return E; 17462 } 17463 17464 ExprResult VisitParenExpr(ParenExpr *E) { 17465 return rebuildSugarExpr(E); 17466 } 17467 17468 ExprResult VisitUnaryExtension(UnaryOperator *E) { 17469 return rebuildSugarExpr(E); 17470 } 17471 17472 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 17473 const PointerType *Ptr = DestType->getAs<PointerType>(); 17474 if (!Ptr) { 17475 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 17476 << E->getSourceRange(); 17477 return ExprError(); 17478 } 17479 17480 if (isa<CallExpr>(E->getSubExpr())) { 17481 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 17482 << E->getSourceRange(); 17483 return ExprError(); 17484 } 17485 17486 assert(E->getValueKind() == VK_RValue); 17487 assert(E->getObjectKind() == OK_Ordinary); 17488 E->setType(DestType); 17489 17490 // Build the sub-expression as if it were an object of the pointee type. 17491 DestType = Ptr->getPointeeType(); 17492 ExprResult SubResult = Visit(E->getSubExpr()); 17493 if (SubResult.isInvalid()) return ExprError(); 17494 E->setSubExpr(SubResult.get()); 17495 return E; 17496 } 17497 17498 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 17499 17500 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 17501 17502 ExprResult VisitMemberExpr(MemberExpr *E) { 17503 return resolveDecl(E, E->getMemberDecl()); 17504 } 17505 17506 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 17507 return resolveDecl(E, E->getDecl()); 17508 } 17509 }; 17510 } 17511 17512 /// Rebuilds a call expression which yielded __unknown_anytype. 17513 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 17514 Expr *CalleeExpr = E->getCallee(); 17515 17516 enum FnKind { 17517 FK_MemberFunction, 17518 FK_FunctionPointer, 17519 FK_BlockPointer 17520 }; 17521 17522 FnKind Kind; 17523 QualType CalleeType = CalleeExpr->getType(); 17524 if (CalleeType == S.Context.BoundMemberTy) { 17525 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 17526 Kind = FK_MemberFunction; 17527 CalleeType = Expr::findBoundMemberType(CalleeExpr); 17528 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 17529 CalleeType = Ptr->getPointeeType(); 17530 Kind = FK_FunctionPointer; 17531 } else { 17532 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 17533 Kind = FK_BlockPointer; 17534 } 17535 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 17536 17537 // Verify that this is a legal result type of a function. 17538 if (DestType->isArrayType() || DestType->isFunctionType()) { 17539 unsigned diagID = diag::err_func_returning_array_function; 17540 if (Kind == FK_BlockPointer) 17541 diagID = diag::err_block_returning_array_function; 17542 17543 S.Diag(E->getExprLoc(), diagID) 17544 << DestType->isFunctionType() << DestType; 17545 return ExprError(); 17546 } 17547 17548 // Otherwise, go ahead and set DestType as the call's result. 17549 E->setType(DestType.getNonLValueExprType(S.Context)); 17550 E->setValueKind(Expr::getValueKindForType(DestType)); 17551 assert(E->getObjectKind() == OK_Ordinary); 17552 17553 // Rebuild the function type, replacing the result type with DestType. 17554 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 17555 if (Proto) { 17556 // __unknown_anytype(...) is a special case used by the debugger when 17557 // it has no idea what a function's signature is. 17558 // 17559 // We want to build this call essentially under the K&R 17560 // unprototyped rules, but making a FunctionNoProtoType in C++ 17561 // would foul up all sorts of assumptions. However, we cannot 17562 // simply pass all arguments as variadic arguments, nor can we 17563 // portably just call the function under a non-variadic type; see 17564 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 17565 // However, it turns out that in practice it is generally safe to 17566 // call a function declared as "A foo(B,C,D);" under the prototype 17567 // "A foo(B,C,D,...);". The only known exception is with the 17568 // Windows ABI, where any variadic function is implicitly cdecl 17569 // regardless of its normal CC. Therefore we change the parameter 17570 // types to match the types of the arguments. 17571 // 17572 // This is a hack, but it is far superior to moving the 17573 // corresponding target-specific code from IR-gen to Sema/AST. 17574 17575 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 17576 SmallVector<QualType, 8> ArgTypes; 17577 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 17578 ArgTypes.reserve(E->getNumArgs()); 17579 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 17580 Expr *Arg = E->getArg(i); 17581 QualType ArgType = Arg->getType(); 17582 if (E->isLValue()) { 17583 ArgType = S.Context.getLValueReferenceType(ArgType); 17584 } else if (E->isXValue()) { 17585 ArgType = S.Context.getRValueReferenceType(ArgType); 17586 } 17587 ArgTypes.push_back(ArgType); 17588 } 17589 ParamTypes = ArgTypes; 17590 } 17591 DestType = S.Context.getFunctionType(DestType, ParamTypes, 17592 Proto->getExtProtoInfo()); 17593 } else { 17594 DestType = S.Context.getFunctionNoProtoType(DestType, 17595 FnType->getExtInfo()); 17596 } 17597 17598 // Rebuild the appropriate pointer-to-function type. 17599 switch (Kind) { 17600 case FK_MemberFunction: 17601 // Nothing to do. 17602 break; 17603 17604 case FK_FunctionPointer: 17605 DestType = S.Context.getPointerType(DestType); 17606 break; 17607 17608 case FK_BlockPointer: 17609 DestType = S.Context.getBlockPointerType(DestType); 17610 break; 17611 } 17612 17613 // Finally, we can recurse. 17614 ExprResult CalleeResult = Visit(CalleeExpr); 17615 if (!CalleeResult.isUsable()) return ExprError(); 17616 E->setCallee(CalleeResult.get()); 17617 17618 // Bind a temporary if necessary. 17619 return S.MaybeBindToTemporary(E); 17620 } 17621 17622 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 17623 // Verify that this is a legal result type of a call. 17624 if (DestType->isArrayType() || DestType->isFunctionType()) { 17625 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 17626 << DestType->isFunctionType() << DestType; 17627 return ExprError(); 17628 } 17629 17630 // Rewrite the method result type if available. 17631 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 17632 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 17633 Method->setReturnType(DestType); 17634 } 17635 17636 // Change the type of the message. 17637 E->setType(DestType.getNonReferenceType()); 17638 E->setValueKind(Expr::getValueKindForType(DestType)); 17639 17640 return S.MaybeBindToTemporary(E); 17641 } 17642 17643 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 17644 // The only case we should ever see here is a function-to-pointer decay. 17645 if (E->getCastKind() == CK_FunctionToPointerDecay) { 17646 assert(E->getValueKind() == VK_RValue); 17647 assert(E->getObjectKind() == OK_Ordinary); 17648 17649 E->setType(DestType); 17650 17651 // Rebuild the sub-expression as the pointee (function) type. 17652 DestType = DestType->castAs<PointerType>()->getPointeeType(); 17653 17654 ExprResult Result = Visit(E->getSubExpr()); 17655 if (!Result.isUsable()) return ExprError(); 17656 17657 E->setSubExpr(Result.get()); 17658 return E; 17659 } else if (E->getCastKind() == CK_LValueToRValue) { 17660 assert(E->getValueKind() == VK_RValue); 17661 assert(E->getObjectKind() == OK_Ordinary); 17662 17663 assert(isa<BlockPointerType>(E->getType())); 17664 17665 E->setType(DestType); 17666 17667 // The sub-expression has to be a lvalue reference, so rebuild it as such. 17668 DestType = S.Context.getLValueReferenceType(DestType); 17669 17670 ExprResult Result = Visit(E->getSubExpr()); 17671 if (!Result.isUsable()) return ExprError(); 17672 17673 E->setSubExpr(Result.get()); 17674 return E; 17675 } else { 17676 llvm_unreachable("Unhandled cast type!"); 17677 } 17678 } 17679 17680 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 17681 ExprValueKind ValueKind = VK_LValue; 17682 QualType Type = DestType; 17683 17684 // We know how to make this work for certain kinds of decls: 17685 17686 // - functions 17687 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 17688 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 17689 DestType = Ptr->getPointeeType(); 17690 ExprResult Result = resolveDecl(E, VD); 17691 if (Result.isInvalid()) return ExprError(); 17692 return S.ImpCastExprToType(Result.get(), Type, 17693 CK_FunctionToPointerDecay, VK_RValue); 17694 } 17695 17696 if (!Type->isFunctionType()) { 17697 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 17698 << VD << E->getSourceRange(); 17699 return ExprError(); 17700 } 17701 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 17702 // We must match the FunctionDecl's type to the hack introduced in 17703 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 17704 // type. See the lengthy commentary in that routine. 17705 QualType FDT = FD->getType(); 17706 const FunctionType *FnType = FDT->castAs<FunctionType>(); 17707 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 17708 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 17709 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 17710 SourceLocation Loc = FD->getLocation(); 17711 FunctionDecl *NewFD = FunctionDecl::Create( 17712 S.Context, FD->getDeclContext(), Loc, Loc, 17713 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 17714 SC_None, false /*isInlineSpecified*/, FD->hasPrototype(), 17715 /*ConstexprKind*/ CSK_unspecified); 17716 17717 if (FD->getQualifier()) 17718 NewFD->setQualifierInfo(FD->getQualifierLoc()); 17719 17720 SmallVector<ParmVarDecl*, 16> Params; 17721 for (const auto &AI : FT->param_types()) { 17722 ParmVarDecl *Param = 17723 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 17724 Param->setScopeInfo(0, Params.size()); 17725 Params.push_back(Param); 17726 } 17727 NewFD->setParams(Params); 17728 DRE->setDecl(NewFD); 17729 VD = DRE->getDecl(); 17730 } 17731 } 17732 17733 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 17734 if (MD->isInstance()) { 17735 ValueKind = VK_RValue; 17736 Type = S.Context.BoundMemberTy; 17737 } 17738 17739 // Function references aren't l-values in C. 17740 if (!S.getLangOpts().CPlusPlus) 17741 ValueKind = VK_RValue; 17742 17743 // - variables 17744 } else if (isa<VarDecl>(VD)) { 17745 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 17746 Type = RefTy->getPointeeType(); 17747 } else if (Type->isFunctionType()) { 17748 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 17749 << VD << E->getSourceRange(); 17750 return ExprError(); 17751 } 17752 17753 // - nothing else 17754 } else { 17755 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 17756 << VD << E->getSourceRange(); 17757 return ExprError(); 17758 } 17759 17760 // Modifying the declaration like this is friendly to IR-gen but 17761 // also really dangerous. 17762 VD->setType(DestType); 17763 E->setType(Type); 17764 E->setValueKind(ValueKind); 17765 return E; 17766 } 17767 17768 /// Check a cast of an unknown-any type. We intentionally only 17769 /// trigger this for C-style casts. 17770 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 17771 Expr *CastExpr, CastKind &CastKind, 17772 ExprValueKind &VK, CXXCastPath &Path) { 17773 // The type we're casting to must be either void or complete. 17774 if (!CastType->isVoidType() && 17775 RequireCompleteType(TypeRange.getBegin(), CastType, 17776 diag::err_typecheck_cast_to_incomplete)) 17777 return ExprError(); 17778 17779 // Rewrite the casted expression from scratch. 17780 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 17781 if (!result.isUsable()) return ExprError(); 17782 17783 CastExpr = result.get(); 17784 VK = CastExpr->getValueKind(); 17785 CastKind = CK_NoOp; 17786 17787 return CastExpr; 17788 } 17789 17790 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 17791 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 17792 } 17793 17794 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 17795 Expr *arg, QualType ¶mType) { 17796 // If the syntactic form of the argument is not an explicit cast of 17797 // any sort, just do default argument promotion. 17798 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 17799 if (!castArg) { 17800 ExprResult result = DefaultArgumentPromotion(arg); 17801 if (result.isInvalid()) return ExprError(); 17802 paramType = result.get()->getType(); 17803 return result; 17804 } 17805 17806 // Otherwise, use the type that was written in the explicit cast. 17807 assert(!arg->hasPlaceholderType()); 17808 paramType = castArg->getTypeAsWritten(); 17809 17810 // Copy-initialize a parameter of that type. 17811 InitializedEntity entity = 17812 InitializedEntity::InitializeParameter(Context, paramType, 17813 /*consumed*/ false); 17814 return PerformCopyInitialization(entity, callLoc, arg); 17815 } 17816 17817 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 17818 Expr *orig = E; 17819 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 17820 while (true) { 17821 E = E->IgnoreParenImpCasts(); 17822 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 17823 E = call->getCallee(); 17824 diagID = diag::err_uncasted_call_of_unknown_any; 17825 } else { 17826 break; 17827 } 17828 } 17829 17830 SourceLocation loc; 17831 NamedDecl *d; 17832 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 17833 loc = ref->getLocation(); 17834 d = ref->getDecl(); 17835 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 17836 loc = mem->getMemberLoc(); 17837 d = mem->getMemberDecl(); 17838 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 17839 diagID = diag::err_uncasted_call_of_unknown_any; 17840 loc = msg->getSelectorStartLoc(); 17841 d = msg->getMethodDecl(); 17842 if (!d) { 17843 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 17844 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 17845 << orig->getSourceRange(); 17846 return ExprError(); 17847 } 17848 } else { 17849 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 17850 << E->getSourceRange(); 17851 return ExprError(); 17852 } 17853 17854 S.Diag(loc, diagID) << d << orig->getSourceRange(); 17855 17856 // Never recoverable. 17857 return ExprError(); 17858 } 17859 17860 /// Check for operands with placeholder types and complain if found. 17861 /// Returns ExprError() if there was an error and no recovery was possible. 17862 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 17863 if (!getLangOpts().CPlusPlus) { 17864 // C cannot handle TypoExpr nodes on either side of a binop because it 17865 // doesn't handle dependent types properly, so make sure any TypoExprs have 17866 // been dealt with before checking the operands. 17867 ExprResult Result = CorrectDelayedTyposInExpr(E); 17868 if (!Result.isUsable()) return ExprError(); 17869 E = Result.get(); 17870 } 17871 17872 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 17873 if (!placeholderType) return E; 17874 17875 switch (placeholderType->getKind()) { 17876 17877 // Overloaded expressions. 17878 case BuiltinType::Overload: { 17879 // Try to resolve a single function template specialization. 17880 // This is obligatory. 17881 ExprResult Result = E; 17882 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 17883 return Result; 17884 17885 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 17886 // leaves Result unchanged on failure. 17887 Result = E; 17888 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) 17889 return Result; 17890 17891 // If that failed, try to recover with a call. 17892 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 17893 /*complain*/ true); 17894 return Result; 17895 } 17896 17897 // Bound member functions. 17898 case BuiltinType::BoundMember: { 17899 ExprResult result = E; 17900 const Expr *BME = E->IgnoreParens(); 17901 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 17902 // Try to give a nicer diagnostic if it is a bound member that we recognize. 17903 if (isa<CXXPseudoDestructorExpr>(BME)) { 17904 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 17905 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 17906 if (ME->getMemberNameInfo().getName().getNameKind() == 17907 DeclarationName::CXXDestructorName) 17908 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 17909 } 17910 tryToRecoverWithCall(result, PD, 17911 /*complain*/ true); 17912 return result; 17913 } 17914 17915 // ARC unbridged casts. 17916 case BuiltinType::ARCUnbridgedCast: { 17917 Expr *realCast = stripARCUnbridgedCast(E); 17918 diagnoseARCUnbridgedCast(realCast); 17919 return realCast; 17920 } 17921 17922 // Expressions of unknown type. 17923 case BuiltinType::UnknownAny: 17924 return diagnoseUnknownAnyExpr(*this, E); 17925 17926 // Pseudo-objects. 17927 case BuiltinType::PseudoObject: 17928 return checkPseudoObjectRValue(E); 17929 17930 case BuiltinType::BuiltinFn: { 17931 // Accept __noop without parens by implicitly converting it to a call expr. 17932 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 17933 if (DRE) { 17934 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 17935 if (FD->getBuiltinID() == Builtin::BI__noop) { 17936 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 17937 CK_BuiltinFnToFnPtr) 17938 .get(); 17939 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 17940 VK_RValue, SourceLocation()); 17941 } 17942 } 17943 17944 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 17945 return ExprError(); 17946 } 17947 17948 // Expressions of unknown type. 17949 case BuiltinType::OMPArraySection: 17950 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 17951 return ExprError(); 17952 17953 // Everything else should be impossible. 17954 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 17955 case BuiltinType::Id: 17956 #include "clang/Basic/OpenCLImageTypes.def" 17957 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 17958 case BuiltinType::Id: 17959 #include "clang/Basic/OpenCLExtensionTypes.def" 17960 #define SVE_TYPE(Name, Id, SingletonId) \ 17961 case BuiltinType::Id: 17962 #include "clang/Basic/AArch64SVEACLETypes.def" 17963 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 17964 #define PLACEHOLDER_TYPE(Id, SingletonId) 17965 #include "clang/AST/BuiltinTypes.def" 17966 break; 17967 } 17968 17969 llvm_unreachable("invalid placeholder type!"); 17970 } 17971 17972 bool Sema::CheckCaseExpression(Expr *E) { 17973 if (E->isTypeDependent()) 17974 return true; 17975 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 17976 return E->getType()->isIntegralOrEnumerationType(); 17977 return false; 17978 } 17979 17980 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 17981 ExprResult 17982 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 17983 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 17984 "Unknown Objective-C Boolean value!"); 17985 QualType BoolT = Context.ObjCBuiltinBoolTy; 17986 if (!Context.getBOOLDecl()) { 17987 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 17988 Sema::LookupOrdinaryName); 17989 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 17990 NamedDecl *ND = Result.getFoundDecl(); 17991 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 17992 Context.setBOOLDecl(TD); 17993 } 17994 } 17995 if (Context.getBOOLDecl()) 17996 BoolT = Context.getBOOLType(); 17997 return new (Context) 17998 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 17999 } 18000 18001 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 18002 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 18003 SourceLocation RParen) { 18004 18005 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 18006 18007 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 18008 return Spec.getPlatform() == Platform; 18009 }); 18010 18011 VersionTuple Version; 18012 if (Spec != AvailSpecs.end()) 18013 Version = Spec->getVersion(); 18014 18015 // The use of `@available` in the enclosing function should be analyzed to 18016 // warn when it's used inappropriately (i.e. not if(@available)). 18017 if (getCurFunctionOrMethodDecl()) 18018 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 18019 else if (getCurBlock() || getCurLambda()) 18020 getCurFunction()->HasPotentialAvailabilityViolations = true; 18021 18022 return new (Context) 18023 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 18024 } 18025