1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for expressions. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "TreeTransform.h" 14 #include "clang/AST/ASTConsumer.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTLambda.h" 17 #include "clang/AST/ASTMutationListener.h" 18 #include "clang/AST/CXXInheritance.h" 19 #include "clang/AST/DeclObjC.h" 20 #include "clang/AST/DeclTemplate.h" 21 #include "clang/AST/EvaluatedExprVisitor.h" 22 #include "clang/AST/Expr.h" 23 #include "clang/AST/ExprCXX.h" 24 #include "clang/AST/ExprObjC.h" 25 #include "clang/AST/ExprOpenMP.h" 26 #include "clang/AST/RecursiveASTVisitor.h" 27 #include "clang/AST/TypeLoc.h" 28 #include "clang/Basic/Builtins.h" 29 #include "clang/Basic/FixedPoint.h" 30 #include "clang/Basic/PartialDiagnostic.h" 31 #include "clang/Basic/SourceManager.h" 32 #include "clang/Basic/TargetInfo.h" 33 #include "clang/Lex/LiteralSupport.h" 34 #include "clang/Lex/Preprocessor.h" 35 #include "clang/Sema/AnalysisBasedWarnings.h" 36 #include "clang/Sema/DeclSpec.h" 37 #include "clang/Sema/DelayedDiagnostic.h" 38 #include "clang/Sema/Designator.h" 39 #include "clang/Sema/Initialization.h" 40 #include "clang/Sema/Lookup.h" 41 #include "clang/Sema/Overload.h" 42 #include "clang/Sema/ParsedTemplate.h" 43 #include "clang/Sema/Scope.h" 44 #include "clang/Sema/ScopeInfo.h" 45 #include "clang/Sema/SemaFixItUtils.h" 46 #include "clang/Sema/SemaInternal.h" 47 #include "clang/Sema/Template.h" 48 #include "llvm/Support/ConvertUTF.h" 49 using namespace clang; 50 using namespace sema; 51 52 /// Determine whether the use of this declaration is valid, without 53 /// emitting diagnostics. 54 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 55 // See if this is an auto-typed variable whose initializer we are parsing. 56 if (ParsingInitForAutoVars.count(D)) 57 return false; 58 59 // See if this is a deleted function. 60 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 61 if (FD->isDeleted()) 62 return false; 63 64 // If the function has a deduced return type, and we can't deduce it, 65 // then we can't use it either. 66 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 67 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 68 return false; 69 70 // See if this is an aligned allocation/deallocation function that is 71 // unavailable. 72 if (TreatUnavailableAsInvalid && 73 isUnavailableAlignedAllocationFunction(*FD)) 74 return false; 75 } 76 77 // See if this function is unavailable. 78 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 79 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 80 return false; 81 82 return true; 83 } 84 85 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 86 // Warn if this is used but marked unused. 87 if (const auto *A = D->getAttr<UnusedAttr>()) { 88 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 89 // should diagnose them. 90 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 91 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 92 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 93 if (DC && !DC->hasAttr<UnusedAttr>()) 94 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 95 } 96 } 97 } 98 99 /// Emit a note explaining that this function is deleted. 100 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 101 assert(Decl && Decl->isDeleted()); 102 103 if (Decl->isDefaulted()) { 104 // If the method was explicitly defaulted, point at that declaration. 105 if (!Decl->isImplicit()) 106 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 107 108 // Try to diagnose why this special member function was implicitly 109 // deleted. This might fail, if that reason no longer applies. 110 DiagnoseDeletedDefaultedFunction(Decl); 111 return; 112 } 113 114 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 115 if (Ctor && Ctor->isInheritingConstructor()) 116 return NoteDeletedInheritingConstructor(Ctor); 117 118 Diag(Decl->getLocation(), diag::note_availability_specified_here) 119 << Decl << 1; 120 } 121 122 /// Determine whether a FunctionDecl was ever declared with an 123 /// explicit storage class. 124 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 125 for (auto I : D->redecls()) { 126 if (I->getStorageClass() != SC_None) 127 return true; 128 } 129 return false; 130 } 131 132 /// Check whether we're in an extern inline function and referring to a 133 /// variable or function with internal linkage (C11 6.7.4p3). 134 /// 135 /// This is only a warning because we used to silently accept this code, but 136 /// in many cases it will not behave correctly. This is not enabled in C++ mode 137 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 138 /// and so while there may still be user mistakes, most of the time we can't 139 /// prove that there are errors. 140 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 141 const NamedDecl *D, 142 SourceLocation Loc) { 143 // This is disabled under C++; there are too many ways for this to fire in 144 // contexts where the warning is a false positive, or where it is technically 145 // correct but benign. 146 if (S.getLangOpts().CPlusPlus) 147 return; 148 149 // Check if this is an inlined function or method. 150 FunctionDecl *Current = S.getCurFunctionDecl(); 151 if (!Current) 152 return; 153 if (!Current->isInlined()) 154 return; 155 if (!Current->isExternallyVisible()) 156 return; 157 158 // Check if the decl has internal linkage. 159 if (D->getFormalLinkage() != InternalLinkage) 160 return; 161 162 // Downgrade from ExtWarn to Extension if 163 // (1) the supposedly external inline function is in the main file, 164 // and probably won't be included anywhere else. 165 // (2) the thing we're referencing is a pure function. 166 // (3) the thing we're referencing is another inline function. 167 // This last can give us false negatives, but it's better than warning on 168 // wrappers for simple C library functions. 169 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 170 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 171 if (!DowngradeWarning && UsedFn) 172 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 173 174 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 175 : diag::ext_internal_in_extern_inline) 176 << /*IsVar=*/!UsedFn << D; 177 178 S.MaybeSuggestAddingStaticToDecl(Current); 179 180 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 181 << D; 182 } 183 184 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 185 const FunctionDecl *First = Cur->getFirstDecl(); 186 187 // Suggest "static" on the function, if possible. 188 if (!hasAnyExplicitStorageClass(First)) { 189 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 190 Diag(DeclBegin, diag::note_convert_inline_to_static) 191 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 192 } 193 } 194 195 /// Determine whether the use of this declaration is valid, and 196 /// emit any corresponding diagnostics. 197 /// 198 /// This routine diagnoses various problems with referencing 199 /// declarations that can occur when using a declaration. For example, 200 /// it might warn if a deprecated or unavailable declaration is being 201 /// used, or produce an error (and return true) if a C++0x deleted 202 /// function is being used. 203 /// 204 /// \returns true if there was an error (this declaration cannot be 205 /// referenced), false otherwise. 206 /// 207 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 208 const ObjCInterfaceDecl *UnknownObjCClass, 209 bool ObjCPropertyAccess, 210 bool AvoidPartialAvailabilityChecks, 211 ObjCInterfaceDecl *ClassReceiver) { 212 SourceLocation Loc = Locs.front(); 213 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 214 // If there were any diagnostics suppressed by template argument deduction, 215 // emit them now. 216 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 217 if (Pos != SuppressedDiagnostics.end()) { 218 for (const PartialDiagnosticAt &Suppressed : Pos->second) 219 Diag(Suppressed.first, Suppressed.second); 220 221 // Clear out the list of suppressed diagnostics, so that we don't emit 222 // them again for this specialization. However, we don't obsolete this 223 // entry from the table, because we want to avoid ever emitting these 224 // diagnostics again. 225 Pos->second.clear(); 226 } 227 228 // C++ [basic.start.main]p3: 229 // The function 'main' shall not be used within a program. 230 if (cast<FunctionDecl>(D)->isMain()) 231 Diag(Loc, diag::ext_main_used); 232 233 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); 234 } 235 236 // See if this is an auto-typed variable whose initializer we are parsing. 237 if (ParsingInitForAutoVars.count(D)) { 238 if (isa<BindingDecl>(D)) { 239 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 240 << D->getDeclName(); 241 } else { 242 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 243 << D->getDeclName() << cast<VarDecl>(D)->getType(); 244 } 245 return true; 246 } 247 248 // See if this is a deleted function. 249 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 250 if (FD->isDeleted()) { 251 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 252 if (Ctor && Ctor->isInheritingConstructor()) 253 Diag(Loc, diag::err_deleted_inherited_ctor_use) 254 << Ctor->getParent() 255 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 256 else 257 Diag(Loc, diag::err_deleted_function_use); 258 NoteDeletedFunction(FD); 259 return true; 260 } 261 262 // If the function has a deduced return type, and we can't deduce it, 263 // then we can't use it either. 264 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 265 DeduceReturnType(FD, Loc)) 266 return true; 267 268 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 269 return true; 270 } 271 272 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 273 // Lambdas are only default-constructible or assignable in C++2a onwards. 274 if (MD->getParent()->isLambda() && 275 ((isa<CXXConstructorDecl>(MD) && 276 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || 277 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { 278 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) 279 << !isa<CXXConstructorDecl>(MD); 280 } 281 } 282 283 auto getReferencedObjCProp = [](const NamedDecl *D) -> 284 const ObjCPropertyDecl * { 285 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 286 return MD->findPropertyDecl(); 287 return nullptr; 288 }; 289 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 290 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 291 return true; 292 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 293 return true; 294 } 295 296 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 297 // Only the variables omp_in and omp_out are allowed in the combiner. 298 // Only the variables omp_priv and omp_orig are allowed in the 299 // initializer-clause. 300 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 301 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 302 isa<VarDecl>(D)) { 303 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 304 << getCurFunction()->HasOMPDeclareReductionCombiner; 305 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 306 return true; 307 } 308 309 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions 310 // List-items in map clauses on this construct may only refer to the declared 311 // variable var and entities that could be referenced by a procedure defined 312 // at the same location 313 auto *DMD = dyn_cast<OMPDeclareMapperDecl>(CurContext); 314 if (LangOpts.OpenMP && DMD && !CurContext->containsDecl(D) && 315 isa<VarDecl>(D)) { 316 Diag(Loc, diag::err_omp_declare_mapper_wrong_var) 317 << DMD->getVarName().getAsString(); 318 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 319 return true; 320 } 321 322 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 323 AvoidPartialAvailabilityChecks, ClassReceiver); 324 325 DiagnoseUnusedOfDecl(*this, D, Loc); 326 327 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 328 329 return false; 330 } 331 332 /// DiagnoseSentinelCalls - This routine checks whether a call or 333 /// message-send is to a declaration with the sentinel attribute, and 334 /// if so, it checks that the requirements of the sentinel are 335 /// satisfied. 336 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 337 ArrayRef<Expr *> Args) { 338 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 339 if (!attr) 340 return; 341 342 // The number of formal parameters of the declaration. 343 unsigned numFormalParams; 344 345 // The kind of declaration. This is also an index into a %select in 346 // the diagnostic. 347 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 348 349 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 350 numFormalParams = MD->param_size(); 351 calleeType = CT_Method; 352 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 353 numFormalParams = FD->param_size(); 354 calleeType = CT_Function; 355 } else if (isa<VarDecl>(D)) { 356 QualType type = cast<ValueDecl>(D)->getType(); 357 const FunctionType *fn = nullptr; 358 if (const PointerType *ptr = type->getAs<PointerType>()) { 359 fn = ptr->getPointeeType()->getAs<FunctionType>(); 360 if (!fn) return; 361 calleeType = CT_Function; 362 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 363 fn = ptr->getPointeeType()->castAs<FunctionType>(); 364 calleeType = CT_Block; 365 } else { 366 return; 367 } 368 369 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 370 numFormalParams = proto->getNumParams(); 371 } else { 372 numFormalParams = 0; 373 } 374 } else { 375 return; 376 } 377 378 // "nullPos" is the number of formal parameters at the end which 379 // effectively count as part of the variadic arguments. This is 380 // useful if you would prefer to not have *any* formal parameters, 381 // but the language forces you to have at least one. 382 unsigned nullPos = attr->getNullPos(); 383 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 384 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 385 386 // The number of arguments which should follow the sentinel. 387 unsigned numArgsAfterSentinel = attr->getSentinel(); 388 389 // If there aren't enough arguments for all the formal parameters, 390 // the sentinel, and the args after the sentinel, complain. 391 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 392 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 393 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 394 return; 395 } 396 397 // Otherwise, find the sentinel expression. 398 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 399 if (!sentinelExpr) return; 400 if (sentinelExpr->isValueDependent()) return; 401 if (Context.isSentinelNullExpr(sentinelExpr)) return; 402 403 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 404 // or 'NULL' if those are actually defined in the context. Only use 405 // 'nil' for ObjC methods, where it's much more likely that the 406 // variadic arguments form a list of object pointers. 407 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 408 std::string NullValue; 409 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 410 NullValue = "nil"; 411 else if (getLangOpts().CPlusPlus11) 412 NullValue = "nullptr"; 413 else if (PP.isMacroDefined("NULL")) 414 NullValue = "NULL"; 415 else 416 NullValue = "(void*) 0"; 417 418 if (MissingNilLoc.isInvalid()) 419 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 420 else 421 Diag(MissingNilLoc, diag::warn_missing_sentinel) 422 << int(calleeType) 423 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 424 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 425 } 426 427 SourceRange Sema::getExprRange(Expr *E) const { 428 return E ? E->getSourceRange() : SourceRange(); 429 } 430 431 //===----------------------------------------------------------------------===// 432 // Standard Promotions and Conversions 433 //===----------------------------------------------------------------------===// 434 435 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 436 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 437 // Handle any placeholder expressions which made it here. 438 if (E->getType()->isPlaceholderType()) { 439 ExprResult result = CheckPlaceholderExpr(E); 440 if (result.isInvalid()) return ExprError(); 441 E = result.get(); 442 } 443 444 QualType Ty = E->getType(); 445 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 446 447 if (Ty->isFunctionType()) { 448 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 449 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 450 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 451 return ExprError(); 452 453 E = ImpCastExprToType(E, Context.getPointerType(Ty), 454 CK_FunctionToPointerDecay).get(); 455 } else if (Ty->isArrayType()) { 456 // In C90 mode, arrays only promote to pointers if the array expression is 457 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 458 // type 'array of type' is converted to an expression that has type 'pointer 459 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 460 // that has type 'array of type' ...". The relevant change is "an lvalue" 461 // (C90) to "an expression" (C99). 462 // 463 // C++ 4.2p1: 464 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 465 // T" can be converted to an rvalue of type "pointer to T". 466 // 467 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 468 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 469 CK_ArrayToPointerDecay).get(); 470 } 471 return E; 472 } 473 474 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 475 // Check to see if we are dereferencing a null pointer. If so, 476 // and if not volatile-qualified, this is undefined behavior that the 477 // optimizer will delete, so warn about it. People sometimes try to use this 478 // to get a deterministic trap and are surprised by clang's behavior. This 479 // only handles the pattern "*null", which is a very syntactic check. 480 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); 481 if (UO && UO->getOpcode() == UO_Deref && 482 UO->getSubExpr()->getType()->isPointerType()) { 483 const LangAS AS = 484 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); 485 if ((!isTargetAddressSpace(AS) || 486 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && 487 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( 488 S.Context, Expr::NPC_ValueDependentIsNotNull) && 489 !UO->getType().isVolatileQualified()) { 490 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 491 S.PDiag(diag::warn_indirection_through_null) 492 << UO->getSubExpr()->getSourceRange()); 493 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 494 S.PDiag(diag::note_indirection_through_null)); 495 } 496 } 497 } 498 499 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 500 SourceLocation AssignLoc, 501 const Expr* RHS) { 502 const ObjCIvarDecl *IV = OIRE->getDecl(); 503 if (!IV) 504 return; 505 506 DeclarationName MemberName = IV->getDeclName(); 507 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 508 if (!Member || !Member->isStr("isa")) 509 return; 510 511 const Expr *Base = OIRE->getBase(); 512 QualType BaseType = Base->getType(); 513 if (OIRE->isArrow()) 514 BaseType = BaseType->getPointeeType(); 515 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 516 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 517 ObjCInterfaceDecl *ClassDeclared = nullptr; 518 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 519 if (!ClassDeclared->getSuperClass() 520 && (*ClassDeclared->ivar_begin()) == IV) { 521 if (RHS) { 522 NamedDecl *ObjectSetClass = 523 S.LookupSingleName(S.TUScope, 524 &S.Context.Idents.get("object_setClass"), 525 SourceLocation(), S.LookupOrdinaryName); 526 if (ObjectSetClass) { 527 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 528 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 529 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 530 "object_setClass(") 531 << FixItHint::CreateReplacement( 532 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 533 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 534 } 535 else 536 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 537 } else { 538 NamedDecl *ObjectGetClass = 539 S.LookupSingleName(S.TUScope, 540 &S.Context.Idents.get("object_getClass"), 541 SourceLocation(), S.LookupOrdinaryName); 542 if (ObjectGetClass) 543 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 544 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 545 "object_getClass(") 546 << FixItHint::CreateReplacement( 547 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 548 else 549 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 550 } 551 S.Diag(IV->getLocation(), diag::note_ivar_decl); 552 } 553 } 554 } 555 556 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 557 // Handle any placeholder expressions which made it here. 558 if (E->getType()->isPlaceholderType()) { 559 ExprResult result = CheckPlaceholderExpr(E); 560 if (result.isInvalid()) return ExprError(); 561 E = result.get(); 562 } 563 564 // C++ [conv.lval]p1: 565 // A glvalue of a non-function, non-array type T can be 566 // converted to a prvalue. 567 if (!E->isGLValue()) return E; 568 569 QualType T = E->getType(); 570 assert(!T.isNull() && "r-value conversion on typeless expression?"); 571 572 // We don't want to throw lvalue-to-rvalue casts on top of 573 // expressions of certain types in C++. 574 if (getLangOpts().CPlusPlus && 575 (E->getType() == Context.OverloadTy || 576 T->isDependentType() || 577 T->isRecordType())) 578 return E; 579 580 // The C standard is actually really unclear on this point, and 581 // DR106 tells us what the result should be but not why. It's 582 // generally best to say that void types just doesn't undergo 583 // lvalue-to-rvalue at all. Note that expressions of unqualified 584 // 'void' type are never l-values, but qualified void can be. 585 if (T->isVoidType()) 586 return E; 587 588 // OpenCL usually rejects direct accesses to values of 'half' type. 589 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 590 T->isHalfType()) { 591 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 592 << 0 << T; 593 return ExprError(); 594 } 595 596 CheckForNullPointerDereference(*this, E); 597 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 598 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 599 &Context.Idents.get("object_getClass"), 600 SourceLocation(), LookupOrdinaryName); 601 if (ObjectGetClass) 602 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 603 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 604 << FixItHint::CreateReplacement( 605 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 606 else 607 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 608 } 609 else if (const ObjCIvarRefExpr *OIRE = 610 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 611 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 612 613 // C++ [conv.lval]p1: 614 // [...] If T is a non-class type, the type of the prvalue is the 615 // cv-unqualified version of T. Otherwise, the type of the 616 // rvalue is T. 617 // 618 // C99 6.3.2.1p2: 619 // If the lvalue has qualified type, the value has the unqualified 620 // version of the type of the lvalue; otherwise, the value has the 621 // type of the lvalue. 622 if (T.hasQualifiers()) 623 T = T.getUnqualifiedType(); 624 625 // Under the MS ABI, lock down the inheritance model now. 626 if (T->isMemberPointerType() && 627 Context.getTargetInfo().getCXXABI().isMicrosoft()) 628 (void)isCompleteType(E->getExprLoc(), T); 629 630 ExprResult Res = CheckLValueToRValueConversionOperand(E); 631 if (Res.isInvalid()) 632 return Res; 633 E = Res.get(); 634 635 // Loading a __weak object implicitly retains the value, so we need a cleanup to 636 // balance that. 637 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 638 Cleanup.setExprNeedsCleanups(true); 639 640 // C++ [conv.lval]p3: 641 // If T is cv std::nullptr_t, the result is a null pointer constant. 642 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; 643 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue); 644 645 // C11 6.3.2.1p2: 646 // ... if the lvalue has atomic type, the value has the non-atomic version 647 // of the type of the lvalue ... 648 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 649 T = Atomic->getValueType().getUnqualifiedType(); 650 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 651 nullptr, VK_RValue); 652 } 653 654 return Res; 655 } 656 657 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 658 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 659 if (Res.isInvalid()) 660 return ExprError(); 661 Res = DefaultLvalueConversion(Res.get()); 662 if (Res.isInvalid()) 663 return ExprError(); 664 return Res; 665 } 666 667 /// CallExprUnaryConversions - a special case of an unary conversion 668 /// performed on a function designator of a call expression. 669 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 670 QualType Ty = E->getType(); 671 ExprResult Res = E; 672 // Only do implicit cast for a function type, but not for a pointer 673 // to function type. 674 if (Ty->isFunctionType()) { 675 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 676 CK_FunctionToPointerDecay).get(); 677 if (Res.isInvalid()) 678 return ExprError(); 679 } 680 Res = DefaultLvalueConversion(Res.get()); 681 if (Res.isInvalid()) 682 return ExprError(); 683 return Res.get(); 684 } 685 686 /// UsualUnaryConversions - Performs various conversions that are common to most 687 /// operators (C99 6.3). The conversions of array and function types are 688 /// sometimes suppressed. For example, the array->pointer conversion doesn't 689 /// apply if the array is an argument to the sizeof or address (&) operators. 690 /// In these instances, this routine should *not* be called. 691 ExprResult Sema::UsualUnaryConversions(Expr *E) { 692 // First, convert to an r-value. 693 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 694 if (Res.isInvalid()) 695 return ExprError(); 696 E = Res.get(); 697 698 QualType Ty = E->getType(); 699 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 700 701 // Half FP have to be promoted to float unless it is natively supported 702 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 703 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 704 705 // Try to perform integral promotions if the object has a theoretically 706 // promotable type. 707 if (Ty->isIntegralOrUnscopedEnumerationType()) { 708 // C99 6.3.1.1p2: 709 // 710 // The following may be used in an expression wherever an int or 711 // unsigned int may be used: 712 // - an object or expression with an integer type whose integer 713 // conversion rank is less than or equal to the rank of int 714 // and unsigned int. 715 // - A bit-field of type _Bool, int, signed int, or unsigned int. 716 // 717 // If an int can represent all values of the original type, the 718 // value is converted to an int; otherwise, it is converted to an 719 // unsigned int. These are called the integer promotions. All 720 // other types are unchanged by the integer promotions. 721 722 QualType PTy = Context.isPromotableBitField(E); 723 if (!PTy.isNull()) { 724 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 725 return E; 726 } 727 if (Ty->isPromotableIntegerType()) { 728 QualType PT = Context.getPromotedIntegerType(Ty); 729 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 730 return E; 731 } 732 } 733 return E; 734 } 735 736 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 737 /// do not have a prototype. Arguments that have type float or __fp16 738 /// are promoted to double. All other argument types are converted by 739 /// UsualUnaryConversions(). 740 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 741 QualType Ty = E->getType(); 742 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 743 744 ExprResult Res = UsualUnaryConversions(E); 745 if (Res.isInvalid()) 746 return ExprError(); 747 E = Res.get(); 748 749 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 750 // promote to double. 751 // Note that default argument promotion applies only to float (and 752 // half/fp16); it does not apply to _Float16. 753 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 754 if (BTy && (BTy->getKind() == BuiltinType::Half || 755 BTy->getKind() == BuiltinType::Float)) { 756 if (getLangOpts().OpenCL && 757 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 758 if (BTy->getKind() == BuiltinType::Half) { 759 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 760 } 761 } else { 762 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 763 } 764 } 765 766 // C++ performs lvalue-to-rvalue conversion as a default argument 767 // promotion, even on class types, but note: 768 // C++11 [conv.lval]p2: 769 // When an lvalue-to-rvalue conversion occurs in an unevaluated 770 // operand or a subexpression thereof the value contained in the 771 // referenced object is not accessed. Otherwise, if the glvalue 772 // has a class type, the conversion copy-initializes a temporary 773 // of type T from the glvalue and the result of the conversion 774 // is a prvalue for the temporary. 775 // FIXME: add some way to gate this entire thing for correctness in 776 // potentially potentially evaluated contexts. 777 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 778 ExprResult Temp = PerformCopyInitialization( 779 InitializedEntity::InitializeTemporary(E->getType()), 780 E->getExprLoc(), E); 781 if (Temp.isInvalid()) 782 return ExprError(); 783 E = Temp.get(); 784 } 785 786 return E; 787 } 788 789 /// Determine the degree of POD-ness for an expression. 790 /// Incomplete types are considered POD, since this check can be performed 791 /// when we're in an unevaluated context. 792 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 793 if (Ty->isIncompleteType()) { 794 // C++11 [expr.call]p7: 795 // After these conversions, if the argument does not have arithmetic, 796 // enumeration, pointer, pointer to member, or class type, the program 797 // is ill-formed. 798 // 799 // Since we've already performed array-to-pointer and function-to-pointer 800 // decay, the only such type in C++ is cv void. This also handles 801 // initializer lists as variadic arguments. 802 if (Ty->isVoidType()) 803 return VAK_Invalid; 804 805 if (Ty->isObjCObjectType()) 806 return VAK_Invalid; 807 return VAK_Valid; 808 } 809 810 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 811 return VAK_Invalid; 812 813 if (Ty.isCXX98PODType(Context)) 814 return VAK_Valid; 815 816 // C++11 [expr.call]p7: 817 // Passing a potentially-evaluated argument of class type (Clause 9) 818 // having a non-trivial copy constructor, a non-trivial move constructor, 819 // or a non-trivial destructor, with no corresponding parameter, 820 // is conditionally-supported with implementation-defined semantics. 821 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 822 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 823 if (!Record->hasNonTrivialCopyConstructor() && 824 !Record->hasNonTrivialMoveConstructor() && 825 !Record->hasNonTrivialDestructor()) 826 return VAK_ValidInCXX11; 827 828 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 829 return VAK_Valid; 830 831 if (Ty->isObjCObjectType()) 832 return VAK_Invalid; 833 834 if (getLangOpts().MSVCCompat) 835 return VAK_MSVCUndefined; 836 837 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 838 // permitted to reject them. We should consider doing so. 839 return VAK_Undefined; 840 } 841 842 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 843 // Don't allow one to pass an Objective-C interface to a vararg. 844 const QualType &Ty = E->getType(); 845 VarArgKind VAK = isValidVarArgType(Ty); 846 847 // Complain about passing non-POD types through varargs. 848 switch (VAK) { 849 case VAK_ValidInCXX11: 850 DiagRuntimeBehavior( 851 E->getBeginLoc(), nullptr, 852 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 853 LLVM_FALLTHROUGH; 854 case VAK_Valid: 855 if (Ty->isRecordType()) { 856 // This is unlikely to be what the user intended. If the class has a 857 // 'c_str' member function, the user probably meant to call that. 858 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 859 PDiag(diag::warn_pass_class_arg_to_vararg) 860 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 861 } 862 break; 863 864 case VAK_Undefined: 865 case VAK_MSVCUndefined: 866 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 867 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 868 << getLangOpts().CPlusPlus11 << Ty << CT); 869 break; 870 871 case VAK_Invalid: 872 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 873 Diag(E->getBeginLoc(), 874 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 875 << Ty << CT; 876 else if (Ty->isObjCObjectType()) 877 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 878 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 879 << Ty << CT); 880 else 881 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 882 << isa<InitListExpr>(E) << Ty << CT; 883 break; 884 } 885 } 886 887 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 888 /// will create a trap if the resulting type is not a POD type. 889 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 890 FunctionDecl *FDecl) { 891 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 892 // Strip the unbridged-cast placeholder expression off, if applicable. 893 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 894 (CT == VariadicMethod || 895 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 896 E = stripARCUnbridgedCast(E); 897 898 // Otherwise, do normal placeholder checking. 899 } else { 900 ExprResult ExprRes = CheckPlaceholderExpr(E); 901 if (ExprRes.isInvalid()) 902 return ExprError(); 903 E = ExprRes.get(); 904 } 905 } 906 907 ExprResult ExprRes = DefaultArgumentPromotion(E); 908 if (ExprRes.isInvalid()) 909 return ExprError(); 910 E = ExprRes.get(); 911 912 // Diagnostics regarding non-POD argument types are 913 // emitted along with format string checking in Sema::CheckFunctionCall(). 914 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 915 // Turn this into a trap. 916 CXXScopeSpec SS; 917 SourceLocation TemplateKWLoc; 918 UnqualifiedId Name; 919 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 920 E->getBeginLoc()); 921 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 922 /*HasTrailingLParen=*/true, 923 /*IsAddressOfOperand=*/false); 924 if (TrapFn.isInvalid()) 925 return ExprError(); 926 927 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 928 None, E->getEndLoc()); 929 if (Call.isInvalid()) 930 return ExprError(); 931 932 ExprResult Comma = 933 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 934 if (Comma.isInvalid()) 935 return ExprError(); 936 return Comma.get(); 937 } 938 939 if (!getLangOpts().CPlusPlus && 940 RequireCompleteType(E->getExprLoc(), E->getType(), 941 diag::err_call_incomplete_argument)) 942 return ExprError(); 943 944 return E; 945 } 946 947 /// Converts an integer to complex float type. Helper function of 948 /// UsualArithmeticConversions() 949 /// 950 /// \return false if the integer expression is an integer type and is 951 /// successfully converted to the complex type. 952 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 953 ExprResult &ComplexExpr, 954 QualType IntTy, 955 QualType ComplexTy, 956 bool SkipCast) { 957 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 958 if (SkipCast) return false; 959 if (IntTy->isIntegerType()) { 960 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 961 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 962 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 963 CK_FloatingRealToComplex); 964 } else { 965 assert(IntTy->isComplexIntegerType()); 966 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 967 CK_IntegralComplexToFloatingComplex); 968 } 969 return false; 970 } 971 972 /// Handle arithmetic conversion with complex types. Helper function of 973 /// UsualArithmeticConversions() 974 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 975 ExprResult &RHS, QualType LHSType, 976 QualType RHSType, 977 bool IsCompAssign) { 978 // if we have an integer operand, the result is the complex type. 979 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 980 /*skipCast*/false)) 981 return LHSType; 982 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 983 /*skipCast*/IsCompAssign)) 984 return RHSType; 985 986 // This handles complex/complex, complex/float, or float/complex. 987 // When both operands are complex, the shorter operand is converted to the 988 // type of the longer, and that is the type of the result. This corresponds 989 // to what is done when combining two real floating-point operands. 990 // The fun begins when size promotion occur across type domains. 991 // From H&S 6.3.4: When one operand is complex and the other is a real 992 // floating-point type, the less precise type is converted, within it's 993 // real or complex domain, to the precision of the other type. For example, 994 // when combining a "long double" with a "double _Complex", the 995 // "double _Complex" is promoted to "long double _Complex". 996 997 // Compute the rank of the two types, regardless of whether they are complex. 998 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 999 1000 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1001 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1002 QualType LHSElementType = 1003 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1004 QualType RHSElementType = 1005 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1006 1007 QualType ResultType = S.Context.getComplexType(LHSElementType); 1008 if (Order < 0) { 1009 // Promote the precision of the LHS if not an assignment. 1010 ResultType = S.Context.getComplexType(RHSElementType); 1011 if (!IsCompAssign) { 1012 if (LHSComplexType) 1013 LHS = 1014 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1015 else 1016 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1017 } 1018 } else if (Order > 0) { 1019 // Promote the precision of the RHS. 1020 if (RHSComplexType) 1021 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1022 else 1023 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1024 } 1025 return ResultType; 1026 } 1027 1028 /// Handle arithmetic conversion from integer to float. Helper function 1029 /// of UsualArithmeticConversions() 1030 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1031 ExprResult &IntExpr, 1032 QualType FloatTy, QualType IntTy, 1033 bool ConvertFloat, bool ConvertInt) { 1034 if (IntTy->isIntegerType()) { 1035 if (ConvertInt) 1036 // Convert intExpr to the lhs floating point type. 1037 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1038 CK_IntegralToFloating); 1039 return FloatTy; 1040 } 1041 1042 // Convert both sides to the appropriate complex float. 1043 assert(IntTy->isComplexIntegerType()); 1044 QualType result = S.Context.getComplexType(FloatTy); 1045 1046 // _Complex int -> _Complex float 1047 if (ConvertInt) 1048 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1049 CK_IntegralComplexToFloatingComplex); 1050 1051 // float -> _Complex float 1052 if (ConvertFloat) 1053 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1054 CK_FloatingRealToComplex); 1055 1056 return result; 1057 } 1058 1059 /// Handle arithmethic conversion with floating point types. Helper 1060 /// function of UsualArithmeticConversions() 1061 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1062 ExprResult &RHS, QualType LHSType, 1063 QualType RHSType, bool IsCompAssign) { 1064 bool LHSFloat = LHSType->isRealFloatingType(); 1065 bool RHSFloat = RHSType->isRealFloatingType(); 1066 1067 // If we have two real floating types, convert the smaller operand 1068 // to the bigger result. 1069 if (LHSFloat && RHSFloat) { 1070 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1071 if (order > 0) { 1072 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1073 return LHSType; 1074 } 1075 1076 assert(order < 0 && "illegal float comparison"); 1077 if (!IsCompAssign) 1078 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1079 return RHSType; 1080 } 1081 1082 if (LHSFloat) { 1083 // Half FP has to be promoted to float unless it is natively supported 1084 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1085 LHSType = S.Context.FloatTy; 1086 1087 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1088 /*ConvertFloat=*/!IsCompAssign, 1089 /*ConvertInt=*/ true); 1090 } 1091 assert(RHSFloat); 1092 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1093 /*convertInt=*/ true, 1094 /*convertFloat=*/!IsCompAssign); 1095 } 1096 1097 /// Diagnose attempts to convert between __float128 and long double if 1098 /// there is no support for such conversion. Helper function of 1099 /// UsualArithmeticConversions(). 1100 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1101 QualType RHSType) { 1102 /* No issue converting if at least one of the types is not a floating point 1103 type or the two types have the same rank. 1104 */ 1105 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1106 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1107 return false; 1108 1109 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1110 "The remaining types must be floating point types."); 1111 1112 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1113 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1114 1115 QualType LHSElemType = LHSComplex ? 1116 LHSComplex->getElementType() : LHSType; 1117 QualType RHSElemType = RHSComplex ? 1118 RHSComplex->getElementType() : RHSType; 1119 1120 // No issue if the two types have the same representation 1121 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1122 &S.Context.getFloatTypeSemantics(RHSElemType)) 1123 return false; 1124 1125 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1126 RHSElemType == S.Context.LongDoubleTy); 1127 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1128 RHSElemType == S.Context.Float128Ty); 1129 1130 // We've handled the situation where __float128 and long double have the same 1131 // representation. We allow all conversions for all possible long double types 1132 // except PPC's double double. 1133 return Float128AndLongDouble && 1134 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1135 &llvm::APFloat::PPCDoubleDouble()); 1136 } 1137 1138 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1139 1140 namespace { 1141 /// These helper callbacks are placed in an anonymous namespace to 1142 /// permit their use as function template parameters. 1143 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1144 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1145 } 1146 1147 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1148 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1149 CK_IntegralComplexCast); 1150 } 1151 } 1152 1153 /// Handle integer arithmetic conversions. Helper function of 1154 /// UsualArithmeticConversions() 1155 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1156 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1157 ExprResult &RHS, QualType LHSType, 1158 QualType RHSType, bool IsCompAssign) { 1159 // The rules for this case are in C99 6.3.1.8 1160 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1161 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1162 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1163 if (LHSSigned == RHSSigned) { 1164 // Same signedness; use the higher-ranked type 1165 if (order >= 0) { 1166 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1167 return LHSType; 1168 } else if (!IsCompAssign) 1169 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1170 return RHSType; 1171 } else if (order != (LHSSigned ? 1 : -1)) { 1172 // The unsigned type has greater than or equal rank to the 1173 // signed type, so use the unsigned type 1174 if (RHSSigned) { 1175 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1176 return LHSType; 1177 } else if (!IsCompAssign) 1178 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1179 return RHSType; 1180 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1181 // The two types are different widths; if we are here, that 1182 // means the signed type is larger than the unsigned type, so 1183 // use the signed type. 1184 if (LHSSigned) { 1185 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1186 return LHSType; 1187 } else if (!IsCompAssign) 1188 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1189 return RHSType; 1190 } else { 1191 // The signed type is higher-ranked than the unsigned type, 1192 // but isn't actually any bigger (like unsigned int and long 1193 // on most 32-bit systems). Use the unsigned type corresponding 1194 // to the signed type. 1195 QualType result = 1196 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1197 RHS = (*doRHSCast)(S, RHS.get(), result); 1198 if (!IsCompAssign) 1199 LHS = (*doLHSCast)(S, LHS.get(), result); 1200 return result; 1201 } 1202 } 1203 1204 /// Handle conversions with GCC complex int extension. Helper function 1205 /// of UsualArithmeticConversions() 1206 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1207 ExprResult &RHS, QualType LHSType, 1208 QualType RHSType, 1209 bool IsCompAssign) { 1210 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1211 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1212 1213 if (LHSComplexInt && RHSComplexInt) { 1214 QualType LHSEltType = LHSComplexInt->getElementType(); 1215 QualType RHSEltType = RHSComplexInt->getElementType(); 1216 QualType ScalarType = 1217 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1218 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1219 1220 return S.Context.getComplexType(ScalarType); 1221 } 1222 1223 if (LHSComplexInt) { 1224 QualType LHSEltType = LHSComplexInt->getElementType(); 1225 QualType ScalarType = 1226 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1227 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1228 QualType ComplexType = S.Context.getComplexType(ScalarType); 1229 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1230 CK_IntegralRealToComplex); 1231 1232 return ComplexType; 1233 } 1234 1235 assert(RHSComplexInt); 1236 1237 QualType RHSEltType = RHSComplexInt->getElementType(); 1238 QualType ScalarType = 1239 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1240 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1241 QualType ComplexType = S.Context.getComplexType(ScalarType); 1242 1243 if (!IsCompAssign) 1244 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1245 CK_IntegralRealToComplex); 1246 return ComplexType; 1247 } 1248 1249 /// Return the rank of a given fixed point or integer type. The value itself 1250 /// doesn't matter, but the values must be increasing with proper increasing 1251 /// rank as described in N1169 4.1.1. 1252 static unsigned GetFixedPointRank(QualType Ty) { 1253 const auto *BTy = Ty->getAs<BuiltinType>(); 1254 assert(BTy && "Expected a builtin type."); 1255 1256 switch (BTy->getKind()) { 1257 case BuiltinType::ShortFract: 1258 case BuiltinType::UShortFract: 1259 case BuiltinType::SatShortFract: 1260 case BuiltinType::SatUShortFract: 1261 return 1; 1262 case BuiltinType::Fract: 1263 case BuiltinType::UFract: 1264 case BuiltinType::SatFract: 1265 case BuiltinType::SatUFract: 1266 return 2; 1267 case BuiltinType::LongFract: 1268 case BuiltinType::ULongFract: 1269 case BuiltinType::SatLongFract: 1270 case BuiltinType::SatULongFract: 1271 return 3; 1272 case BuiltinType::ShortAccum: 1273 case BuiltinType::UShortAccum: 1274 case BuiltinType::SatShortAccum: 1275 case BuiltinType::SatUShortAccum: 1276 return 4; 1277 case BuiltinType::Accum: 1278 case BuiltinType::UAccum: 1279 case BuiltinType::SatAccum: 1280 case BuiltinType::SatUAccum: 1281 return 5; 1282 case BuiltinType::LongAccum: 1283 case BuiltinType::ULongAccum: 1284 case BuiltinType::SatLongAccum: 1285 case BuiltinType::SatULongAccum: 1286 return 6; 1287 default: 1288 if (BTy->isInteger()) 1289 return 0; 1290 llvm_unreachable("Unexpected fixed point or integer type"); 1291 } 1292 } 1293 1294 /// handleFixedPointConversion - Fixed point operations between fixed 1295 /// point types and integers or other fixed point types do not fall under 1296 /// usual arithmetic conversion since these conversions could result in loss 1297 /// of precsision (N1169 4.1.4). These operations should be calculated with 1298 /// the full precision of their result type (N1169 4.1.6.2.1). 1299 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1300 QualType RHSTy) { 1301 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1302 "Expected at least one of the operands to be a fixed point type"); 1303 assert((LHSTy->isFixedPointOrIntegerType() || 1304 RHSTy->isFixedPointOrIntegerType()) && 1305 "Special fixed point arithmetic operation conversions are only " 1306 "applied to ints or other fixed point types"); 1307 1308 // If one operand has signed fixed-point type and the other operand has 1309 // unsigned fixed-point type, then the unsigned fixed-point operand is 1310 // converted to its corresponding signed fixed-point type and the resulting 1311 // type is the type of the converted operand. 1312 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1313 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1314 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1315 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1316 1317 // The result type is the type with the highest rank, whereby a fixed-point 1318 // conversion rank is always greater than an integer conversion rank; if the 1319 // type of either of the operands is a saturating fixedpoint type, the result 1320 // type shall be the saturating fixed-point type corresponding to the type 1321 // with the highest rank; the resulting value is converted (taking into 1322 // account rounding and overflow) to the precision of the resulting type. 1323 // Same ranks between signed and unsigned types are resolved earlier, so both 1324 // types are either signed or both unsigned at this point. 1325 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1326 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1327 1328 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1329 1330 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1331 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1332 1333 return ResultTy; 1334 } 1335 1336 /// UsualArithmeticConversions - Performs various conversions that are common to 1337 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1338 /// routine returns the first non-arithmetic type found. The client is 1339 /// responsible for emitting appropriate error diagnostics. 1340 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1341 bool IsCompAssign) { 1342 if (!IsCompAssign) { 1343 LHS = UsualUnaryConversions(LHS.get()); 1344 if (LHS.isInvalid()) 1345 return QualType(); 1346 } 1347 1348 RHS = UsualUnaryConversions(RHS.get()); 1349 if (RHS.isInvalid()) 1350 return QualType(); 1351 1352 // For conversion purposes, we ignore any qualifiers. 1353 // For example, "const float" and "float" are equivalent. 1354 QualType LHSType = 1355 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1356 QualType RHSType = 1357 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1358 1359 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1360 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1361 LHSType = AtomicLHS->getValueType(); 1362 1363 // If both types are identical, no conversion is needed. 1364 if (LHSType == RHSType) 1365 return LHSType; 1366 1367 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1368 // The caller can deal with this (e.g. pointer + int). 1369 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1370 return QualType(); 1371 1372 // Apply unary and bitfield promotions to the LHS's type. 1373 QualType LHSUnpromotedType = LHSType; 1374 if (LHSType->isPromotableIntegerType()) 1375 LHSType = Context.getPromotedIntegerType(LHSType); 1376 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1377 if (!LHSBitfieldPromoteTy.isNull()) 1378 LHSType = LHSBitfieldPromoteTy; 1379 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1380 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1381 1382 // If both types are identical, no conversion is needed. 1383 if (LHSType == RHSType) 1384 return LHSType; 1385 1386 // At this point, we have two different arithmetic types. 1387 1388 // Diagnose attempts to convert between __float128 and long double where 1389 // such conversions currently can't be handled. 1390 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1391 return QualType(); 1392 1393 // Handle complex types first (C99 6.3.1.8p1). 1394 if (LHSType->isComplexType() || RHSType->isComplexType()) 1395 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1396 IsCompAssign); 1397 1398 // Now handle "real" floating types (i.e. float, double, long double). 1399 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1400 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1401 IsCompAssign); 1402 1403 // Handle GCC complex int extension. 1404 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1405 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1406 IsCompAssign); 1407 1408 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1409 return handleFixedPointConversion(*this, LHSType, RHSType); 1410 1411 // Finally, we have two differing integer types. 1412 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1413 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1414 } 1415 1416 //===----------------------------------------------------------------------===// 1417 // Semantic Analysis for various Expression Types 1418 //===----------------------------------------------------------------------===// 1419 1420 1421 ExprResult 1422 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1423 SourceLocation DefaultLoc, 1424 SourceLocation RParenLoc, 1425 Expr *ControllingExpr, 1426 ArrayRef<ParsedType> ArgTypes, 1427 ArrayRef<Expr *> ArgExprs) { 1428 unsigned NumAssocs = ArgTypes.size(); 1429 assert(NumAssocs == ArgExprs.size()); 1430 1431 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1432 for (unsigned i = 0; i < NumAssocs; ++i) { 1433 if (ArgTypes[i]) 1434 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1435 else 1436 Types[i] = nullptr; 1437 } 1438 1439 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1440 ControllingExpr, 1441 llvm::makeArrayRef(Types, NumAssocs), 1442 ArgExprs); 1443 delete [] Types; 1444 return ER; 1445 } 1446 1447 ExprResult 1448 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1449 SourceLocation DefaultLoc, 1450 SourceLocation RParenLoc, 1451 Expr *ControllingExpr, 1452 ArrayRef<TypeSourceInfo *> Types, 1453 ArrayRef<Expr *> Exprs) { 1454 unsigned NumAssocs = Types.size(); 1455 assert(NumAssocs == Exprs.size()); 1456 1457 // Decay and strip qualifiers for the controlling expression type, and handle 1458 // placeholder type replacement. See committee discussion from WG14 DR423. 1459 { 1460 EnterExpressionEvaluationContext Unevaluated( 1461 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1462 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1463 if (R.isInvalid()) 1464 return ExprError(); 1465 ControllingExpr = R.get(); 1466 } 1467 1468 // The controlling expression is an unevaluated operand, so side effects are 1469 // likely unintended. 1470 if (!inTemplateInstantiation() && 1471 ControllingExpr->HasSideEffects(Context, false)) 1472 Diag(ControllingExpr->getExprLoc(), 1473 diag::warn_side_effects_unevaluated_context); 1474 1475 bool TypeErrorFound = false, 1476 IsResultDependent = ControllingExpr->isTypeDependent(), 1477 ContainsUnexpandedParameterPack 1478 = ControllingExpr->containsUnexpandedParameterPack(); 1479 1480 for (unsigned i = 0; i < NumAssocs; ++i) { 1481 if (Exprs[i]->containsUnexpandedParameterPack()) 1482 ContainsUnexpandedParameterPack = true; 1483 1484 if (Types[i]) { 1485 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1486 ContainsUnexpandedParameterPack = true; 1487 1488 if (Types[i]->getType()->isDependentType()) { 1489 IsResultDependent = true; 1490 } else { 1491 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1492 // complete object type other than a variably modified type." 1493 unsigned D = 0; 1494 if (Types[i]->getType()->isIncompleteType()) 1495 D = diag::err_assoc_type_incomplete; 1496 else if (!Types[i]->getType()->isObjectType()) 1497 D = diag::err_assoc_type_nonobject; 1498 else if (Types[i]->getType()->isVariablyModifiedType()) 1499 D = diag::err_assoc_type_variably_modified; 1500 1501 if (D != 0) { 1502 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1503 << Types[i]->getTypeLoc().getSourceRange() 1504 << Types[i]->getType(); 1505 TypeErrorFound = true; 1506 } 1507 1508 // C11 6.5.1.1p2 "No two generic associations in the same generic 1509 // selection shall specify compatible types." 1510 for (unsigned j = i+1; j < NumAssocs; ++j) 1511 if (Types[j] && !Types[j]->getType()->isDependentType() && 1512 Context.typesAreCompatible(Types[i]->getType(), 1513 Types[j]->getType())) { 1514 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1515 diag::err_assoc_compatible_types) 1516 << Types[j]->getTypeLoc().getSourceRange() 1517 << Types[j]->getType() 1518 << Types[i]->getType(); 1519 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1520 diag::note_compat_assoc) 1521 << Types[i]->getTypeLoc().getSourceRange() 1522 << Types[i]->getType(); 1523 TypeErrorFound = true; 1524 } 1525 } 1526 } 1527 } 1528 if (TypeErrorFound) 1529 return ExprError(); 1530 1531 // If we determined that the generic selection is result-dependent, don't 1532 // try to compute the result expression. 1533 if (IsResultDependent) 1534 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1535 Exprs, DefaultLoc, RParenLoc, 1536 ContainsUnexpandedParameterPack); 1537 1538 SmallVector<unsigned, 1> CompatIndices; 1539 unsigned DefaultIndex = -1U; 1540 for (unsigned i = 0; i < NumAssocs; ++i) { 1541 if (!Types[i]) 1542 DefaultIndex = i; 1543 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1544 Types[i]->getType())) 1545 CompatIndices.push_back(i); 1546 } 1547 1548 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1549 // type compatible with at most one of the types named in its generic 1550 // association list." 1551 if (CompatIndices.size() > 1) { 1552 // We strip parens here because the controlling expression is typically 1553 // parenthesized in macro definitions. 1554 ControllingExpr = ControllingExpr->IgnoreParens(); 1555 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1556 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1557 << (unsigned)CompatIndices.size(); 1558 for (unsigned I : CompatIndices) { 1559 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1560 diag::note_compat_assoc) 1561 << Types[I]->getTypeLoc().getSourceRange() 1562 << Types[I]->getType(); 1563 } 1564 return ExprError(); 1565 } 1566 1567 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1568 // its controlling expression shall have type compatible with exactly one of 1569 // the types named in its generic association list." 1570 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1571 // We strip parens here because the controlling expression is typically 1572 // parenthesized in macro definitions. 1573 ControllingExpr = ControllingExpr->IgnoreParens(); 1574 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1575 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1576 return ExprError(); 1577 } 1578 1579 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1580 // type name that is compatible with the type of the controlling expression, 1581 // then the result expression of the generic selection is the expression 1582 // in that generic association. Otherwise, the result expression of the 1583 // generic selection is the expression in the default generic association." 1584 unsigned ResultIndex = 1585 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1586 1587 return GenericSelectionExpr::Create( 1588 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1589 ContainsUnexpandedParameterPack, ResultIndex); 1590 } 1591 1592 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1593 /// location of the token and the offset of the ud-suffix within it. 1594 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1595 unsigned Offset) { 1596 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1597 S.getLangOpts()); 1598 } 1599 1600 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1601 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1602 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1603 IdentifierInfo *UDSuffix, 1604 SourceLocation UDSuffixLoc, 1605 ArrayRef<Expr*> Args, 1606 SourceLocation LitEndLoc) { 1607 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1608 1609 QualType ArgTy[2]; 1610 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1611 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1612 if (ArgTy[ArgIdx]->isArrayType()) 1613 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1614 } 1615 1616 DeclarationName OpName = 1617 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1618 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1619 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1620 1621 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1622 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1623 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1624 /*AllowStringTemplate*/ false, 1625 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1626 return ExprError(); 1627 1628 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1629 } 1630 1631 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1632 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1633 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1634 /// multiple tokens. However, the common case is that StringToks points to one 1635 /// string. 1636 /// 1637 ExprResult 1638 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1639 assert(!StringToks.empty() && "Must have at least one string!"); 1640 1641 StringLiteralParser Literal(StringToks, PP); 1642 if (Literal.hadError) 1643 return ExprError(); 1644 1645 SmallVector<SourceLocation, 4> StringTokLocs; 1646 for (const Token &Tok : StringToks) 1647 StringTokLocs.push_back(Tok.getLocation()); 1648 1649 QualType CharTy = Context.CharTy; 1650 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1651 if (Literal.isWide()) { 1652 CharTy = Context.getWideCharType(); 1653 Kind = StringLiteral::Wide; 1654 } else if (Literal.isUTF8()) { 1655 if (getLangOpts().Char8) 1656 CharTy = Context.Char8Ty; 1657 Kind = StringLiteral::UTF8; 1658 } else if (Literal.isUTF16()) { 1659 CharTy = Context.Char16Ty; 1660 Kind = StringLiteral::UTF16; 1661 } else if (Literal.isUTF32()) { 1662 CharTy = Context.Char32Ty; 1663 Kind = StringLiteral::UTF32; 1664 } else if (Literal.isPascal()) { 1665 CharTy = Context.UnsignedCharTy; 1666 } 1667 1668 // Warn on initializing an array of char from a u8 string literal; this 1669 // becomes ill-formed in C++2a. 1670 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus2a && 1671 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1672 Diag(StringTokLocs.front(), diag::warn_cxx2a_compat_utf8_string); 1673 1674 // Create removals for all 'u8' prefixes in the string literal(s). This 1675 // ensures C++2a compatibility (but may change the program behavior when 1676 // built by non-Clang compilers for which the execution character set is 1677 // not always UTF-8). 1678 auto RemovalDiag = PDiag(diag::note_cxx2a_compat_utf8_string_remove_u8); 1679 SourceLocation RemovalDiagLoc; 1680 for (const Token &Tok : StringToks) { 1681 if (Tok.getKind() == tok::utf8_string_literal) { 1682 if (RemovalDiagLoc.isInvalid()) 1683 RemovalDiagLoc = Tok.getLocation(); 1684 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1685 Tok.getLocation(), 1686 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1687 getSourceManager(), getLangOpts()))); 1688 } 1689 } 1690 Diag(RemovalDiagLoc, RemovalDiag); 1691 } 1692 1693 QualType StrTy = 1694 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); 1695 1696 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1697 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1698 Kind, Literal.Pascal, StrTy, 1699 &StringTokLocs[0], 1700 StringTokLocs.size()); 1701 if (Literal.getUDSuffix().empty()) 1702 return Lit; 1703 1704 // We're building a user-defined literal. 1705 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1706 SourceLocation UDSuffixLoc = 1707 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1708 Literal.getUDSuffixOffset()); 1709 1710 // Make sure we're allowed user-defined literals here. 1711 if (!UDLScope) 1712 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1713 1714 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1715 // operator "" X (str, len) 1716 QualType SizeType = Context.getSizeType(); 1717 1718 DeclarationName OpName = 1719 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1720 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1721 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1722 1723 QualType ArgTy[] = { 1724 Context.getArrayDecayedType(StrTy), SizeType 1725 }; 1726 1727 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1728 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1729 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1730 /*AllowStringTemplate*/ true, 1731 /*DiagnoseMissing*/ true)) { 1732 1733 case LOLR_Cooked: { 1734 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1735 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1736 StringTokLocs[0]); 1737 Expr *Args[] = { Lit, LenArg }; 1738 1739 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1740 } 1741 1742 case LOLR_StringTemplate: { 1743 TemplateArgumentListInfo ExplicitArgs; 1744 1745 unsigned CharBits = Context.getIntWidth(CharTy); 1746 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1747 llvm::APSInt Value(CharBits, CharIsUnsigned); 1748 1749 TemplateArgument TypeArg(CharTy); 1750 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1751 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1752 1753 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1754 Value = Lit->getCodeUnit(I); 1755 TemplateArgument Arg(Context, Value, CharTy); 1756 TemplateArgumentLocInfo ArgInfo; 1757 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1758 } 1759 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1760 &ExplicitArgs); 1761 } 1762 case LOLR_Raw: 1763 case LOLR_Template: 1764 case LOLR_ErrorNoDiagnostic: 1765 llvm_unreachable("unexpected literal operator lookup result"); 1766 case LOLR_Error: 1767 return ExprError(); 1768 } 1769 llvm_unreachable("unexpected literal operator lookup result"); 1770 } 1771 1772 DeclRefExpr * 1773 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1774 SourceLocation Loc, 1775 const CXXScopeSpec *SS) { 1776 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1777 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1778 } 1779 1780 DeclRefExpr * 1781 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1782 const DeclarationNameInfo &NameInfo, 1783 const CXXScopeSpec *SS, NamedDecl *FoundD, 1784 SourceLocation TemplateKWLoc, 1785 const TemplateArgumentListInfo *TemplateArgs) { 1786 NestedNameSpecifierLoc NNS = 1787 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); 1788 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, 1789 TemplateArgs); 1790 } 1791 1792 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { 1793 // A declaration named in an unevaluated operand never constitutes an odr-use. 1794 if (isUnevaluatedContext()) 1795 return NOUR_Unevaluated; 1796 1797 // C++2a [basic.def.odr]p4: 1798 // A variable x whose name appears as a potentially-evaluated expression e 1799 // is odr-used by e unless [...] x is a reference that is usable in 1800 // constant expressions. 1801 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 1802 if (VD->getType()->isReferenceType() && 1803 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && 1804 VD->isUsableInConstantExpressions(Context)) 1805 return NOUR_Constant; 1806 } 1807 1808 // All remaining non-variable cases constitute an odr-use. For variables, we 1809 // need to wait and see how the expression is used. 1810 return NOUR_None; 1811 } 1812 1813 /// BuildDeclRefExpr - Build an expression that references a 1814 /// declaration that does not require a closure capture. 1815 DeclRefExpr * 1816 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1817 const DeclarationNameInfo &NameInfo, 1818 NestedNameSpecifierLoc NNS, NamedDecl *FoundD, 1819 SourceLocation TemplateKWLoc, 1820 const TemplateArgumentListInfo *TemplateArgs) { 1821 bool RefersToCapturedVariable = 1822 isa<VarDecl>(D) && 1823 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1824 1825 DeclRefExpr *E = DeclRefExpr::Create( 1826 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, 1827 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); 1828 MarkDeclRefReferenced(E); 1829 1830 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1831 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 1832 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 1833 getCurFunction()->recordUseOfWeak(E); 1834 1835 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1836 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 1837 FD = IFD->getAnonField(); 1838 if (FD) { 1839 UnusedPrivateFields.remove(FD); 1840 // Just in case we're building an illegal pointer-to-member. 1841 if (FD->isBitField()) 1842 E->setObjectKind(OK_BitField); 1843 } 1844 1845 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1846 // designates a bit-field. 1847 if (auto *BD = dyn_cast<BindingDecl>(D)) 1848 if (auto *BE = BD->getBinding()) 1849 E->setObjectKind(BE->getObjectKind()); 1850 1851 return E; 1852 } 1853 1854 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1855 /// possibly a list of template arguments. 1856 /// 1857 /// If this produces template arguments, it is permitted to call 1858 /// DecomposeTemplateName. 1859 /// 1860 /// This actually loses a lot of source location information for 1861 /// non-standard name kinds; we should consider preserving that in 1862 /// some way. 1863 void 1864 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1865 TemplateArgumentListInfo &Buffer, 1866 DeclarationNameInfo &NameInfo, 1867 const TemplateArgumentListInfo *&TemplateArgs) { 1868 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 1869 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1870 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1871 1872 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1873 Id.TemplateId->NumArgs); 1874 translateTemplateArguments(TemplateArgsPtr, Buffer); 1875 1876 TemplateName TName = Id.TemplateId->Template.get(); 1877 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1878 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1879 TemplateArgs = &Buffer; 1880 } else { 1881 NameInfo = GetNameFromUnqualifiedId(Id); 1882 TemplateArgs = nullptr; 1883 } 1884 } 1885 1886 static void emitEmptyLookupTypoDiagnostic( 1887 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1888 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1889 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1890 DeclContext *Ctx = 1891 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1892 if (!TC) { 1893 // Emit a special diagnostic for failed member lookups. 1894 // FIXME: computing the declaration context might fail here (?) 1895 if (Ctx) 1896 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1897 << SS.getRange(); 1898 else 1899 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1900 return; 1901 } 1902 1903 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1904 bool DroppedSpecifier = 1905 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1906 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1907 ? diag::note_implicit_param_decl 1908 : diag::note_previous_decl; 1909 if (!Ctx) 1910 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1911 SemaRef.PDiag(NoteID)); 1912 else 1913 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1914 << Typo << Ctx << DroppedSpecifier 1915 << SS.getRange(), 1916 SemaRef.PDiag(NoteID)); 1917 } 1918 1919 /// Diagnose an empty lookup. 1920 /// 1921 /// \return false if new lookup candidates were found 1922 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1923 CorrectionCandidateCallback &CCC, 1924 TemplateArgumentListInfo *ExplicitTemplateArgs, 1925 ArrayRef<Expr *> Args, TypoExpr **Out) { 1926 DeclarationName Name = R.getLookupName(); 1927 1928 unsigned diagnostic = diag::err_undeclared_var_use; 1929 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1930 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1931 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1932 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1933 diagnostic = diag::err_undeclared_use; 1934 diagnostic_suggest = diag::err_undeclared_use_suggest; 1935 } 1936 1937 // If the original lookup was an unqualified lookup, fake an 1938 // unqualified lookup. This is useful when (for example) the 1939 // original lookup would not have found something because it was a 1940 // dependent name. 1941 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1942 while (DC) { 1943 if (isa<CXXRecordDecl>(DC)) { 1944 LookupQualifiedName(R, DC); 1945 1946 if (!R.empty()) { 1947 // Don't give errors about ambiguities in this lookup. 1948 R.suppressDiagnostics(); 1949 1950 // During a default argument instantiation the CurContext points 1951 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1952 // function parameter list, hence add an explicit check. 1953 bool isDefaultArgument = 1954 !CodeSynthesisContexts.empty() && 1955 CodeSynthesisContexts.back().Kind == 1956 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 1957 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1958 bool isInstance = CurMethod && 1959 CurMethod->isInstance() && 1960 DC == CurMethod->getParent() && !isDefaultArgument; 1961 1962 // Give a code modification hint to insert 'this->'. 1963 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1964 // Actually quite difficult! 1965 if (getLangOpts().MSVCCompat) 1966 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1967 if (isInstance) { 1968 Diag(R.getNameLoc(), diagnostic) << Name 1969 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1970 CheckCXXThisCapture(R.getNameLoc()); 1971 } else { 1972 Diag(R.getNameLoc(), diagnostic) << Name; 1973 } 1974 1975 // Do we really want to note all of these? 1976 for (NamedDecl *D : R) 1977 Diag(D->getLocation(), diag::note_dependent_var_use); 1978 1979 // Return true if we are inside a default argument instantiation 1980 // and the found name refers to an instance member function, otherwise 1981 // the function calling DiagnoseEmptyLookup will try to create an 1982 // implicit member call and this is wrong for default argument. 1983 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1984 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1985 return true; 1986 } 1987 1988 // Tell the callee to try to recover. 1989 return false; 1990 } 1991 1992 R.clear(); 1993 } 1994 1995 DC = DC->getLookupParent(); 1996 } 1997 1998 // We didn't find anything, so try to correct for a typo. 1999 TypoCorrection Corrected; 2000 if (S && Out) { 2001 SourceLocation TypoLoc = R.getNameLoc(); 2002 assert(!ExplicitTemplateArgs && 2003 "Diagnosing an empty lookup with explicit template args!"); 2004 *Out = CorrectTypoDelayed( 2005 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 2006 [=](const TypoCorrection &TC) { 2007 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2008 diagnostic, diagnostic_suggest); 2009 }, 2010 nullptr, CTK_ErrorRecovery); 2011 if (*Out) 2012 return true; 2013 } else if (S && 2014 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 2015 S, &SS, CCC, CTK_ErrorRecovery))) { 2016 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2017 bool DroppedSpecifier = 2018 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2019 R.setLookupName(Corrected.getCorrection()); 2020 2021 bool AcceptableWithRecovery = false; 2022 bool AcceptableWithoutRecovery = false; 2023 NamedDecl *ND = Corrected.getFoundDecl(); 2024 if (ND) { 2025 if (Corrected.isOverloaded()) { 2026 OverloadCandidateSet OCS(R.getNameLoc(), 2027 OverloadCandidateSet::CSK_Normal); 2028 OverloadCandidateSet::iterator Best; 2029 for (NamedDecl *CD : Corrected) { 2030 if (FunctionTemplateDecl *FTD = 2031 dyn_cast<FunctionTemplateDecl>(CD)) 2032 AddTemplateOverloadCandidate( 2033 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2034 Args, OCS); 2035 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2036 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2037 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2038 Args, OCS); 2039 } 2040 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2041 case OR_Success: 2042 ND = Best->FoundDecl; 2043 Corrected.setCorrectionDecl(ND); 2044 break; 2045 default: 2046 // FIXME: Arbitrarily pick the first declaration for the note. 2047 Corrected.setCorrectionDecl(ND); 2048 break; 2049 } 2050 } 2051 R.addDecl(ND); 2052 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2053 CXXRecordDecl *Record = nullptr; 2054 if (Corrected.getCorrectionSpecifier()) { 2055 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2056 Record = Ty->getAsCXXRecordDecl(); 2057 } 2058 if (!Record) 2059 Record = cast<CXXRecordDecl>( 2060 ND->getDeclContext()->getRedeclContext()); 2061 R.setNamingClass(Record); 2062 } 2063 2064 auto *UnderlyingND = ND->getUnderlyingDecl(); 2065 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2066 isa<FunctionTemplateDecl>(UnderlyingND); 2067 // FIXME: If we ended up with a typo for a type name or 2068 // Objective-C class name, we're in trouble because the parser 2069 // is in the wrong place to recover. Suggest the typo 2070 // correction, but don't make it a fix-it since we're not going 2071 // to recover well anyway. 2072 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || 2073 getAsTypeTemplateDecl(UnderlyingND) || 2074 isa<ObjCInterfaceDecl>(UnderlyingND); 2075 } else { 2076 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2077 // because we aren't able to recover. 2078 AcceptableWithoutRecovery = true; 2079 } 2080 2081 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2082 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2083 ? diag::note_implicit_param_decl 2084 : diag::note_previous_decl; 2085 if (SS.isEmpty()) 2086 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2087 PDiag(NoteID), AcceptableWithRecovery); 2088 else 2089 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2090 << Name << computeDeclContext(SS, false) 2091 << DroppedSpecifier << SS.getRange(), 2092 PDiag(NoteID), AcceptableWithRecovery); 2093 2094 // Tell the callee whether to try to recover. 2095 return !AcceptableWithRecovery; 2096 } 2097 } 2098 R.clear(); 2099 2100 // Emit a special diagnostic for failed member lookups. 2101 // FIXME: computing the declaration context might fail here (?) 2102 if (!SS.isEmpty()) { 2103 Diag(R.getNameLoc(), diag::err_no_member) 2104 << Name << computeDeclContext(SS, false) 2105 << SS.getRange(); 2106 return true; 2107 } 2108 2109 // Give up, we can't recover. 2110 Diag(R.getNameLoc(), diagnostic) << Name; 2111 return true; 2112 } 2113 2114 /// In Microsoft mode, if we are inside a template class whose parent class has 2115 /// dependent base classes, and we can't resolve an unqualified identifier, then 2116 /// assume the identifier is a member of a dependent base class. We can only 2117 /// recover successfully in static methods, instance methods, and other contexts 2118 /// where 'this' is available. This doesn't precisely match MSVC's 2119 /// instantiation model, but it's close enough. 2120 static Expr * 2121 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2122 DeclarationNameInfo &NameInfo, 2123 SourceLocation TemplateKWLoc, 2124 const TemplateArgumentListInfo *TemplateArgs) { 2125 // Only try to recover from lookup into dependent bases in static methods or 2126 // contexts where 'this' is available. 2127 QualType ThisType = S.getCurrentThisType(); 2128 const CXXRecordDecl *RD = nullptr; 2129 if (!ThisType.isNull()) 2130 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2131 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2132 RD = MD->getParent(); 2133 if (!RD || !RD->hasAnyDependentBases()) 2134 return nullptr; 2135 2136 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2137 // is available, suggest inserting 'this->' as a fixit. 2138 SourceLocation Loc = NameInfo.getLoc(); 2139 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2140 DB << NameInfo.getName() << RD; 2141 2142 if (!ThisType.isNull()) { 2143 DB << FixItHint::CreateInsertion(Loc, "this->"); 2144 return CXXDependentScopeMemberExpr::Create( 2145 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2146 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2147 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); 2148 } 2149 2150 // Synthesize a fake NNS that points to the derived class. This will 2151 // perform name lookup during template instantiation. 2152 CXXScopeSpec SS; 2153 auto *NNS = 2154 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2155 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2156 return DependentScopeDeclRefExpr::Create( 2157 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2158 TemplateArgs); 2159 } 2160 2161 ExprResult 2162 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2163 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2164 bool HasTrailingLParen, bool IsAddressOfOperand, 2165 CorrectionCandidateCallback *CCC, 2166 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2167 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2168 "cannot be direct & operand and have a trailing lparen"); 2169 if (SS.isInvalid()) 2170 return ExprError(); 2171 2172 TemplateArgumentListInfo TemplateArgsBuffer; 2173 2174 // Decompose the UnqualifiedId into the following data. 2175 DeclarationNameInfo NameInfo; 2176 const TemplateArgumentListInfo *TemplateArgs; 2177 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2178 2179 DeclarationName Name = NameInfo.getName(); 2180 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2181 SourceLocation NameLoc = NameInfo.getLoc(); 2182 2183 if (II && II->isEditorPlaceholder()) { 2184 // FIXME: When typed placeholders are supported we can create a typed 2185 // placeholder expression node. 2186 return ExprError(); 2187 } 2188 2189 // C++ [temp.dep.expr]p3: 2190 // An id-expression is type-dependent if it contains: 2191 // -- an identifier that was declared with a dependent type, 2192 // (note: handled after lookup) 2193 // -- a template-id that is dependent, 2194 // (note: handled in BuildTemplateIdExpr) 2195 // -- a conversion-function-id that specifies a dependent type, 2196 // -- a nested-name-specifier that contains a class-name that 2197 // names a dependent type. 2198 // Determine whether this is a member of an unknown specialization; 2199 // we need to handle these differently. 2200 bool DependentID = false; 2201 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2202 Name.getCXXNameType()->isDependentType()) { 2203 DependentID = true; 2204 } else if (SS.isSet()) { 2205 if (DeclContext *DC = computeDeclContext(SS, false)) { 2206 if (RequireCompleteDeclContext(SS, DC)) 2207 return ExprError(); 2208 } else { 2209 DependentID = true; 2210 } 2211 } 2212 2213 if (DependentID) 2214 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2215 IsAddressOfOperand, TemplateArgs); 2216 2217 // Perform the required lookup. 2218 LookupResult R(*this, NameInfo, 2219 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2220 ? LookupObjCImplicitSelfParam 2221 : LookupOrdinaryName); 2222 if (TemplateKWLoc.isValid() || TemplateArgs) { 2223 // Lookup the template name again to correctly establish the context in 2224 // which it was found. This is really unfortunate as we already did the 2225 // lookup to determine that it was a template name in the first place. If 2226 // this becomes a performance hit, we can work harder to preserve those 2227 // results until we get here but it's likely not worth it. 2228 bool MemberOfUnknownSpecialization; 2229 AssumedTemplateKind AssumedTemplate; 2230 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2231 MemberOfUnknownSpecialization, TemplateKWLoc, 2232 &AssumedTemplate)) 2233 return ExprError(); 2234 2235 if (MemberOfUnknownSpecialization || 2236 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2237 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2238 IsAddressOfOperand, TemplateArgs); 2239 } else { 2240 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2241 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2242 2243 // If the result might be in a dependent base class, this is a dependent 2244 // id-expression. 2245 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2246 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2247 IsAddressOfOperand, TemplateArgs); 2248 2249 // If this reference is in an Objective-C method, then we need to do 2250 // some special Objective-C lookup, too. 2251 if (IvarLookupFollowUp) { 2252 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2253 if (E.isInvalid()) 2254 return ExprError(); 2255 2256 if (Expr *Ex = E.getAs<Expr>()) 2257 return Ex; 2258 } 2259 } 2260 2261 if (R.isAmbiguous()) 2262 return ExprError(); 2263 2264 // This could be an implicitly declared function reference (legal in C90, 2265 // extension in C99, forbidden in C++). 2266 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2267 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2268 if (D) R.addDecl(D); 2269 } 2270 2271 // Determine whether this name might be a candidate for 2272 // argument-dependent lookup. 2273 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2274 2275 if (R.empty() && !ADL) { 2276 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2277 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2278 TemplateKWLoc, TemplateArgs)) 2279 return E; 2280 } 2281 2282 // Don't diagnose an empty lookup for inline assembly. 2283 if (IsInlineAsmIdentifier) 2284 return ExprError(); 2285 2286 // If this name wasn't predeclared and if this is not a function 2287 // call, diagnose the problem. 2288 TypoExpr *TE = nullptr; 2289 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2290 : nullptr); 2291 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2292 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2293 "Typo correction callback misconfigured"); 2294 if (CCC) { 2295 // Make sure the callback knows what the typo being diagnosed is. 2296 CCC->setTypoName(II); 2297 if (SS.isValid()) 2298 CCC->setTypoNNS(SS.getScopeRep()); 2299 } 2300 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2301 // a template name, but we happen to have always already looked up the name 2302 // before we get here if it must be a template name. 2303 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2304 None, &TE)) { 2305 if (TE && KeywordReplacement) { 2306 auto &State = getTypoExprState(TE); 2307 auto BestTC = State.Consumer->getNextCorrection(); 2308 if (BestTC.isKeyword()) { 2309 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2310 if (State.DiagHandler) 2311 State.DiagHandler(BestTC); 2312 KeywordReplacement->startToken(); 2313 KeywordReplacement->setKind(II->getTokenID()); 2314 KeywordReplacement->setIdentifierInfo(II); 2315 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2316 // Clean up the state associated with the TypoExpr, since it has 2317 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2318 clearDelayedTypo(TE); 2319 // Signal that a correction to a keyword was performed by returning a 2320 // valid-but-null ExprResult. 2321 return (Expr*)nullptr; 2322 } 2323 State.Consumer->resetCorrectionStream(); 2324 } 2325 return TE ? TE : ExprError(); 2326 } 2327 2328 assert(!R.empty() && 2329 "DiagnoseEmptyLookup returned false but added no results"); 2330 2331 // If we found an Objective-C instance variable, let 2332 // LookupInObjCMethod build the appropriate expression to 2333 // reference the ivar. 2334 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2335 R.clear(); 2336 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2337 // In a hopelessly buggy code, Objective-C instance variable 2338 // lookup fails and no expression will be built to reference it. 2339 if (!E.isInvalid() && !E.get()) 2340 return ExprError(); 2341 return E; 2342 } 2343 } 2344 2345 // This is guaranteed from this point on. 2346 assert(!R.empty() || ADL); 2347 2348 // Check whether this might be a C++ implicit instance member access. 2349 // C++ [class.mfct.non-static]p3: 2350 // When an id-expression that is not part of a class member access 2351 // syntax and not used to form a pointer to member is used in the 2352 // body of a non-static member function of class X, if name lookup 2353 // resolves the name in the id-expression to a non-static non-type 2354 // member of some class C, the id-expression is transformed into a 2355 // class member access expression using (*this) as the 2356 // postfix-expression to the left of the . operator. 2357 // 2358 // But we don't actually need to do this for '&' operands if R 2359 // resolved to a function or overloaded function set, because the 2360 // expression is ill-formed if it actually works out to be a 2361 // non-static member function: 2362 // 2363 // C++ [expr.ref]p4: 2364 // Otherwise, if E1.E2 refers to a non-static member function. . . 2365 // [t]he expression can be used only as the left-hand operand of a 2366 // member function call. 2367 // 2368 // There are other safeguards against such uses, but it's important 2369 // to get this right here so that we don't end up making a 2370 // spuriously dependent expression if we're inside a dependent 2371 // instance method. 2372 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2373 bool MightBeImplicitMember; 2374 if (!IsAddressOfOperand) 2375 MightBeImplicitMember = true; 2376 else if (!SS.isEmpty()) 2377 MightBeImplicitMember = false; 2378 else if (R.isOverloadedResult()) 2379 MightBeImplicitMember = false; 2380 else if (R.isUnresolvableResult()) 2381 MightBeImplicitMember = true; 2382 else 2383 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2384 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2385 isa<MSPropertyDecl>(R.getFoundDecl()); 2386 2387 if (MightBeImplicitMember) 2388 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2389 R, TemplateArgs, S); 2390 } 2391 2392 if (TemplateArgs || TemplateKWLoc.isValid()) { 2393 2394 // In C++1y, if this is a variable template id, then check it 2395 // in BuildTemplateIdExpr(). 2396 // The single lookup result must be a variable template declaration. 2397 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2398 Id.TemplateId->Kind == TNK_Var_template) { 2399 assert(R.getAsSingle<VarTemplateDecl>() && 2400 "There should only be one declaration found."); 2401 } 2402 2403 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2404 } 2405 2406 return BuildDeclarationNameExpr(SS, R, ADL); 2407 } 2408 2409 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2410 /// declaration name, generally during template instantiation. 2411 /// There's a large number of things which don't need to be done along 2412 /// this path. 2413 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2414 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2415 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2416 DeclContext *DC = computeDeclContext(SS, false); 2417 if (!DC) 2418 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2419 NameInfo, /*TemplateArgs=*/nullptr); 2420 2421 if (RequireCompleteDeclContext(SS, DC)) 2422 return ExprError(); 2423 2424 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2425 LookupQualifiedName(R, DC); 2426 2427 if (R.isAmbiguous()) 2428 return ExprError(); 2429 2430 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2431 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2432 NameInfo, /*TemplateArgs=*/nullptr); 2433 2434 if (R.empty()) { 2435 Diag(NameInfo.getLoc(), diag::err_no_member) 2436 << NameInfo.getName() << DC << SS.getRange(); 2437 return ExprError(); 2438 } 2439 2440 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2441 // Diagnose a missing typename if this resolved unambiguously to a type in 2442 // a dependent context. If we can recover with a type, downgrade this to 2443 // a warning in Microsoft compatibility mode. 2444 unsigned DiagID = diag::err_typename_missing; 2445 if (RecoveryTSI && getLangOpts().MSVCCompat) 2446 DiagID = diag::ext_typename_missing; 2447 SourceLocation Loc = SS.getBeginLoc(); 2448 auto D = Diag(Loc, DiagID); 2449 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2450 << SourceRange(Loc, NameInfo.getEndLoc()); 2451 2452 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2453 // context. 2454 if (!RecoveryTSI) 2455 return ExprError(); 2456 2457 // Only issue the fixit if we're prepared to recover. 2458 D << FixItHint::CreateInsertion(Loc, "typename "); 2459 2460 // Recover by pretending this was an elaborated type. 2461 QualType Ty = Context.getTypeDeclType(TD); 2462 TypeLocBuilder TLB; 2463 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2464 2465 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2466 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2467 QTL.setElaboratedKeywordLoc(SourceLocation()); 2468 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2469 2470 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2471 2472 return ExprEmpty(); 2473 } 2474 2475 // Defend against this resolving to an implicit member access. We usually 2476 // won't get here if this might be a legitimate a class member (we end up in 2477 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2478 // a pointer-to-member or in an unevaluated context in C++11. 2479 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2480 return BuildPossibleImplicitMemberExpr(SS, 2481 /*TemplateKWLoc=*/SourceLocation(), 2482 R, /*TemplateArgs=*/nullptr, S); 2483 2484 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2485 } 2486 2487 /// The parser has read a name in, and Sema has detected that we're currently 2488 /// inside an ObjC method. Perform some additional checks and determine if we 2489 /// should form a reference to an ivar. 2490 /// 2491 /// Ideally, most of this would be done by lookup, but there's 2492 /// actually quite a lot of extra work involved. 2493 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 2494 IdentifierInfo *II) { 2495 SourceLocation Loc = Lookup.getNameLoc(); 2496 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2497 2498 // Check for error condition which is already reported. 2499 if (!CurMethod) 2500 return DeclResult(true); 2501 2502 // There are two cases to handle here. 1) scoped lookup could have failed, 2503 // in which case we should look for an ivar. 2) scoped lookup could have 2504 // found a decl, but that decl is outside the current instance method (i.e. 2505 // a global variable). In these two cases, we do a lookup for an ivar with 2506 // this name, if the lookup sucedes, we replace it our current decl. 2507 2508 // If we're in a class method, we don't normally want to look for 2509 // ivars. But if we don't find anything else, and there's an 2510 // ivar, that's an error. 2511 bool IsClassMethod = CurMethod->isClassMethod(); 2512 2513 bool LookForIvars; 2514 if (Lookup.empty()) 2515 LookForIvars = true; 2516 else if (IsClassMethod) 2517 LookForIvars = false; 2518 else 2519 LookForIvars = (Lookup.isSingleResult() && 2520 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2521 ObjCInterfaceDecl *IFace = nullptr; 2522 if (LookForIvars) { 2523 IFace = CurMethod->getClassInterface(); 2524 ObjCInterfaceDecl *ClassDeclared; 2525 ObjCIvarDecl *IV = nullptr; 2526 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2527 // Diagnose using an ivar in a class method. 2528 if (IsClassMethod) { 2529 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2530 return DeclResult(true); 2531 } 2532 2533 // Diagnose the use of an ivar outside of the declaring class. 2534 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2535 !declaresSameEntity(ClassDeclared, IFace) && 2536 !getLangOpts().DebuggerSupport) 2537 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2538 2539 // Success. 2540 return IV; 2541 } 2542 } else if (CurMethod->isInstanceMethod()) { 2543 // We should warn if a local variable hides an ivar. 2544 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2545 ObjCInterfaceDecl *ClassDeclared; 2546 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2547 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2548 declaresSameEntity(IFace, ClassDeclared)) 2549 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2550 } 2551 } 2552 } else if (Lookup.isSingleResult() && 2553 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2554 // If accessing a stand-alone ivar in a class method, this is an error. 2555 if (const ObjCIvarDecl *IV = 2556 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { 2557 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2558 return DeclResult(true); 2559 } 2560 } 2561 2562 // Didn't encounter an error, didn't find an ivar. 2563 return DeclResult(false); 2564 } 2565 2566 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, 2567 ObjCIvarDecl *IV) { 2568 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2569 assert(CurMethod && CurMethod->isInstanceMethod() && 2570 "should not reference ivar from this context"); 2571 2572 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 2573 assert(IFace && "should not reference ivar from this context"); 2574 2575 // If we're referencing an invalid decl, just return this as a silent 2576 // error node. The error diagnostic was already emitted on the decl. 2577 if (IV->isInvalidDecl()) 2578 return ExprError(); 2579 2580 // Check if referencing a field with __attribute__((deprecated)). 2581 if (DiagnoseUseOfDecl(IV, Loc)) 2582 return ExprError(); 2583 2584 // FIXME: This should use a new expr for a direct reference, don't 2585 // turn this into Self->ivar, just return a BareIVarExpr or something. 2586 IdentifierInfo &II = Context.Idents.get("self"); 2587 UnqualifiedId SelfName; 2588 SelfName.setIdentifier(&II, SourceLocation()); 2589 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam); 2590 CXXScopeSpec SelfScopeSpec; 2591 SourceLocation TemplateKWLoc; 2592 ExprResult SelfExpr = 2593 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2594 /*HasTrailingLParen=*/false, 2595 /*IsAddressOfOperand=*/false); 2596 if (SelfExpr.isInvalid()) 2597 return ExprError(); 2598 2599 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2600 if (SelfExpr.isInvalid()) 2601 return ExprError(); 2602 2603 MarkAnyDeclReferenced(Loc, IV, true); 2604 2605 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2606 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2607 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2608 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2609 2610 ObjCIvarRefExpr *Result = new (Context) 2611 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2612 IV->getLocation(), SelfExpr.get(), true, true); 2613 2614 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2615 if (!isUnevaluatedContext() && 2616 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2617 getCurFunction()->recordUseOfWeak(Result); 2618 } 2619 if (getLangOpts().ObjCAutoRefCount) 2620 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2621 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2622 2623 return Result; 2624 } 2625 2626 /// The parser has read a name in, and Sema has detected that we're currently 2627 /// inside an ObjC method. Perform some additional checks and determine if we 2628 /// should form a reference to an ivar. If so, build an expression referencing 2629 /// that ivar. 2630 ExprResult 2631 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2632 IdentifierInfo *II, bool AllowBuiltinCreation) { 2633 // FIXME: Integrate this lookup step into LookupParsedName. 2634 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); 2635 if (Ivar.isInvalid()) 2636 return ExprError(); 2637 if (Ivar.isUsable()) 2638 return BuildIvarRefExpr(S, Lookup.getNameLoc(), 2639 cast<ObjCIvarDecl>(Ivar.get())); 2640 2641 if (Lookup.empty() && II && AllowBuiltinCreation) 2642 LookupBuiltin(Lookup); 2643 2644 // Sentinel value saying that we didn't do anything special. 2645 return ExprResult(false); 2646 } 2647 2648 /// Cast a base object to a member's actual type. 2649 /// 2650 /// Logically this happens in three phases: 2651 /// 2652 /// * First we cast from the base type to the naming class. 2653 /// The naming class is the class into which we were looking 2654 /// when we found the member; it's the qualifier type if a 2655 /// qualifier was provided, and otherwise it's the base type. 2656 /// 2657 /// * Next we cast from the naming class to the declaring class. 2658 /// If the member we found was brought into a class's scope by 2659 /// a using declaration, this is that class; otherwise it's 2660 /// the class declaring the member. 2661 /// 2662 /// * Finally we cast from the declaring class to the "true" 2663 /// declaring class of the member. This conversion does not 2664 /// obey access control. 2665 ExprResult 2666 Sema::PerformObjectMemberConversion(Expr *From, 2667 NestedNameSpecifier *Qualifier, 2668 NamedDecl *FoundDecl, 2669 NamedDecl *Member) { 2670 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2671 if (!RD) 2672 return From; 2673 2674 QualType DestRecordType; 2675 QualType DestType; 2676 QualType FromRecordType; 2677 QualType FromType = From->getType(); 2678 bool PointerConversions = false; 2679 if (isa<FieldDecl>(Member)) { 2680 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2681 auto FromPtrType = FromType->getAs<PointerType>(); 2682 DestRecordType = Context.getAddrSpaceQualType( 2683 DestRecordType, FromPtrType 2684 ? FromType->getPointeeType().getAddressSpace() 2685 : FromType.getAddressSpace()); 2686 2687 if (FromPtrType) { 2688 DestType = Context.getPointerType(DestRecordType); 2689 FromRecordType = FromPtrType->getPointeeType(); 2690 PointerConversions = true; 2691 } else { 2692 DestType = DestRecordType; 2693 FromRecordType = FromType; 2694 } 2695 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2696 if (Method->isStatic()) 2697 return From; 2698 2699 DestType = Method->getThisType(); 2700 DestRecordType = DestType->getPointeeType(); 2701 2702 if (FromType->getAs<PointerType>()) { 2703 FromRecordType = FromType->getPointeeType(); 2704 PointerConversions = true; 2705 } else { 2706 FromRecordType = FromType; 2707 DestType = DestRecordType; 2708 } 2709 2710 LangAS FromAS = FromRecordType.getAddressSpace(); 2711 LangAS DestAS = DestRecordType.getAddressSpace(); 2712 if (FromAS != DestAS) { 2713 QualType FromRecordTypeWithoutAS = 2714 Context.removeAddrSpaceQualType(FromRecordType); 2715 QualType FromTypeWithDestAS = 2716 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); 2717 if (PointerConversions) 2718 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); 2719 From = ImpCastExprToType(From, FromTypeWithDestAS, 2720 CK_AddressSpaceConversion, From->getValueKind()) 2721 .get(); 2722 } 2723 } else { 2724 // No conversion necessary. 2725 return From; 2726 } 2727 2728 if (DestType->isDependentType() || FromType->isDependentType()) 2729 return From; 2730 2731 // If the unqualified types are the same, no conversion is necessary. 2732 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2733 return From; 2734 2735 SourceRange FromRange = From->getSourceRange(); 2736 SourceLocation FromLoc = FromRange.getBegin(); 2737 2738 ExprValueKind VK = From->getValueKind(); 2739 2740 // C++ [class.member.lookup]p8: 2741 // [...] Ambiguities can often be resolved by qualifying a name with its 2742 // class name. 2743 // 2744 // If the member was a qualified name and the qualified referred to a 2745 // specific base subobject type, we'll cast to that intermediate type 2746 // first and then to the object in which the member is declared. That allows 2747 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2748 // 2749 // class Base { public: int x; }; 2750 // class Derived1 : public Base { }; 2751 // class Derived2 : public Base { }; 2752 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2753 // 2754 // void VeryDerived::f() { 2755 // x = 17; // error: ambiguous base subobjects 2756 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2757 // } 2758 if (Qualifier && Qualifier->getAsType()) { 2759 QualType QType = QualType(Qualifier->getAsType(), 0); 2760 assert(QType->isRecordType() && "lookup done with non-record type"); 2761 2762 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2763 2764 // In C++98, the qualifier type doesn't actually have to be a base 2765 // type of the object type, in which case we just ignore it. 2766 // Otherwise build the appropriate casts. 2767 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2768 CXXCastPath BasePath; 2769 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2770 FromLoc, FromRange, &BasePath)) 2771 return ExprError(); 2772 2773 if (PointerConversions) 2774 QType = Context.getPointerType(QType); 2775 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2776 VK, &BasePath).get(); 2777 2778 FromType = QType; 2779 FromRecordType = QRecordType; 2780 2781 // If the qualifier type was the same as the destination type, 2782 // we're done. 2783 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2784 return From; 2785 } 2786 } 2787 2788 bool IgnoreAccess = false; 2789 2790 // If we actually found the member through a using declaration, cast 2791 // down to the using declaration's type. 2792 // 2793 // Pointer equality is fine here because only one declaration of a 2794 // class ever has member declarations. 2795 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2796 assert(isa<UsingShadowDecl>(FoundDecl)); 2797 QualType URecordType = Context.getTypeDeclType( 2798 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2799 2800 // We only need to do this if the naming-class to declaring-class 2801 // conversion is non-trivial. 2802 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2803 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2804 CXXCastPath BasePath; 2805 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2806 FromLoc, FromRange, &BasePath)) 2807 return ExprError(); 2808 2809 QualType UType = URecordType; 2810 if (PointerConversions) 2811 UType = Context.getPointerType(UType); 2812 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2813 VK, &BasePath).get(); 2814 FromType = UType; 2815 FromRecordType = URecordType; 2816 } 2817 2818 // We don't do access control for the conversion from the 2819 // declaring class to the true declaring class. 2820 IgnoreAccess = true; 2821 } 2822 2823 CXXCastPath BasePath; 2824 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2825 FromLoc, FromRange, &BasePath, 2826 IgnoreAccess)) 2827 return ExprError(); 2828 2829 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2830 VK, &BasePath); 2831 } 2832 2833 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2834 const LookupResult &R, 2835 bool HasTrailingLParen) { 2836 // Only when used directly as the postfix-expression of a call. 2837 if (!HasTrailingLParen) 2838 return false; 2839 2840 // Never if a scope specifier was provided. 2841 if (SS.isSet()) 2842 return false; 2843 2844 // Only in C++ or ObjC++. 2845 if (!getLangOpts().CPlusPlus) 2846 return false; 2847 2848 // Turn off ADL when we find certain kinds of declarations during 2849 // normal lookup: 2850 for (NamedDecl *D : R) { 2851 // C++0x [basic.lookup.argdep]p3: 2852 // -- a declaration of a class member 2853 // Since using decls preserve this property, we check this on the 2854 // original decl. 2855 if (D->isCXXClassMember()) 2856 return false; 2857 2858 // C++0x [basic.lookup.argdep]p3: 2859 // -- a block-scope function declaration that is not a 2860 // using-declaration 2861 // NOTE: we also trigger this for function templates (in fact, we 2862 // don't check the decl type at all, since all other decl types 2863 // turn off ADL anyway). 2864 if (isa<UsingShadowDecl>(D)) 2865 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2866 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2867 return false; 2868 2869 // C++0x [basic.lookup.argdep]p3: 2870 // -- a declaration that is neither a function or a function 2871 // template 2872 // And also for builtin functions. 2873 if (isa<FunctionDecl>(D)) { 2874 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2875 2876 // But also builtin functions. 2877 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2878 return false; 2879 } else if (!isa<FunctionTemplateDecl>(D)) 2880 return false; 2881 } 2882 2883 return true; 2884 } 2885 2886 2887 /// Diagnoses obvious problems with the use of the given declaration 2888 /// as an expression. This is only actually called for lookups that 2889 /// were not overloaded, and it doesn't promise that the declaration 2890 /// will in fact be used. 2891 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2892 if (D->isInvalidDecl()) 2893 return true; 2894 2895 if (isa<TypedefNameDecl>(D)) { 2896 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2897 return true; 2898 } 2899 2900 if (isa<ObjCInterfaceDecl>(D)) { 2901 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2902 return true; 2903 } 2904 2905 if (isa<NamespaceDecl>(D)) { 2906 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2907 return true; 2908 } 2909 2910 return false; 2911 } 2912 2913 // Certain multiversion types should be treated as overloaded even when there is 2914 // only one result. 2915 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 2916 assert(R.isSingleResult() && "Expected only a single result"); 2917 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 2918 return FD && 2919 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 2920 } 2921 2922 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2923 LookupResult &R, bool NeedsADL, 2924 bool AcceptInvalidDecl) { 2925 // If this is a single, fully-resolved result and we don't need ADL, 2926 // just build an ordinary singleton decl ref. 2927 if (!NeedsADL && R.isSingleResult() && 2928 !R.getAsSingle<FunctionTemplateDecl>() && 2929 !ShouldLookupResultBeMultiVersionOverload(R)) 2930 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2931 R.getRepresentativeDecl(), nullptr, 2932 AcceptInvalidDecl); 2933 2934 // We only need to check the declaration if there's exactly one 2935 // result, because in the overloaded case the results can only be 2936 // functions and function templates. 2937 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 2938 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2939 return ExprError(); 2940 2941 // Otherwise, just build an unresolved lookup expression. Suppress 2942 // any lookup-related diagnostics; we'll hash these out later, when 2943 // we've picked a target. 2944 R.suppressDiagnostics(); 2945 2946 UnresolvedLookupExpr *ULE 2947 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2948 SS.getWithLocInContext(Context), 2949 R.getLookupNameInfo(), 2950 NeedsADL, R.isOverloadedResult(), 2951 R.begin(), R.end()); 2952 2953 return ULE; 2954 } 2955 2956 static void 2957 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 2958 ValueDecl *var, DeclContext *DC); 2959 2960 /// Complete semantic analysis for a reference to the given declaration. 2961 ExprResult Sema::BuildDeclarationNameExpr( 2962 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2963 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2964 bool AcceptInvalidDecl) { 2965 assert(D && "Cannot refer to a NULL declaration"); 2966 assert(!isa<FunctionTemplateDecl>(D) && 2967 "Cannot refer unambiguously to a function template"); 2968 2969 SourceLocation Loc = NameInfo.getLoc(); 2970 if (CheckDeclInExpr(*this, Loc, D)) 2971 return ExprError(); 2972 2973 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2974 // Specifically diagnose references to class templates that are missing 2975 // a template argument list. 2976 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 2977 return ExprError(); 2978 } 2979 2980 // Make sure that we're referring to a value. 2981 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2982 if (!VD) { 2983 Diag(Loc, diag::err_ref_non_value) 2984 << D << SS.getRange(); 2985 Diag(D->getLocation(), diag::note_declared_at); 2986 return ExprError(); 2987 } 2988 2989 // Check whether this declaration can be used. Note that we suppress 2990 // this check when we're going to perform argument-dependent lookup 2991 // on this function name, because this might not be the function 2992 // that overload resolution actually selects. 2993 if (DiagnoseUseOfDecl(VD, Loc)) 2994 return ExprError(); 2995 2996 // Only create DeclRefExpr's for valid Decl's. 2997 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2998 return ExprError(); 2999 3000 // Handle members of anonymous structs and unions. If we got here, 3001 // and the reference is to a class member indirect field, then this 3002 // must be the subject of a pointer-to-member expression. 3003 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 3004 if (!indirectField->isCXXClassMember()) 3005 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 3006 indirectField); 3007 3008 { 3009 QualType type = VD->getType(); 3010 if (type.isNull()) 3011 return ExprError(); 3012 if (auto *FPT = type->getAs<FunctionProtoType>()) { 3013 // C++ [except.spec]p17: 3014 // An exception-specification is considered to be needed when: 3015 // - in an expression, the function is the unique lookup result or 3016 // the selected member of a set of overloaded functions. 3017 ResolveExceptionSpec(Loc, FPT); 3018 type = VD->getType(); 3019 } 3020 ExprValueKind valueKind = VK_RValue; 3021 3022 switch (D->getKind()) { 3023 // Ignore all the non-ValueDecl kinds. 3024 #define ABSTRACT_DECL(kind) 3025 #define VALUE(type, base) 3026 #define DECL(type, base) \ 3027 case Decl::type: 3028 #include "clang/AST/DeclNodes.inc" 3029 llvm_unreachable("invalid value decl kind"); 3030 3031 // These shouldn't make it here. 3032 case Decl::ObjCAtDefsField: 3033 llvm_unreachable("forming non-member reference to ivar?"); 3034 3035 // Enum constants are always r-values and never references. 3036 // Unresolved using declarations are dependent. 3037 case Decl::EnumConstant: 3038 case Decl::UnresolvedUsingValue: 3039 case Decl::OMPDeclareReduction: 3040 case Decl::OMPDeclareMapper: 3041 valueKind = VK_RValue; 3042 break; 3043 3044 // Fields and indirect fields that got here must be for 3045 // pointer-to-member expressions; we just call them l-values for 3046 // internal consistency, because this subexpression doesn't really 3047 // exist in the high-level semantics. 3048 case Decl::Field: 3049 case Decl::IndirectField: 3050 case Decl::ObjCIvar: 3051 assert(getLangOpts().CPlusPlus && 3052 "building reference to field in C?"); 3053 3054 // These can't have reference type in well-formed programs, but 3055 // for internal consistency we do this anyway. 3056 type = type.getNonReferenceType(); 3057 valueKind = VK_LValue; 3058 break; 3059 3060 // Non-type template parameters are either l-values or r-values 3061 // depending on the type. 3062 case Decl::NonTypeTemplateParm: { 3063 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3064 type = reftype->getPointeeType(); 3065 valueKind = VK_LValue; // even if the parameter is an r-value reference 3066 break; 3067 } 3068 3069 // For non-references, we need to strip qualifiers just in case 3070 // the template parameter was declared as 'const int' or whatever. 3071 valueKind = VK_RValue; 3072 type = type.getUnqualifiedType(); 3073 break; 3074 } 3075 3076 case Decl::Var: 3077 case Decl::VarTemplateSpecialization: 3078 case Decl::VarTemplatePartialSpecialization: 3079 case Decl::Decomposition: 3080 case Decl::OMPCapturedExpr: 3081 // In C, "extern void blah;" is valid and is an r-value. 3082 if (!getLangOpts().CPlusPlus && 3083 !type.hasQualifiers() && 3084 type->isVoidType()) { 3085 valueKind = VK_RValue; 3086 break; 3087 } 3088 LLVM_FALLTHROUGH; 3089 3090 case Decl::ImplicitParam: 3091 case Decl::ParmVar: { 3092 // These are always l-values. 3093 valueKind = VK_LValue; 3094 type = type.getNonReferenceType(); 3095 3096 // FIXME: Does the addition of const really only apply in 3097 // potentially-evaluated contexts? Since the variable isn't actually 3098 // captured in an unevaluated context, it seems that the answer is no. 3099 if (!isUnevaluatedContext()) { 3100 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3101 if (!CapturedType.isNull()) 3102 type = CapturedType; 3103 } 3104 3105 break; 3106 } 3107 3108 case Decl::Binding: { 3109 // These are always lvalues. 3110 valueKind = VK_LValue; 3111 type = type.getNonReferenceType(); 3112 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3113 // decides how that's supposed to work. 3114 auto *BD = cast<BindingDecl>(VD); 3115 if (BD->getDeclContext() != CurContext) { 3116 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); 3117 if (DD && DD->hasLocalStorage()) 3118 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 3119 } 3120 break; 3121 } 3122 3123 case Decl::Function: { 3124 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3125 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3126 type = Context.BuiltinFnTy; 3127 valueKind = VK_RValue; 3128 break; 3129 } 3130 } 3131 3132 const FunctionType *fty = type->castAs<FunctionType>(); 3133 3134 // If we're referring to a function with an __unknown_anytype 3135 // result type, make the entire expression __unknown_anytype. 3136 if (fty->getReturnType() == Context.UnknownAnyTy) { 3137 type = Context.UnknownAnyTy; 3138 valueKind = VK_RValue; 3139 break; 3140 } 3141 3142 // Functions are l-values in C++. 3143 if (getLangOpts().CPlusPlus) { 3144 valueKind = VK_LValue; 3145 break; 3146 } 3147 3148 // C99 DR 316 says that, if a function type comes from a 3149 // function definition (without a prototype), that type is only 3150 // used for checking compatibility. Therefore, when referencing 3151 // the function, we pretend that we don't have the full function 3152 // type. 3153 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3154 isa<FunctionProtoType>(fty)) 3155 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3156 fty->getExtInfo()); 3157 3158 // Functions are r-values in C. 3159 valueKind = VK_RValue; 3160 break; 3161 } 3162 3163 case Decl::CXXDeductionGuide: 3164 llvm_unreachable("building reference to deduction guide"); 3165 3166 case Decl::MSProperty: 3167 valueKind = VK_LValue; 3168 break; 3169 3170 case Decl::CXXMethod: 3171 // If we're referring to a method with an __unknown_anytype 3172 // result type, make the entire expression __unknown_anytype. 3173 // This should only be possible with a type written directly. 3174 if (const FunctionProtoType *proto 3175 = dyn_cast<FunctionProtoType>(VD->getType())) 3176 if (proto->getReturnType() == Context.UnknownAnyTy) { 3177 type = Context.UnknownAnyTy; 3178 valueKind = VK_RValue; 3179 break; 3180 } 3181 3182 // C++ methods are l-values if static, r-values if non-static. 3183 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3184 valueKind = VK_LValue; 3185 break; 3186 } 3187 LLVM_FALLTHROUGH; 3188 3189 case Decl::CXXConversion: 3190 case Decl::CXXDestructor: 3191 case Decl::CXXConstructor: 3192 valueKind = VK_RValue; 3193 break; 3194 } 3195 3196 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3197 /*FIXME: TemplateKWLoc*/ SourceLocation(), 3198 TemplateArgs); 3199 } 3200 } 3201 3202 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3203 SmallString<32> &Target) { 3204 Target.resize(CharByteWidth * (Source.size() + 1)); 3205 char *ResultPtr = &Target[0]; 3206 const llvm::UTF8 *ErrorPtr; 3207 bool success = 3208 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3209 (void)success; 3210 assert(success); 3211 Target.resize(ResultPtr - &Target[0]); 3212 } 3213 3214 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3215 PredefinedExpr::IdentKind IK) { 3216 // Pick the current block, lambda, captured statement or function. 3217 Decl *currentDecl = nullptr; 3218 if (const BlockScopeInfo *BSI = getCurBlock()) 3219 currentDecl = BSI->TheDecl; 3220 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3221 currentDecl = LSI->CallOperator; 3222 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3223 currentDecl = CSI->TheCapturedDecl; 3224 else 3225 currentDecl = getCurFunctionOrMethodDecl(); 3226 3227 if (!currentDecl) { 3228 Diag(Loc, diag::ext_predef_outside_function); 3229 currentDecl = Context.getTranslationUnitDecl(); 3230 } 3231 3232 QualType ResTy; 3233 StringLiteral *SL = nullptr; 3234 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3235 ResTy = Context.DependentTy; 3236 else { 3237 // Pre-defined identifiers are of type char[x], where x is the length of 3238 // the string. 3239 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3240 unsigned Length = Str.length(); 3241 3242 llvm::APInt LengthI(32, Length + 1); 3243 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3244 ResTy = 3245 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3246 SmallString<32> RawChars; 3247 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3248 Str, RawChars); 3249 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3250 ArrayType::Normal, 3251 /*IndexTypeQuals*/ 0); 3252 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3253 /*Pascal*/ false, ResTy, Loc); 3254 } else { 3255 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3256 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3257 ArrayType::Normal, 3258 /*IndexTypeQuals*/ 0); 3259 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3260 /*Pascal*/ false, ResTy, Loc); 3261 } 3262 } 3263 3264 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3265 } 3266 3267 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3268 PredefinedExpr::IdentKind IK; 3269 3270 switch (Kind) { 3271 default: llvm_unreachable("Unknown simple primary expr!"); 3272 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3273 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3274 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3275 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3276 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3277 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3278 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3279 } 3280 3281 return BuildPredefinedExpr(Loc, IK); 3282 } 3283 3284 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3285 SmallString<16> CharBuffer; 3286 bool Invalid = false; 3287 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3288 if (Invalid) 3289 return ExprError(); 3290 3291 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3292 PP, Tok.getKind()); 3293 if (Literal.hadError()) 3294 return ExprError(); 3295 3296 QualType Ty; 3297 if (Literal.isWide()) 3298 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3299 else if (Literal.isUTF8() && getLangOpts().Char8) 3300 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3301 else if (Literal.isUTF16()) 3302 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3303 else if (Literal.isUTF32()) 3304 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3305 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3306 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3307 else 3308 Ty = Context.CharTy; // 'x' -> char in C++ 3309 3310 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3311 if (Literal.isWide()) 3312 Kind = CharacterLiteral::Wide; 3313 else if (Literal.isUTF16()) 3314 Kind = CharacterLiteral::UTF16; 3315 else if (Literal.isUTF32()) 3316 Kind = CharacterLiteral::UTF32; 3317 else if (Literal.isUTF8()) 3318 Kind = CharacterLiteral::UTF8; 3319 3320 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3321 Tok.getLocation()); 3322 3323 if (Literal.getUDSuffix().empty()) 3324 return Lit; 3325 3326 // We're building a user-defined literal. 3327 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3328 SourceLocation UDSuffixLoc = 3329 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3330 3331 // Make sure we're allowed user-defined literals here. 3332 if (!UDLScope) 3333 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3334 3335 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3336 // operator "" X (ch) 3337 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3338 Lit, Tok.getLocation()); 3339 } 3340 3341 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3342 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3343 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3344 Context.IntTy, Loc); 3345 } 3346 3347 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3348 QualType Ty, SourceLocation Loc) { 3349 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3350 3351 using llvm::APFloat; 3352 APFloat Val(Format); 3353 3354 APFloat::opStatus result = Literal.GetFloatValue(Val); 3355 3356 // Overflow is always an error, but underflow is only an error if 3357 // we underflowed to zero (APFloat reports denormals as underflow). 3358 if ((result & APFloat::opOverflow) || 3359 ((result & APFloat::opUnderflow) && Val.isZero())) { 3360 unsigned diagnostic; 3361 SmallString<20> buffer; 3362 if (result & APFloat::opOverflow) { 3363 diagnostic = diag::warn_float_overflow; 3364 APFloat::getLargest(Format).toString(buffer); 3365 } else { 3366 diagnostic = diag::warn_float_underflow; 3367 APFloat::getSmallest(Format).toString(buffer); 3368 } 3369 3370 S.Diag(Loc, diagnostic) 3371 << Ty 3372 << StringRef(buffer.data(), buffer.size()); 3373 } 3374 3375 bool isExact = (result == APFloat::opOK); 3376 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3377 } 3378 3379 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3380 assert(E && "Invalid expression"); 3381 3382 if (E->isValueDependent()) 3383 return false; 3384 3385 QualType QT = E->getType(); 3386 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3387 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3388 return true; 3389 } 3390 3391 llvm::APSInt ValueAPS; 3392 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3393 3394 if (R.isInvalid()) 3395 return true; 3396 3397 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3398 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3399 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3400 << ValueAPS.toString(10) << ValueIsPositive; 3401 return true; 3402 } 3403 3404 return false; 3405 } 3406 3407 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3408 // Fast path for a single digit (which is quite common). A single digit 3409 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3410 if (Tok.getLength() == 1) { 3411 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3412 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3413 } 3414 3415 SmallString<128> SpellingBuffer; 3416 // NumericLiteralParser wants to overread by one character. Add padding to 3417 // the buffer in case the token is copied to the buffer. If getSpelling() 3418 // returns a StringRef to the memory buffer, it should have a null char at 3419 // the EOF, so it is also safe. 3420 SpellingBuffer.resize(Tok.getLength() + 1); 3421 3422 // Get the spelling of the token, which eliminates trigraphs, etc. 3423 bool Invalid = false; 3424 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3425 if (Invalid) 3426 return ExprError(); 3427 3428 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3429 if (Literal.hadError) 3430 return ExprError(); 3431 3432 if (Literal.hasUDSuffix()) { 3433 // We're building a user-defined literal. 3434 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3435 SourceLocation UDSuffixLoc = 3436 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3437 3438 // Make sure we're allowed user-defined literals here. 3439 if (!UDLScope) 3440 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3441 3442 QualType CookedTy; 3443 if (Literal.isFloatingLiteral()) { 3444 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3445 // long double, the literal is treated as a call of the form 3446 // operator "" X (f L) 3447 CookedTy = Context.LongDoubleTy; 3448 } else { 3449 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3450 // unsigned long long, the literal is treated as a call of the form 3451 // operator "" X (n ULL) 3452 CookedTy = Context.UnsignedLongLongTy; 3453 } 3454 3455 DeclarationName OpName = 3456 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3457 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3458 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3459 3460 SourceLocation TokLoc = Tok.getLocation(); 3461 3462 // Perform literal operator lookup to determine if we're building a raw 3463 // literal or a cooked one. 3464 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3465 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3466 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3467 /*AllowStringTemplate*/ false, 3468 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3469 case LOLR_ErrorNoDiagnostic: 3470 // Lookup failure for imaginary constants isn't fatal, there's still the 3471 // GNU extension producing _Complex types. 3472 break; 3473 case LOLR_Error: 3474 return ExprError(); 3475 case LOLR_Cooked: { 3476 Expr *Lit; 3477 if (Literal.isFloatingLiteral()) { 3478 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3479 } else { 3480 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3481 if (Literal.GetIntegerValue(ResultVal)) 3482 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3483 << /* Unsigned */ 1; 3484 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3485 Tok.getLocation()); 3486 } 3487 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3488 } 3489 3490 case LOLR_Raw: { 3491 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3492 // literal is treated as a call of the form 3493 // operator "" X ("n") 3494 unsigned Length = Literal.getUDSuffixOffset(); 3495 QualType StrTy = Context.getConstantArrayType( 3496 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3497 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); 3498 Expr *Lit = StringLiteral::Create( 3499 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3500 /*Pascal*/false, StrTy, &TokLoc, 1); 3501 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3502 } 3503 3504 case LOLR_Template: { 3505 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3506 // template), L is treated as a call fo the form 3507 // operator "" X <'c1', 'c2', ... 'ck'>() 3508 // where n is the source character sequence c1 c2 ... ck. 3509 TemplateArgumentListInfo ExplicitArgs; 3510 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3511 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3512 llvm::APSInt Value(CharBits, CharIsUnsigned); 3513 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3514 Value = TokSpelling[I]; 3515 TemplateArgument Arg(Context, Value, Context.CharTy); 3516 TemplateArgumentLocInfo ArgInfo; 3517 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3518 } 3519 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3520 &ExplicitArgs); 3521 } 3522 case LOLR_StringTemplate: 3523 llvm_unreachable("unexpected literal operator lookup result"); 3524 } 3525 } 3526 3527 Expr *Res; 3528 3529 if (Literal.isFixedPointLiteral()) { 3530 QualType Ty; 3531 3532 if (Literal.isAccum) { 3533 if (Literal.isHalf) { 3534 Ty = Context.ShortAccumTy; 3535 } else if (Literal.isLong) { 3536 Ty = Context.LongAccumTy; 3537 } else { 3538 Ty = Context.AccumTy; 3539 } 3540 } else if (Literal.isFract) { 3541 if (Literal.isHalf) { 3542 Ty = Context.ShortFractTy; 3543 } else if (Literal.isLong) { 3544 Ty = Context.LongFractTy; 3545 } else { 3546 Ty = Context.FractTy; 3547 } 3548 } 3549 3550 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3551 3552 bool isSigned = !Literal.isUnsigned; 3553 unsigned scale = Context.getFixedPointScale(Ty); 3554 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3555 3556 llvm::APInt Val(bit_width, 0, isSigned); 3557 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3558 bool ValIsZero = Val.isNullValue() && !Overflowed; 3559 3560 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3561 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3562 // Clause 6.4.4 - The value of a constant shall be in the range of 3563 // representable values for its type, with exception for constants of a 3564 // fract type with a value of exactly 1; such a constant shall denote 3565 // the maximal value for the type. 3566 --Val; 3567 else if (Val.ugt(MaxVal) || Overflowed) 3568 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3569 3570 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3571 Tok.getLocation(), scale); 3572 } else if (Literal.isFloatingLiteral()) { 3573 QualType Ty; 3574 if (Literal.isHalf){ 3575 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3576 Ty = Context.HalfTy; 3577 else { 3578 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3579 return ExprError(); 3580 } 3581 } else if (Literal.isFloat) 3582 Ty = Context.FloatTy; 3583 else if (Literal.isLong) 3584 Ty = Context.LongDoubleTy; 3585 else if (Literal.isFloat16) 3586 Ty = Context.Float16Ty; 3587 else if (Literal.isFloat128) 3588 Ty = Context.Float128Ty; 3589 else 3590 Ty = Context.DoubleTy; 3591 3592 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3593 3594 if (Ty == Context.DoubleTy) { 3595 if (getLangOpts().SinglePrecisionConstants) { 3596 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3597 if (BTy->getKind() != BuiltinType::Float) { 3598 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3599 } 3600 } else if (getLangOpts().OpenCL && 3601 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3602 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3603 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3604 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3605 } 3606 } 3607 } else if (!Literal.isIntegerLiteral()) { 3608 return ExprError(); 3609 } else { 3610 QualType Ty; 3611 3612 // 'long long' is a C99 or C++11 feature. 3613 if (!getLangOpts().C99 && Literal.isLongLong) { 3614 if (getLangOpts().CPlusPlus) 3615 Diag(Tok.getLocation(), 3616 getLangOpts().CPlusPlus11 ? 3617 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3618 else 3619 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3620 } 3621 3622 // Get the value in the widest-possible width. 3623 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3624 llvm::APInt ResultVal(MaxWidth, 0); 3625 3626 if (Literal.GetIntegerValue(ResultVal)) { 3627 // If this value didn't fit into uintmax_t, error and force to ull. 3628 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3629 << /* Unsigned */ 1; 3630 Ty = Context.UnsignedLongLongTy; 3631 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3632 "long long is not intmax_t?"); 3633 } else { 3634 // If this value fits into a ULL, try to figure out what else it fits into 3635 // according to the rules of C99 6.4.4.1p5. 3636 3637 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3638 // be an unsigned int. 3639 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3640 3641 // Check from smallest to largest, picking the smallest type we can. 3642 unsigned Width = 0; 3643 3644 // Microsoft specific integer suffixes are explicitly sized. 3645 if (Literal.MicrosoftInteger) { 3646 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3647 Width = 8; 3648 Ty = Context.CharTy; 3649 } else { 3650 Width = Literal.MicrosoftInteger; 3651 Ty = Context.getIntTypeForBitwidth(Width, 3652 /*Signed=*/!Literal.isUnsigned); 3653 } 3654 } 3655 3656 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3657 // Are int/unsigned possibilities? 3658 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3659 3660 // Does it fit in a unsigned int? 3661 if (ResultVal.isIntN(IntSize)) { 3662 // Does it fit in a signed int? 3663 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3664 Ty = Context.IntTy; 3665 else if (AllowUnsigned) 3666 Ty = Context.UnsignedIntTy; 3667 Width = IntSize; 3668 } 3669 } 3670 3671 // Are long/unsigned long possibilities? 3672 if (Ty.isNull() && !Literal.isLongLong) { 3673 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3674 3675 // Does it fit in a unsigned long? 3676 if (ResultVal.isIntN(LongSize)) { 3677 // Does it fit in a signed long? 3678 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3679 Ty = Context.LongTy; 3680 else if (AllowUnsigned) 3681 Ty = Context.UnsignedLongTy; 3682 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3683 // is compatible. 3684 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3685 const unsigned LongLongSize = 3686 Context.getTargetInfo().getLongLongWidth(); 3687 Diag(Tok.getLocation(), 3688 getLangOpts().CPlusPlus 3689 ? Literal.isLong 3690 ? diag::warn_old_implicitly_unsigned_long_cxx 3691 : /*C++98 UB*/ diag:: 3692 ext_old_implicitly_unsigned_long_cxx 3693 : diag::warn_old_implicitly_unsigned_long) 3694 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3695 : /*will be ill-formed*/ 1); 3696 Ty = Context.UnsignedLongTy; 3697 } 3698 Width = LongSize; 3699 } 3700 } 3701 3702 // Check long long if needed. 3703 if (Ty.isNull()) { 3704 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3705 3706 // Does it fit in a unsigned long long? 3707 if (ResultVal.isIntN(LongLongSize)) { 3708 // Does it fit in a signed long long? 3709 // To be compatible with MSVC, hex integer literals ending with the 3710 // LL or i64 suffix are always signed in Microsoft mode. 3711 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3712 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3713 Ty = Context.LongLongTy; 3714 else if (AllowUnsigned) 3715 Ty = Context.UnsignedLongLongTy; 3716 Width = LongLongSize; 3717 } 3718 } 3719 3720 // If we still couldn't decide a type, we probably have something that 3721 // does not fit in a signed long long, but has no U suffix. 3722 if (Ty.isNull()) { 3723 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3724 Ty = Context.UnsignedLongLongTy; 3725 Width = Context.getTargetInfo().getLongLongWidth(); 3726 } 3727 3728 if (ResultVal.getBitWidth() != Width) 3729 ResultVal = ResultVal.trunc(Width); 3730 } 3731 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3732 } 3733 3734 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3735 if (Literal.isImaginary) { 3736 Res = new (Context) ImaginaryLiteral(Res, 3737 Context.getComplexType(Res->getType())); 3738 3739 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3740 } 3741 return Res; 3742 } 3743 3744 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3745 assert(E && "ActOnParenExpr() missing expr"); 3746 return new (Context) ParenExpr(L, R, E); 3747 } 3748 3749 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3750 SourceLocation Loc, 3751 SourceRange ArgRange) { 3752 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3753 // scalar or vector data type argument..." 3754 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3755 // type (C99 6.2.5p18) or void. 3756 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3757 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3758 << T << ArgRange; 3759 return true; 3760 } 3761 3762 assert((T->isVoidType() || !T->isIncompleteType()) && 3763 "Scalar types should always be complete"); 3764 return false; 3765 } 3766 3767 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3768 SourceLocation Loc, 3769 SourceRange ArgRange, 3770 UnaryExprOrTypeTrait TraitKind) { 3771 // Invalid types must be hard errors for SFINAE in C++. 3772 if (S.LangOpts.CPlusPlus) 3773 return true; 3774 3775 // C99 6.5.3.4p1: 3776 if (T->isFunctionType() && 3777 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 3778 TraitKind == UETT_PreferredAlignOf)) { 3779 // sizeof(function)/alignof(function) is allowed as an extension. 3780 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3781 << TraitKind << ArgRange; 3782 return false; 3783 } 3784 3785 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3786 // this is an error (OpenCL v1.1 s6.3.k) 3787 if (T->isVoidType()) { 3788 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3789 : diag::ext_sizeof_alignof_void_type; 3790 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3791 return false; 3792 } 3793 3794 return true; 3795 } 3796 3797 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3798 SourceLocation Loc, 3799 SourceRange ArgRange, 3800 UnaryExprOrTypeTrait TraitKind) { 3801 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3802 // runtime doesn't allow it. 3803 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3804 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3805 << T << (TraitKind == UETT_SizeOf) 3806 << ArgRange; 3807 return true; 3808 } 3809 3810 return false; 3811 } 3812 3813 /// Check whether E is a pointer from a decayed array type (the decayed 3814 /// pointer type is equal to T) and emit a warning if it is. 3815 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3816 Expr *E) { 3817 // Don't warn if the operation changed the type. 3818 if (T != E->getType()) 3819 return; 3820 3821 // Now look for array decays. 3822 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3823 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3824 return; 3825 3826 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3827 << ICE->getType() 3828 << ICE->getSubExpr()->getType(); 3829 } 3830 3831 /// Check the constraints on expression operands to unary type expression 3832 /// and type traits. 3833 /// 3834 /// Completes any types necessary and validates the constraints on the operand 3835 /// expression. The logic mostly mirrors the type-based overload, but may modify 3836 /// the expression as it completes the type for that expression through template 3837 /// instantiation, etc. 3838 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3839 UnaryExprOrTypeTrait ExprKind) { 3840 QualType ExprTy = E->getType(); 3841 assert(!ExprTy->isReferenceType()); 3842 3843 bool IsUnevaluatedOperand = 3844 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 3845 ExprKind == UETT_PreferredAlignOf); 3846 if (IsUnevaluatedOperand) { 3847 ExprResult Result = CheckUnevaluatedOperand(E); 3848 if (Result.isInvalid()) 3849 return true; 3850 E = Result.get(); 3851 } 3852 3853 if (ExprKind == UETT_VecStep) 3854 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3855 E->getSourceRange()); 3856 3857 // Whitelist some types as extensions 3858 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3859 E->getSourceRange(), ExprKind)) 3860 return false; 3861 3862 // 'alignof' applied to an expression only requires the base element type of 3863 // the expression to be complete. 'sizeof' requires the expression's type to 3864 // be complete (and will attempt to complete it if it's an array of unknown 3865 // bound). 3866 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 3867 if (RequireCompleteType(E->getExprLoc(), 3868 Context.getBaseElementType(E->getType()), 3869 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3870 E->getSourceRange())) 3871 return true; 3872 } else { 3873 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3874 ExprKind, E->getSourceRange())) 3875 return true; 3876 } 3877 3878 // Completing the expression's type may have changed it. 3879 ExprTy = E->getType(); 3880 assert(!ExprTy->isReferenceType()); 3881 3882 if (ExprTy->isFunctionType()) { 3883 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3884 << ExprKind << E->getSourceRange(); 3885 return true; 3886 } 3887 3888 // The operand for sizeof and alignof is in an unevaluated expression context, 3889 // so side effects could result in unintended consequences. 3890 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 3891 E->HasSideEffects(Context, false)) 3892 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3893 3894 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3895 E->getSourceRange(), ExprKind)) 3896 return true; 3897 3898 if (ExprKind == UETT_SizeOf) { 3899 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3900 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3901 QualType OType = PVD->getOriginalType(); 3902 QualType Type = PVD->getType(); 3903 if (Type->isPointerType() && OType->isArrayType()) { 3904 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3905 << Type << OType; 3906 Diag(PVD->getLocation(), diag::note_declared_at); 3907 } 3908 } 3909 } 3910 3911 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3912 // decays into a pointer and returns an unintended result. This is most 3913 // likely a typo for "sizeof(array) op x". 3914 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3915 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3916 BO->getLHS()); 3917 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3918 BO->getRHS()); 3919 } 3920 } 3921 3922 return false; 3923 } 3924 3925 /// Check the constraints on operands to unary expression and type 3926 /// traits. 3927 /// 3928 /// This will complete any types necessary, and validate the various constraints 3929 /// on those operands. 3930 /// 3931 /// The UsualUnaryConversions() function is *not* called by this routine. 3932 /// C99 6.3.2.1p[2-4] all state: 3933 /// Except when it is the operand of the sizeof operator ... 3934 /// 3935 /// C++ [expr.sizeof]p4 3936 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3937 /// standard conversions are not applied to the operand of sizeof. 3938 /// 3939 /// This policy is followed for all of the unary trait expressions. 3940 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3941 SourceLocation OpLoc, 3942 SourceRange ExprRange, 3943 UnaryExprOrTypeTrait ExprKind) { 3944 if (ExprType->isDependentType()) 3945 return false; 3946 3947 // C++ [expr.sizeof]p2: 3948 // When applied to a reference or a reference type, the result 3949 // is the size of the referenced type. 3950 // C++11 [expr.alignof]p3: 3951 // When alignof is applied to a reference type, the result 3952 // shall be the alignment of the referenced type. 3953 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3954 ExprType = Ref->getPointeeType(); 3955 3956 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3957 // When alignof or _Alignof is applied to an array type, the result 3958 // is the alignment of the element type. 3959 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 3960 ExprKind == UETT_OpenMPRequiredSimdAlign) 3961 ExprType = Context.getBaseElementType(ExprType); 3962 3963 if (ExprKind == UETT_VecStep) 3964 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3965 3966 // Whitelist some types as extensions 3967 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3968 ExprKind)) 3969 return false; 3970 3971 if (RequireCompleteType(OpLoc, ExprType, 3972 diag::err_sizeof_alignof_incomplete_type, 3973 ExprKind, ExprRange)) 3974 return true; 3975 3976 if (ExprType->isFunctionType()) { 3977 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3978 << ExprKind << ExprRange; 3979 return true; 3980 } 3981 3982 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3983 ExprKind)) 3984 return true; 3985 3986 return false; 3987 } 3988 3989 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 3990 // Cannot know anything else if the expression is dependent. 3991 if (E->isTypeDependent()) 3992 return false; 3993 3994 if (E->getObjectKind() == OK_BitField) { 3995 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3996 << 1 << E->getSourceRange(); 3997 return true; 3998 } 3999 4000 ValueDecl *D = nullptr; 4001 Expr *Inner = E->IgnoreParens(); 4002 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 4003 D = DRE->getDecl(); 4004 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 4005 D = ME->getMemberDecl(); 4006 } 4007 4008 // If it's a field, require the containing struct to have a 4009 // complete definition so that we can compute the layout. 4010 // 4011 // This can happen in C++11 onwards, either by naming the member 4012 // in a way that is not transformed into a member access expression 4013 // (in an unevaluated operand, for instance), or by naming the member 4014 // in a trailing-return-type. 4015 // 4016 // For the record, since __alignof__ on expressions is a GCC 4017 // extension, GCC seems to permit this but always gives the 4018 // nonsensical answer 0. 4019 // 4020 // We don't really need the layout here --- we could instead just 4021 // directly check for all the appropriate alignment-lowing 4022 // attributes --- but that would require duplicating a lot of 4023 // logic that just isn't worth duplicating for such a marginal 4024 // use-case. 4025 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4026 // Fast path this check, since we at least know the record has a 4027 // definition if we can find a member of it. 4028 if (!FD->getParent()->isCompleteDefinition()) { 4029 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4030 << E->getSourceRange(); 4031 return true; 4032 } 4033 4034 // Otherwise, if it's a field, and the field doesn't have 4035 // reference type, then it must have a complete type (or be a 4036 // flexible array member, which we explicitly want to 4037 // white-list anyway), which makes the following checks trivial. 4038 if (!FD->getType()->isReferenceType()) 4039 return false; 4040 } 4041 4042 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4043 } 4044 4045 bool Sema::CheckVecStepExpr(Expr *E) { 4046 E = E->IgnoreParens(); 4047 4048 // Cannot know anything else if the expression is dependent. 4049 if (E->isTypeDependent()) 4050 return false; 4051 4052 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4053 } 4054 4055 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4056 CapturingScopeInfo *CSI) { 4057 assert(T->isVariablyModifiedType()); 4058 assert(CSI != nullptr); 4059 4060 // We're going to walk down into the type and look for VLA expressions. 4061 do { 4062 const Type *Ty = T.getTypePtr(); 4063 switch (Ty->getTypeClass()) { 4064 #define TYPE(Class, Base) 4065 #define ABSTRACT_TYPE(Class, Base) 4066 #define NON_CANONICAL_TYPE(Class, Base) 4067 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4068 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4069 #include "clang/AST/TypeNodes.inc" 4070 T = QualType(); 4071 break; 4072 // These types are never variably-modified. 4073 case Type::Builtin: 4074 case Type::Complex: 4075 case Type::Vector: 4076 case Type::ExtVector: 4077 case Type::Record: 4078 case Type::Enum: 4079 case Type::Elaborated: 4080 case Type::TemplateSpecialization: 4081 case Type::ObjCObject: 4082 case Type::ObjCInterface: 4083 case Type::ObjCObjectPointer: 4084 case Type::ObjCTypeParam: 4085 case Type::Pipe: 4086 llvm_unreachable("type class is never variably-modified!"); 4087 case Type::Adjusted: 4088 T = cast<AdjustedType>(Ty)->getOriginalType(); 4089 break; 4090 case Type::Decayed: 4091 T = cast<DecayedType>(Ty)->getPointeeType(); 4092 break; 4093 case Type::Pointer: 4094 T = cast<PointerType>(Ty)->getPointeeType(); 4095 break; 4096 case Type::BlockPointer: 4097 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4098 break; 4099 case Type::LValueReference: 4100 case Type::RValueReference: 4101 T = cast<ReferenceType>(Ty)->getPointeeType(); 4102 break; 4103 case Type::MemberPointer: 4104 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4105 break; 4106 case Type::ConstantArray: 4107 case Type::IncompleteArray: 4108 // Losing element qualification here is fine. 4109 T = cast<ArrayType>(Ty)->getElementType(); 4110 break; 4111 case Type::VariableArray: { 4112 // Losing element qualification here is fine. 4113 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4114 4115 // Unknown size indication requires no size computation. 4116 // Otherwise, evaluate and record it. 4117 auto Size = VAT->getSizeExpr(); 4118 if (Size && !CSI->isVLATypeCaptured(VAT) && 4119 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4120 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4121 4122 T = VAT->getElementType(); 4123 break; 4124 } 4125 case Type::FunctionProto: 4126 case Type::FunctionNoProto: 4127 T = cast<FunctionType>(Ty)->getReturnType(); 4128 break; 4129 case Type::Paren: 4130 case Type::TypeOf: 4131 case Type::UnaryTransform: 4132 case Type::Attributed: 4133 case Type::SubstTemplateTypeParm: 4134 case Type::PackExpansion: 4135 case Type::MacroQualified: 4136 // Keep walking after single level desugaring. 4137 T = T.getSingleStepDesugaredType(Context); 4138 break; 4139 case Type::Typedef: 4140 T = cast<TypedefType>(Ty)->desugar(); 4141 break; 4142 case Type::Decltype: 4143 T = cast<DecltypeType>(Ty)->desugar(); 4144 break; 4145 case Type::Auto: 4146 case Type::DeducedTemplateSpecialization: 4147 T = cast<DeducedType>(Ty)->getDeducedType(); 4148 break; 4149 case Type::TypeOfExpr: 4150 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4151 break; 4152 case Type::Atomic: 4153 T = cast<AtomicType>(Ty)->getValueType(); 4154 break; 4155 } 4156 } while (!T.isNull() && T->isVariablyModifiedType()); 4157 } 4158 4159 /// Build a sizeof or alignof expression given a type operand. 4160 ExprResult 4161 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4162 SourceLocation OpLoc, 4163 UnaryExprOrTypeTrait ExprKind, 4164 SourceRange R) { 4165 if (!TInfo) 4166 return ExprError(); 4167 4168 QualType T = TInfo->getType(); 4169 4170 if (!T->isDependentType() && 4171 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4172 return ExprError(); 4173 4174 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4175 if (auto *TT = T->getAs<TypedefType>()) { 4176 for (auto I = FunctionScopes.rbegin(), 4177 E = std::prev(FunctionScopes.rend()); 4178 I != E; ++I) { 4179 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4180 if (CSI == nullptr) 4181 break; 4182 DeclContext *DC = nullptr; 4183 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4184 DC = LSI->CallOperator; 4185 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4186 DC = CRSI->TheCapturedDecl; 4187 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4188 DC = BSI->TheDecl; 4189 if (DC) { 4190 if (DC->containsDecl(TT->getDecl())) 4191 break; 4192 captureVariablyModifiedType(Context, T, CSI); 4193 } 4194 } 4195 } 4196 } 4197 4198 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4199 return new (Context) UnaryExprOrTypeTraitExpr( 4200 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4201 } 4202 4203 /// Build a sizeof or alignof expression given an expression 4204 /// operand. 4205 ExprResult 4206 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4207 UnaryExprOrTypeTrait ExprKind) { 4208 ExprResult PE = CheckPlaceholderExpr(E); 4209 if (PE.isInvalid()) 4210 return ExprError(); 4211 4212 E = PE.get(); 4213 4214 // Verify that the operand is valid. 4215 bool isInvalid = false; 4216 if (E->isTypeDependent()) { 4217 // Delay type-checking for type-dependent expressions. 4218 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4219 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4220 } else if (ExprKind == UETT_VecStep) { 4221 isInvalid = CheckVecStepExpr(E); 4222 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4223 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4224 isInvalid = true; 4225 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4226 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4227 isInvalid = true; 4228 } else { 4229 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4230 } 4231 4232 if (isInvalid) 4233 return ExprError(); 4234 4235 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4236 PE = TransformToPotentiallyEvaluated(E); 4237 if (PE.isInvalid()) return ExprError(); 4238 E = PE.get(); 4239 } 4240 4241 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4242 return new (Context) UnaryExprOrTypeTraitExpr( 4243 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4244 } 4245 4246 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4247 /// expr and the same for @c alignof and @c __alignof 4248 /// Note that the ArgRange is invalid if isType is false. 4249 ExprResult 4250 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4251 UnaryExprOrTypeTrait ExprKind, bool IsType, 4252 void *TyOrEx, SourceRange ArgRange) { 4253 // If error parsing type, ignore. 4254 if (!TyOrEx) return ExprError(); 4255 4256 if (IsType) { 4257 TypeSourceInfo *TInfo; 4258 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4259 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4260 } 4261 4262 Expr *ArgEx = (Expr *)TyOrEx; 4263 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4264 return Result; 4265 } 4266 4267 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4268 bool IsReal) { 4269 if (V.get()->isTypeDependent()) 4270 return S.Context.DependentTy; 4271 4272 // _Real and _Imag are only l-values for normal l-values. 4273 if (V.get()->getObjectKind() != OK_Ordinary) { 4274 V = S.DefaultLvalueConversion(V.get()); 4275 if (V.isInvalid()) 4276 return QualType(); 4277 } 4278 4279 // These operators return the element type of a complex type. 4280 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4281 return CT->getElementType(); 4282 4283 // Otherwise they pass through real integer and floating point types here. 4284 if (V.get()->getType()->isArithmeticType()) 4285 return V.get()->getType(); 4286 4287 // Test for placeholders. 4288 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4289 if (PR.isInvalid()) return QualType(); 4290 if (PR.get() != V.get()) { 4291 V = PR; 4292 return CheckRealImagOperand(S, V, Loc, IsReal); 4293 } 4294 4295 // Reject anything else. 4296 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4297 << (IsReal ? "__real" : "__imag"); 4298 return QualType(); 4299 } 4300 4301 4302 4303 ExprResult 4304 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4305 tok::TokenKind Kind, Expr *Input) { 4306 UnaryOperatorKind Opc; 4307 switch (Kind) { 4308 default: llvm_unreachable("Unknown unary op!"); 4309 case tok::plusplus: Opc = UO_PostInc; break; 4310 case tok::minusminus: Opc = UO_PostDec; break; 4311 } 4312 4313 // Since this might is a postfix expression, get rid of ParenListExprs. 4314 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4315 if (Result.isInvalid()) return ExprError(); 4316 Input = Result.get(); 4317 4318 return BuildUnaryOp(S, OpLoc, Opc, Input); 4319 } 4320 4321 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4322 /// 4323 /// \return true on error 4324 static bool checkArithmeticOnObjCPointer(Sema &S, 4325 SourceLocation opLoc, 4326 Expr *op) { 4327 assert(op->getType()->isObjCObjectPointerType()); 4328 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4329 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4330 return false; 4331 4332 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4333 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4334 << op->getSourceRange(); 4335 return true; 4336 } 4337 4338 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4339 auto *BaseNoParens = Base->IgnoreParens(); 4340 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4341 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4342 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4343 } 4344 4345 ExprResult 4346 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4347 Expr *idx, SourceLocation rbLoc) { 4348 if (base && !base->getType().isNull() && 4349 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4350 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4351 /*Length=*/nullptr, rbLoc); 4352 4353 // Since this might be a postfix expression, get rid of ParenListExprs. 4354 if (isa<ParenListExpr>(base)) { 4355 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4356 if (result.isInvalid()) return ExprError(); 4357 base = result.get(); 4358 } 4359 4360 // A comma-expression as the index is deprecated in C++2a onwards. 4361 if (getLangOpts().CPlusPlus2a && 4362 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4363 (isa<CXXOperatorCallExpr>(idx) && 4364 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { 4365 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4366 << SourceRange(base->getBeginLoc(), rbLoc); 4367 } 4368 4369 // Handle any non-overload placeholder types in the base and index 4370 // expressions. We can't handle overloads here because the other 4371 // operand might be an overloadable type, in which case the overload 4372 // resolution for the operator overload should get the first crack 4373 // at the overload. 4374 bool IsMSPropertySubscript = false; 4375 if (base->getType()->isNonOverloadPlaceholderType()) { 4376 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4377 if (!IsMSPropertySubscript) { 4378 ExprResult result = CheckPlaceholderExpr(base); 4379 if (result.isInvalid()) 4380 return ExprError(); 4381 base = result.get(); 4382 } 4383 } 4384 if (idx->getType()->isNonOverloadPlaceholderType()) { 4385 ExprResult result = CheckPlaceholderExpr(idx); 4386 if (result.isInvalid()) return ExprError(); 4387 idx = result.get(); 4388 } 4389 4390 // Build an unanalyzed expression if either operand is type-dependent. 4391 if (getLangOpts().CPlusPlus && 4392 (base->isTypeDependent() || idx->isTypeDependent())) { 4393 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4394 VK_LValue, OK_Ordinary, rbLoc); 4395 } 4396 4397 // MSDN, property (C++) 4398 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4399 // This attribute can also be used in the declaration of an empty array in a 4400 // class or structure definition. For example: 4401 // __declspec(property(get=GetX, put=PutX)) int x[]; 4402 // The above statement indicates that x[] can be used with one or more array 4403 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4404 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4405 if (IsMSPropertySubscript) { 4406 // Build MS property subscript expression if base is MS property reference 4407 // or MS property subscript. 4408 return new (Context) MSPropertySubscriptExpr( 4409 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4410 } 4411 4412 // Use C++ overloaded-operator rules if either operand has record 4413 // type. The spec says to do this if either type is *overloadable*, 4414 // but enum types can't declare subscript operators or conversion 4415 // operators, so there's nothing interesting for overload resolution 4416 // to do if there aren't any record types involved. 4417 // 4418 // ObjC pointers have their own subscripting logic that is not tied 4419 // to overload resolution and so should not take this path. 4420 if (getLangOpts().CPlusPlus && 4421 (base->getType()->isRecordType() || 4422 (!base->getType()->isObjCObjectPointerType() && 4423 idx->getType()->isRecordType()))) { 4424 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4425 } 4426 4427 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4428 4429 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4430 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4431 4432 return Res; 4433 } 4434 4435 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4436 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4437 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4438 4439 // For expressions like `&(*s).b`, the base is recorded and what should be 4440 // checked. 4441 const MemberExpr *Member = nullptr; 4442 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4443 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4444 4445 LastRecord.PossibleDerefs.erase(StrippedExpr); 4446 } 4447 4448 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4449 QualType ResultTy = E->getType(); 4450 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4451 4452 // Bail if the element is an array since it is not memory access. 4453 if (isa<ArrayType>(ResultTy)) 4454 return; 4455 4456 if (ResultTy->hasAttr(attr::NoDeref)) { 4457 LastRecord.PossibleDerefs.insert(E); 4458 return; 4459 } 4460 4461 // Check if the base type is a pointer to a member access of a struct 4462 // marked with noderef. 4463 const Expr *Base = E->getBase(); 4464 QualType BaseTy = Base->getType(); 4465 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4466 // Not a pointer access 4467 return; 4468 4469 const MemberExpr *Member = nullptr; 4470 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4471 Member->isArrow()) 4472 Base = Member->getBase(); 4473 4474 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4475 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4476 LastRecord.PossibleDerefs.insert(E); 4477 } 4478 } 4479 4480 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4481 Expr *LowerBound, 4482 SourceLocation ColonLoc, Expr *Length, 4483 SourceLocation RBLoc) { 4484 if (Base->getType()->isPlaceholderType() && 4485 !Base->getType()->isSpecificPlaceholderType( 4486 BuiltinType::OMPArraySection)) { 4487 ExprResult Result = CheckPlaceholderExpr(Base); 4488 if (Result.isInvalid()) 4489 return ExprError(); 4490 Base = Result.get(); 4491 } 4492 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4493 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4494 if (Result.isInvalid()) 4495 return ExprError(); 4496 Result = DefaultLvalueConversion(Result.get()); 4497 if (Result.isInvalid()) 4498 return ExprError(); 4499 LowerBound = Result.get(); 4500 } 4501 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4502 ExprResult Result = CheckPlaceholderExpr(Length); 4503 if (Result.isInvalid()) 4504 return ExprError(); 4505 Result = DefaultLvalueConversion(Result.get()); 4506 if (Result.isInvalid()) 4507 return ExprError(); 4508 Length = Result.get(); 4509 } 4510 4511 // Build an unanalyzed expression if either operand is type-dependent. 4512 if (Base->isTypeDependent() || 4513 (LowerBound && 4514 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4515 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4516 return new (Context) 4517 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4518 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4519 } 4520 4521 // Perform default conversions. 4522 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4523 QualType ResultTy; 4524 if (OriginalTy->isAnyPointerType()) { 4525 ResultTy = OriginalTy->getPointeeType(); 4526 } else if (OriginalTy->isArrayType()) { 4527 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4528 } else { 4529 return ExprError( 4530 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4531 << Base->getSourceRange()); 4532 } 4533 // C99 6.5.2.1p1 4534 if (LowerBound) { 4535 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4536 LowerBound); 4537 if (Res.isInvalid()) 4538 return ExprError(Diag(LowerBound->getExprLoc(), 4539 diag::err_omp_typecheck_section_not_integer) 4540 << 0 << LowerBound->getSourceRange()); 4541 LowerBound = Res.get(); 4542 4543 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4544 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4545 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4546 << 0 << LowerBound->getSourceRange(); 4547 } 4548 if (Length) { 4549 auto Res = 4550 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4551 if (Res.isInvalid()) 4552 return ExprError(Diag(Length->getExprLoc(), 4553 diag::err_omp_typecheck_section_not_integer) 4554 << 1 << Length->getSourceRange()); 4555 Length = Res.get(); 4556 4557 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4558 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4559 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4560 << 1 << Length->getSourceRange(); 4561 } 4562 4563 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4564 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4565 // type. Note that functions are not objects, and that (in C99 parlance) 4566 // incomplete types are not object types. 4567 if (ResultTy->isFunctionType()) { 4568 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4569 << ResultTy << Base->getSourceRange(); 4570 return ExprError(); 4571 } 4572 4573 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4574 diag::err_omp_section_incomplete_type, Base)) 4575 return ExprError(); 4576 4577 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4578 Expr::EvalResult Result; 4579 if (LowerBound->EvaluateAsInt(Result, Context)) { 4580 // OpenMP 4.5, [2.4 Array Sections] 4581 // The array section must be a subset of the original array. 4582 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 4583 if (LowerBoundValue.isNegative()) { 4584 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4585 << LowerBound->getSourceRange(); 4586 return ExprError(); 4587 } 4588 } 4589 } 4590 4591 if (Length) { 4592 Expr::EvalResult Result; 4593 if (Length->EvaluateAsInt(Result, Context)) { 4594 // OpenMP 4.5, [2.4 Array Sections] 4595 // The length must evaluate to non-negative integers. 4596 llvm::APSInt LengthValue = Result.Val.getInt(); 4597 if (LengthValue.isNegative()) { 4598 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4599 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4600 << Length->getSourceRange(); 4601 return ExprError(); 4602 } 4603 } 4604 } else if (ColonLoc.isValid() && 4605 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4606 !OriginalTy->isVariableArrayType()))) { 4607 // OpenMP 4.5, [2.4 Array Sections] 4608 // When the size of the array dimension is not known, the length must be 4609 // specified explicitly. 4610 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4611 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4612 return ExprError(); 4613 } 4614 4615 if (!Base->getType()->isSpecificPlaceholderType( 4616 BuiltinType::OMPArraySection)) { 4617 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4618 if (Result.isInvalid()) 4619 return ExprError(); 4620 Base = Result.get(); 4621 } 4622 return new (Context) 4623 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4624 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4625 } 4626 4627 ExprResult 4628 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4629 Expr *Idx, SourceLocation RLoc) { 4630 Expr *LHSExp = Base; 4631 Expr *RHSExp = Idx; 4632 4633 ExprValueKind VK = VK_LValue; 4634 ExprObjectKind OK = OK_Ordinary; 4635 4636 // Per C++ core issue 1213, the result is an xvalue if either operand is 4637 // a non-lvalue array, and an lvalue otherwise. 4638 if (getLangOpts().CPlusPlus11) { 4639 for (auto *Op : {LHSExp, RHSExp}) { 4640 Op = Op->IgnoreImplicit(); 4641 if (Op->getType()->isArrayType() && !Op->isLValue()) 4642 VK = VK_XValue; 4643 } 4644 } 4645 4646 // Perform default conversions. 4647 if (!LHSExp->getType()->getAs<VectorType>()) { 4648 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4649 if (Result.isInvalid()) 4650 return ExprError(); 4651 LHSExp = Result.get(); 4652 } 4653 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4654 if (Result.isInvalid()) 4655 return ExprError(); 4656 RHSExp = Result.get(); 4657 4658 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4659 4660 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4661 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4662 // in the subscript position. As a result, we need to derive the array base 4663 // and index from the expression types. 4664 Expr *BaseExpr, *IndexExpr; 4665 QualType ResultType; 4666 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4667 BaseExpr = LHSExp; 4668 IndexExpr = RHSExp; 4669 ResultType = Context.DependentTy; 4670 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4671 BaseExpr = LHSExp; 4672 IndexExpr = RHSExp; 4673 ResultType = PTy->getPointeeType(); 4674 } else if (const ObjCObjectPointerType *PTy = 4675 LHSTy->getAs<ObjCObjectPointerType>()) { 4676 BaseExpr = LHSExp; 4677 IndexExpr = RHSExp; 4678 4679 // Use custom logic if this should be the pseudo-object subscript 4680 // expression. 4681 if (!LangOpts.isSubscriptPointerArithmetic()) 4682 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4683 nullptr); 4684 4685 ResultType = PTy->getPointeeType(); 4686 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4687 // Handle the uncommon case of "123[Ptr]". 4688 BaseExpr = RHSExp; 4689 IndexExpr = LHSExp; 4690 ResultType = PTy->getPointeeType(); 4691 } else if (const ObjCObjectPointerType *PTy = 4692 RHSTy->getAs<ObjCObjectPointerType>()) { 4693 // Handle the uncommon case of "123[Ptr]". 4694 BaseExpr = RHSExp; 4695 IndexExpr = LHSExp; 4696 ResultType = PTy->getPointeeType(); 4697 if (!LangOpts.isSubscriptPointerArithmetic()) { 4698 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4699 << ResultType << BaseExpr->getSourceRange(); 4700 return ExprError(); 4701 } 4702 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4703 BaseExpr = LHSExp; // vectors: V[123] 4704 IndexExpr = RHSExp; 4705 // We apply C++ DR1213 to vector subscripting too. 4706 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { 4707 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 4708 if (Materialized.isInvalid()) 4709 return ExprError(); 4710 LHSExp = Materialized.get(); 4711 } 4712 VK = LHSExp->getValueKind(); 4713 if (VK != VK_RValue) 4714 OK = OK_VectorComponent; 4715 4716 ResultType = VTy->getElementType(); 4717 QualType BaseType = BaseExpr->getType(); 4718 Qualifiers BaseQuals = BaseType.getQualifiers(); 4719 Qualifiers MemberQuals = ResultType.getQualifiers(); 4720 Qualifiers Combined = BaseQuals + MemberQuals; 4721 if (Combined != MemberQuals) 4722 ResultType = Context.getQualifiedType(ResultType, Combined); 4723 } else if (LHSTy->isArrayType()) { 4724 // If we see an array that wasn't promoted by 4725 // DefaultFunctionArrayLvalueConversion, it must be an array that 4726 // wasn't promoted because of the C90 rule that doesn't 4727 // allow promoting non-lvalue arrays. Warn, then 4728 // force the promotion here. 4729 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 4730 << LHSExp->getSourceRange(); 4731 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4732 CK_ArrayToPointerDecay).get(); 4733 LHSTy = LHSExp->getType(); 4734 4735 BaseExpr = LHSExp; 4736 IndexExpr = RHSExp; 4737 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4738 } else if (RHSTy->isArrayType()) { 4739 // Same as previous, except for 123[f().a] case 4740 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 4741 << RHSExp->getSourceRange(); 4742 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4743 CK_ArrayToPointerDecay).get(); 4744 RHSTy = RHSExp->getType(); 4745 4746 BaseExpr = RHSExp; 4747 IndexExpr = LHSExp; 4748 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4749 } else { 4750 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4751 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4752 } 4753 // C99 6.5.2.1p1 4754 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4755 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4756 << IndexExpr->getSourceRange()); 4757 4758 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4759 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4760 && !IndexExpr->isTypeDependent()) 4761 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4762 4763 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4764 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4765 // type. Note that Functions are not objects, and that (in C99 parlance) 4766 // incomplete types are not object types. 4767 if (ResultType->isFunctionType()) { 4768 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 4769 << ResultType << BaseExpr->getSourceRange(); 4770 return ExprError(); 4771 } 4772 4773 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4774 // GNU extension: subscripting on pointer to void 4775 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4776 << BaseExpr->getSourceRange(); 4777 4778 // C forbids expressions of unqualified void type from being l-values. 4779 // See IsCForbiddenLValueType. 4780 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4781 } else if (!ResultType->isDependentType() && 4782 RequireCompleteType(LLoc, ResultType, 4783 diag::err_subscript_incomplete_type, BaseExpr)) 4784 return ExprError(); 4785 4786 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4787 !ResultType.isCForbiddenLValueType()); 4788 4789 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 4790 FunctionScopes.size() > 1) { 4791 if (auto *TT = 4792 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 4793 for (auto I = FunctionScopes.rbegin(), 4794 E = std::prev(FunctionScopes.rend()); 4795 I != E; ++I) { 4796 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4797 if (CSI == nullptr) 4798 break; 4799 DeclContext *DC = nullptr; 4800 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4801 DC = LSI->CallOperator; 4802 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4803 DC = CRSI->TheCapturedDecl; 4804 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4805 DC = BSI->TheDecl; 4806 if (DC) { 4807 if (DC->containsDecl(TT->getDecl())) 4808 break; 4809 captureVariablyModifiedType( 4810 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 4811 } 4812 } 4813 } 4814 } 4815 4816 return new (Context) 4817 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4818 } 4819 4820 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 4821 ParmVarDecl *Param) { 4822 if (Param->hasUnparsedDefaultArg()) { 4823 Diag(CallLoc, 4824 diag::err_use_of_default_argument_to_function_declared_later) << 4825 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4826 Diag(UnparsedDefaultArgLocs[Param], 4827 diag::note_default_argument_declared_here); 4828 return true; 4829 } 4830 4831 if (Param->hasUninstantiatedDefaultArg()) { 4832 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4833 4834 EnterExpressionEvaluationContext EvalContext( 4835 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 4836 4837 // Instantiate the expression. 4838 // 4839 // FIXME: Pass in a correct Pattern argument, otherwise 4840 // getTemplateInstantiationArgs uses the lexical context of FD, e.g. 4841 // 4842 // template<typename T> 4843 // struct A { 4844 // static int FooImpl(); 4845 // 4846 // template<typename Tp> 4847 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level 4848 // // template argument list [[T], [Tp]], should be [[Tp]]. 4849 // friend A<Tp> Foo(int a); 4850 // }; 4851 // 4852 // template<typename T> 4853 // A<T> Foo(int a = A<T>::FooImpl()); 4854 MultiLevelTemplateArgumentList MutiLevelArgList 4855 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4856 4857 InstantiatingTemplate Inst(*this, CallLoc, Param, 4858 MutiLevelArgList.getInnermost()); 4859 if (Inst.isInvalid()) 4860 return true; 4861 if (Inst.isAlreadyInstantiating()) { 4862 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 4863 Param->setInvalidDecl(); 4864 return true; 4865 } 4866 4867 ExprResult Result; 4868 { 4869 // C++ [dcl.fct.default]p5: 4870 // The names in the [default argument] expression are bound, and 4871 // the semantic constraints are checked, at the point where the 4872 // default argument expression appears. 4873 ContextRAII SavedContext(*this, FD); 4874 LocalInstantiationScope Local(*this); 4875 runWithSufficientStackSpace(CallLoc, [&] { 4876 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 4877 /*DirectInit*/false); 4878 }); 4879 } 4880 if (Result.isInvalid()) 4881 return true; 4882 4883 // Check the expression as an initializer for the parameter. 4884 InitializedEntity Entity 4885 = InitializedEntity::InitializeParameter(Context, Param); 4886 InitializationKind Kind = InitializationKind::CreateCopy( 4887 Param->getLocation(), 4888 /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc()); 4889 Expr *ResultE = Result.getAs<Expr>(); 4890 4891 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4892 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4893 if (Result.isInvalid()) 4894 return true; 4895 4896 Result = 4897 ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(), 4898 /*DiscardedValue*/ false); 4899 if (Result.isInvalid()) 4900 return true; 4901 4902 // Remember the instantiated default argument. 4903 Param->setDefaultArg(Result.getAs<Expr>()); 4904 if (ASTMutationListener *L = getASTMutationListener()) { 4905 L->DefaultArgumentInstantiated(Param); 4906 } 4907 } 4908 4909 // If the default argument expression is not set yet, we are building it now. 4910 if (!Param->hasInit()) { 4911 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 4912 Param->setInvalidDecl(); 4913 return true; 4914 } 4915 4916 // If the default expression creates temporaries, we need to 4917 // push them to the current stack of expression temporaries so they'll 4918 // be properly destroyed. 4919 // FIXME: We should really be rebuilding the default argument with new 4920 // bound temporaries; see the comment in PR5810. 4921 // We don't need to do that with block decls, though, because 4922 // blocks in default argument expression can never capture anything. 4923 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 4924 // Set the "needs cleanups" bit regardless of whether there are 4925 // any explicit objects. 4926 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 4927 4928 // Append all the objects to the cleanup list. Right now, this 4929 // should always be a no-op, because blocks in default argument 4930 // expressions should never be able to capture anything. 4931 assert(!Init->getNumObjects() && 4932 "default argument expression has capturing blocks?"); 4933 } 4934 4935 // We already type-checked the argument, so we know it works. 4936 // Just mark all of the declarations in this potentially-evaluated expression 4937 // as being "referenced". 4938 EnterExpressionEvaluationContext EvalContext( 4939 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 4940 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4941 /*SkipLocalVariables=*/true); 4942 return false; 4943 } 4944 4945 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4946 FunctionDecl *FD, ParmVarDecl *Param) { 4947 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 4948 return ExprError(); 4949 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 4950 } 4951 4952 Sema::VariadicCallType 4953 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4954 Expr *Fn) { 4955 if (Proto && Proto->isVariadic()) { 4956 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4957 return VariadicConstructor; 4958 else if (Fn && Fn->getType()->isBlockPointerType()) 4959 return VariadicBlock; 4960 else if (FDecl) { 4961 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4962 if (Method->isInstance()) 4963 return VariadicMethod; 4964 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4965 return VariadicMethod; 4966 return VariadicFunction; 4967 } 4968 return VariadicDoesNotApply; 4969 } 4970 4971 namespace { 4972 class FunctionCallCCC final : public FunctionCallFilterCCC { 4973 public: 4974 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4975 unsigned NumArgs, MemberExpr *ME) 4976 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4977 FunctionName(FuncName) {} 4978 4979 bool ValidateCandidate(const TypoCorrection &candidate) override { 4980 if (!candidate.getCorrectionSpecifier() || 4981 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4982 return false; 4983 } 4984 4985 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4986 } 4987 4988 std::unique_ptr<CorrectionCandidateCallback> clone() override { 4989 return std::make_unique<FunctionCallCCC>(*this); 4990 } 4991 4992 private: 4993 const IdentifierInfo *const FunctionName; 4994 }; 4995 } 4996 4997 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4998 FunctionDecl *FDecl, 4999 ArrayRef<Expr *> Args) { 5000 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 5001 DeclarationName FuncName = FDecl->getDeclName(); 5002 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 5003 5004 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 5005 if (TypoCorrection Corrected = S.CorrectTypo( 5006 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 5007 S.getScopeForContext(S.CurContext), nullptr, CCC, 5008 Sema::CTK_ErrorRecovery)) { 5009 if (NamedDecl *ND = Corrected.getFoundDecl()) { 5010 if (Corrected.isOverloaded()) { 5011 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 5012 OverloadCandidateSet::iterator Best; 5013 for (NamedDecl *CD : Corrected) { 5014 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 5015 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 5016 OCS); 5017 } 5018 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 5019 case OR_Success: 5020 ND = Best->FoundDecl; 5021 Corrected.setCorrectionDecl(ND); 5022 break; 5023 default: 5024 break; 5025 } 5026 } 5027 ND = ND->getUnderlyingDecl(); 5028 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 5029 return Corrected; 5030 } 5031 } 5032 return TypoCorrection(); 5033 } 5034 5035 /// ConvertArgumentsForCall - Converts the arguments specified in 5036 /// Args/NumArgs to the parameter types of the function FDecl with 5037 /// function prototype Proto. Call is the call expression itself, and 5038 /// Fn is the function expression. For a C++ member function, this 5039 /// routine does not attempt to convert the object argument. Returns 5040 /// true if the call is ill-formed. 5041 bool 5042 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5043 FunctionDecl *FDecl, 5044 const FunctionProtoType *Proto, 5045 ArrayRef<Expr *> Args, 5046 SourceLocation RParenLoc, 5047 bool IsExecConfig) { 5048 // Bail out early if calling a builtin with custom typechecking. 5049 if (FDecl) 5050 if (unsigned ID = FDecl->getBuiltinID()) 5051 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 5052 return false; 5053 5054 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 5055 // assignment, to the types of the corresponding parameter, ... 5056 unsigned NumParams = Proto->getNumParams(); 5057 bool Invalid = false; 5058 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 5059 unsigned FnKind = Fn->getType()->isBlockPointerType() 5060 ? 1 /* block */ 5061 : (IsExecConfig ? 3 /* kernel function (exec config) */ 5062 : 0 /* function */); 5063 5064 // If too few arguments are available (and we don't have default 5065 // arguments for the remaining parameters), don't make the call. 5066 if (Args.size() < NumParams) { 5067 if (Args.size() < MinArgs) { 5068 TypoCorrection TC; 5069 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5070 unsigned diag_id = 5071 MinArgs == NumParams && !Proto->isVariadic() 5072 ? diag::err_typecheck_call_too_few_args_suggest 5073 : diag::err_typecheck_call_too_few_args_at_least_suggest; 5074 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 5075 << static_cast<unsigned>(Args.size()) 5076 << TC.getCorrectionRange()); 5077 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 5078 Diag(RParenLoc, 5079 MinArgs == NumParams && !Proto->isVariadic() 5080 ? diag::err_typecheck_call_too_few_args_one 5081 : diag::err_typecheck_call_too_few_args_at_least_one) 5082 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 5083 else 5084 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 5085 ? diag::err_typecheck_call_too_few_args 5086 : diag::err_typecheck_call_too_few_args_at_least) 5087 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 5088 << Fn->getSourceRange(); 5089 5090 // Emit the location of the prototype. 5091 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5092 Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl; 5093 5094 return true; 5095 } 5096 // We reserve space for the default arguments when we create 5097 // the call expression, before calling ConvertArgumentsForCall. 5098 assert((Call->getNumArgs() == NumParams) && 5099 "We should have reserved space for the default arguments before!"); 5100 } 5101 5102 // If too many are passed and not variadic, error on the extras and drop 5103 // them. 5104 if (Args.size() > NumParams) { 5105 if (!Proto->isVariadic()) { 5106 TypoCorrection TC; 5107 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5108 unsigned diag_id = 5109 MinArgs == NumParams && !Proto->isVariadic() 5110 ? diag::err_typecheck_call_too_many_args_suggest 5111 : diag::err_typecheck_call_too_many_args_at_most_suggest; 5112 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 5113 << static_cast<unsigned>(Args.size()) 5114 << TC.getCorrectionRange()); 5115 } else if (NumParams == 1 && FDecl && 5116 FDecl->getParamDecl(0)->getDeclName()) 5117 Diag(Args[NumParams]->getBeginLoc(), 5118 MinArgs == NumParams 5119 ? diag::err_typecheck_call_too_many_args_one 5120 : diag::err_typecheck_call_too_many_args_at_most_one) 5121 << FnKind << FDecl->getParamDecl(0) 5122 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 5123 << SourceRange(Args[NumParams]->getBeginLoc(), 5124 Args.back()->getEndLoc()); 5125 else 5126 Diag(Args[NumParams]->getBeginLoc(), 5127 MinArgs == NumParams 5128 ? diag::err_typecheck_call_too_many_args 5129 : diag::err_typecheck_call_too_many_args_at_most) 5130 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 5131 << Fn->getSourceRange() 5132 << SourceRange(Args[NumParams]->getBeginLoc(), 5133 Args.back()->getEndLoc()); 5134 5135 // Emit the location of the prototype. 5136 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5137 Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl; 5138 5139 // This deletes the extra arguments. 5140 Call->shrinkNumArgs(NumParams); 5141 return true; 5142 } 5143 } 5144 SmallVector<Expr *, 8> AllArgs; 5145 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 5146 5147 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 5148 AllArgs, CallType); 5149 if (Invalid) 5150 return true; 5151 unsigned TotalNumArgs = AllArgs.size(); 5152 for (unsigned i = 0; i < TotalNumArgs; ++i) 5153 Call->setArg(i, AllArgs[i]); 5154 5155 return false; 5156 } 5157 5158 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 5159 const FunctionProtoType *Proto, 5160 unsigned FirstParam, ArrayRef<Expr *> Args, 5161 SmallVectorImpl<Expr *> &AllArgs, 5162 VariadicCallType CallType, bool AllowExplicit, 5163 bool IsListInitialization) { 5164 unsigned NumParams = Proto->getNumParams(); 5165 bool Invalid = false; 5166 size_t ArgIx = 0; 5167 // Continue to check argument types (even if we have too few/many args). 5168 for (unsigned i = FirstParam; i < NumParams; i++) { 5169 QualType ProtoArgType = Proto->getParamType(i); 5170 5171 Expr *Arg; 5172 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 5173 if (ArgIx < Args.size()) { 5174 Arg = Args[ArgIx++]; 5175 5176 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5177 diag::err_call_incomplete_argument, Arg)) 5178 return true; 5179 5180 // Strip the unbridged-cast placeholder expression off, if applicable. 5181 bool CFAudited = false; 5182 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5183 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5184 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5185 Arg = stripARCUnbridgedCast(Arg); 5186 else if (getLangOpts().ObjCAutoRefCount && 5187 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5188 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5189 CFAudited = true; 5190 5191 if (Proto->getExtParameterInfo(i).isNoEscape()) 5192 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 5193 BE->getBlockDecl()->setDoesNotEscape(); 5194 5195 InitializedEntity Entity = 5196 Param ? InitializedEntity::InitializeParameter(Context, Param, 5197 ProtoArgType) 5198 : InitializedEntity::InitializeParameter( 5199 Context, ProtoArgType, Proto->isParamConsumed(i)); 5200 5201 // Remember that parameter belongs to a CF audited API. 5202 if (CFAudited) 5203 Entity.setParameterCFAudited(); 5204 5205 ExprResult ArgE = PerformCopyInitialization( 5206 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 5207 if (ArgE.isInvalid()) 5208 return true; 5209 5210 Arg = ArgE.getAs<Expr>(); 5211 } else { 5212 assert(Param && "can't use default arguments without a known callee"); 5213 5214 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 5215 if (ArgExpr.isInvalid()) 5216 return true; 5217 5218 Arg = ArgExpr.getAs<Expr>(); 5219 } 5220 5221 // Check for array bounds violations for each argument to the call. This 5222 // check only triggers warnings when the argument isn't a more complex Expr 5223 // with its own checking, such as a BinaryOperator. 5224 CheckArrayAccess(Arg); 5225 5226 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 5227 CheckStaticArrayArgument(CallLoc, Param, Arg); 5228 5229 AllArgs.push_back(Arg); 5230 } 5231 5232 // If this is a variadic call, handle args passed through "...". 5233 if (CallType != VariadicDoesNotApply) { 5234 // Assume that extern "C" functions with variadic arguments that 5235 // return __unknown_anytype aren't *really* variadic. 5236 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 5237 FDecl->isExternC()) { 5238 for (Expr *A : Args.slice(ArgIx)) { 5239 QualType paramType; // ignored 5240 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 5241 Invalid |= arg.isInvalid(); 5242 AllArgs.push_back(arg.get()); 5243 } 5244 5245 // Otherwise do argument promotion, (C99 6.5.2.2p7). 5246 } else { 5247 for (Expr *A : Args.slice(ArgIx)) { 5248 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 5249 Invalid |= Arg.isInvalid(); 5250 AllArgs.push_back(Arg.get()); 5251 } 5252 } 5253 5254 // Check for array bounds violations. 5255 for (Expr *A : Args.slice(ArgIx)) 5256 CheckArrayAccess(A); 5257 } 5258 return Invalid; 5259 } 5260 5261 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 5262 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 5263 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 5264 TL = DTL.getOriginalLoc(); 5265 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 5266 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 5267 << ATL.getLocalSourceRange(); 5268 } 5269 5270 /// CheckStaticArrayArgument - If the given argument corresponds to a static 5271 /// array parameter, check that it is non-null, and that if it is formed by 5272 /// array-to-pointer decay, the underlying array is sufficiently large. 5273 /// 5274 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 5275 /// array type derivation, then for each call to the function, the value of the 5276 /// corresponding actual argument shall provide access to the first element of 5277 /// an array with at least as many elements as specified by the size expression. 5278 void 5279 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 5280 ParmVarDecl *Param, 5281 const Expr *ArgExpr) { 5282 // Static array parameters are not supported in C++. 5283 if (!Param || getLangOpts().CPlusPlus) 5284 return; 5285 5286 QualType OrigTy = Param->getOriginalType(); 5287 5288 const ArrayType *AT = Context.getAsArrayType(OrigTy); 5289 if (!AT || AT->getSizeModifier() != ArrayType::Static) 5290 return; 5291 5292 if (ArgExpr->isNullPointerConstant(Context, 5293 Expr::NPC_NeverValueDependent)) { 5294 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 5295 DiagnoseCalleeStaticArrayParam(*this, Param); 5296 return; 5297 } 5298 5299 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 5300 if (!CAT) 5301 return; 5302 5303 const ConstantArrayType *ArgCAT = 5304 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 5305 if (!ArgCAT) 5306 return; 5307 5308 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 5309 ArgCAT->getElementType())) { 5310 if (ArgCAT->getSize().ult(CAT->getSize())) { 5311 Diag(CallLoc, diag::warn_static_array_too_small) 5312 << ArgExpr->getSourceRange() 5313 << (unsigned)ArgCAT->getSize().getZExtValue() 5314 << (unsigned)CAT->getSize().getZExtValue() << 0; 5315 DiagnoseCalleeStaticArrayParam(*this, Param); 5316 } 5317 return; 5318 } 5319 5320 Optional<CharUnits> ArgSize = 5321 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 5322 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 5323 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 5324 Diag(CallLoc, diag::warn_static_array_too_small) 5325 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 5326 << (unsigned)ParmSize->getQuantity() << 1; 5327 DiagnoseCalleeStaticArrayParam(*this, Param); 5328 } 5329 } 5330 5331 /// Given a function expression of unknown-any type, try to rebuild it 5332 /// to have a function type. 5333 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 5334 5335 /// Is the given type a placeholder that we need to lower out 5336 /// immediately during argument processing? 5337 static bool isPlaceholderToRemoveAsArg(QualType type) { 5338 // Placeholders are never sugared. 5339 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 5340 if (!placeholder) return false; 5341 5342 switch (placeholder->getKind()) { 5343 // Ignore all the non-placeholder types. 5344 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 5345 case BuiltinType::Id: 5346 #include "clang/Basic/OpenCLImageTypes.def" 5347 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 5348 case BuiltinType::Id: 5349 #include "clang/Basic/OpenCLExtensionTypes.def" 5350 // In practice we'll never use this, since all SVE types are sugared 5351 // via TypedefTypes rather than exposed directly as BuiltinTypes. 5352 #define SVE_TYPE(Name, Id, SingletonId) \ 5353 case BuiltinType::Id: 5354 #include "clang/Basic/AArch64SVEACLETypes.def" 5355 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 5356 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 5357 #include "clang/AST/BuiltinTypes.def" 5358 return false; 5359 5360 // We cannot lower out overload sets; they might validly be resolved 5361 // by the call machinery. 5362 case BuiltinType::Overload: 5363 return false; 5364 5365 // Unbridged casts in ARC can be handled in some call positions and 5366 // should be left in place. 5367 case BuiltinType::ARCUnbridgedCast: 5368 return false; 5369 5370 // Pseudo-objects should be converted as soon as possible. 5371 case BuiltinType::PseudoObject: 5372 return true; 5373 5374 // The debugger mode could theoretically but currently does not try 5375 // to resolve unknown-typed arguments based on known parameter types. 5376 case BuiltinType::UnknownAny: 5377 return true; 5378 5379 // These are always invalid as call arguments and should be reported. 5380 case BuiltinType::BoundMember: 5381 case BuiltinType::BuiltinFn: 5382 case BuiltinType::OMPArraySection: 5383 return true; 5384 5385 } 5386 llvm_unreachable("bad builtin type kind"); 5387 } 5388 5389 /// Check an argument list for placeholders that we won't try to 5390 /// handle later. 5391 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5392 // Apply this processing to all the arguments at once instead of 5393 // dying at the first failure. 5394 bool hasInvalid = false; 5395 for (size_t i = 0, e = args.size(); i != e; i++) { 5396 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5397 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5398 if (result.isInvalid()) hasInvalid = true; 5399 else args[i] = result.get(); 5400 } else if (hasInvalid) { 5401 (void)S.CorrectDelayedTyposInExpr(args[i]); 5402 } 5403 } 5404 return hasInvalid; 5405 } 5406 5407 /// If a builtin function has a pointer argument with no explicit address 5408 /// space, then it should be able to accept a pointer to any address 5409 /// space as input. In order to do this, we need to replace the 5410 /// standard builtin declaration with one that uses the same address space 5411 /// as the call. 5412 /// 5413 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5414 /// it does not contain any pointer arguments without 5415 /// an address space qualifer. Otherwise the rewritten 5416 /// FunctionDecl is returned. 5417 /// TODO: Handle pointer return types. 5418 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5419 FunctionDecl *FDecl, 5420 MultiExprArg ArgExprs) { 5421 5422 QualType DeclType = FDecl->getType(); 5423 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5424 5425 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 5426 ArgExprs.size() < FT->getNumParams()) 5427 return nullptr; 5428 5429 bool NeedsNewDecl = false; 5430 unsigned i = 0; 5431 SmallVector<QualType, 8> OverloadParams; 5432 5433 for (QualType ParamType : FT->param_types()) { 5434 5435 // Convert array arguments to pointer to simplify type lookup. 5436 ExprResult ArgRes = 5437 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5438 if (ArgRes.isInvalid()) 5439 return nullptr; 5440 Expr *Arg = ArgRes.get(); 5441 QualType ArgType = Arg->getType(); 5442 if (!ParamType->isPointerType() || 5443 ParamType.hasAddressSpace() || 5444 !ArgType->isPointerType() || 5445 !ArgType->getPointeeType().hasAddressSpace()) { 5446 OverloadParams.push_back(ParamType); 5447 continue; 5448 } 5449 5450 QualType PointeeType = ParamType->getPointeeType(); 5451 if (PointeeType.hasAddressSpace()) 5452 continue; 5453 5454 NeedsNewDecl = true; 5455 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 5456 5457 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5458 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5459 } 5460 5461 if (!NeedsNewDecl) 5462 return nullptr; 5463 5464 FunctionProtoType::ExtProtoInfo EPI; 5465 EPI.Variadic = FT->isVariadic(); 5466 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5467 OverloadParams, EPI); 5468 DeclContext *Parent = FDecl->getParent(); 5469 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5470 FDecl->getLocation(), 5471 FDecl->getLocation(), 5472 FDecl->getIdentifier(), 5473 OverloadTy, 5474 /*TInfo=*/nullptr, 5475 SC_Extern, false, 5476 /*hasPrototype=*/true); 5477 SmallVector<ParmVarDecl*, 16> Params; 5478 FT = cast<FunctionProtoType>(OverloadTy); 5479 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5480 QualType ParamType = FT->getParamType(i); 5481 ParmVarDecl *Parm = 5482 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5483 SourceLocation(), nullptr, ParamType, 5484 /*TInfo=*/nullptr, SC_None, nullptr); 5485 Parm->setScopeInfo(0, i); 5486 Params.push_back(Parm); 5487 } 5488 OverloadDecl->setParams(Params); 5489 return OverloadDecl; 5490 } 5491 5492 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 5493 FunctionDecl *Callee, 5494 MultiExprArg ArgExprs) { 5495 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 5496 // similar attributes) really don't like it when functions are called with an 5497 // invalid number of args. 5498 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 5499 /*PartialOverloading=*/false) && 5500 !Callee->isVariadic()) 5501 return; 5502 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 5503 return; 5504 5505 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) { 5506 S.Diag(Fn->getBeginLoc(), 5507 isa<CXXMethodDecl>(Callee) 5508 ? diag::err_ovl_no_viable_member_function_in_call 5509 : diag::err_ovl_no_viable_function_in_call) 5510 << Callee << Callee->getSourceRange(); 5511 S.Diag(Callee->getLocation(), 5512 diag::note_ovl_candidate_disabled_by_function_cond_attr) 5513 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5514 return; 5515 } 5516 } 5517 5518 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 5519 const UnresolvedMemberExpr *const UME, Sema &S) { 5520 5521 const auto GetFunctionLevelDCIfCXXClass = 5522 [](Sema &S) -> const CXXRecordDecl * { 5523 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 5524 if (!DC || !DC->getParent()) 5525 return nullptr; 5526 5527 // If the call to some member function was made from within a member 5528 // function body 'M' return return 'M's parent. 5529 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 5530 return MD->getParent()->getCanonicalDecl(); 5531 // else the call was made from within a default member initializer of a 5532 // class, so return the class. 5533 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 5534 return RD->getCanonicalDecl(); 5535 return nullptr; 5536 }; 5537 // If our DeclContext is neither a member function nor a class (in the 5538 // case of a lambda in a default member initializer), we can't have an 5539 // enclosing 'this'. 5540 5541 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 5542 if (!CurParentClass) 5543 return false; 5544 5545 // The naming class for implicit member functions call is the class in which 5546 // name lookup starts. 5547 const CXXRecordDecl *const NamingClass = 5548 UME->getNamingClass()->getCanonicalDecl(); 5549 assert(NamingClass && "Must have naming class even for implicit access"); 5550 5551 // If the unresolved member functions were found in a 'naming class' that is 5552 // related (either the same or derived from) to the class that contains the 5553 // member function that itself contained the implicit member access. 5554 5555 return CurParentClass == NamingClass || 5556 CurParentClass->isDerivedFrom(NamingClass); 5557 } 5558 5559 static void 5560 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5561 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 5562 5563 if (!UME) 5564 return; 5565 5566 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 5567 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 5568 // already been captured, or if this is an implicit member function call (if 5569 // it isn't, an attempt to capture 'this' should already have been made). 5570 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 5571 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 5572 return; 5573 5574 // Check if the naming class in which the unresolved members were found is 5575 // related (same as or is a base of) to the enclosing class. 5576 5577 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 5578 return; 5579 5580 5581 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 5582 // If the enclosing function is not dependent, then this lambda is 5583 // capture ready, so if we can capture this, do so. 5584 if (!EnclosingFunctionCtx->isDependentContext()) { 5585 // If the current lambda and all enclosing lambdas can capture 'this' - 5586 // then go ahead and capture 'this' (since our unresolved overload set 5587 // contains at least one non-static member function). 5588 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 5589 S.CheckCXXThisCapture(CallLoc); 5590 } else if (S.CurContext->isDependentContext()) { 5591 // ... since this is an implicit member reference, that might potentially 5592 // involve a 'this' capture, mark 'this' for potential capture in 5593 // enclosing lambdas. 5594 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 5595 CurLSI->addPotentialThisCapture(CallLoc); 5596 } 5597 } 5598 5599 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5600 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5601 Expr *ExecConfig) { 5602 ExprResult Call = 5603 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig); 5604 if (Call.isInvalid()) 5605 return Call; 5606 5607 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 5608 // language modes. 5609 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 5610 if (ULE->hasExplicitTemplateArgs() && 5611 ULE->decls_begin() == ULE->decls_end()) { 5612 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus2a 5613 ? diag::warn_cxx17_compat_adl_only_template_id 5614 : diag::ext_adl_only_template_id) 5615 << ULE->getName(); 5616 } 5617 } 5618 5619 return Call; 5620 } 5621 5622 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 5623 /// This provides the location of the left/right parens and a list of comma 5624 /// locations. 5625 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5626 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5627 Expr *ExecConfig, bool IsExecConfig) { 5628 // Since this might be a postfix expression, get rid of ParenListExprs. 5629 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 5630 if (Result.isInvalid()) return ExprError(); 5631 Fn = Result.get(); 5632 5633 if (checkArgsForPlaceholders(*this, ArgExprs)) 5634 return ExprError(); 5635 5636 if (getLangOpts().CPlusPlus) { 5637 // If this is a pseudo-destructor expression, build the call immediately. 5638 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5639 if (!ArgExprs.empty()) { 5640 // Pseudo-destructor calls should not have any arguments. 5641 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 5642 << FixItHint::CreateRemoval( 5643 SourceRange(ArgExprs.front()->getBeginLoc(), 5644 ArgExprs.back()->getEndLoc())); 5645 } 5646 5647 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 5648 VK_RValue, RParenLoc); 5649 } 5650 if (Fn->getType() == Context.PseudoObjectTy) { 5651 ExprResult result = CheckPlaceholderExpr(Fn); 5652 if (result.isInvalid()) return ExprError(); 5653 Fn = result.get(); 5654 } 5655 5656 // Determine whether this is a dependent call inside a C++ template, 5657 // in which case we won't do any semantic analysis now. 5658 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 5659 if (ExecConfig) { 5660 return CUDAKernelCallExpr::Create( 5661 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5662 Context.DependentTy, VK_RValue, RParenLoc); 5663 } else { 5664 5665 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5666 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 5667 Fn->getBeginLoc()); 5668 5669 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 5670 VK_RValue, RParenLoc); 5671 } 5672 } 5673 5674 // Determine whether this is a call to an object (C++ [over.call.object]). 5675 if (Fn->getType()->isRecordType()) 5676 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 5677 RParenLoc); 5678 5679 if (Fn->getType() == Context.UnknownAnyTy) { 5680 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5681 if (result.isInvalid()) return ExprError(); 5682 Fn = result.get(); 5683 } 5684 5685 if (Fn->getType() == Context.BoundMemberTy) { 5686 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5687 RParenLoc); 5688 } 5689 } 5690 5691 // Check for overloaded calls. This can happen even in C due to extensions. 5692 if (Fn->getType() == Context.OverloadTy) { 5693 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5694 5695 // We aren't supposed to apply this logic if there's an '&' involved. 5696 if (!find.HasFormOfMemberPointer) { 5697 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5698 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 5699 VK_RValue, RParenLoc); 5700 OverloadExpr *ovl = find.Expression; 5701 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5702 return BuildOverloadedCallExpr( 5703 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 5704 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 5705 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5706 RParenLoc); 5707 } 5708 } 5709 5710 // If we're directly calling a function, get the appropriate declaration. 5711 if (Fn->getType() == Context.UnknownAnyTy) { 5712 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5713 if (result.isInvalid()) return ExprError(); 5714 Fn = result.get(); 5715 } 5716 5717 Expr *NakedFn = Fn->IgnoreParens(); 5718 5719 bool CallingNDeclIndirectly = false; 5720 NamedDecl *NDecl = nullptr; 5721 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5722 if (UnOp->getOpcode() == UO_AddrOf) { 5723 CallingNDeclIndirectly = true; 5724 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5725 } 5726 } 5727 5728 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 5729 NDecl = DRE->getDecl(); 5730 5731 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5732 if (FDecl && FDecl->getBuiltinID()) { 5733 // Rewrite the function decl for this builtin by replacing parameters 5734 // with no explicit address space with the address space of the arguments 5735 // in ArgExprs. 5736 if ((FDecl = 5737 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5738 NDecl = FDecl; 5739 Fn = DeclRefExpr::Create( 5740 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 5741 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 5742 nullptr, DRE->isNonOdrUse()); 5743 } 5744 } 5745 } else if (isa<MemberExpr>(NakedFn)) 5746 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5747 5748 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5749 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 5750 FD, /*Complain=*/true, Fn->getBeginLoc())) 5751 return ExprError(); 5752 5753 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 5754 return ExprError(); 5755 5756 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 5757 } 5758 5759 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5760 ExecConfig, IsExecConfig); 5761 } 5762 5763 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5764 /// 5765 /// __builtin_astype( value, dst type ) 5766 /// 5767 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5768 SourceLocation BuiltinLoc, 5769 SourceLocation RParenLoc) { 5770 ExprValueKind VK = VK_RValue; 5771 ExprObjectKind OK = OK_Ordinary; 5772 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5773 QualType SrcTy = E->getType(); 5774 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5775 return ExprError(Diag(BuiltinLoc, 5776 diag::err_invalid_astype_of_different_size) 5777 << DstTy 5778 << SrcTy 5779 << E->getSourceRange()); 5780 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5781 } 5782 5783 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5784 /// provided arguments. 5785 /// 5786 /// __builtin_convertvector( value, dst type ) 5787 /// 5788 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5789 SourceLocation BuiltinLoc, 5790 SourceLocation RParenLoc) { 5791 TypeSourceInfo *TInfo; 5792 GetTypeFromParser(ParsedDestTy, &TInfo); 5793 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5794 } 5795 5796 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5797 /// i.e. an expression not of \p OverloadTy. The expression should 5798 /// unary-convert to an expression of function-pointer or 5799 /// block-pointer type. 5800 /// 5801 /// \param NDecl the declaration being called, if available 5802 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5803 SourceLocation LParenLoc, 5804 ArrayRef<Expr *> Args, 5805 SourceLocation RParenLoc, Expr *Config, 5806 bool IsExecConfig, ADLCallKind UsesADL) { 5807 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5808 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5809 5810 // Functions with 'interrupt' attribute cannot be called directly. 5811 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5812 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5813 return ExprError(); 5814 } 5815 5816 // Interrupt handlers don't save off the VFP regs automatically on ARM, 5817 // so there's some risk when calling out to non-interrupt handler functions 5818 // that the callee might not preserve them. This is easy to diagnose here, 5819 // but can be very challenging to debug. 5820 if (auto *Caller = getCurFunctionDecl()) 5821 if (Caller->hasAttr<ARMInterruptAttr>()) { 5822 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 5823 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) 5824 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 5825 } 5826 5827 // Promote the function operand. 5828 // We special-case function promotion here because we only allow promoting 5829 // builtin functions to function pointers in the callee of a call. 5830 ExprResult Result; 5831 QualType ResultTy; 5832 if (BuiltinID && 5833 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5834 // Extract the return type from the (builtin) function pointer type. 5835 // FIXME Several builtins still have setType in 5836 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 5837 // Builtins.def to ensure they are correct before removing setType calls. 5838 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 5839 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 5840 ResultTy = FDecl->getCallResultType(); 5841 } else { 5842 Result = CallExprUnaryConversions(Fn); 5843 ResultTy = Context.BoolTy; 5844 } 5845 if (Result.isInvalid()) 5846 return ExprError(); 5847 Fn = Result.get(); 5848 5849 // Check for a valid function type, but only if it is not a builtin which 5850 // requires custom type checking. These will be handled by 5851 // CheckBuiltinFunctionCall below just after creation of the call expression. 5852 const FunctionType *FuncT = nullptr; 5853 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 5854 retry: 5855 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5856 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5857 // have type pointer to function". 5858 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5859 if (!FuncT) 5860 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5861 << Fn->getType() << Fn->getSourceRange()); 5862 } else if (const BlockPointerType *BPT = 5863 Fn->getType()->getAs<BlockPointerType>()) { 5864 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5865 } else { 5866 // Handle calls to expressions of unknown-any type. 5867 if (Fn->getType() == Context.UnknownAnyTy) { 5868 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5869 if (rewrite.isInvalid()) 5870 return ExprError(); 5871 Fn = rewrite.get(); 5872 goto retry; 5873 } 5874 5875 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5876 << Fn->getType() << Fn->getSourceRange()); 5877 } 5878 } 5879 5880 // Get the number of parameters in the function prototype, if any. 5881 // We will allocate space for max(Args.size(), NumParams) arguments 5882 // in the call expression. 5883 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 5884 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 5885 5886 CallExpr *TheCall; 5887 if (Config) { 5888 assert(UsesADL == ADLCallKind::NotADL && 5889 "CUDAKernelCallExpr should not use ADL"); 5890 TheCall = 5891 CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args, 5892 ResultTy, VK_RValue, RParenLoc, NumParams); 5893 } else { 5894 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, 5895 RParenLoc, NumParams, UsesADL); 5896 } 5897 5898 if (!getLangOpts().CPlusPlus) { 5899 // Forget about the nulled arguments since typo correction 5900 // do not handle them well. 5901 TheCall->shrinkNumArgs(Args.size()); 5902 // C cannot always handle TypoExpr nodes in builtin calls and direct 5903 // function calls as their argument checking don't necessarily handle 5904 // dependent types properly, so make sure any TypoExprs have been 5905 // dealt with. 5906 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5907 if (!Result.isUsable()) return ExprError(); 5908 CallExpr *TheOldCall = TheCall; 5909 TheCall = dyn_cast<CallExpr>(Result.get()); 5910 bool CorrectedTypos = TheCall != TheOldCall; 5911 if (!TheCall) return Result; 5912 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5913 5914 // A new call expression node was created if some typos were corrected. 5915 // However it may not have been constructed with enough storage. In this 5916 // case, rebuild the node with enough storage. The waste of space is 5917 // immaterial since this only happens when some typos were corrected. 5918 if (CorrectedTypos && Args.size() < NumParams) { 5919 if (Config) 5920 TheCall = CUDAKernelCallExpr::Create( 5921 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue, 5922 RParenLoc, NumParams); 5923 else 5924 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, 5925 RParenLoc, NumParams, UsesADL); 5926 } 5927 // We can now handle the nulled arguments for the default arguments. 5928 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 5929 } 5930 5931 // Bail out early if calling a builtin with custom type checking. 5932 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5933 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5934 5935 if (getLangOpts().CUDA) { 5936 if (Config) { 5937 // CUDA: Kernel calls must be to global functions 5938 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5939 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5940 << FDecl << Fn->getSourceRange()); 5941 5942 // CUDA: Kernel function must have 'void' return type 5943 if (!FuncT->getReturnType()->isVoidType() && 5944 !FuncT->getReturnType()->getAs<AutoType>() && 5945 !FuncT->getReturnType()->isInstantiationDependentType()) 5946 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5947 << Fn->getType() << Fn->getSourceRange()); 5948 } else { 5949 // CUDA: Calls to global functions must be configured 5950 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5951 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5952 << FDecl << Fn->getSourceRange()); 5953 } 5954 } 5955 5956 // Check for a valid return type 5957 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 5958 FDecl)) 5959 return ExprError(); 5960 5961 // We know the result type of the call, set it. 5962 TheCall->setType(FuncT->getCallResultType(Context)); 5963 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5964 5965 if (Proto) { 5966 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5967 IsExecConfig)) 5968 return ExprError(); 5969 } else { 5970 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5971 5972 if (FDecl) { 5973 // Check if we have too few/too many template arguments, based 5974 // on our knowledge of the function definition. 5975 const FunctionDecl *Def = nullptr; 5976 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5977 Proto = Def->getType()->getAs<FunctionProtoType>(); 5978 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5979 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5980 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5981 } 5982 5983 // If the function we're calling isn't a function prototype, but we have 5984 // a function prototype from a prior declaratiom, use that prototype. 5985 if (!FDecl->hasPrototype()) 5986 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5987 } 5988 5989 // Promote the arguments (C99 6.5.2.2p6). 5990 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5991 Expr *Arg = Args[i]; 5992 5993 if (Proto && i < Proto->getNumParams()) { 5994 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5995 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5996 ExprResult ArgE = 5997 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5998 if (ArgE.isInvalid()) 5999 return true; 6000 6001 Arg = ArgE.getAs<Expr>(); 6002 6003 } else { 6004 ExprResult ArgE = DefaultArgumentPromotion(Arg); 6005 6006 if (ArgE.isInvalid()) 6007 return true; 6008 6009 Arg = ArgE.getAs<Expr>(); 6010 } 6011 6012 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 6013 diag::err_call_incomplete_argument, Arg)) 6014 return ExprError(); 6015 6016 TheCall->setArg(i, Arg); 6017 } 6018 } 6019 6020 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 6021 if (!Method->isStatic()) 6022 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 6023 << Fn->getSourceRange()); 6024 6025 // Check for sentinels 6026 if (NDecl) 6027 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 6028 6029 // Do special checking on direct calls to functions. 6030 if (FDecl) { 6031 if (CheckFunctionCall(FDecl, TheCall, Proto)) 6032 return ExprError(); 6033 6034 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 6035 6036 if (BuiltinID) 6037 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6038 } else if (NDecl) { 6039 if (CheckPointerCall(NDecl, TheCall, Proto)) 6040 return ExprError(); 6041 } else { 6042 if (CheckOtherCall(TheCall, Proto)) 6043 return ExprError(); 6044 } 6045 6046 return MaybeBindToTemporary(TheCall); 6047 } 6048 6049 ExprResult 6050 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 6051 SourceLocation RParenLoc, Expr *InitExpr) { 6052 assert(Ty && "ActOnCompoundLiteral(): missing type"); 6053 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 6054 6055 TypeSourceInfo *TInfo; 6056 QualType literalType = GetTypeFromParser(Ty, &TInfo); 6057 if (!TInfo) 6058 TInfo = Context.getTrivialTypeSourceInfo(literalType); 6059 6060 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 6061 } 6062 6063 ExprResult 6064 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 6065 SourceLocation RParenLoc, Expr *LiteralExpr) { 6066 QualType literalType = TInfo->getType(); 6067 6068 if (literalType->isArrayType()) { 6069 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 6070 diag::err_illegal_decl_array_incomplete_type, 6071 SourceRange(LParenLoc, 6072 LiteralExpr->getSourceRange().getEnd()))) 6073 return ExprError(); 6074 if (literalType->isVariableArrayType()) 6075 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 6076 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 6077 } else if (!literalType->isDependentType() && 6078 RequireCompleteType(LParenLoc, literalType, 6079 diag::err_typecheck_decl_incomplete_type, 6080 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6081 return ExprError(); 6082 6083 InitializedEntity Entity 6084 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 6085 InitializationKind Kind 6086 = InitializationKind::CreateCStyleCast(LParenLoc, 6087 SourceRange(LParenLoc, RParenLoc), 6088 /*InitList=*/true); 6089 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 6090 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 6091 &literalType); 6092 if (Result.isInvalid()) 6093 return ExprError(); 6094 LiteralExpr = Result.get(); 6095 6096 bool isFileScope = !CurContext->isFunctionOrMethod(); 6097 6098 // In C, compound literals are l-values for some reason. 6099 // For GCC compatibility, in C++, file-scope array compound literals with 6100 // constant initializers are also l-values, and compound literals are 6101 // otherwise prvalues. 6102 // 6103 // (GCC also treats C++ list-initialized file-scope array prvalues with 6104 // constant initializers as l-values, but that's non-conforming, so we don't 6105 // follow it there.) 6106 // 6107 // FIXME: It would be better to handle the lvalue cases as materializing and 6108 // lifetime-extending a temporary object, but our materialized temporaries 6109 // representation only supports lifetime extension from a variable, not "out 6110 // of thin air". 6111 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 6112 // is bound to the result of applying array-to-pointer decay to the compound 6113 // literal. 6114 // FIXME: GCC supports compound literals of reference type, which should 6115 // obviously have a value kind derived from the kind of reference involved. 6116 ExprValueKind VK = 6117 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 6118 ? VK_RValue 6119 : VK_LValue; 6120 6121 if (isFileScope) 6122 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 6123 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 6124 Expr *Init = ILE->getInit(i); 6125 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 6126 } 6127 6128 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 6129 VK, LiteralExpr, isFileScope); 6130 if (isFileScope) { 6131 if (!LiteralExpr->isTypeDependent() && 6132 !LiteralExpr->isValueDependent() && 6133 !literalType->isDependentType()) // C99 6.5.2.5p3 6134 if (CheckForConstantInitializer(LiteralExpr, literalType)) 6135 return ExprError(); 6136 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 6137 literalType.getAddressSpace() != LangAS::Default) { 6138 // Embedded-C extensions to C99 6.5.2.5: 6139 // "If the compound literal occurs inside the body of a function, the 6140 // type name shall not be qualified by an address-space qualifier." 6141 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 6142 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 6143 return ExprError(); 6144 } 6145 6146 // Compound literals that have automatic storage duration are destroyed at 6147 // the end of the scope. Emit diagnostics if it is or contains a C union type 6148 // that is non-trivial to destruct. 6149 if (!isFileScope) 6150 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 6151 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 6152 NTCUC_CompoundLiteral, NTCUK_Destruct); 6153 6154 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 6155 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 6156 checkNonTrivialCUnionInInitializer(E->getInitializer(), 6157 E->getInitializer()->getExprLoc()); 6158 6159 return MaybeBindToTemporary(E); 6160 } 6161 6162 ExprResult 6163 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6164 SourceLocation RBraceLoc) { 6165 // Only produce each kind of designated initialization diagnostic once. 6166 SourceLocation FirstDesignator; 6167 bool DiagnosedArrayDesignator = false; 6168 bool DiagnosedNestedDesignator = false; 6169 bool DiagnosedMixedDesignator = false; 6170 6171 // Check that any designated initializers are syntactically valid in the 6172 // current language mode. 6173 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6174 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 6175 if (FirstDesignator.isInvalid()) 6176 FirstDesignator = DIE->getBeginLoc(); 6177 6178 if (!getLangOpts().CPlusPlus) 6179 break; 6180 6181 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 6182 DiagnosedNestedDesignator = true; 6183 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 6184 << DIE->getDesignatorsSourceRange(); 6185 } 6186 6187 for (auto &Desig : DIE->designators()) { 6188 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 6189 DiagnosedArrayDesignator = true; 6190 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 6191 << Desig.getSourceRange(); 6192 } 6193 } 6194 6195 if (!DiagnosedMixedDesignator && 6196 !isa<DesignatedInitExpr>(InitArgList[0])) { 6197 DiagnosedMixedDesignator = true; 6198 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6199 << DIE->getSourceRange(); 6200 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 6201 << InitArgList[0]->getSourceRange(); 6202 } 6203 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 6204 isa<DesignatedInitExpr>(InitArgList[0])) { 6205 DiagnosedMixedDesignator = true; 6206 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 6207 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6208 << DIE->getSourceRange(); 6209 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 6210 << InitArgList[I]->getSourceRange(); 6211 } 6212 } 6213 6214 if (FirstDesignator.isValid()) { 6215 // Only diagnose designated initiaization as a C++20 extension if we didn't 6216 // already diagnose use of (non-C++20) C99 designator syntax. 6217 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 6218 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 6219 Diag(FirstDesignator, getLangOpts().CPlusPlus2a 6220 ? diag::warn_cxx17_compat_designated_init 6221 : diag::ext_cxx_designated_init); 6222 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 6223 Diag(FirstDesignator, diag::ext_designated_init); 6224 } 6225 } 6226 6227 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 6228 } 6229 6230 ExprResult 6231 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6232 SourceLocation RBraceLoc) { 6233 // Semantic analysis for initializers is done by ActOnDeclarator() and 6234 // CheckInitializer() - it requires knowledge of the object being initialized. 6235 6236 // Immediately handle non-overload placeholders. Overloads can be 6237 // resolved contextually, but everything else here can't. 6238 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6239 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 6240 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 6241 6242 // Ignore failures; dropping the entire initializer list because 6243 // of one failure would be terrible for indexing/etc. 6244 if (result.isInvalid()) continue; 6245 6246 InitArgList[I] = result.get(); 6247 } 6248 } 6249 6250 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 6251 RBraceLoc); 6252 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 6253 return E; 6254 } 6255 6256 /// Do an explicit extend of the given block pointer if we're in ARC. 6257 void Sema::maybeExtendBlockObject(ExprResult &E) { 6258 assert(E.get()->getType()->isBlockPointerType()); 6259 assert(E.get()->isRValue()); 6260 6261 // Only do this in an r-value context. 6262 if (!getLangOpts().ObjCAutoRefCount) return; 6263 6264 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 6265 CK_ARCExtendBlockObject, E.get(), 6266 /*base path*/ nullptr, VK_RValue); 6267 Cleanup.setExprNeedsCleanups(true); 6268 } 6269 6270 /// Prepare a conversion of the given expression to an ObjC object 6271 /// pointer type. 6272 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 6273 QualType type = E.get()->getType(); 6274 if (type->isObjCObjectPointerType()) { 6275 return CK_BitCast; 6276 } else if (type->isBlockPointerType()) { 6277 maybeExtendBlockObject(E); 6278 return CK_BlockPointerToObjCPointerCast; 6279 } else { 6280 assert(type->isPointerType()); 6281 return CK_CPointerToObjCPointerCast; 6282 } 6283 } 6284 6285 /// Prepares for a scalar cast, performing all the necessary stages 6286 /// except the final cast and returning the kind required. 6287 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 6288 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 6289 // Also, callers should have filtered out the invalid cases with 6290 // pointers. Everything else should be possible. 6291 6292 QualType SrcTy = Src.get()->getType(); 6293 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 6294 return CK_NoOp; 6295 6296 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 6297 case Type::STK_MemberPointer: 6298 llvm_unreachable("member pointer type in C"); 6299 6300 case Type::STK_CPointer: 6301 case Type::STK_BlockPointer: 6302 case Type::STK_ObjCObjectPointer: 6303 switch (DestTy->getScalarTypeKind()) { 6304 case Type::STK_CPointer: { 6305 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 6306 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 6307 if (SrcAS != DestAS) 6308 return CK_AddressSpaceConversion; 6309 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 6310 return CK_NoOp; 6311 return CK_BitCast; 6312 } 6313 case Type::STK_BlockPointer: 6314 return (SrcKind == Type::STK_BlockPointer 6315 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 6316 case Type::STK_ObjCObjectPointer: 6317 if (SrcKind == Type::STK_ObjCObjectPointer) 6318 return CK_BitCast; 6319 if (SrcKind == Type::STK_CPointer) 6320 return CK_CPointerToObjCPointerCast; 6321 maybeExtendBlockObject(Src); 6322 return CK_BlockPointerToObjCPointerCast; 6323 case Type::STK_Bool: 6324 return CK_PointerToBoolean; 6325 case Type::STK_Integral: 6326 return CK_PointerToIntegral; 6327 case Type::STK_Floating: 6328 case Type::STK_FloatingComplex: 6329 case Type::STK_IntegralComplex: 6330 case Type::STK_MemberPointer: 6331 case Type::STK_FixedPoint: 6332 llvm_unreachable("illegal cast from pointer"); 6333 } 6334 llvm_unreachable("Should have returned before this"); 6335 6336 case Type::STK_FixedPoint: 6337 switch (DestTy->getScalarTypeKind()) { 6338 case Type::STK_FixedPoint: 6339 return CK_FixedPointCast; 6340 case Type::STK_Bool: 6341 return CK_FixedPointToBoolean; 6342 case Type::STK_Integral: 6343 return CK_FixedPointToIntegral; 6344 case Type::STK_Floating: 6345 case Type::STK_IntegralComplex: 6346 case Type::STK_FloatingComplex: 6347 Diag(Src.get()->getExprLoc(), 6348 diag::err_unimplemented_conversion_with_fixed_point_type) 6349 << DestTy; 6350 return CK_IntegralCast; 6351 case Type::STK_CPointer: 6352 case Type::STK_ObjCObjectPointer: 6353 case Type::STK_BlockPointer: 6354 case Type::STK_MemberPointer: 6355 llvm_unreachable("illegal cast to pointer type"); 6356 } 6357 llvm_unreachable("Should have returned before this"); 6358 6359 case Type::STK_Bool: // casting from bool is like casting from an integer 6360 case Type::STK_Integral: 6361 switch (DestTy->getScalarTypeKind()) { 6362 case Type::STK_CPointer: 6363 case Type::STK_ObjCObjectPointer: 6364 case Type::STK_BlockPointer: 6365 if (Src.get()->isNullPointerConstant(Context, 6366 Expr::NPC_ValueDependentIsNull)) 6367 return CK_NullToPointer; 6368 return CK_IntegralToPointer; 6369 case Type::STK_Bool: 6370 return CK_IntegralToBoolean; 6371 case Type::STK_Integral: 6372 return CK_IntegralCast; 6373 case Type::STK_Floating: 6374 return CK_IntegralToFloating; 6375 case Type::STK_IntegralComplex: 6376 Src = ImpCastExprToType(Src.get(), 6377 DestTy->castAs<ComplexType>()->getElementType(), 6378 CK_IntegralCast); 6379 return CK_IntegralRealToComplex; 6380 case Type::STK_FloatingComplex: 6381 Src = ImpCastExprToType(Src.get(), 6382 DestTy->castAs<ComplexType>()->getElementType(), 6383 CK_IntegralToFloating); 6384 return CK_FloatingRealToComplex; 6385 case Type::STK_MemberPointer: 6386 llvm_unreachable("member pointer type in C"); 6387 case Type::STK_FixedPoint: 6388 return CK_IntegralToFixedPoint; 6389 } 6390 llvm_unreachable("Should have returned before this"); 6391 6392 case Type::STK_Floating: 6393 switch (DestTy->getScalarTypeKind()) { 6394 case Type::STK_Floating: 6395 return CK_FloatingCast; 6396 case Type::STK_Bool: 6397 return CK_FloatingToBoolean; 6398 case Type::STK_Integral: 6399 return CK_FloatingToIntegral; 6400 case Type::STK_FloatingComplex: 6401 Src = ImpCastExprToType(Src.get(), 6402 DestTy->castAs<ComplexType>()->getElementType(), 6403 CK_FloatingCast); 6404 return CK_FloatingRealToComplex; 6405 case Type::STK_IntegralComplex: 6406 Src = ImpCastExprToType(Src.get(), 6407 DestTy->castAs<ComplexType>()->getElementType(), 6408 CK_FloatingToIntegral); 6409 return CK_IntegralRealToComplex; 6410 case Type::STK_CPointer: 6411 case Type::STK_ObjCObjectPointer: 6412 case Type::STK_BlockPointer: 6413 llvm_unreachable("valid float->pointer cast?"); 6414 case Type::STK_MemberPointer: 6415 llvm_unreachable("member pointer type in C"); 6416 case Type::STK_FixedPoint: 6417 Diag(Src.get()->getExprLoc(), 6418 diag::err_unimplemented_conversion_with_fixed_point_type) 6419 << SrcTy; 6420 return CK_IntegralCast; 6421 } 6422 llvm_unreachable("Should have returned before this"); 6423 6424 case Type::STK_FloatingComplex: 6425 switch (DestTy->getScalarTypeKind()) { 6426 case Type::STK_FloatingComplex: 6427 return CK_FloatingComplexCast; 6428 case Type::STK_IntegralComplex: 6429 return CK_FloatingComplexToIntegralComplex; 6430 case Type::STK_Floating: { 6431 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 6432 if (Context.hasSameType(ET, DestTy)) 6433 return CK_FloatingComplexToReal; 6434 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 6435 return CK_FloatingCast; 6436 } 6437 case Type::STK_Bool: 6438 return CK_FloatingComplexToBoolean; 6439 case Type::STK_Integral: 6440 Src = ImpCastExprToType(Src.get(), 6441 SrcTy->castAs<ComplexType>()->getElementType(), 6442 CK_FloatingComplexToReal); 6443 return CK_FloatingToIntegral; 6444 case Type::STK_CPointer: 6445 case Type::STK_ObjCObjectPointer: 6446 case Type::STK_BlockPointer: 6447 llvm_unreachable("valid complex float->pointer cast?"); 6448 case Type::STK_MemberPointer: 6449 llvm_unreachable("member pointer type in C"); 6450 case Type::STK_FixedPoint: 6451 Diag(Src.get()->getExprLoc(), 6452 diag::err_unimplemented_conversion_with_fixed_point_type) 6453 << SrcTy; 6454 return CK_IntegralCast; 6455 } 6456 llvm_unreachable("Should have returned before this"); 6457 6458 case Type::STK_IntegralComplex: 6459 switch (DestTy->getScalarTypeKind()) { 6460 case Type::STK_FloatingComplex: 6461 return CK_IntegralComplexToFloatingComplex; 6462 case Type::STK_IntegralComplex: 6463 return CK_IntegralComplexCast; 6464 case Type::STK_Integral: { 6465 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 6466 if (Context.hasSameType(ET, DestTy)) 6467 return CK_IntegralComplexToReal; 6468 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 6469 return CK_IntegralCast; 6470 } 6471 case Type::STK_Bool: 6472 return CK_IntegralComplexToBoolean; 6473 case Type::STK_Floating: 6474 Src = ImpCastExprToType(Src.get(), 6475 SrcTy->castAs<ComplexType>()->getElementType(), 6476 CK_IntegralComplexToReal); 6477 return CK_IntegralToFloating; 6478 case Type::STK_CPointer: 6479 case Type::STK_ObjCObjectPointer: 6480 case Type::STK_BlockPointer: 6481 llvm_unreachable("valid complex int->pointer cast?"); 6482 case Type::STK_MemberPointer: 6483 llvm_unreachable("member pointer type in C"); 6484 case Type::STK_FixedPoint: 6485 Diag(Src.get()->getExprLoc(), 6486 diag::err_unimplemented_conversion_with_fixed_point_type) 6487 << SrcTy; 6488 return CK_IntegralCast; 6489 } 6490 llvm_unreachable("Should have returned before this"); 6491 } 6492 6493 llvm_unreachable("Unhandled scalar cast"); 6494 } 6495 6496 static bool breakDownVectorType(QualType type, uint64_t &len, 6497 QualType &eltType) { 6498 // Vectors are simple. 6499 if (const VectorType *vecType = type->getAs<VectorType>()) { 6500 len = vecType->getNumElements(); 6501 eltType = vecType->getElementType(); 6502 assert(eltType->isScalarType()); 6503 return true; 6504 } 6505 6506 // We allow lax conversion to and from non-vector types, but only if 6507 // they're real types (i.e. non-complex, non-pointer scalar types). 6508 if (!type->isRealType()) return false; 6509 6510 len = 1; 6511 eltType = type; 6512 return true; 6513 } 6514 6515 /// Are the two types lax-compatible vector types? That is, given 6516 /// that one of them is a vector, do they have equal storage sizes, 6517 /// where the storage size is the number of elements times the element 6518 /// size? 6519 /// 6520 /// This will also return false if either of the types is neither a 6521 /// vector nor a real type. 6522 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 6523 assert(destTy->isVectorType() || srcTy->isVectorType()); 6524 6525 // Disallow lax conversions between scalars and ExtVectors (these 6526 // conversions are allowed for other vector types because common headers 6527 // depend on them). Most scalar OP ExtVector cases are handled by the 6528 // splat path anyway, which does what we want (convert, not bitcast). 6529 // What this rules out for ExtVectors is crazy things like char4*float. 6530 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 6531 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 6532 6533 uint64_t srcLen, destLen; 6534 QualType srcEltTy, destEltTy; 6535 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 6536 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 6537 6538 // ASTContext::getTypeSize will return the size rounded up to a 6539 // power of 2, so instead of using that, we need to use the raw 6540 // element size multiplied by the element count. 6541 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 6542 uint64_t destEltSize = Context.getTypeSize(destEltTy); 6543 6544 return (srcLen * srcEltSize == destLen * destEltSize); 6545 } 6546 6547 /// Is this a legal conversion between two types, one of which is 6548 /// known to be a vector type? 6549 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 6550 assert(destTy->isVectorType() || srcTy->isVectorType()); 6551 6552 switch (Context.getLangOpts().getLaxVectorConversions()) { 6553 case LangOptions::LaxVectorConversionKind::None: 6554 return false; 6555 6556 case LangOptions::LaxVectorConversionKind::Integer: 6557 if (!srcTy->isIntegralOrEnumerationType()) { 6558 auto *Vec = srcTy->getAs<VectorType>(); 6559 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 6560 return false; 6561 } 6562 if (!destTy->isIntegralOrEnumerationType()) { 6563 auto *Vec = destTy->getAs<VectorType>(); 6564 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 6565 return false; 6566 } 6567 // OK, integer (vector) -> integer (vector) bitcast. 6568 break; 6569 6570 case LangOptions::LaxVectorConversionKind::All: 6571 break; 6572 } 6573 6574 return areLaxCompatibleVectorTypes(srcTy, destTy); 6575 } 6576 6577 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 6578 CastKind &Kind) { 6579 assert(VectorTy->isVectorType() && "Not a vector type!"); 6580 6581 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 6582 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 6583 return Diag(R.getBegin(), 6584 Ty->isVectorType() ? 6585 diag::err_invalid_conversion_between_vectors : 6586 diag::err_invalid_conversion_between_vector_and_integer) 6587 << VectorTy << Ty << R; 6588 } else 6589 return Diag(R.getBegin(), 6590 diag::err_invalid_conversion_between_vector_and_scalar) 6591 << VectorTy << Ty << R; 6592 6593 Kind = CK_BitCast; 6594 return false; 6595 } 6596 6597 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 6598 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 6599 6600 if (DestElemTy == SplattedExpr->getType()) 6601 return SplattedExpr; 6602 6603 assert(DestElemTy->isFloatingType() || 6604 DestElemTy->isIntegralOrEnumerationType()); 6605 6606 CastKind CK; 6607 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 6608 // OpenCL requires that we convert `true` boolean expressions to -1, but 6609 // only when splatting vectors. 6610 if (DestElemTy->isFloatingType()) { 6611 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 6612 // in two steps: boolean to signed integral, then to floating. 6613 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 6614 CK_BooleanToSignedIntegral); 6615 SplattedExpr = CastExprRes.get(); 6616 CK = CK_IntegralToFloating; 6617 } else { 6618 CK = CK_BooleanToSignedIntegral; 6619 } 6620 } else { 6621 ExprResult CastExprRes = SplattedExpr; 6622 CK = PrepareScalarCast(CastExprRes, DestElemTy); 6623 if (CastExprRes.isInvalid()) 6624 return ExprError(); 6625 SplattedExpr = CastExprRes.get(); 6626 } 6627 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 6628 } 6629 6630 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 6631 Expr *CastExpr, CastKind &Kind) { 6632 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 6633 6634 QualType SrcTy = CastExpr->getType(); 6635 6636 // If SrcTy is a VectorType, the total size must match to explicitly cast to 6637 // an ExtVectorType. 6638 // In OpenCL, casts between vectors of different types are not allowed. 6639 // (See OpenCL 6.2). 6640 if (SrcTy->isVectorType()) { 6641 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 6642 (getLangOpts().OpenCL && 6643 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 6644 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 6645 << DestTy << SrcTy << R; 6646 return ExprError(); 6647 } 6648 Kind = CK_BitCast; 6649 return CastExpr; 6650 } 6651 6652 // All non-pointer scalars can be cast to ExtVector type. The appropriate 6653 // conversion will take place first from scalar to elt type, and then 6654 // splat from elt type to vector. 6655 if (SrcTy->isPointerType()) 6656 return Diag(R.getBegin(), 6657 diag::err_invalid_conversion_between_vector_and_scalar) 6658 << DestTy << SrcTy << R; 6659 6660 Kind = CK_VectorSplat; 6661 return prepareVectorSplat(DestTy, CastExpr); 6662 } 6663 6664 ExprResult 6665 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 6666 Declarator &D, ParsedType &Ty, 6667 SourceLocation RParenLoc, Expr *CastExpr) { 6668 assert(!D.isInvalidType() && (CastExpr != nullptr) && 6669 "ActOnCastExpr(): missing type or expr"); 6670 6671 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 6672 if (D.isInvalidType()) 6673 return ExprError(); 6674 6675 if (getLangOpts().CPlusPlus) { 6676 // Check that there are no default arguments (C++ only). 6677 CheckExtraCXXDefaultArguments(D); 6678 } else { 6679 // Make sure any TypoExprs have been dealt with. 6680 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 6681 if (!Res.isUsable()) 6682 return ExprError(); 6683 CastExpr = Res.get(); 6684 } 6685 6686 checkUnusedDeclAttributes(D); 6687 6688 QualType castType = castTInfo->getType(); 6689 Ty = CreateParsedType(castType, castTInfo); 6690 6691 bool isVectorLiteral = false; 6692 6693 // Check for an altivec or OpenCL literal, 6694 // i.e. all the elements are integer constants. 6695 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 6696 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 6697 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 6698 && castType->isVectorType() && (PE || PLE)) { 6699 if (PLE && PLE->getNumExprs() == 0) { 6700 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 6701 return ExprError(); 6702 } 6703 if (PE || PLE->getNumExprs() == 1) { 6704 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 6705 if (!E->getType()->isVectorType()) 6706 isVectorLiteral = true; 6707 } 6708 else 6709 isVectorLiteral = true; 6710 } 6711 6712 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 6713 // then handle it as such. 6714 if (isVectorLiteral) 6715 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 6716 6717 // If the Expr being casted is a ParenListExpr, handle it specially. 6718 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 6719 // sequence of BinOp comma operators. 6720 if (isa<ParenListExpr>(CastExpr)) { 6721 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 6722 if (Result.isInvalid()) return ExprError(); 6723 CastExpr = Result.get(); 6724 } 6725 6726 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6727 !getSourceManager().isInSystemMacro(LParenLoc)) 6728 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6729 6730 CheckTollFreeBridgeCast(castType, CastExpr); 6731 6732 CheckObjCBridgeRelatedCast(castType, CastExpr); 6733 6734 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 6735 6736 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6737 } 6738 6739 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6740 SourceLocation RParenLoc, Expr *E, 6741 TypeSourceInfo *TInfo) { 6742 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6743 "Expected paren or paren list expression"); 6744 6745 Expr **exprs; 6746 unsigned numExprs; 6747 Expr *subExpr; 6748 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6749 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6750 LiteralLParenLoc = PE->getLParenLoc(); 6751 LiteralRParenLoc = PE->getRParenLoc(); 6752 exprs = PE->getExprs(); 6753 numExprs = PE->getNumExprs(); 6754 } else { // isa<ParenExpr> by assertion at function entrance 6755 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6756 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6757 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6758 exprs = &subExpr; 6759 numExprs = 1; 6760 } 6761 6762 QualType Ty = TInfo->getType(); 6763 assert(Ty->isVectorType() && "Expected vector type"); 6764 6765 SmallVector<Expr *, 8> initExprs; 6766 const VectorType *VTy = Ty->castAs<VectorType>(); 6767 unsigned numElems = VTy->getNumElements(); 6768 6769 // '(...)' form of vector initialization in AltiVec: the number of 6770 // initializers must be one or must match the size of the vector. 6771 // If a single value is specified in the initializer then it will be 6772 // replicated to all the components of the vector 6773 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6774 // The number of initializers must be one or must match the size of the 6775 // vector. If a single value is specified in the initializer then it will 6776 // be replicated to all the components of the vector 6777 if (numExprs == 1) { 6778 QualType ElemTy = VTy->getElementType(); 6779 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6780 if (Literal.isInvalid()) 6781 return ExprError(); 6782 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6783 PrepareScalarCast(Literal, ElemTy)); 6784 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6785 } 6786 else if (numExprs < numElems) { 6787 Diag(E->getExprLoc(), 6788 diag::err_incorrect_number_of_vector_initializers); 6789 return ExprError(); 6790 } 6791 else 6792 initExprs.append(exprs, exprs + numExprs); 6793 } 6794 else { 6795 // For OpenCL, when the number of initializers is a single value, 6796 // it will be replicated to all components of the vector. 6797 if (getLangOpts().OpenCL && 6798 VTy->getVectorKind() == VectorType::GenericVector && 6799 numExprs == 1) { 6800 QualType ElemTy = VTy->getElementType(); 6801 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6802 if (Literal.isInvalid()) 6803 return ExprError(); 6804 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6805 PrepareScalarCast(Literal, ElemTy)); 6806 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6807 } 6808 6809 initExprs.append(exprs, exprs + numExprs); 6810 } 6811 // FIXME: This means that pretty-printing the final AST will produce curly 6812 // braces instead of the original commas. 6813 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6814 initExprs, LiteralRParenLoc); 6815 initE->setType(Ty); 6816 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6817 } 6818 6819 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6820 /// the ParenListExpr into a sequence of comma binary operators. 6821 ExprResult 6822 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6823 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6824 if (!E) 6825 return OrigExpr; 6826 6827 ExprResult Result(E->getExpr(0)); 6828 6829 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6830 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6831 E->getExpr(i)); 6832 6833 if (Result.isInvalid()) return ExprError(); 6834 6835 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6836 } 6837 6838 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6839 SourceLocation R, 6840 MultiExprArg Val) { 6841 return ParenListExpr::Create(Context, L, Val, R); 6842 } 6843 6844 /// Emit a specialized diagnostic when one expression is a null pointer 6845 /// constant and the other is not a pointer. Returns true if a diagnostic is 6846 /// emitted. 6847 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6848 SourceLocation QuestionLoc) { 6849 Expr *NullExpr = LHSExpr; 6850 Expr *NonPointerExpr = RHSExpr; 6851 Expr::NullPointerConstantKind NullKind = 6852 NullExpr->isNullPointerConstant(Context, 6853 Expr::NPC_ValueDependentIsNotNull); 6854 6855 if (NullKind == Expr::NPCK_NotNull) { 6856 NullExpr = RHSExpr; 6857 NonPointerExpr = LHSExpr; 6858 NullKind = 6859 NullExpr->isNullPointerConstant(Context, 6860 Expr::NPC_ValueDependentIsNotNull); 6861 } 6862 6863 if (NullKind == Expr::NPCK_NotNull) 6864 return false; 6865 6866 if (NullKind == Expr::NPCK_ZeroExpression) 6867 return false; 6868 6869 if (NullKind == Expr::NPCK_ZeroLiteral) { 6870 // In this case, check to make sure that we got here from a "NULL" 6871 // string in the source code. 6872 NullExpr = NullExpr->IgnoreParenImpCasts(); 6873 SourceLocation loc = NullExpr->getExprLoc(); 6874 if (!findMacroSpelling(loc, "NULL")) 6875 return false; 6876 } 6877 6878 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6879 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6880 << NonPointerExpr->getType() << DiagType 6881 << NonPointerExpr->getSourceRange(); 6882 return true; 6883 } 6884 6885 /// Return false if the condition expression is valid, true otherwise. 6886 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6887 QualType CondTy = Cond->getType(); 6888 6889 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6890 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6891 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6892 << CondTy << Cond->getSourceRange(); 6893 return true; 6894 } 6895 6896 // C99 6.5.15p2 6897 if (CondTy->isScalarType()) return false; 6898 6899 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6900 << CondTy << Cond->getSourceRange(); 6901 return true; 6902 } 6903 6904 /// Handle when one or both operands are void type. 6905 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6906 ExprResult &RHS) { 6907 Expr *LHSExpr = LHS.get(); 6908 Expr *RHSExpr = RHS.get(); 6909 6910 if (!LHSExpr->getType()->isVoidType()) 6911 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 6912 << RHSExpr->getSourceRange(); 6913 if (!RHSExpr->getType()->isVoidType()) 6914 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 6915 << LHSExpr->getSourceRange(); 6916 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6917 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6918 return S.Context.VoidTy; 6919 } 6920 6921 /// Return false if the NullExpr can be promoted to PointerTy, 6922 /// true otherwise. 6923 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6924 QualType PointerTy) { 6925 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6926 !NullExpr.get()->isNullPointerConstant(S.Context, 6927 Expr::NPC_ValueDependentIsNull)) 6928 return true; 6929 6930 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6931 return false; 6932 } 6933 6934 /// Checks compatibility between two pointers and return the resulting 6935 /// type. 6936 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6937 ExprResult &RHS, 6938 SourceLocation Loc) { 6939 QualType LHSTy = LHS.get()->getType(); 6940 QualType RHSTy = RHS.get()->getType(); 6941 6942 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6943 // Two identical pointers types are always compatible. 6944 return LHSTy; 6945 } 6946 6947 QualType lhptee, rhptee; 6948 6949 // Get the pointee types. 6950 bool IsBlockPointer = false; 6951 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6952 lhptee = LHSBTy->getPointeeType(); 6953 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6954 IsBlockPointer = true; 6955 } else { 6956 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6957 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6958 } 6959 6960 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6961 // differently qualified versions of compatible types, the result type is 6962 // a pointer to an appropriately qualified version of the composite 6963 // type. 6964 6965 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6966 // clause doesn't make sense for our extensions. E.g. address space 2 should 6967 // be incompatible with address space 3: they may live on different devices or 6968 // anything. 6969 Qualifiers lhQual = lhptee.getQualifiers(); 6970 Qualifiers rhQual = rhptee.getQualifiers(); 6971 6972 LangAS ResultAddrSpace = LangAS::Default; 6973 LangAS LAddrSpace = lhQual.getAddressSpace(); 6974 LangAS RAddrSpace = rhQual.getAddressSpace(); 6975 6976 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 6977 // spaces is disallowed. 6978 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 6979 ResultAddrSpace = LAddrSpace; 6980 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 6981 ResultAddrSpace = RAddrSpace; 6982 else { 6983 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 6984 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 6985 << RHS.get()->getSourceRange(); 6986 return QualType(); 6987 } 6988 6989 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6990 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 6991 lhQual.removeCVRQualifiers(); 6992 rhQual.removeCVRQualifiers(); 6993 6994 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 6995 // (C99 6.7.3) for address spaces. We assume that the check should behave in 6996 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 6997 // qual types are compatible iff 6998 // * corresponded types are compatible 6999 // * CVR qualifiers are equal 7000 // * address spaces are equal 7001 // Thus for conditional operator we merge CVR and address space unqualified 7002 // pointees and if there is a composite type we return a pointer to it with 7003 // merged qualifiers. 7004 LHSCastKind = 7005 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7006 RHSCastKind = 7007 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7008 lhQual.removeAddressSpace(); 7009 rhQual.removeAddressSpace(); 7010 7011 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 7012 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 7013 7014 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 7015 7016 if (CompositeTy.isNull()) { 7017 // In this situation, we assume void* type. No especially good 7018 // reason, but this is what gcc does, and we do have to pick 7019 // to get a consistent AST. 7020 QualType incompatTy; 7021 incompatTy = S.Context.getPointerType( 7022 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 7023 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 7024 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 7025 7026 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 7027 // for casts between types with incompatible address space qualifiers. 7028 // For the following code the compiler produces casts between global and 7029 // local address spaces of the corresponded innermost pointees: 7030 // local int *global *a; 7031 // global int *global *b; 7032 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 7033 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 7034 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7035 << RHS.get()->getSourceRange(); 7036 7037 return incompatTy; 7038 } 7039 7040 // The pointer types are compatible. 7041 // In case of OpenCL ResultTy should have the address space qualifier 7042 // which is a superset of address spaces of both the 2nd and the 3rd 7043 // operands of the conditional operator. 7044 QualType ResultTy = [&, ResultAddrSpace]() { 7045 if (S.getLangOpts().OpenCL) { 7046 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 7047 CompositeQuals.setAddressSpace(ResultAddrSpace); 7048 return S.Context 7049 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 7050 .withCVRQualifiers(MergedCVRQual); 7051 } 7052 return CompositeTy.withCVRQualifiers(MergedCVRQual); 7053 }(); 7054 if (IsBlockPointer) 7055 ResultTy = S.Context.getBlockPointerType(ResultTy); 7056 else 7057 ResultTy = S.Context.getPointerType(ResultTy); 7058 7059 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 7060 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 7061 return ResultTy; 7062 } 7063 7064 /// Return the resulting type when the operands are both block pointers. 7065 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 7066 ExprResult &LHS, 7067 ExprResult &RHS, 7068 SourceLocation Loc) { 7069 QualType LHSTy = LHS.get()->getType(); 7070 QualType RHSTy = RHS.get()->getType(); 7071 7072 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 7073 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 7074 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 7075 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7076 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7077 return destType; 7078 } 7079 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 7080 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7081 << RHS.get()->getSourceRange(); 7082 return QualType(); 7083 } 7084 7085 // We have 2 block pointer types. 7086 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7087 } 7088 7089 /// Return the resulting type when the operands are both pointers. 7090 static QualType 7091 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 7092 ExprResult &RHS, 7093 SourceLocation Loc) { 7094 // get the pointer types 7095 QualType LHSTy = LHS.get()->getType(); 7096 QualType RHSTy = RHS.get()->getType(); 7097 7098 // get the "pointed to" types 7099 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7100 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7101 7102 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 7103 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 7104 // Figure out necessary qualifiers (C99 6.5.15p6) 7105 QualType destPointee 7106 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7107 QualType destType = S.Context.getPointerType(destPointee); 7108 // Add qualifiers if necessary. 7109 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7110 // Promote to void*. 7111 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7112 return destType; 7113 } 7114 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 7115 QualType destPointee 7116 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7117 QualType destType = S.Context.getPointerType(destPointee); 7118 // Add qualifiers if necessary. 7119 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7120 // Promote to void*. 7121 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7122 return destType; 7123 } 7124 7125 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7126 } 7127 7128 /// Return false if the first expression is not an integer and the second 7129 /// expression is not a pointer, true otherwise. 7130 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 7131 Expr* PointerExpr, SourceLocation Loc, 7132 bool IsIntFirstExpr) { 7133 if (!PointerExpr->getType()->isPointerType() || 7134 !Int.get()->getType()->isIntegerType()) 7135 return false; 7136 7137 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 7138 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 7139 7140 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 7141 << Expr1->getType() << Expr2->getType() 7142 << Expr1->getSourceRange() << Expr2->getSourceRange(); 7143 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 7144 CK_IntegralToPointer); 7145 return true; 7146 } 7147 7148 /// Simple conversion between integer and floating point types. 7149 /// 7150 /// Used when handling the OpenCL conditional operator where the 7151 /// condition is a vector while the other operands are scalar. 7152 /// 7153 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 7154 /// types are either integer or floating type. Between the two 7155 /// operands, the type with the higher rank is defined as the "result 7156 /// type". The other operand needs to be promoted to the same type. No 7157 /// other type promotion is allowed. We cannot use 7158 /// UsualArithmeticConversions() for this purpose, since it always 7159 /// promotes promotable types. 7160 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 7161 ExprResult &RHS, 7162 SourceLocation QuestionLoc) { 7163 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 7164 if (LHS.isInvalid()) 7165 return QualType(); 7166 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 7167 if (RHS.isInvalid()) 7168 return QualType(); 7169 7170 // For conversion purposes, we ignore any qualifiers. 7171 // For example, "const float" and "float" are equivalent. 7172 QualType LHSType = 7173 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 7174 QualType RHSType = 7175 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 7176 7177 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 7178 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7179 << LHSType << LHS.get()->getSourceRange(); 7180 return QualType(); 7181 } 7182 7183 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 7184 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7185 << RHSType << RHS.get()->getSourceRange(); 7186 return QualType(); 7187 } 7188 7189 // If both types are identical, no conversion is needed. 7190 if (LHSType == RHSType) 7191 return LHSType; 7192 7193 // Now handle "real" floating types (i.e. float, double, long double). 7194 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 7195 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 7196 /*IsCompAssign = */ false); 7197 7198 // Finally, we have two differing integer types. 7199 return handleIntegerConversion<doIntegralCast, doIntegralCast> 7200 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 7201 } 7202 7203 /// Convert scalar operands to a vector that matches the 7204 /// condition in length. 7205 /// 7206 /// Used when handling the OpenCL conditional operator where the 7207 /// condition is a vector while the other operands are scalar. 7208 /// 7209 /// We first compute the "result type" for the scalar operands 7210 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 7211 /// into a vector of that type where the length matches the condition 7212 /// vector type. s6.11.6 requires that the element types of the result 7213 /// and the condition must have the same number of bits. 7214 static QualType 7215 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 7216 QualType CondTy, SourceLocation QuestionLoc) { 7217 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 7218 if (ResTy.isNull()) return QualType(); 7219 7220 const VectorType *CV = CondTy->getAs<VectorType>(); 7221 assert(CV); 7222 7223 // Determine the vector result type 7224 unsigned NumElements = CV->getNumElements(); 7225 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 7226 7227 // Ensure that all types have the same number of bits 7228 if (S.Context.getTypeSize(CV->getElementType()) 7229 != S.Context.getTypeSize(ResTy)) { 7230 // Since VectorTy is created internally, it does not pretty print 7231 // with an OpenCL name. Instead, we just print a description. 7232 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 7233 SmallString<64> Str; 7234 llvm::raw_svector_ostream OS(Str); 7235 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 7236 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 7237 << CondTy << OS.str(); 7238 return QualType(); 7239 } 7240 7241 // Convert operands to the vector result type 7242 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 7243 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 7244 7245 return VectorTy; 7246 } 7247 7248 /// Return false if this is a valid OpenCL condition vector 7249 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 7250 SourceLocation QuestionLoc) { 7251 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 7252 // integral type. 7253 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 7254 assert(CondTy); 7255 QualType EleTy = CondTy->getElementType(); 7256 if (EleTy->isIntegerType()) return false; 7257 7258 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7259 << Cond->getType() << Cond->getSourceRange(); 7260 return true; 7261 } 7262 7263 /// Return false if the vector condition type and the vector 7264 /// result type are compatible. 7265 /// 7266 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 7267 /// number of elements, and their element types have the same number 7268 /// of bits. 7269 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 7270 SourceLocation QuestionLoc) { 7271 const VectorType *CV = CondTy->getAs<VectorType>(); 7272 const VectorType *RV = VecResTy->getAs<VectorType>(); 7273 assert(CV && RV); 7274 7275 if (CV->getNumElements() != RV->getNumElements()) { 7276 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 7277 << CondTy << VecResTy; 7278 return true; 7279 } 7280 7281 QualType CVE = CV->getElementType(); 7282 QualType RVE = RV->getElementType(); 7283 7284 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 7285 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 7286 << CondTy << VecResTy; 7287 return true; 7288 } 7289 7290 return false; 7291 } 7292 7293 /// Return the resulting type for the conditional operator in 7294 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 7295 /// s6.3.i) when the condition is a vector type. 7296 static QualType 7297 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 7298 ExprResult &LHS, ExprResult &RHS, 7299 SourceLocation QuestionLoc) { 7300 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 7301 if (Cond.isInvalid()) 7302 return QualType(); 7303 QualType CondTy = Cond.get()->getType(); 7304 7305 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 7306 return QualType(); 7307 7308 // If either operand is a vector then find the vector type of the 7309 // result as specified in OpenCL v1.1 s6.3.i. 7310 if (LHS.get()->getType()->isVectorType() || 7311 RHS.get()->getType()->isVectorType()) { 7312 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 7313 /*isCompAssign*/false, 7314 /*AllowBothBool*/true, 7315 /*AllowBoolConversions*/false); 7316 if (VecResTy.isNull()) return QualType(); 7317 // The result type must match the condition type as specified in 7318 // OpenCL v1.1 s6.11.6. 7319 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 7320 return QualType(); 7321 return VecResTy; 7322 } 7323 7324 // Both operands are scalar. 7325 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 7326 } 7327 7328 /// Return true if the Expr is block type 7329 static bool checkBlockType(Sema &S, const Expr *E) { 7330 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 7331 QualType Ty = CE->getCallee()->getType(); 7332 if (Ty->isBlockPointerType()) { 7333 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 7334 return true; 7335 } 7336 } 7337 return false; 7338 } 7339 7340 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 7341 /// In that case, LHS = cond. 7342 /// C99 6.5.15 7343 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 7344 ExprResult &RHS, ExprValueKind &VK, 7345 ExprObjectKind &OK, 7346 SourceLocation QuestionLoc) { 7347 7348 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 7349 if (!LHSResult.isUsable()) return QualType(); 7350 LHS = LHSResult; 7351 7352 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 7353 if (!RHSResult.isUsable()) return QualType(); 7354 RHS = RHSResult; 7355 7356 // C++ is sufficiently different to merit its own checker. 7357 if (getLangOpts().CPlusPlus) 7358 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 7359 7360 VK = VK_RValue; 7361 OK = OK_Ordinary; 7362 7363 // The OpenCL operator with a vector condition is sufficiently 7364 // different to merit its own checker. 7365 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 7366 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 7367 7368 // First, check the condition. 7369 Cond = UsualUnaryConversions(Cond.get()); 7370 if (Cond.isInvalid()) 7371 return QualType(); 7372 if (checkCondition(*this, Cond.get(), QuestionLoc)) 7373 return QualType(); 7374 7375 // Now check the two expressions. 7376 if (LHS.get()->getType()->isVectorType() || 7377 RHS.get()->getType()->isVectorType()) 7378 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 7379 /*AllowBothBool*/true, 7380 /*AllowBoolConversions*/false); 7381 7382 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 7383 if (LHS.isInvalid() || RHS.isInvalid()) 7384 return QualType(); 7385 7386 QualType LHSTy = LHS.get()->getType(); 7387 QualType RHSTy = RHS.get()->getType(); 7388 7389 // Diagnose attempts to convert between __float128 and long double where 7390 // such conversions currently can't be handled. 7391 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 7392 Diag(QuestionLoc, 7393 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 7394 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7395 return QualType(); 7396 } 7397 7398 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 7399 // selection operator (?:). 7400 if (getLangOpts().OpenCL && 7401 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 7402 return QualType(); 7403 } 7404 7405 // If both operands have arithmetic type, do the usual arithmetic conversions 7406 // to find a common type: C99 6.5.15p3,5. 7407 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 7408 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 7409 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 7410 7411 return ResTy; 7412 } 7413 7414 // If both operands are the same structure or union type, the result is that 7415 // type. 7416 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 7417 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 7418 if (LHSRT->getDecl() == RHSRT->getDecl()) 7419 // "If both the operands have structure or union type, the result has 7420 // that type." This implies that CV qualifiers are dropped. 7421 return LHSTy.getUnqualifiedType(); 7422 // FIXME: Type of conditional expression must be complete in C mode. 7423 } 7424 7425 // C99 6.5.15p5: "If both operands have void type, the result has void type." 7426 // The following || allows only one side to be void (a GCC-ism). 7427 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 7428 return checkConditionalVoidType(*this, LHS, RHS); 7429 } 7430 7431 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 7432 // the type of the other operand." 7433 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 7434 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 7435 7436 // All objective-c pointer type analysis is done here. 7437 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 7438 QuestionLoc); 7439 if (LHS.isInvalid() || RHS.isInvalid()) 7440 return QualType(); 7441 if (!compositeType.isNull()) 7442 return compositeType; 7443 7444 7445 // Handle block pointer types. 7446 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 7447 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 7448 QuestionLoc); 7449 7450 // Check constraints for C object pointers types (C99 6.5.15p3,6). 7451 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 7452 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 7453 QuestionLoc); 7454 7455 // GCC compatibility: soften pointer/integer mismatch. Note that 7456 // null pointers have been filtered out by this point. 7457 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 7458 /*IsIntFirstExpr=*/true)) 7459 return RHSTy; 7460 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 7461 /*IsIntFirstExpr=*/false)) 7462 return LHSTy; 7463 7464 // Emit a better diagnostic if one of the expressions is a null pointer 7465 // constant and the other is not a pointer type. In this case, the user most 7466 // likely forgot to take the address of the other expression. 7467 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 7468 return QualType(); 7469 7470 // Otherwise, the operands are not compatible. 7471 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 7472 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7473 << RHS.get()->getSourceRange(); 7474 return QualType(); 7475 } 7476 7477 /// FindCompositeObjCPointerType - Helper method to find composite type of 7478 /// two objective-c pointer types of the two input expressions. 7479 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 7480 SourceLocation QuestionLoc) { 7481 QualType LHSTy = LHS.get()->getType(); 7482 QualType RHSTy = RHS.get()->getType(); 7483 7484 // Handle things like Class and struct objc_class*. Here we case the result 7485 // to the pseudo-builtin, because that will be implicitly cast back to the 7486 // redefinition type if an attempt is made to access its fields. 7487 if (LHSTy->isObjCClassType() && 7488 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 7489 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 7490 return LHSTy; 7491 } 7492 if (RHSTy->isObjCClassType() && 7493 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 7494 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 7495 return RHSTy; 7496 } 7497 // And the same for struct objc_object* / id 7498 if (LHSTy->isObjCIdType() && 7499 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 7500 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 7501 return LHSTy; 7502 } 7503 if (RHSTy->isObjCIdType() && 7504 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 7505 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 7506 return RHSTy; 7507 } 7508 // And the same for struct objc_selector* / SEL 7509 if (Context.isObjCSelType(LHSTy) && 7510 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 7511 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 7512 return LHSTy; 7513 } 7514 if (Context.isObjCSelType(RHSTy) && 7515 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 7516 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 7517 return RHSTy; 7518 } 7519 // Check constraints for Objective-C object pointers types. 7520 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 7521 7522 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 7523 // Two identical object pointer types are always compatible. 7524 return LHSTy; 7525 } 7526 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 7527 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 7528 QualType compositeType = LHSTy; 7529 7530 // If both operands are interfaces and either operand can be 7531 // assigned to the other, use that type as the composite 7532 // type. This allows 7533 // xxx ? (A*) a : (B*) b 7534 // where B is a subclass of A. 7535 // 7536 // Additionally, as for assignment, if either type is 'id' 7537 // allow silent coercion. Finally, if the types are 7538 // incompatible then make sure to use 'id' as the composite 7539 // type so the result is acceptable for sending messages to. 7540 7541 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 7542 // It could return the composite type. 7543 if (!(compositeType = 7544 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 7545 // Nothing more to do. 7546 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 7547 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 7548 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 7549 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 7550 } else if ((LHSOPT->isObjCQualifiedIdType() || 7551 RHSOPT->isObjCQualifiedIdType()) && 7552 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 7553 true)) { 7554 // Need to handle "id<xx>" explicitly. 7555 // GCC allows qualified id and any Objective-C type to devolve to 7556 // id. Currently localizing to here until clear this should be 7557 // part of ObjCQualifiedIdTypesAreCompatible. 7558 compositeType = Context.getObjCIdType(); 7559 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 7560 compositeType = Context.getObjCIdType(); 7561 } else { 7562 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 7563 << LHSTy << RHSTy 7564 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7565 QualType incompatTy = Context.getObjCIdType(); 7566 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 7567 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 7568 return incompatTy; 7569 } 7570 // The object pointer types are compatible. 7571 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 7572 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 7573 return compositeType; 7574 } 7575 // Check Objective-C object pointer types and 'void *' 7576 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 7577 if (getLangOpts().ObjCAutoRefCount) { 7578 // ARC forbids the implicit conversion of object pointers to 'void *', 7579 // so these types are not compatible. 7580 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7581 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7582 LHS = RHS = true; 7583 return QualType(); 7584 } 7585 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7586 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 7587 QualType destPointee 7588 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7589 QualType destType = Context.getPointerType(destPointee); 7590 // Add qualifiers if necessary. 7591 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7592 // Promote to void*. 7593 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7594 return destType; 7595 } 7596 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 7597 if (getLangOpts().ObjCAutoRefCount) { 7598 // ARC forbids the implicit conversion of object pointers to 'void *', 7599 // so these types are not compatible. 7600 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7601 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7602 LHS = RHS = true; 7603 return QualType(); 7604 } 7605 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 7606 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7607 QualType destPointee 7608 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7609 QualType destType = Context.getPointerType(destPointee); 7610 // Add qualifiers if necessary. 7611 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7612 // Promote to void*. 7613 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7614 return destType; 7615 } 7616 return QualType(); 7617 } 7618 7619 /// SuggestParentheses - Emit a note with a fixit hint that wraps 7620 /// ParenRange in parentheses. 7621 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 7622 const PartialDiagnostic &Note, 7623 SourceRange ParenRange) { 7624 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 7625 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 7626 EndLoc.isValid()) { 7627 Self.Diag(Loc, Note) 7628 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 7629 << FixItHint::CreateInsertion(EndLoc, ")"); 7630 } else { 7631 // We can't display the parentheses, so just show the bare note. 7632 Self.Diag(Loc, Note) << ParenRange; 7633 } 7634 } 7635 7636 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 7637 return BinaryOperator::isAdditiveOp(Opc) || 7638 BinaryOperator::isMultiplicativeOp(Opc) || 7639 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 7640 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 7641 // not any of the logical operators. Bitwise-xor is commonly used as a 7642 // logical-xor because there is no logical-xor operator. The logical 7643 // operators, including uses of xor, have a high false positive rate for 7644 // precedence warnings. 7645 } 7646 7647 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 7648 /// expression, either using a built-in or overloaded operator, 7649 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 7650 /// expression. 7651 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 7652 Expr **RHSExprs) { 7653 // Don't strip parenthesis: we should not warn if E is in parenthesis. 7654 E = E->IgnoreImpCasts(); 7655 E = E->IgnoreConversionOperator(); 7656 E = E->IgnoreImpCasts(); 7657 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 7658 E = MTE->getSubExpr(); 7659 E = E->IgnoreImpCasts(); 7660 } 7661 7662 // Built-in binary operator. 7663 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 7664 if (IsArithmeticOp(OP->getOpcode())) { 7665 *Opcode = OP->getOpcode(); 7666 *RHSExprs = OP->getRHS(); 7667 return true; 7668 } 7669 } 7670 7671 // Overloaded operator. 7672 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 7673 if (Call->getNumArgs() != 2) 7674 return false; 7675 7676 // Make sure this is really a binary operator that is safe to pass into 7677 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 7678 OverloadedOperatorKind OO = Call->getOperator(); 7679 if (OO < OO_Plus || OO > OO_Arrow || 7680 OO == OO_PlusPlus || OO == OO_MinusMinus) 7681 return false; 7682 7683 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 7684 if (IsArithmeticOp(OpKind)) { 7685 *Opcode = OpKind; 7686 *RHSExprs = Call->getArg(1); 7687 return true; 7688 } 7689 } 7690 7691 return false; 7692 } 7693 7694 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 7695 /// or is a logical expression such as (x==y) which has int type, but is 7696 /// commonly interpreted as boolean. 7697 static bool ExprLooksBoolean(Expr *E) { 7698 E = E->IgnoreParenImpCasts(); 7699 7700 if (E->getType()->isBooleanType()) 7701 return true; 7702 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 7703 return OP->isComparisonOp() || OP->isLogicalOp(); 7704 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 7705 return OP->getOpcode() == UO_LNot; 7706 if (E->getType()->isPointerType()) 7707 return true; 7708 // FIXME: What about overloaded operator calls returning "unspecified boolean 7709 // type"s (commonly pointer-to-members)? 7710 7711 return false; 7712 } 7713 7714 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 7715 /// and binary operator are mixed in a way that suggests the programmer assumed 7716 /// the conditional operator has higher precedence, for example: 7717 /// "int x = a + someBinaryCondition ? 1 : 2". 7718 static void DiagnoseConditionalPrecedence(Sema &Self, 7719 SourceLocation OpLoc, 7720 Expr *Condition, 7721 Expr *LHSExpr, 7722 Expr *RHSExpr) { 7723 BinaryOperatorKind CondOpcode; 7724 Expr *CondRHS; 7725 7726 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 7727 return; 7728 if (!ExprLooksBoolean(CondRHS)) 7729 return; 7730 7731 // The condition is an arithmetic binary expression, with a right- 7732 // hand side that looks boolean, so warn. 7733 7734 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 7735 ? diag::warn_precedence_bitwise_conditional 7736 : diag::warn_precedence_conditional; 7737 7738 Self.Diag(OpLoc, DiagID) 7739 << Condition->getSourceRange() 7740 << BinaryOperator::getOpcodeStr(CondOpcode); 7741 7742 SuggestParentheses( 7743 Self, OpLoc, 7744 Self.PDiag(diag::note_precedence_silence) 7745 << BinaryOperator::getOpcodeStr(CondOpcode), 7746 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 7747 7748 SuggestParentheses(Self, OpLoc, 7749 Self.PDiag(diag::note_precedence_conditional_first), 7750 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 7751 } 7752 7753 /// Compute the nullability of a conditional expression. 7754 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 7755 QualType LHSTy, QualType RHSTy, 7756 ASTContext &Ctx) { 7757 if (!ResTy->isAnyPointerType()) 7758 return ResTy; 7759 7760 auto GetNullability = [&Ctx](QualType Ty) { 7761 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 7762 if (Kind) 7763 return *Kind; 7764 return NullabilityKind::Unspecified; 7765 }; 7766 7767 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 7768 NullabilityKind MergedKind; 7769 7770 // Compute nullability of a binary conditional expression. 7771 if (IsBin) { 7772 if (LHSKind == NullabilityKind::NonNull) 7773 MergedKind = NullabilityKind::NonNull; 7774 else 7775 MergedKind = RHSKind; 7776 // Compute nullability of a normal conditional expression. 7777 } else { 7778 if (LHSKind == NullabilityKind::Nullable || 7779 RHSKind == NullabilityKind::Nullable) 7780 MergedKind = NullabilityKind::Nullable; 7781 else if (LHSKind == NullabilityKind::NonNull) 7782 MergedKind = RHSKind; 7783 else if (RHSKind == NullabilityKind::NonNull) 7784 MergedKind = LHSKind; 7785 else 7786 MergedKind = NullabilityKind::Unspecified; 7787 } 7788 7789 // Return if ResTy already has the correct nullability. 7790 if (GetNullability(ResTy) == MergedKind) 7791 return ResTy; 7792 7793 // Strip all nullability from ResTy. 7794 while (ResTy->getNullability(Ctx)) 7795 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 7796 7797 // Create a new AttributedType with the new nullability kind. 7798 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 7799 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 7800 } 7801 7802 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7803 /// in the case of a the GNU conditional expr extension. 7804 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7805 SourceLocation ColonLoc, 7806 Expr *CondExpr, Expr *LHSExpr, 7807 Expr *RHSExpr) { 7808 if (!getLangOpts().CPlusPlus) { 7809 // C cannot handle TypoExpr nodes in the condition because it 7810 // doesn't handle dependent types properly, so make sure any TypoExprs have 7811 // been dealt with before checking the operands. 7812 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7813 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7814 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7815 7816 if (!CondResult.isUsable()) 7817 return ExprError(); 7818 7819 if (LHSExpr) { 7820 if (!LHSResult.isUsable()) 7821 return ExprError(); 7822 } 7823 7824 if (!RHSResult.isUsable()) 7825 return ExprError(); 7826 7827 CondExpr = CondResult.get(); 7828 LHSExpr = LHSResult.get(); 7829 RHSExpr = RHSResult.get(); 7830 } 7831 7832 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7833 // was the condition. 7834 OpaqueValueExpr *opaqueValue = nullptr; 7835 Expr *commonExpr = nullptr; 7836 if (!LHSExpr) { 7837 commonExpr = CondExpr; 7838 // Lower out placeholder types first. This is important so that we don't 7839 // try to capture a placeholder. This happens in few cases in C++; such 7840 // as Objective-C++'s dictionary subscripting syntax. 7841 if (commonExpr->hasPlaceholderType()) { 7842 ExprResult result = CheckPlaceholderExpr(commonExpr); 7843 if (!result.isUsable()) return ExprError(); 7844 commonExpr = result.get(); 7845 } 7846 // We usually want to apply unary conversions *before* saving, except 7847 // in the special case of a C++ l-value conditional. 7848 if (!(getLangOpts().CPlusPlus 7849 && !commonExpr->isTypeDependent() 7850 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7851 && commonExpr->isGLValue() 7852 && commonExpr->isOrdinaryOrBitFieldObject() 7853 && RHSExpr->isOrdinaryOrBitFieldObject() 7854 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7855 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7856 if (commonRes.isInvalid()) 7857 return ExprError(); 7858 commonExpr = commonRes.get(); 7859 } 7860 7861 // If the common expression is a class or array prvalue, materialize it 7862 // so that we can safely refer to it multiple times. 7863 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 7864 commonExpr->getType()->isArrayType())) { 7865 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 7866 if (MatExpr.isInvalid()) 7867 return ExprError(); 7868 commonExpr = MatExpr.get(); 7869 } 7870 7871 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7872 commonExpr->getType(), 7873 commonExpr->getValueKind(), 7874 commonExpr->getObjectKind(), 7875 commonExpr); 7876 LHSExpr = CondExpr = opaqueValue; 7877 } 7878 7879 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 7880 ExprValueKind VK = VK_RValue; 7881 ExprObjectKind OK = OK_Ordinary; 7882 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7883 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7884 VK, OK, QuestionLoc); 7885 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7886 RHS.isInvalid()) 7887 return ExprError(); 7888 7889 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7890 RHS.get()); 7891 7892 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 7893 7894 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 7895 Context); 7896 7897 if (!commonExpr) 7898 return new (Context) 7899 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 7900 RHS.get(), result, VK, OK); 7901 7902 return new (Context) BinaryConditionalOperator( 7903 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 7904 ColonLoc, result, VK, OK); 7905 } 7906 7907 // checkPointerTypesForAssignment - This is a very tricky routine (despite 7908 // being closely modeled after the C99 spec:-). The odd characteristic of this 7909 // routine is it effectively iqnores the qualifiers on the top level pointee. 7910 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 7911 // FIXME: add a couple examples in this comment. 7912 static Sema::AssignConvertType 7913 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 7914 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7915 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7916 7917 // get the "pointed to" type (ignoring qualifiers at the top level) 7918 const Type *lhptee, *rhptee; 7919 Qualifiers lhq, rhq; 7920 std::tie(lhptee, lhq) = 7921 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 7922 std::tie(rhptee, rhq) = 7923 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 7924 7925 Sema::AssignConvertType ConvTy = Sema::Compatible; 7926 7927 // C99 6.5.16.1p1: This following citation is common to constraints 7928 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 7929 // qualifiers of the type *pointed to* by the right; 7930 7931 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 7932 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 7933 lhq.compatiblyIncludesObjCLifetime(rhq)) { 7934 // Ignore lifetime for further calculation. 7935 lhq.removeObjCLifetime(); 7936 rhq.removeObjCLifetime(); 7937 } 7938 7939 if (!lhq.compatiblyIncludes(rhq)) { 7940 // Treat address-space mismatches as fatal. 7941 if (!lhq.isAddressSpaceSupersetOf(rhq)) 7942 return Sema::IncompatiblePointerDiscardsQualifiers; 7943 7944 // It's okay to add or remove GC or lifetime qualifiers when converting to 7945 // and from void*. 7946 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 7947 .compatiblyIncludes( 7948 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 7949 && (lhptee->isVoidType() || rhptee->isVoidType())) 7950 ; // keep old 7951 7952 // Treat lifetime mismatches as fatal. 7953 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 7954 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7955 7956 // For GCC/MS compatibility, other qualifier mismatches are treated 7957 // as still compatible in C. 7958 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7959 } 7960 7961 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 7962 // incomplete type and the other is a pointer to a qualified or unqualified 7963 // version of void... 7964 if (lhptee->isVoidType()) { 7965 if (rhptee->isIncompleteOrObjectType()) 7966 return ConvTy; 7967 7968 // As an extension, we allow cast to/from void* to function pointer. 7969 assert(rhptee->isFunctionType()); 7970 return Sema::FunctionVoidPointer; 7971 } 7972 7973 if (rhptee->isVoidType()) { 7974 if (lhptee->isIncompleteOrObjectType()) 7975 return ConvTy; 7976 7977 // As an extension, we allow cast to/from void* to function pointer. 7978 assert(lhptee->isFunctionType()); 7979 return Sema::FunctionVoidPointer; 7980 } 7981 7982 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7983 // unqualified versions of compatible types, ... 7984 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7985 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7986 // Check if the pointee types are compatible ignoring the sign. 7987 // We explicitly check for char so that we catch "char" vs 7988 // "unsigned char" on systems where "char" is unsigned. 7989 if (lhptee->isCharType()) 7990 ltrans = S.Context.UnsignedCharTy; 7991 else if (lhptee->hasSignedIntegerRepresentation()) 7992 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7993 7994 if (rhptee->isCharType()) 7995 rtrans = S.Context.UnsignedCharTy; 7996 else if (rhptee->hasSignedIntegerRepresentation()) 7997 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 7998 7999 if (ltrans == rtrans) { 8000 // Types are compatible ignoring the sign. Qualifier incompatibility 8001 // takes priority over sign incompatibility because the sign 8002 // warning can be disabled. 8003 if (ConvTy != Sema::Compatible) 8004 return ConvTy; 8005 8006 return Sema::IncompatiblePointerSign; 8007 } 8008 8009 // If we are a multi-level pointer, it's possible that our issue is simply 8010 // one of qualification - e.g. char ** -> const char ** is not allowed. If 8011 // the eventual target type is the same and the pointers have the same 8012 // level of indirection, this must be the issue. 8013 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 8014 do { 8015 std::tie(lhptee, lhq) = 8016 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 8017 std::tie(rhptee, rhq) = 8018 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 8019 8020 // Inconsistent address spaces at this point is invalid, even if the 8021 // address spaces would be compatible. 8022 // FIXME: This doesn't catch address space mismatches for pointers of 8023 // different nesting levels, like: 8024 // __local int *** a; 8025 // int ** b = a; 8026 // It's not clear how to actually determine when such pointers are 8027 // invalidly incompatible. 8028 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 8029 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 8030 8031 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 8032 8033 if (lhptee == rhptee) 8034 return Sema::IncompatibleNestedPointerQualifiers; 8035 } 8036 8037 // General pointer incompatibility takes priority over qualifiers. 8038 return Sema::IncompatiblePointer; 8039 } 8040 if (!S.getLangOpts().CPlusPlus && 8041 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 8042 return Sema::IncompatiblePointer; 8043 return ConvTy; 8044 } 8045 8046 /// checkBlockPointerTypesForAssignment - This routine determines whether two 8047 /// block pointer types are compatible or whether a block and normal pointer 8048 /// are compatible. It is more restrict than comparing two function pointer 8049 // types. 8050 static Sema::AssignConvertType 8051 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 8052 QualType RHSType) { 8053 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8054 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8055 8056 QualType lhptee, rhptee; 8057 8058 // get the "pointed to" type (ignoring qualifiers at the top level) 8059 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 8060 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 8061 8062 // In C++, the types have to match exactly. 8063 if (S.getLangOpts().CPlusPlus) 8064 return Sema::IncompatibleBlockPointer; 8065 8066 Sema::AssignConvertType ConvTy = Sema::Compatible; 8067 8068 // For blocks we enforce that qualifiers are identical. 8069 Qualifiers LQuals = lhptee.getLocalQualifiers(); 8070 Qualifiers RQuals = rhptee.getLocalQualifiers(); 8071 if (S.getLangOpts().OpenCL) { 8072 LQuals.removeAddressSpace(); 8073 RQuals.removeAddressSpace(); 8074 } 8075 if (LQuals != RQuals) 8076 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8077 8078 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 8079 // assignment. 8080 // The current behavior is similar to C++ lambdas. A block might be 8081 // assigned to a variable iff its return type and parameters are compatible 8082 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 8083 // an assignment. Presumably it should behave in way that a function pointer 8084 // assignment does in C, so for each parameter and return type: 8085 // * CVR and address space of LHS should be a superset of CVR and address 8086 // space of RHS. 8087 // * unqualified types should be compatible. 8088 if (S.getLangOpts().OpenCL) { 8089 if (!S.Context.typesAreBlockPointerCompatible( 8090 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 8091 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 8092 return Sema::IncompatibleBlockPointer; 8093 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 8094 return Sema::IncompatibleBlockPointer; 8095 8096 return ConvTy; 8097 } 8098 8099 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 8100 /// for assignment compatibility. 8101 static Sema::AssignConvertType 8102 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 8103 QualType RHSType) { 8104 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 8105 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 8106 8107 if (LHSType->isObjCBuiltinType()) { 8108 // Class is not compatible with ObjC object pointers. 8109 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 8110 !RHSType->isObjCQualifiedClassType()) 8111 return Sema::IncompatiblePointer; 8112 return Sema::Compatible; 8113 } 8114 if (RHSType->isObjCBuiltinType()) { 8115 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 8116 !LHSType->isObjCQualifiedClassType()) 8117 return Sema::IncompatiblePointer; 8118 return Sema::Compatible; 8119 } 8120 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8121 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8122 8123 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 8124 // make an exception for id<P> 8125 !LHSType->isObjCQualifiedIdType()) 8126 return Sema::CompatiblePointerDiscardsQualifiers; 8127 8128 if (S.Context.typesAreCompatible(LHSType, RHSType)) 8129 return Sema::Compatible; 8130 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 8131 return Sema::IncompatibleObjCQualifiedId; 8132 return Sema::IncompatiblePointer; 8133 } 8134 8135 Sema::AssignConvertType 8136 Sema::CheckAssignmentConstraints(SourceLocation Loc, 8137 QualType LHSType, QualType RHSType) { 8138 // Fake up an opaque expression. We don't actually care about what 8139 // cast operations are required, so if CheckAssignmentConstraints 8140 // adds casts to this they'll be wasted, but fortunately that doesn't 8141 // usually happen on valid code. 8142 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 8143 ExprResult RHSPtr = &RHSExpr; 8144 CastKind K; 8145 8146 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 8147 } 8148 8149 /// This helper function returns true if QT is a vector type that has element 8150 /// type ElementType. 8151 static bool isVector(QualType QT, QualType ElementType) { 8152 if (const VectorType *VT = QT->getAs<VectorType>()) 8153 return VT->getElementType() == ElementType; 8154 return false; 8155 } 8156 8157 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 8158 /// has code to accommodate several GCC extensions when type checking 8159 /// pointers. Here are some objectionable examples that GCC considers warnings: 8160 /// 8161 /// int a, *pint; 8162 /// short *pshort; 8163 /// struct foo *pfoo; 8164 /// 8165 /// pint = pshort; // warning: assignment from incompatible pointer type 8166 /// a = pint; // warning: assignment makes integer from pointer without a cast 8167 /// pint = a; // warning: assignment makes pointer from integer without a cast 8168 /// pint = pfoo; // warning: assignment from incompatible pointer type 8169 /// 8170 /// As a result, the code for dealing with pointers is more complex than the 8171 /// C99 spec dictates. 8172 /// 8173 /// Sets 'Kind' for any result kind except Incompatible. 8174 Sema::AssignConvertType 8175 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 8176 CastKind &Kind, bool ConvertRHS) { 8177 QualType RHSType = RHS.get()->getType(); 8178 QualType OrigLHSType = LHSType; 8179 8180 // Get canonical types. We're not formatting these types, just comparing 8181 // them. 8182 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 8183 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 8184 8185 // Common case: no conversion required. 8186 if (LHSType == RHSType) { 8187 Kind = CK_NoOp; 8188 return Compatible; 8189 } 8190 8191 // If we have an atomic type, try a non-atomic assignment, then just add an 8192 // atomic qualification step. 8193 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 8194 Sema::AssignConvertType result = 8195 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 8196 if (result != Compatible) 8197 return result; 8198 if (Kind != CK_NoOp && ConvertRHS) 8199 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 8200 Kind = CK_NonAtomicToAtomic; 8201 return Compatible; 8202 } 8203 8204 // If the left-hand side is a reference type, then we are in a 8205 // (rare!) case where we've allowed the use of references in C, 8206 // e.g., as a parameter type in a built-in function. In this case, 8207 // just make sure that the type referenced is compatible with the 8208 // right-hand side type. The caller is responsible for adjusting 8209 // LHSType so that the resulting expression does not have reference 8210 // type. 8211 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 8212 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 8213 Kind = CK_LValueBitCast; 8214 return Compatible; 8215 } 8216 return Incompatible; 8217 } 8218 8219 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 8220 // to the same ExtVector type. 8221 if (LHSType->isExtVectorType()) { 8222 if (RHSType->isExtVectorType()) 8223 return Incompatible; 8224 if (RHSType->isArithmeticType()) { 8225 // CK_VectorSplat does T -> vector T, so first cast to the element type. 8226 if (ConvertRHS) 8227 RHS = prepareVectorSplat(LHSType, RHS.get()); 8228 Kind = CK_VectorSplat; 8229 return Compatible; 8230 } 8231 } 8232 8233 // Conversions to or from vector type. 8234 if (LHSType->isVectorType() || RHSType->isVectorType()) { 8235 if (LHSType->isVectorType() && RHSType->isVectorType()) { 8236 // Allow assignments of an AltiVec vector type to an equivalent GCC 8237 // vector type and vice versa 8238 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8239 Kind = CK_BitCast; 8240 return Compatible; 8241 } 8242 8243 // If we are allowing lax vector conversions, and LHS and RHS are both 8244 // vectors, the total size only needs to be the same. This is a bitcast; 8245 // no bits are changed but the result type is different. 8246 if (isLaxVectorConversion(RHSType, LHSType)) { 8247 Kind = CK_BitCast; 8248 return IncompatibleVectors; 8249 } 8250 } 8251 8252 // When the RHS comes from another lax conversion (e.g. binops between 8253 // scalars and vectors) the result is canonicalized as a vector. When the 8254 // LHS is also a vector, the lax is allowed by the condition above. Handle 8255 // the case where LHS is a scalar. 8256 if (LHSType->isScalarType()) { 8257 const VectorType *VecType = RHSType->getAs<VectorType>(); 8258 if (VecType && VecType->getNumElements() == 1 && 8259 isLaxVectorConversion(RHSType, LHSType)) { 8260 ExprResult *VecExpr = &RHS; 8261 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 8262 Kind = CK_BitCast; 8263 return Compatible; 8264 } 8265 } 8266 8267 return Incompatible; 8268 } 8269 8270 // Diagnose attempts to convert between __float128 and long double where 8271 // such conversions currently can't be handled. 8272 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 8273 return Incompatible; 8274 8275 // Disallow assigning a _Complex to a real type in C++ mode since it simply 8276 // discards the imaginary part. 8277 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 8278 !LHSType->getAs<ComplexType>()) 8279 return Incompatible; 8280 8281 // Arithmetic conversions. 8282 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 8283 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 8284 if (ConvertRHS) 8285 Kind = PrepareScalarCast(RHS, LHSType); 8286 return Compatible; 8287 } 8288 8289 // Conversions to normal pointers. 8290 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 8291 // U* -> T* 8292 if (isa<PointerType>(RHSType)) { 8293 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 8294 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 8295 if (AddrSpaceL != AddrSpaceR) 8296 Kind = CK_AddressSpaceConversion; 8297 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 8298 Kind = CK_NoOp; 8299 else 8300 Kind = CK_BitCast; 8301 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 8302 } 8303 8304 // int -> T* 8305 if (RHSType->isIntegerType()) { 8306 Kind = CK_IntegralToPointer; // FIXME: null? 8307 return IntToPointer; 8308 } 8309 8310 // C pointers are not compatible with ObjC object pointers, 8311 // with two exceptions: 8312 if (isa<ObjCObjectPointerType>(RHSType)) { 8313 // - conversions to void* 8314 if (LHSPointer->getPointeeType()->isVoidType()) { 8315 Kind = CK_BitCast; 8316 return Compatible; 8317 } 8318 8319 // - conversions from 'Class' to the redefinition type 8320 if (RHSType->isObjCClassType() && 8321 Context.hasSameType(LHSType, 8322 Context.getObjCClassRedefinitionType())) { 8323 Kind = CK_BitCast; 8324 return Compatible; 8325 } 8326 8327 Kind = CK_BitCast; 8328 return IncompatiblePointer; 8329 } 8330 8331 // U^ -> void* 8332 if (RHSType->getAs<BlockPointerType>()) { 8333 if (LHSPointer->getPointeeType()->isVoidType()) { 8334 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 8335 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 8336 ->getPointeeType() 8337 .getAddressSpace(); 8338 Kind = 8339 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 8340 return Compatible; 8341 } 8342 } 8343 8344 return Incompatible; 8345 } 8346 8347 // Conversions to block pointers. 8348 if (isa<BlockPointerType>(LHSType)) { 8349 // U^ -> T^ 8350 if (RHSType->isBlockPointerType()) { 8351 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 8352 ->getPointeeType() 8353 .getAddressSpace(); 8354 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 8355 ->getPointeeType() 8356 .getAddressSpace(); 8357 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 8358 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 8359 } 8360 8361 // int or null -> T^ 8362 if (RHSType->isIntegerType()) { 8363 Kind = CK_IntegralToPointer; // FIXME: null 8364 return IntToBlockPointer; 8365 } 8366 8367 // id -> T^ 8368 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 8369 Kind = CK_AnyPointerToBlockPointerCast; 8370 return Compatible; 8371 } 8372 8373 // void* -> T^ 8374 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 8375 if (RHSPT->getPointeeType()->isVoidType()) { 8376 Kind = CK_AnyPointerToBlockPointerCast; 8377 return Compatible; 8378 } 8379 8380 return Incompatible; 8381 } 8382 8383 // Conversions to Objective-C pointers. 8384 if (isa<ObjCObjectPointerType>(LHSType)) { 8385 // A* -> B* 8386 if (RHSType->isObjCObjectPointerType()) { 8387 Kind = CK_BitCast; 8388 Sema::AssignConvertType result = 8389 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 8390 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8391 result == Compatible && 8392 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 8393 result = IncompatibleObjCWeakRef; 8394 return result; 8395 } 8396 8397 // int or null -> A* 8398 if (RHSType->isIntegerType()) { 8399 Kind = CK_IntegralToPointer; // FIXME: null 8400 return IntToPointer; 8401 } 8402 8403 // In general, C pointers are not compatible with ObjC object pointers, 8404 // with two exceptions: 8405 if (isa<PointerType>(RHSType)) { 8406 Kind = CK_CPointerToObjCPointerCast; 8407 8408 // - conversions from 'void*' 8409 if (RHSType->isVoidPointerType()) { 8410 return Compatible; 8411 } 8412 8413 // - conversions to 'Class' from its redefinition type 8414 if (LHSType->isObjCClassType() && 8415 Context.hasSameType(RHSType, 8416 Context.getObjCClassRedefinitionType())) { 8417 return Compatible; 8418 } 8419 8420 return IncompatiblePointer; 8421 } 8422 8423 // Only under strict condition T^ is compatible with an Objective-C pointer. 8424 if (RHSType->isBlockPointerType() && 8425 LHSType->isBlockCompatibleObjCPointerType(Context)) { 8426 if (ConvertRHS) 8427 maybeExtendBlockObject(RHS); 8428 Kind = CK_BlockPointerToObjCPointerCast; 8429 return Compatible; 8430 } 8431 8432 return Incompatible; 8433 } 8434 8435 // Conversions from pointers that are not covered by the above. 8436 if (isa<PointerType>(RHSType)) { 8437 // T* -> _Bool 8438 if (LHSType == Context.BoolTy) { 8439 Kind = CK_PointerToBoolean; 8440 return Compatible; 8441 } 8442 8443 // T* -> int 8444 if (LHSType->isIntegerType()) { 8445 Kind = CK_PointerToIntegral; 8446 return PointerToInt; 8447 } 8448 8449 return Incompatible; 8450 } 8451 8452 // Conversions from Objective-C pointers that are not covered by the above. 8453 if (isa<ObjCObjectPointerType>(RHSType)) { 8454 // T* -> _Bool 8455 if (LHSType == Context.BoolTy) { 8456 Kind = CK_PointerToBoolean; 8457 return Compatible; 8458 } 8459 8460 // T* -> int 8461 if (LHSType->isIntegerType()) { 8462 Kind = CK_PointerToIntegral; 8463 return PointerToInt; 8464 } 8465 8466 return Incompatible; 8467 } 8468 8469 // struct A -> struct B 8470 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 8471 if (Context.typesAreCompatible(LHSType, RHSType)) { 8472 Kind = CK_NoOp; 8473 return Compatible; 8474 } 8475 } 8476 8477 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 8478 Kind = CK_IntToOCLSampler; 8479 return Compatible; 8480 } 8481 8482 return Incompatible; 8483 } 8484 8485 /// Constructs a transparent union from an expression that is 8486 /// used to initialize the transparent union. 8487 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 8488 ExprResult &EResult, QualType UnionType, 8489 FieldDecl *Field) { 8490 // Build an initializer list that designates the appropriate member 8491 // of the transparent union. 8492 Expr *E = EResult.get(); 8493 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 8494 E, SourceLocation()); 8495 Initializer->setType(UnionType); 8496 Initializer->setInitializedFieldInUnion(Field); 8497 8498 // Build a compound literal constructing a value of the transparent 8499 // union type from this initializer list. 8500 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 8501 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 8502 VK_RValue, Initializer, false); 8503 } 8504 8505 Sema::AssignConvertType 8506 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 8507 ExprResult &RHS) { 8508 QualType RHSType = RHS.get()->getType(); 8509 8510 // If the ArgType is a Union type, we want to handle a potential 8511 // transparent_union GCC extension. 8512 const RecordType *UT = ArgType->getAsUnionType(); 8513 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 8514 return Incompatible; 8515 8516 // The field to initialize within the transparent union. 8517 RecordDecl *UD = UT->getDecl(); 8518 FieldDecl *InitField = nullptr; 8519 // It's compatible if the expression matches any of the fields. 8520 for (auto *it : UD->fields()) { 8521 if (it->getType()->isPointerType()) { 8522 // If the transparent union contains a pointer type, we allow: 8523 // 1) void pointer 8524 // 2) null pointer constant 8525 if (RHSType->isPointerType()) 8526 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 8527 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 8528 InitField = it; 8529 break; 8530 } 8531 8532 if (RHS.get()->isNullPointerConstant(Context, 8533 Expr::NPC_ValueDependentIsNull)) { 8534 RHS = ImpCastExprToType(RHS.get(), it->getType(), 8535 CK_NullToPointer); 8536 InitField = it; 8537 break; 8538 } 8539 } 8540 8541 CastKind Kind; 8542 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 8543 == Compatible) { 8544 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 8545 InitField = it; 8546 break; 8547 } 8548 } 8549 8550 if (!InitField) 8551 return Incompatible; 8552 8553 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 8554 return Compatible; 8555 } 8556 8557 Sema::AssignConvertType 8558 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 8559 bool Diagnose, 8560 bool DiagnoseCFAudited, 8561 bool ConvertRHS) { 8562 // We need to be able to tell the caller whether we diagnosed a problem, if 8563 // they ask us to issue diagnostics. 8564 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 8565 8566 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 8567 // we can't avoid *all* modifications at the moment, so we need some somewhere 8568 // to put the updated value. 8569 ExprResult LocalRHS = CallerRHS; 8570 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 8571 8572 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 8573 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 8574 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 8575 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 8576 Diag(RHS.get()->getExprLoc(), 8577 diag::warn_noderef_to_dereferenceable_pointer) 8578 << RHS.get()->getSourceRange(); 8579 } 8580 } 8581 } 8582 8583 if (getLangOpts().CPlusPlus) { 8584 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 8585 // C++ 5.17p3: If the left operand is not of class type, the 8586 // expression is implicitly converted (C++ 4) to the 8587 // cv-unqualified type of the left operand. 8588 QualType RHSType = RHS.get()->getType(); 8589 if (Diagnose) { 8590 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8591 AA_Assigning); 8592 } else { 8593 ImplicitConversionSequence ICS = 8594 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8595 /*SuppressUserConversions=*/false, 8596 /*AllowExplicit=*/false, 8597 /*InOverloadResolution=*/false, 8598 /*CStyle=*/false, 8599 /*AllowObjCWritebackConversion=*/false); 8600 if (ICS.isFailure()) 8601 return Incompatible; 8602 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8603 ICS, AA_Assigning); 8604 } 8605 if (RHS.isInvalid()) 8606 return Incompatible; 8607 Sema::AssignConvertType result = Compatible; 8608 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8609 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 8610 result = IncompatibleObjCWeakRef; 8611 return result; 8612 } 8613 8614 // FIXME: Currently, we fall through and treat C++ classes like C 8615 // structures. 8616 // FIXME: We also fall through for atomics; not sure what should 8617 // happen there, though. 8618 } else if (RHS.get()->getType() == Context.OverloadTy) { 8619 // As a set of extensions to C, we support overloading on functions. These 8620 // functions need to be resolved here. 8621 DeclAccessPair DAP; 8622 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 8623 RHS.get(), LHSType, /*Complain=*/false, DAP)) 8624 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 8625 else 8626 return Incompatible; 8627 } 8628 8629 // C99 6.5.16.1p1: the left operand is a pointer and the right is 8630 // a null pointer constant. 8631 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 8632 LHSType->isBlockPointerType()) && 8633 RHS.get()->isNullPointerConstant(Context, 8634 Expr::NPC_ValueDependentIsNull)) { 8635 if (Diagnose || ConvertRHS) { 8636 CastKind Kind; 8637 CXXCastPath Path; 8638 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 8639 /*IgnoreBaseAccess=*/false, Diagnose); 8640 if (ConvertRHS) 8641 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 8642 } 8643 return Compatible; 8644 } 8645 8646 // OpenCL queue_t type assignment. 8647 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 8648 Context, Expr::NPC_ValueDependentIsNull)) { 8649 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 8650 return Compatible; 8651 } 8652 8653 // This check seems unnatural, however it is necessary to ensure the proper 8654 // conversion of functions/arrays. If the conversion were done for all 8655 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 8656 // expressions that suppress this implicit conversion (&, sizeof). 8657 // 8658 // Suppress this for references: C++ 8.5.3p5. 8659 if (!LHSType->isReferenceType()) { 8660 // FIXME: We potentially allocate here even if ConvertRHS is false. 8661 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 8662 if (RHS.isInvalid()) 8663 return Incompatible; 8664 } 8665 CastKind Kind; 8666 Sema::AssignConvertType result = 8667 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 8668 8669 // C99 6.5.16.1p2: The value of the right operand is converted to the 8670 // type of the assignment expression. 8671 // CheckAssignmentConstraints allows the left-hand side to be a reference, 8672 // so that we can use references in built-in functions even in C. 8673 // The getNonReferenceType() call makes sure that the resulting expression 8674 // does not have reference type. 8675 if (result != Incompatible && RHS.get()->getType() != LHSType) { 8676 QualType Ty = LHSType.getNonLValueExprType(Context); 8677 Expr *E = RHS.get(); 8678 8679 // Check for various Objective-C errors. If we are not reporting 8680 // diagnostics and just checking for errors, e.g., during overload 8681 // resolution, return Incompatible to indicate the failure. 8682 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8683 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 8684 Diagnose, DiagnoseCFAudited) != ACR_okay) { 8685 if (!Diagnose) 8686 return Incompatible; 8687 } 8688 if (getLangOpts().ObjC && 8689 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 8690 E->getType(), E, Diagnose) || 8691 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 8692 if (!Diagnose) 8693 return Incompatible; 8694 // Replace the expression with a corrected version and continue so we 8695 // can find further errors. 8696 RHS = E; 8697 return Compatible; 8698 } 8699 8700 if (ConvertRHS) 8701 RHS = ImpCastExprToType(E, Ty, Kind); 8702 } 8703 8704 return result; 8705 } 8706 8707 namespace { 8708 /// The original operand to an operator, prior to the application of the usual 8709 /// arithmetic conversions and converting the arguments of a builtin operator 8710 /// candidate. 8711 struct OriginalOperand { 8712 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 8713 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 8714 Op = MTE->getSubExpr(); 8715 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 8716 Op = BTE->getSubExpr(); 8717 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 8718 Orig = ICE->getSubExprAsWritten(); 8719 Conversion = ICE->getConversionFunction(); 8720 } 8721 } 8722 8723 QualType getType() const { return Orig->getType(); } 8724 8725 Expr *Orig; 8726 NamedDecl *Conversion; 8727 }; 8728 } 8729 8730 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 8731 ExprResult &RHS) { 8732 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 8733 8734 Diag(Loc, diag::err_typecheck_invalid_operands) 8735 << OrigLHS.getType() << OrigRHS.getType() 8736 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8737 8738 // If a user-defined conversion was applied to either of the operands prior 8739 // to applying the built-in operator rules, tell the user about it. 8740 if (OrigLHS.Conversion) { 8741 Diag(OrigLHS.Conversion->getLocation(), 8742 diag::note_typecheck_invalid_operands_converted) 8743 << 0 << LHS.get()->getType(); 8744 } 8745 if (OrigRHS.Conversion) { 8746 Diag(OrigRHS.Conversion->getLocation(), 8747 diag::note_typecheck_invalid_operands_converted) 8748 << 1 << RHS.get()->getType(); 8749 } 8750 8751 return QualType(); 8752 } 8753 8754 // Diagnose cases where a scalar was implicitly converted to a vector and 8755 // diagnose the underlying types. Otherwise, diagnose the error 8756 // as invalid vector logical operands for non-C++ cases. 8757 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 8758 ExprResult &RHS) { 8759 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 8760 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 8761 8762 bool LHSNatVec = LHSType->isVectorType(); 8763 bool RHSNatVec = RHSType->isVectorType(); 8764 8765 if (!(LHSNatVec && RHSNatVec)) { 8766 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 8767 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 8768 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8769 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 8770 << Vector->getSourceRange(); 8771 return QualType(); 8772 } 8773 8774 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8775 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 8776 << RHS.get()->getSourceRange(); 8777 8778 return QualType(); 8779 } 8780 8781 /// Try to convert a value of non-vector type to a vector type by converting 8782 /// the type to the element type of the vector and then performing a splat. 8783 /// If the language is OpenCL, we only use conversions that promote scalar 8784 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 8785 /// for float->int. 8786 /// 8787 /// OpenCL V2.0 6.2.6.p2: 8788 /// An error shall occur if any scalar operand type has greater rank 8789 /// than the type of the vector element. 8790 /// 8791 /// \param scalar - if non-null, actually perform the conversions 8792 /// \return true if the operation fails (but without diagnosing the failure) 8793 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 8794 QualType scalarTy, 8795 QualType vectorEltTy, 8796 QualType vectorTy, 8797 unsigned &DiagID) { 8798 // The conversion to apply to the scalar before splatting it, 8799 // if necessary. 8800 CastKind scalarCast = CK_NoOp; 8801 8802 if (vectorEltTy->isIntegralType(S.Context)) { 8803 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 8804 (scalarTy->isIntegerType() && 8805 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 8806 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8807 return true; 8808 } 8809 if (!scalarTy->isIntegralType(S.Context)) 8810 return true; 8811 scalarCast = CK_IntegralCast; 8812 } else if (vectorEltTy->isRealFloatingType()) { 8813 if (scalarTy->isRealFloatingType()) { 8814 if (S.getLangOpts().OpenCL && 8815 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 8816 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8817 return true; 8818 } 8819 scalarCast = CK_FloatingCast; 8820 } 8821 else if (scalarTy->isIntegralType(S.Context)) 8822 scalarCast = CK_IntegralToFloating; 8823 else 8824 return true; 8825 } else { 8826 return true; 8827 } 8828 8829 // Adjust scalar if desired. 8830 if (scalar) { 8831 if (scalarCast != CK_NoOp) 8832 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 8833 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 8834 } 8835 return false; 8836 } 8837 8838 /// Convert vector E to a vector with the same number of elements but different 8839 /// element type. 8840 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 8841 const auto *VecTy = E->getType()->getAs<VectorType>(); 8842 assert(VecTy && "Expression E must be a vector"); 8843 QualType NewVecTy = S.Context.getVectorType(ElementType, 8844 VecTy->getNumElements(), 8845 VecTy->getVectorKind()); 8846 8847 // Look through the implicit cast. Return the subexpression if its type is 8848 // NewVecTy. 8849 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 8850 if (ICE->getSubExpr()->getType() == NewVecTy) 8851 return ICE->getSubExpr(); 8852 8853 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 8854 return S.ImpCastExprToType(E, NewVecTy, Cast); 8855 } 8856 8857 /// Test if a (constant) integer Int can be casted to another integer type 8858 /// IntTy without losing precision. 8859 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 8860 QualType OtherIntTy) { 8861 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8862 8863 // Reject cases where the value of the Int is unknown as that would 8864 // possibly cause truncation, but accept cases where the scalar can be 8865 // demoted without loss of precision. 8866 Expr::EvalResult EVResult; 8867 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 8868 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 8869 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 8870 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 8871 8872 if (CstInt) { 8873 // If the scalar is constant and is of a higher order and has more active 8874 // bits that the vector element type, reject it. 8875 llvm::APSInt Result = EVResult.Val.getInt(); 8876 unsigned NumBits = IntSigned 8877 ? (Result.isNegative() ? Result.getMinSignedBits() 8878 : Result.getActiveBits()) 8879 : Result.getActiveBits(); 8880 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 8881 return true; 8882 8883 // If the signedness of the scalar type and the vector element type 8884 // differs and the number of bits is greater than that of the vector 8885 // element reject it. 8886 return (IntSigned != OtherIntSigned && 8887 NumBits > S.Context.getIntWidth(OtherIntTy)); 8888 } 8889 8890 // Reject cases where the value of the scalar is not constant and it's 8891 // order is greater than that of the vector element type. 8892 return (Order < 0); 8893 } 8894 8895 /// Test if a (constant) integer Int can be casted to floating point type 8896 /// FloatTy without losing precision. 8897 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 8898 QualType FloatTy) { 8899 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8900 8901 // Determine if the integer constant can be expressed as a floating point 8902 // number of the appropriate type. 8903 Expr::EvalResult EVResult; 8904 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 8905 8906 uint64_t Bits = 0; 8907 if (CstInt) { 8908 // Reject constants that would be truncated if they were converted to 8909 // the floating point type. Test by simple to/from conversion. 8910 // FIXME: Ideally the conversion to an APFloat and from an APFloat 8911 // could be avoided if there was a convertFromAPInt method 8912 // which could signal back if implicit truncation occurred. 8913 llvm::APSInt Result = EVResult.Val.getInt(); 8914 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 8915 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 8916 llvm::APFloat::rmTowardZero); 8917 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 8918 !IntTy->hasSignedIntegerRepresentation()); 8919 bool Ignored = false; 8920 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 8921 &Ignored); 8922 if (Result != ConvertBack) 8923 return true; 8924 } else { 8925 // Reject types that cannot be fully encoded into the mantissa of 8926 // the float. 8927 Bits = S.Context.getTypeSize(IntTy); 8928 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 8929 S.Context.getFloatTypeSemantics(FloatTy)); 8930 if (Bits > FloatPrec) 8931 return true; 8932 } 8933 8934 return false; 8935 } 8936 8937 /// Attempt to convert and splat Scalar into a vector whose types matches 8938 /// Vector following GCC conversion rules. The rule is that implicit 8939 /// conversion can occur when Scalar can be casted to match Vector's element 8940 /// type without causing truncation of Scalar. 8941 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 8942 ExprResult *Vector) { 8943 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 8944 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 8945 const VectorType *VT = VectorTy->getAs<VectorType>(); 8946 8947 assert(!isa<ExtVectorType>(VT) && 8948 "ExtVectorTypes should not be handled here!"); 8949 8950 QualType VectorEltTy = VT->getElementType(); 8951 8952 // Reject cases where the vector element type or the scalar element type are 8953 // not integral or floating point types. 8954 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 8955 return true; 8956 8957 // The conversion to apply to the scalar before splatting it, 8958 // if necessary. 8959 CastKind ScalarCast = CK_NoOp; 8960 8961 // Accept cases where the vector elements are integers and the scalar is 8962 // an integer. 8963 // FIXME: Notionally if the scalar was a floating point value with a precise 8964 // integral representation, we could cast it to an appropriate integer 8965 // type and then perform the rest of the checks here. GCC will perform 8966 // this conversion in some cases as determined by the input language. 8967 // We should accept it on a language independent basis. 8968 if (VectorEltTy->isIntegralType(S.Context) && 8969 ScalarTy->isIntegralType(S.Context) && 8970 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 8971 8972 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 8973 return true; 8974 8975 ScalarCast = CK_IntegralCast; 8976 } else if (VectorEltTy->isRealFloatingType()) { 8977 if (ScalarTy->isRealFloatingType()) { 8978 8979 // Reject cases where the scalar type is not a constant and has a higher 8980 // Order than the vector element type. 8981 llvm::APFloat Result(0.0); 8982 bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context); 8983 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 8984 if (!CstScalar && Order < 0) 8985 return true; 8986 8987 // If the scalar cannot be safely casted to the vector element type, 8988 // reject it. 8989 if (CstScalar) { 8990 bool Truncated = false; 8991 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 8992 llvm::APFloat::rmNearestTiesToEven, &Truncated); 8993 if (Truncated) 8994 return true; 8995 } 8996 8997 ScalarCast = CK_FloatingCast; 8998 } else if (ScalarTy->isIntegralType(S.Context)) { 8999 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 9000 return true; 9001 9002 ScalarCast = CK_IntegralToFloating; 9003 } else 9004 return true; 9005 } 9006 9007 // Adjust scalar if desired. 9008 if (Scalar) { 9009 if (ScalarCast != CK_NoOp) 9010 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 9011 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 9012 } 9013 return false; 9014 } 9015 9016 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 9017 SourceLocation Loc, bool IsCompAssign, 9018 bool AllowBothBool, 9019 bool AllowBoolConversions) { 9020 if (!IsCompAssign) { 9021 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 9022 if (LHS.isInvalid()) 9023 return QualType(); 9024 } 9025 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 9026 if (RHS.isInvalid()) 9027 return QualType(); 9028 9029 // For conversion purposes, we ignore any qualifiers. 9030 // For example, "const float" and "float" are equivalent. 9031 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 9032 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 9033 9034 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 9035 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 9036 assert(LHSVecType || RHSVecType); 9037 9038 // AltiVec-style "vector bool op vector bool" combinations are allowed 9039 // for some operators but not others. 9040 if (!AllowBothBool && 9041 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9042 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9043 return InvalidOperands(Loc, LHS, RHS); 9044 9045 // If the vector types are identical, return. 9046 if (Context.hasSameType(LHSType, RHSType)) 9047 return LHSType; 9048 9049 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 9050 if (LHSVecType && RHSVecType && 9051 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9052 if (isa<ExtVectorType>(LHSVecType)) { 9053 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9054 return LHSType; 9055 } 9056 9057 if (!IsCompAssign) 9058 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9059 return RHSType; 9060 } 9061 9062 // AllowBoolConversions says that bool and non-bool AltiVec vectors 9063 // can be mixed, with the result being the non-bool type. The non-bool 9064 // operand must have integer element type. 9065 if (AllowBoolConversions && LHSVecType && RHSVecType && 9066 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 9067 (Context.getTypeSize(LHSVecType->getElementType()) == 9068 Context.getTypeSize(RHSVecType->getElementType()))) { 9069 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 9070 LHSVecType->getElementType()->isIntegerType() && 9071 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 9072 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9073 return LHSType; 9074 } 9075 if (!IsCompAssign && 9076 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9077 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 9078 RHSVecType->getElementType()->isIntegerType()) { 9079 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9080 return RHSType; 9081 } 9082 } 9083 9084 // If there's a vector type and a scalar, try to convert the scalar to 9085 // the vector element type and splat. 9086 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 9087 if (!RHSVecType) { 9088 if (isa<ExtVectorType>(LHSVecType)) { 9089 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 9090 LHSVecType->getElementType(), LHSType, 9091 DiagID)) 9092 return LHSType; 9093 } else { 9094 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 9095 return LHSType; 9096 } 9097 } 9098 if (!LHSVecType) { 9099 if (isa<ExtVectorType>(RHSVecType)) { 9100 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 9101 LHSType, RHSVecType->getElementType(), 9102 RHSType, DiagID)) 9103 return RHSType; 9104 } else { 9105 if (LHS.get()->getValueKind() == VK_LValue || 9106 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 9107 return RHSType; 9108 } 9109 } 9110 9111 // FIXME: The code below also handles conversion between vectors and 9112 // non-scalars, we should break this down into fine grained specific checks 9113 // and emit proper diagnostics. 9114 QualType VecType = LHSVecType ? LHSType : RHSType; 9115 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 9116 QualType OtherType = LHSVecType ? RHSType : LHSType; 9117 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 9118 if (isLaxVectorConversion(OtherType, VecType)) { 9119 // If we're allowing lax vector conversions, only the total (data) size 9120 // needs to be the same. For non compound assignment, if one of the types is 9121 // scalar, the result is always the vector type. 9122 if (!IsCompAssign) { 9123 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 9124 return VecType; 9125 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 9126 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 9127 // type. Note that this is already done by non-compound assignments in 9128 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 9129 // <1 x T> -> T. The result is also a vector type. 9130 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 9131 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 9132 ExprResult *RHSExpr = &RHS; 9133 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 9134 return VecType; 9135 } 9136 } 9137 9138 // Okay, the expression is invalid. 9139 9140 // If there's a non-vector, non-real operand, diagnose that. 9141 if ((!RHSVecType && !RHSType->isRealType()) || 9142 (!LHSVecType && !LHSType->isRealType())) { 9143 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 9144 << LHSType << RHSType 9145 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9146 return QualType(); 9147 } 9148 9149 // OpenCL V1.1 6.2.6.p1: 9150 // If the operands are of more than one vector type, then an error shall 9151 // occur. Implicit conversions between vector types are not permitted, per 9152 // section 6.2.1. 9153 if (getLangOpts().OpenCL && 9154 RHSVecType && isa<ExtVectorType>(RHSVecType) && 9155 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 9156 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 9157 << RHSType; 9158 return QualType(); 9159 } 9160 9161 9162 // If there is a vector type that is not a ExtVector and a scalar, we reach 9163 // this point if scalar could not be converted to the vector's element type 9164 // without truncation. 9165 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 9166 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 9167 QualType Scalar = LHSVecType ? RHSType : LHSType; 9168 QualType Vector = LHSVecType ? LHSType : RHSType; 9169 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 9170 Diag(Loc, 9171 diag::err_typecheck_vector_not_convertable_implict_truncation) 9172 << ScalarOrVector << Scalar << Vector; 9173 9174 return QualType(); 9175 } 9176 9177 // Otherwise, use the generic diagnostic. 9178 Diag(Loc, DiagID) 9179 << LHSType << RHSType 9180 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9181 return QualType(); 9182 } 9183 9184 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 9185 // expression. These are mainly cases where the null pointer is used as an 9186 // integer instead of a pointer. 9187 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 9188 SourceLocation Loc, bool IsCompare) { 9189 // The canonical way to check for a GNU null is with isNullPointerConstant, 9190 // but we use a bit of a hack here for speed; this is a relatively 9191 // hot path, and isNullPointerConstant is slow. 9192 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 9193 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 9194 9195 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 9196 9197 // Avoid analyzing cases where the result will either be invalid (and 9198 // diagnosed as such) or entirely valid and not something to warn about. 9199 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 9200 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 9201 return; 9202 9203 // Comparison operations would not make sense with a null pointer no matter 9204 // what the other expression is. 9205 if (!IsCompare) { 9206 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 9207 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 9208 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 9209 return; 9210 } 9211 9212 // The rest of the operations only make sense with a null pointer 9213 // if the other expression is a pointer. 9214 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 9215 NonNullType->canDecayToPointerType()) 9216 return; 9217 9218 S.Diag(Loc, diag::warn_null_in_comparison_operation) 9219 << LHSNull /* LHS is NULL */ << NonNullType 9220 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9221 } 9222 9223 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 9224 SourceLocation Loc) { 9225 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 9226 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 9227 if (!LUE || !RUE) 9228 return; 9229 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 9230 RUE->getKind() != UETT_SizeOf) 9231 return; 9232 9233 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 9234 QualType LHSTy = LHSArg->getType(); 9235 QualType RHSTy; 9236 9237 if (RUE->isArgumentType()) 9238 RHSTy = RUE->getArgumentType(); 9239 else 9240 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 9241 9242 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 9243 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 9244 return; 9245 9246 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 9247 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 9248 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 9249 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 9250 << LHSArgDecl; 9251 } 9252 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 9253 QualType ArrayElemTy = ArrayTy->getElementType(); 9254 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 9255 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 9256 ArrayElemTy->isCharType() || 9257 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 9258 return; 9259 S.Diag(Loc, diag::warn_division_sizeof_array) 9260 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 9261 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 9262 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 9263 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 9264 << LHSArgDecl; 9265 } 9266 9267 S.Diag(Loc, diag::note_precedence_silence) << RHS; 9268 } 9269 } 9270 9271 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 9272 ExprResult &RHS, 9273 SourceLocation Loc, bool IsDiv) { 9274 // Check for division/remainder by zero. 9275 Expr::EvalResult RHSValue; 9276 if (!RHS.get()->isValueDependent() && 9277 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 9278 RHSValue.Val.getInt() == 0) 9279 S.DiagRuntimeBehavior(Loc, RHS.get(), 9280 S.PDiag(diag::warn_remainder_division_by_zero) 9281 << IsDiv << RHS.get()->getSourceRange()); 9282 } 9283 9284 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 9285 SourceLocation Loc, 9286 bool IsCompAssign, bool IsDiv) { 9287 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9288 9289 if (LHS.get()->getType()->isVectorType() || 9290 RHS.get()->getType()->isVectorType()) 9291 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9292 /*AllowBothBool*/getLangOpts().AltiVec, 9293 /*AllowBoolConversions*/false); 9294 9295 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 9296 if (LHS.isInvalid() || RHS.isInvalid()) 9297 return QualType(); 9298 9299 9300 if (compType.isNull() || !compType->isArithmeticType()) 9301 return InvalidOperands(Loc, LHS, RHS); 9302 if (IsDiv) { 9303 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 9304 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 9305 } 9306 return compType; 9307 } 9308 9309 QualType Sema::CheckRemainderOperands( 9310 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 9311 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9312 9313 if (LHS.get()->getType()->isVectorType() || 9314 RHS.get()->getType()->isVectorType()) { 9315 if (LHS.get()->getType()->hasIntegerRepresentation() && 9316 RHS.get()->getType()->hasIntegerRepresentation()) 9317 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9318 /*AllowBothBool*/getLangOpts().AltiVec, 9319 /*AllowBoolConversions*/false); 9320 return InvalidOperands(Loc, LHS, RHS); 9321 } 9322 9323 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 9324 if (LHS.isInvalid() || RHS.isInvalid()) 9325 return QualType(); 9326 9327 if (compType.isNull() || !compType->isIntegerType()) 9328 return InvalidOperands(Loc, LHS, RHS); 9329 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 9330 return compType; 9331 } 9332 9333 /// Diagnose invalid arithmetic on two void pointers. 9334 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 9335 Expr *LHSExpr, Expr *RHSExpr) { 9336 S.Diag(Loc, S.getLangOpts().CPlusPlus 9337 ? diag::err_typecheck_pointer_arith_void_type 9338 : diag::ext_gnu_void_ptr) 9339 << 1 /* two pointers */ << LHSExpr->getSourceRange() 9340 << RHSExpr->getSourceRange(); 9341 } 9342 9343 /// Diagnose invalid arithmetic on a void pointer. 9344 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 9345 Expr *Pointer) { 9346 S.Diag(Loc, S.getLangOpts().CPlusPlus 9347 ? diag::err_typecheck_pointer_arith_void_type 9348 : diag::ext_gnu_void_ptr) 9349 << 0 /* one pointer */ << Pointer->getSourceRange(); 9350 } 9351 9352 /// Diagnose invalid arithmetic on a null pointer. 9353 /// 9354 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 9355 /// idiom, which we recognize as a GNU extension. 9356 /// 9357 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 9358 Expr *Pointer, bool IsGNUIdiom) { 9359 if (IsGNUIdiom) 9360 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 9361 << Pointer->getSourceRange(); 9362 else 9363 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 9364 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 9365 } 9366 9367 /// Diagnose invalid arithmetic on two function pointers. 9368 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 9369 Expr *LHS, Expr *RHS) { 9370 assert(LHS->getType()->isAnyPointerType()); 9371 assert(RHS->getType()->isAnyPointerType()); 9372 S.Diag(Loc, S.getLangOpts().CPlusPlus 9373 ? diag::err_typecheck_pointer_arith_function_type 9374 : diag::ext_gnu_ptr_func_arith) 9375 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 9376 // We only show the second type if it differs from the first. 9377 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 9378 RHS->getType()) 9379 << RHS->getType()->getPointeeType() 9380 << LHS->getSourceRange() << RHS->getSourceRange(); 9381 } 9382 9383 /// Diagnose invalid arithmetic on a function pointer. 9384 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 9385 Expr *Pointer) { 9386 assert(Pointer->getType()->isAnyPointerType()); 9387 S.Diag(Loc, S.getLangOpts().CPlusPlus 9388 ? diag::err_typecheck_pointer_arith_function_type 9389 : diag::ext_gnu_ptr_func_arith) 9390 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 9391 << 0 /* one pointer, so only one type */ 9392 << Pointer->getSourceRange(); 9393 } 9394 9395 /// Emit error if Operand is incomplete pointer type 9396 /// 9397 /// \returns True if pointer has incomplete type 9398 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 9399 Expr *Operand) { 9400 QualType ResType = Operand->getType(); 9401 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 9402 ResType = ResAtomicType->getValueType(); 9403 9404 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 9405 QualType PointeeTy = ResType->getPointeeType(); 9406 return S.RequireCompleteType(Loc, PointeeTy, 9407 diag::err_typecheck_arithmetic_incomplete_type, 9408 PointeeTy, Operand->getSourceRange()); 9409 } 9410 9411 /// Check the validity of an arithmetic pointer operand. 9412 /// 9413 /// If the operand has pointer type, this code will check for pointer types 9414 /// which are invalid in arithmetic operations. These will be diagnosed 9415 /// appropriately, including whether or not the use is supported as an 9416 /// extension. 9417 /// 9418 /// \returns True when the operand is valid to use (even if as an extension). 9419 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 9420 Expr *Operand) { 9421 QualType ResType = Operand->getType(); 9422 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 9423 ResType = ResAtomicType->getValueType(); 9424 9425 if (!ResType->isAnyPointerType()) return true; 9426 9427 QualType PointeeTy = ResType->getPointeeType(); 9428 if (PointeeTy->isVoidType()) { 9429 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 9430 return !S.getLangOpts().CPlusPlus; 9431 } 9432 if (PointeeTy->isFunctionType()) { 9433 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 9434 return !S.getLangOpts().CPlusPlus; 9435 } 9436 9437 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 9438 9439 return true; 9440 } 9441 9442 /// Check the validity of a binary arithmetic operation w.r.t. pointer 9443 /// operands. 9444 /// 9445 /// This routine will diagnose any invalid arithmetic on pointer operands much 9446 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 9447 /// for emitting a single diagnostic even for operations where both LHS and RHS 9448 /// are (potentially problematic) pointers. 9449 /// 9450 /// \returns True when the operand is valid to use (even if as an extension). 9451 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 9452 Expr *LHSExpr, Expr *RHSExpr) { 9453 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 9454 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 9455 if (!isLHSPointer && !isRHSPointer) return true; 9456 9457 QualType LHSPointeeTy, RHSPointeeTy; 9458 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 9459 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 9460 9461 // if both are pointers check if operation is valid wrt address spaces 9462 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 9463 const PointerType *lhsPtr = LHSExpr->getType()->castAs<PointerType>(); 9464 const PointerType *rhsPtr = RHSExpr->getType()->castAs<PointerType>(); 9465 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 9466 S.Diag(Loc, 9467 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 9468 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 9469 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 9470 return false; 9471 } 9472 } 9473 9474 // Check for arithmetic on pointers to incomplete types. 9475 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 9476 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 9477 if (isLHSVoidPtr || isRHSVoidPtr) { 9478 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 9479 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 9480 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 9481 9482 return !S.getLangOpts().CPlusPlus; 9483 } 9484 9485 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 9486 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 9487 if (isLHSFuncPtr || isRHSFuncPtr) { 9488 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 9489 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 9490 RHSExpr); 9491 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 9492 9493 return !S.getLangOpts().CPlusPlus; 9494 } 9495 9496 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 9497 return false; 9498 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 9499 return false; 9500 9501 return true; 9502 } 9503 9504 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 9505 /// literal. 9506 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 9507 Expr *LHSExpr, Expr *RHSExpr) { 9508 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 9509 Expr* IndexExpr = RHSExpr; 9510 if (!StrExpr) { 9511 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 9512 IndexExpr = LHSExpr; 9513 } 9514 9515 bool IsStringPlusInt = StrExpr && 9516 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 9517 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 9518 return; 9519 9520 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 9521 Self.Diag(OpLoc, diag::warn_string_plus_int) 9522 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 9523 9524 // Only print a fixit for "str" + int, not for int + "str". 9525 if (IndexExpr == RHSExpr) { 9526 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 9527 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 9528 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 9529 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 9530 << FixItHint::CreateInsertion(EndLoc, "]"); 9531 } else 9532 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 9533 } 9534 9535 /// Emit a warning when adding a char literal to a string. 9536 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 9537 Expr *LHSExpr, Expr *RHSExpr) { 9538 const Expr *StringRefExpr = LHSExpr; 9539 const CharacterLiteral *CharExpr = 9540 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 9541 9542 if (!CharExpr) { 9543 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 9544 StringRefExpr = RHSExpr; 9545 } 9546 9547 if (!CharExpr || !StringRefExpr) 9548 return; 9549 9550 const QualType StringType = StringRefExpr->getType(); 9551 9552 // Return if not a PointerType. 9553 if (!StringType->isAnyPointerType()) 9554 return; 9555 9556 // Return if not a CharacterType. 9557 if (!StringType->getPointeeType()->isAnyCharacterType()) 9558 return; 9559 9560 ASTContext &Ctx = Self.getASTContext(); 9561 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 9562 9563 const QualType CharType = CharExpr->getType(); 9564 if (!CharType->isAnyCharacterType() && 9565 CharType->isIntegerType() && 9566 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 9567 Self.Diag(OpLoc, diag::warn_string_plus_char) 9568 << DiagRange << Ctx.CharTy; 9569 } else { 9570 Self.Diag(OpLoc, diag::warn_string_plus_char) 9571 << DiagRange << CharExpr->getType(); 9572 } 9573 9574 // Only print a fixit for str + char, not for char + str. 9575 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 9576 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 9577 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 9578 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 9579 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 9580 << FixItHint::CreateInsertion(EndLoc, "]"); 9581 } else { 9582 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 9583 } 9584 } 9585 9586 /// Emit error when two pointers are incompatible. 9587 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 9588 Expr *LHSExpr, Expr *RHSExpr) { 9589 assert(LHSExpr->getType()->isAnyPointerType()); 9590 assert(RHSExpr->getType()->isAnyPointerType()); 9591 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 9592 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 9593 << RHSExpr->getSourceRange(); 9594 } 9595 9596 // C99 6.5.6 9597 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 9598 SourceLocation Loc, BinaryOperatorKind Opc, 9599 QualType* CompLHSTy) { 9600 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9601 9602 if (LHS.get()->getType()->isVectorType() || 9603 RHS.get()->getType()->isVectorType()) { 9604 QualType compType = CheckVectorOperands( 9605 LHS, RHS, Loc, CompLHSTy, 9606 /*AllowBothBool*/getLangOpts().AltiVec, 9607 /*AllowBoolConversions*/getLangOpts().ZVector); 9608 if (CompLHSTy) *CompLHSTy = compType; 9609 return compType; 9610 } 9611 9612 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 9613 if (LHS.isInvalid() || RHS.isInvalid()) 9614 return QualType(); 9615 9616 // Diagnose "string literal" '+' int and string '+' "char literal". 9617 if (Opc == BO_Add) { 9618 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 9619 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 9620 } 9621 9622 // handle the common case first (both operands are arithmetic). 9623 if (!compType.isNull() && compType->isArithmeticType()) { 9624 if (CompLHSTy) *CompLHSTy = compType; 9625 return compType; 9626 } 9627 9628 // Type-checking. Ultimately the pointer's going to be in PExp; 9629 // note that we bias towards the LHS being the pointer. 9630 Expr *PExp = LHS.get(), *IExp = RHS.get(); 9631 9632 bool isObjCPointer; 9633 if (PExp->getType()->isPointerType()) { 9634 isObjCPointer = false; 9635 } else if (PExp->getType()->isObjCObjectPointerType()) { 9636 isObjCPointer = true; 9637 } else { 9638 std::swap(PExp, IExp); 9639 if (PExp->getType()->isPointerType()) { 9640 isObjCPointer = false; 9641 } else if (PExp->getType()->isObjCObjectPointerType()) { 9642 isObjCPointer = true; 9643 } else { 9644 return InvalidOperands(Loc, LHS, RHS); 9645 } 9646 } 9647 assert(PExp->getType()->isAnyPointerType()); 9648 9649 if (!IExp->getType()->isIntegerType()) 9650 return InvalidOperands(Loc, LHS, RHS); 9651 9652 // Adding to a null pointer results in undefined behavior. 9653 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 9654 Context, Expr::NPC_ValueDependentIsNotNull)) { 9655 // In C++ adding zero to a null pointer is defined. 9656 Expr::EvalResult KnownVal; 9657 if (!getLangOpts().CPlusPlus || 9658 (!IExp->isValueDependent() && 9659 (!IExp->EvaluateAsInt(KnownVal, Context) || 9660 KnownVal.Val.getInt() != 0))) { 9661 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 9662 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 9663 Context, BO_Add, PExp, IExp); 9664 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 9665 } 9666 } 9667 9668 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 9669 return QualType(); 9670 9671 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 9672 return QualType(); 9673 9674 // Check array bounds for pointer arithemtic 9675 CheckArrayAccess(PExp, IExp); 9676 9677 if (CompLHSTy) { 9678 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 9679 if (LHSTy.isNull()) { 9680 LHSTy = LHS.get()->getType(); 9681 if (LHSTy->isPromotableIntegerType()) 9682 LHSTy = Context.getPromotedIntegerType(LHSTy); 9683 } 9684 *CompLHSTy = LHSTy; 9685 } 9686 9687 return PExp->getType(); 9688 } 9689 9690 // C99 6.5.6 9691 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 9692 SourceLocation Loc, 9693 QualType* CompLHSTy) { 9694 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9695 9696 if (LHS.get()->getType()->isVectorType() || 9697 RHS.get()->getType()->isVectorType()) { 9698 QualType compType = CheckVectorOperands( 9699 LHS, RHS, Loc, CompLHSTy, 9700 /*AllowBothBool*/getLangOpts().AltiVec, 9701 /*AllowBoolConversions*/getLangOpts().ZVector); 9702 if (CompLHSTy) *CompLHSTy = compType; 9703 return compType; 9704 } 9705 9706 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 9707 if (LHS.isInvalid() || RHS.isInvalid()) 9708 return QualType(); 9709 9710 // Enforce type constraints: C99 6.5.6p3. 9711 9712 // Handle the common case first (both operands are arithmetic). 9713 if (!compType.isNull() && compType->isArithmeticType()) { 9714 if (CompLHSTy) *CompLHSTy = compType; 9715 return compType; 9716 } 9717 9718 // Either ptr - int or ptr - ptr. 9719 if (LHS.get()->getType()->isAnyPointerType()) { 9720 QualType lpointee = LHS.get()->getType()->getPointeeType(); 9721 9722 // Diagnose bad cases where we step over interface counts. 9723 if (LHS.get()->getType()->isObjCObjectPointerType() && 9724 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 9725 return QualType(); 9726 9727 // The result type of a pointer-int computation is the pointer type. 9728 if (RHS.get()->getType()->isIntegerType()) { 9729 // Subtracting from a null pointer should produce a warning. 9730 // The last argument to the diagnose call says this doesn't match the 9731 // GNU int-to-pointer idiom. 9732 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 9733 Expr::NPC_ValueDependentIsNotNull)) { 9734 // In C++ adding zero to a null pointer is defined. 9735 Expr::EvalResult KnownVal; 9736 if (!getLangOpts().CPlusPlus || 9737 (!RHS.get()->isValueDependent() && 9738 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 9739 KnownVal.Val.getInt() != 0))) { 9740 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 9741 } 9742 } 9743 9744 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 9745 return QualType(); 9746 9747 // Check array bounds for pointer arithemtic 9748 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 9749 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 9750 9751 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9752 return LHS.get()->getType(); 9753 } 9754 9755 // Handle pointer-pointer subtractions. 9756 if (const PointerType *RHSPTy 9757 = RHS.get()->getType()->getAs<PointerType>()) { 9758 QualType rpointee = RHSPTy->getPointeeType(); 9759 9760 if (getLangOpts().CPlusPlus) { 9761 // Pointee types must be the same: C++ [expr.add] 9762 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 9763 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9764 } 9765 } else { 9766 // Pointee types must be compatible C99 6.5.6p3 9767 if (!Context.typesAreCompatible( 9768 Context.getCanonicalType(lpointee).getUnqualifiedType(), 9769 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 9770 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9771 return QualType(); 9772 } 9773 } 9774 9775 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 9776 LHS.get(), RHS.get())) 9777 return QualType(); 9778 9779 // FIXME: Add warnings for nullptr - ptr. 9780 9781 // The pointee type may have zero size. As an extension, a structure or 9782 // union may have zero size or an array may have zero length. In this 9783 // case subtraction does not make sense. 9784 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 9785 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 9786 if (ElementSize.isZero()) { 9787 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 9788 << rpointee.getUnqualifiedType() 9789 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9790 } 9791 } 9792 9793 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9794 return Context.getPointerDiffType(); 9795 } 9796 } 9797 9798 return InvalidOperands(Loc, LHS, RHS); 9799 } 9800 9801 static bool isScopedEnumerationType(QualType T) { 9802 if (const EnumType *ET = T->getAs<EnumType>()) 9803 return ET->getDecl()->isScoped(); 9804 return false; 9805 } 9806 9807 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 9808 SourceLocation Loc, BinaryOperatorKind Opc, 9809 QualType LHSType) { 9810 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 9811 // so skip remaining warnings as we don't want to modify values within Sema. 9812 if (S.getLangOpts().OpenCL) 9813 return; 9814 9815 // Check right/shifter operand 9816 Expr::EvalResult RHSResult; 9817 if (RHS.get()->isValueDependent() || 9818 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 9819 return; 9820 llvm::APSInt Right = RHSResult.Val.getInt(); 9821 9822 if (Right.isNegative()) { 9823 S.DiagRuntimeBehavior(Loc, RHS.get(), 9824 S.PDiag(diag::warn_shift_negative) 9825 << RHS.get()->getSourceRange()); 9826 return; 9827 } 9828 llvm::APInt LeftBits(Right.getBitWidth(), 9829 S.Context.getTypeSize(LHS.get()->getType())); 9830 if (Right.uge(LeftBits)) { 9831 S.DiagRuntimeBehavior(Loc, RHS.get(), 9832 S.PDiag(diag::warn_shift_gt_typewidth) 9833 << RHS.get()->getSourceRange()); 9834 return; 9835 } 9836 if (Opc != BO_Shl) 9837 return; 9838 9839 // When left shifting an ICE which is signed, we can check for overflow which 9840 // according to C++ standards prior to C++2a has undefined behavior 9841 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 9842 // more than the maximum value representable in the result type, so never 9843 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 9844 // expression is still probably a bug.) 9845 Expr::EvalResult LHSResult; 9846 if (LHS.get()->isValueDependent() || 9847 LHSType->hasUnsignedIntegerRepresentation() || 9848 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 9849 return; 9850 llvm::APSInt Left = LHSResult.Val.getInt(); 9851 9852 // If LHS does not have a signed type and non-negative value 9853 // then, the behavior is undefined before C++2a. Warn about it. 9854 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 9855 !S.getLangOpts().CPlusPlus2a) { 9856 S.DiagRuntimeBehavior(Loc, LHS.get(), 9857 S.PDiag(diag::warn_shift_lhs_negative) 9858 << LHS.get()->getSourceRange()); 9859 return; 9860 } 9861 9862 llvm::APInt ResultBits = 9863 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 9864 if (LeftBits.uge(ResultBits)) 9865 return; 9866 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 9867 Result = Result.shl(Right); 9868 9869 // Print the bit representation of the signed integer as an unsigned 9870 // hexadecimal number. 9871 SmallString<40> HexResult; 9872 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 9873 9874 // If we are only missing a sign bit, this is less likely to result in actual 9875 // bugs -- if the result is cast back to an unsigned type, it will have the 9876 // expected value. Thus we place this behind a different warning that can be 9877 // turned off separately if needed. 9878 if (LeftBits == ResultBits - 1) { 9879 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 9880 << HexResult << LHSType 9881 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9882 return; 9883 } 9884 9885 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 9886 << HexResult.str() << Result.getMinSignedBits() << LHSType 9887 << Left.getBitWidth() << LHS.get()->getSourceRange() 9888 << RHS.get()->getSourceRange(); 9889 } 9890 9891 /// Return the resulting type when a vector is shifted 9892 /// by a scalar or vector shift amount. 9893 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 9894 SourceLocation Loc, bool IsCompAssign) { 9895 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 9896 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 9897 !LHS.get()->getType()->isVectorType()) { 9898 S.Diag(Loc, diag::err_shift_rhs_only_vector) 9899 << RHS.get()->getType() << LHS.get()->getType() 9900 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9901 return QualType(); 9902 } 9903 9904 if (!IsCompAssign) { 9905 LHS = S.UsualUnaryConversions(LHS.get()); 9906 if (LHS.isInvalid()) return QualType(); 9907 } 9908 9909 RHS = S.UsualUnaryConversions(RHS.get()); 9910 if (RHS.isInvalid()) return QualType(); 9911 9912 QualType LHSType = LHS.get()->getType(); 9913 // Note that LHS might be a scalar because the routine calls not only in 9914 // OpenCL case. 9915 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 9916 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 9917 9918 // Note that RHS might not be a vector. 9919 QualType RHSType = RHS.get()->getType(); 9920 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 9921 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 9922 9923 // The operands need to be integers. 9924 if (!LHSEleType->isIntegerType()) { 9925 S.Diag(Loc, diag::err_typecheck_expect_int) 9926 << LHS.get()->getType() << LHS.get()->getSourceRange(); 9927 return QualType(); 9928 } 9929 9930 if (!RHSEleType->isIntegerType()) { 9931 S.Diag(Loc, diag::err_typecheck_expect_int) 9932 << RHS.get()->getType() << RHS.get()->getSourceRange(); 9933 return QualType(); 9934 } 9935 9936 if (!LHSVecTy) { 9937 assert(RHSVecTy); 9938 if (IsCompAssign) 9939 return RHSType; 9940 if (LHSEleType != RHSEleType) { 9941 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 9942 LHSEleType = RHSEleType; 9943 } 9944 QualType VecTy = 9945 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 9946 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 9947 LHSType = VecTy; 9948 } else if (RHSVecTy) { 9949 // OpenCL v1.1 s6.3.j says that for vector types, the operators 9950 // are applied component-wise. So if RHS is a vector, then ensure 9951 // that the number of elements is the same as LHS... 9952 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 9953 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 9954 << LHS.get()->getType() << RHS.get()->getType() 9955 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9956 return QualType(); 9957 } 9958 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 9959 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 9960 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 9961 if (LHSBT != RHSBT && 9962 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 9963 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 9964 << LHS.get()->getType() << RHS.get()->getType() 9965 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9966 } 9967 } 9968 } else { 9969 // ...else expand RHS to match the number of elements in LHS. 9970 QualType VecTy = 9971 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 9972 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 9973 } 9974 9975 return LHSType; 9976 } 9977 9978 // C99 6.5.7 9979 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 9980 SourceLocation Loc, BinaryOperatorKind Opc, 9981 bool IsCompAssign) { 9982 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9983 9984 // Vector shifts promote their scalar inputs to vector type. 9985 if (LHS.get()->getType()->isVectorType() || 9986 RHS.get()->getType()->isVectorType()) { 9987 if (LangOpts.ZVector) { 9988 // The shift operators for the z vector extensions work basically 9989 // like general shifts, except that neither the LHS nor the RHS is 9990 // allowed to be a "vector bool". 9991 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 9992 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 9993 return InvalidOperands(Loc, LHS, RHS); 9994 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 9995 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9996 return InvalidOperands(Loc, LHS, RHS); 9997 } 9998 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 9999 } 10000 10001 // Shifts don't perform usual arithmetic conversions, they just do integer 10002 // promotions on each operand. C99 6.5.7p3 10003 10004 // For the LHS, do usual unary conversions, but then reset them away 10005 // if this is a compound assignment. 10006 ExprResult OldLHS = LHS; 10007 LHS = UsualUnaryConversions(LHS.get()); 10008 if (LHS.isInvalid()) 10009 return QualType(); 10010 QualType LHSType = LHS.get()->getType(); 10011 if (IsCompAssign) LHS = OldLHS; 10012 10013 // The RHS is simpler. 10014 RHS = UsualUnaryConversions(RHS.get()); 10015 if (RHS.isInvalid()) 10016 return QualType(); 10017 QualType RHSType = RHS.get()->getType(); 10018 10019 // C99 6.5.7p2: Each of the operands shall have integer type. 10020 if (!LHSType->hasIntegerRepresentation() || 10021 !RHSType->hasIntegerRepresentation()) 10022 return InvalidOperands(Loc, LHS, RHS); 10023 10024 // C++0x: Don't allow scoped enums. FIXME: Use something better than 10025 // hasIntegerRepresentation() above instead of this. 10026 if (isScopedEnumerationType(LHSType) || 10027 isScopedEnumerationType(RHSType)) { 10028 return InvalidOperands(Loc, LHS, RHS); 10029 } 10030 // Sanity-check shift operands 10031 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 10032 10033 // "The type of the result is that of the promoted left operand." 10034 return LHSType; 10035 } 10036 10037 /// If two different enums are compared, raise a warning. 10038 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 10039 Expr *RHS) { 10040 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 10041 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 10042 10043 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 10044 if (!LHSEnumType) 10045 return; 10046 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 10047 if (!RHSEnumType) 10048 return; 10049 10050 // Ignore anonymous enums. 10051 if (!LHSEnumType->getDecl()->getIdentifier() && 10052 !LHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 10053 return; 10054 if (!RHSEnumType->getDecl()->getIdentifier() && 10055 !RHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 10056 return; 10057 10058 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 10059 return; 10060 10061 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 10062 << LHSStrippedType << RHSStrippedType 10063 << LHS->getSourceRange() << RHS->getSourceRange(); 10064 } 10065 10066 /// Diagnose bad pointer comparisons. 10067 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 10068 ExprResult &LHS, ExprResult &RHS, 10069 bool IsError) { 10070 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 10071 : diag::ext_typecheck_comparison_of_distinct_pointers) 10072 << LHS.get()->getType() << RHS.get()->getType() 10073 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10074 } 10075 10076 /// Returns false if the pointers are converted to a composite type, 10077 /// true otherwise. 10078 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 10079 ExprResult &LHS, ExprResult &RHS) { 10080 // C++ [expr.rel]p2: 10081 // [...] Pointer conversions (4.10) and qualification 10082 // conversions (4.4) are performed on pointer operands (or on 10083 // a pointer operand and a null pointer constant) to bring 10084 // them to their composite pointer type. [...] 10085 // 10086 // C++ [expr.eq]p1 uses the same notion for (in)equality 10087 // comparisons of pointers. 10088 10089 QualType LHSType = LHS.get()->getType(); 10090 QualType RHSType = RHS.get()->getType(); 10091 assert(LHSType->isPointerType() || RHSType->isPointerType() || 10092 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 10093 10094 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 10095 if (T.isNull()) { 10096 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 10097 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 10098 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 10099 else 10100 S.InvalidOperands(Loc, LHS, RHS); 10101 return true; 10102 } 10103 10104 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 10105 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 10106 return false; 10107 } 10108 10109 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 10110 ExprResult &LHS, 10111 ExprResult &RHS, 10112 bool IsError) { 10113 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 10114 : diag::ext_typecheck_comparison_of_fptr_to_void) 10115 << LHS.get()->getType() << RHS.get()->getType() 10116 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10117 } 10118 10119 static bool isObjCObjectLiteral(ExprResult &E) { 10120 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 10121 case Stmt::ObjCArrayLiteralClass: 10122 case Stmt::ObjCDictionaryLiteralClass: 10123 case Stmt::ObjCStringLiteralClass: 10124 case Stmt::ObjCBoxedExprClass: 10125 return true; 10126 default: 10127 // Note that ObjCBoolLiteral is NOT an object literal! 10128 return false; 10129 } 10130 } 10131 10132 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 10133 const ObjCObjectPointerType *Type = 10134 LHS->getType()->getAs<ObjCObjectPointerType>(); 10135 10136 // If this is not actually an Objective-C object, bail out. 10137 if (!Type) 10138 return false; 10139 10140 // Get the LHS object's interface type. 10141 QualType InterfaceType = Type->getPointeeType(); 10142 10143 // If the RHS isn't an Objective-C object, bail out. 10144 if (!RHS->getType()->isObjCObjectPointerType()) 10145 return false; 10146 10147 // Try to find the -isEqual: method. 10148 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 10149 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 10150 InterfaceType, 10151 /*IsInstance=*/true); 10152 if (!Method) { 10153 if (Type->isObjCIdType()) { 10154 // For 'id', just check the global pool. 10155 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 10156 /*receiverId=*/true); 10157 } else { 10158 // Check protocols. 10159 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 10160 /*IsInstance=*/true); 10161 } 10162 } 10163 10164 if (!Method) 10165 return false; 10166 10167 QualType T = Method->parameters()[0]->getType(); 10168 if (!T->isObjCObjectPointerType()) 10169 return false; 10170 10171 QualType R = Method->getReturnType(); 10172 if (!R->isScalarType()) 10173 return false; 10174 10175 return true; 10176 } 10177 10178 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 10179 FromE = FromE->IgnoreParenImpCasts(); 10180 switch (FromE->getStmtClass()) { 10181 default: 10182 break; 10183 case Stmt::ObjCStringLiteralClass: 10184 // "string literal" 10185 return LK_String; 10186 case Stmt::ObjCArrayLiteralClass: 10187 // "array literal" 10188 return LK_Array; 10189 case Stmt::ObjCDictionaryLiteralClass: 10190 // "dictionary literal" 10191 return LK_Dictionary; 10192 case Stmt::BlockExprClass: 10193 return LK_Block; 10194 case Stmt::ObjCBoxedExprClass: { 10195 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 10196 switch (Inner->getStmtClass()) { 10197 case Stmt::IntegerLiteralClass: 10198 case Stmt::FloatingLiteralClass: 10199 case Stmt::CharacterLiteralClass: 10200 case Stmt::ObjCBoolLiteralExprClass: 10201 case Stmt::CXXBoolLiteralExprClass: 10202 // "numeric literal" 10203 return LK_Numeric; 10204 case Stmt::ImplicitCastExprClass: { 10205 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 10206 // Boolean literals can be represented by implicit casts. 10207 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 10208 return LK_Numeric; 10209 break; 10210 } 10211 default: 10212 break; 10213 } 10214 return LK_Boxed; 10215 } 10216 } 10217 return LK_None; 10218 } 10219 10220 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 10221 ExprResult &LHS, ExprResult &RHS, 10222 BinaryOperator::Opcode Opc){ 10223 Expr *Literal; 10224 Expr *Other; 10225 if (isObjCObjectLiteral(LHS)) { 10226 Literal = LHS.get(); 10227 Other = RHS.get(); 10228 } else { 10229 Literal = RHS.get(); 10230 Other = LHS.get(); 10231 } 10232 10233 // Don't warn on comparisons against nil. 10234 Other = Other->IgnoreParenCasts(); 10235 if (Other->isNullPointerConstant(S.getASTContext(), 10236 Expr::NPC_ValueDependentIsNotNull)) 10237 return; 10238 10239 // This should be kept in sync with warn_objc_literal_comparison. 10240 // LK_String should always be after the other literals, since it has its own 10241 // warning flag. 10242 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 10243 assert(LiteralKind != Sema::LK_Block); 10244 if (LiteralKind == Sema::LK_None) { 10245 llvm_unreachable("Unknown Objective-C object literal kind"); 10246 } 10247 10248 if (LiteralKind == Sema::LK_String) 10249 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 10250 << Literal->getSourceRange(); 10251 else 10252 S.Diag(Loc, diag::warn_objc_literal_comparison) 10253 << LiteralKind << Literal->getSourceRange(); 10254 10255 if (BinaryOperator::isEqualityOp(Opc) && 10256 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 10257 SourceLocation Start = LHS.get()->getBeginLoc(); 10258 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 10259 CharSourceRange OpRange = 10260 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 10261 10262 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 10263 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 10264 << FixItHint::CreateReplacement(OpRange, " isEqual:") 10265 << FixItHint::CreateInsertion(End, "]"); 10266 } 10267 } 10268 10269 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 10270 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 10271 ExprResult &RHS, SourceLocation Loc, 10272 BinaryOperatorKind Opc) { 10273 // Check that left hand side is !something. 10274 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 10275 if (!UO || UO->getOpcode() != UO_LNot) return; 10276 10277 // Only check if the right hand side is non-bool arithmetic type. 10278 if (RHS.get()->isKnownToHaveBooleanValue()) return; 10279 10280 // Make sure that the something in !something is not bool. 10281 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 10282 if (SubExpr->isKnownToHaveBooleanValue()) return; 10283 10284 // Emit warning. 10285 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 10286 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 10287 << Loc << IsBitwiseOp; 10288 10289 // First note suggest !(x < y) 10290 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 10291 SourceLocation FirstClose = RHS.get()->getEndLoc(); 10292 FirstClose = S.getLocForEndOfToken(FirstClose); 10293 if (FirstClose.isInvalid()) 10294 FirstOpen = SourceLocation(); 10295 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 10296 << IsBitwiseOp 10297 << FixItHint::CreateInsertion(FirstOpen, "(") 10298 << FixItHint::CreateInsertion(FirstClose, ")"); 10299 10300 // Second note suggests (!x) < y 10301 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 10302 SourceLocation SecondClose = LHS.get()->getEndLoc(); 10303 SecondClose = S.getLocForEndOfToken(SecondClose); 10304 if (SecondClose.isInvalid()) 10305 SecondOpen = SourceLocation(); 10306 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 10307 << FixItHint::CreateInsertion(SecondOpen, "(") 10308 << FixItHint::CreateInsertion(SecondClose, ")"); 10309 } 10310 10311 // Returns true if E refers to a non-weak array. 10312 static bool checkForArray(const Expr *E) { 10313 const ValueDecl *D = nullptr; 10314 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 10315 D = DR->getDecl(); 10316 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 10317 if (Mem->isImplicitAccess()) 10318 D = Mem->getMemberDecl(); 10319 } 10320 if (!D) 10321 return false; 10322 return D->getType()->isArrayType() && !D->isWeak(); 10323 } 10324 10325 /// Diagnose some forms of syntactically-obvious tautological comparison. 10326 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 10327 Expr *LHS, Expr *RHS, 10328 BinaryOperatorKind Opc) { 10329 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 10330 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 10331 10332 QualType LHSType = LHS->getType(); 10333 QualType RHSType = RHS->getType(); 10334 if (LHSType->hasFloatingRepresentation() || 10335 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 10336 S.inTemplateInstantiation()) 10337 return; 10338 10339 // Comparisons between two array types are ill-formed for operator<=>, so 10340 // we shouldn't emit any additional warnings about it. 10341 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 10342 return; 10343 10344 // For non-floating point types, check for self-comparisons of the form 10345 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 10346 // often indicate logic errors in the program. 10347 // 10348 // NOTE: Don't warn about comparison expressions resulting from macro 10349 // expansion. Also don't warn about comparisons which are only self 10350 // comparisons within a template instantiation. The warnings should catch 10351 // obvious cases in the definition of the template anyways. The idea is to 10352 // warn when the typed comparison operator will always evaluate to the same 10353 // result. 10354 10355 // Used for indexing into %select in warn_comparison_always 10356 enum { 10357 AlwaysConstant, 10358 AlwaysTrue, 10359 AlwaysFalse, 10360 AlwaysEqual, // std::strong_ordering::equal from operator<=> 10361 }; 10362 10363 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 10364 if (Expr::isSameComparisonOperand(LHS, RHS)) { 10365 unsigned Result; 10366 switch (Opc) { 10367 case BO_EQ: 10368 case BO_LE: 10369 case BO_GE: 10370 Result = AlwaysTrue; 10371 break; 10372 case BO_NE: 10373 case BO_LT: 10374 case BO_GT: 10375 Result = AlwaysFalse; 10376 break; 10377 case BO_Cmp: 10378 Result = AlwaysEqual; 10379 break; 10380 default: 10381 Result = AlwaysConstant; 10382 break; 10383 } 10384 S.DiagRuntimeBehavior(Loc, nullptr, 10385 S.PDiag(diag::warn_comparison_always) 10386 << 0 /*self-comparison*/ 10387 << Result); 10388 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 10389 // What is it always going to evaluate to? 10390 unsigned Result; 10391 switch (Opc) { 10392 case BO_EQ: // e.g. array1 == array2 10393 Result = AlwaysFalse; 10394 break; 10395 case BO_NE: // e.g. array1 != array2 10396 Result = AlwaysTrue; 10397 break; 10398 default: // e.g. array1 <= array2 10399 // The best we can say is 'a constant' 10400 Result = AlwaysConstant; 10401 break; 10402 } 10403 S.DiagRuntimeBehavior(Loc, nullptr, 10404 S.PDiag(diag::warn_comparison_always) 10405 << 1 /*array comparison*/ 10406 << Result); 10407 } 10408 } 10409 10410 if (isa<CastExpr>(LHSStripped)) 10411 LHSStripped = LHSStripped->IgnoreParenCasts(); 10412 if (isa<CastExpr>(RHSStripped)) 10413 RHSStripped = RHSStripped->IgnoreParenCasts(); 10414 10415 // Warn about comparisons against a string constant (unless the other 10416 // operand is null); the user probably wants string comparison function. 10417 Expr *LiteralString = nullptr; 10418 Expr *LiteralStringStripped = nullptr; 10419 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 10420 !RHSStripped->isNullPointerConstant(S.Context, 10421 Expr::NPC_ValueDependentIsNull)) { 10422 LiteralString = LHS; 10423 LiteralStringStripped = LHSStripped; 10424 } else if ((isa<StringLiteral>(RHSStripped) || 10425 isa<ObjCEncodeExpr>(RHSStripped)) && 10426 !LHSStripped->isNullPointerConstant(S.Context, 10427 Expr::NPC_ValueDependentIsNull)) { 10428 LiteralString = RHS; 10429 LiteralStringStripped = RHSStripped; 10430 } 10431 10432 if (LiteralString) { 10433 S.DiagRuntimeBehavior(Loc, nullptr, 10434 S.PDiag(diag::warn_stringcompare) 10435 << isa<ObjCEncodeExpr>(LiteralStringStripped) 10436 << LiteralString->getSourceRange()); 10437 } 10438 } 10439 10440 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 10441 switch (CK) { 10442 default: { 10443 #ifndef NDEBUG 10444 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 10445 << "\n"; 10446 #endif 10447 llvm_unreachable("unhandled cast kind"); 10448 } 10449 case CK_UserDefinedConversion: 10450 return ICK_Identity; 10451 case CK_LValueToRValue: 10452 return ICK_Lvalue_To_Rvalue; 10453 case CK_ArrayToPointerDecay: 10454 return ICK_Array_To_Pointer; 10455 case CK_FunctionToPointerDecay: 10456 return ICK_Function_To_Pointer; 10457 case CK_IntegralCast: 10458 return ICK_Integral_Conversion; 10459 case CK_FloatingCast: 10460 return ICK_Floating_Conversion; 10461 case CK_IntegralToFloating: 10462 case CK_FloatingToIntegral: 10463 return ICK_Floating_Integral; 10464 case CK_IntegralComplexCast: 10465 case CK_FloatingComplexCast: 10466 case CK_FloatingComplexToIntegralComplex: 10467 case CK_IntegralComplexToFloatingComplex: 10468 return ICK_Complex_Conversion; 10469 case CK_FloatingComplexToReal: 10470 case CK_FloatingRealToComplex: 10471 case CK_IntegralComplexToReal: 10472 case CK_IntegralRealToComplex: 10473 return ICK_Complex_Real; 10474 } 10475 } 10476 10477 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 10478 QualType FromType, 10479 SourceLocation Loc) { 10480 // Check for a narrowing implicit conversion. 10481 StandardConversionSequence SCS; 10482 SCS.setAsIdentityConversion(); 10483 SCS.setToType(0, FromType); 10484 SCS.setToType(1, ToType); 10485 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 10486 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 10487 10488 APValue PreNarrowingValue; 10489 QualType PreNarrowingType; 10490 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 10491 PreNarrowingType, 10492 /*IgnoreFloatToIntegralConversion*/ true)) { 10493 case NK_Dependent_Narrowing: 10494 // Implicit conversion to a narrower type, but the expression is 10495 // value-dependent so we can't tell whether it's actually narrowing. 10496 case NK_Not_Narrowing: 10497 return false; 10498 10499 case NK_Constant_Narrowing: 10500 // Implicit conversion to a narrower type, and the value is not a constant 10501 // expression. 10502 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 10503 << /*Constant*/ 1 10504 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 10505 return true; 10506 10507 case NK_Variable_Narrowing: 10508 // Implicit conversion to a narrower type, and the value is not a constant 10509 // expression. 10510 case NK_Type_Narrowing: 10511 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 10512 << /*Constant*/ 0 << FromType << ToType; 10513 // TODO: It's not a constant expression, but what if the user intended it 10514 // to be? Can we produce notes to help them figure out why it isn't? 10515 return true; 10516 } 10517 llvm_unreachable("unhandled case in switch"); 10518 } 10519 10520 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 10521 ExprResult &LHS, 10522 ExprResult &RHS, 10523 SourceLocation Loc) { 10524 QualType LHSType = LHS.get()->getType(); 10525 QualType RHSType = RHS.get()->getType(); 10526 // Dig out the original argument type and expression before implicit casts 10527 // were applied. These are the types/expressions we need to check the 10528 // [expr.spaceship] requirements against. 10529 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 10530 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 10531 QualType LHSStrippedType = LHSStripped.get()->getType(); 10532 QualType RHSStrippedType = RHSStripped.get()->getType(); 10533 10534 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 10535 // other is not, the program is ill-formed. 10536 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 10537 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 10538 return QualType(); 10539 } 10540 10541 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 10542 RHSStrippedType->isEnumeralType(); 10543 if (NumEnumArgs == 1) { 10544 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 10545 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 10546 if (OtherTy->hasFloatingRepresentation()) { 10547 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 10548 return QualType(); 10549 } 10550 } 10551 if (NumEnumArgs == 2) { 10552 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 10553 // type E, the operator yields the result of converting the operands 10554 // to the underlying type of E and applying <=> to the converted operands. 10555 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 10556 S.InvalidOperands(Loc, LHS, RHS); 10557 return QualType(); 10558 } 10559 QualType IntType = 10560 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 10561 assert(IntType->isArithmeticType()); 10562 10563 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 10564 // promote the boolean type, and all other promotable integer types, to 10565 // avoid this. 10566 if (IntType->isPromotableIntegerType()) 10567 IntType = S.Context.getPromotedIntegerType(IntType); 10568 10569 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 10570 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 10571 LHSType = RHSType = IntType; 10572 } 10573 10574 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 10575 // usual arithmetic conversions are applied to the operands. 10576 QualType Type = S.UsualArithmeticConversions(LHS, RHS); 10577 if (LHS.isInvalid() || RHS.isInvalid()) 10578 return QualType(); 10579 if (Type.isNull()) 10580 return S.InvalidOperands(Loc, LHS, RHS); 10581 assert(Type->isArithmeticType() || Type->isEnumeralType()); 10582 10583 // FIXME: Reject complex types, consistent with P1959R0. 10584 10585 bool HasNarrowing = checkThreeWayNarrowingConversion( 10586 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 10587 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 10588 RHS.get()->getBeginLoc()); 10589 if (HasNarrowing) 10590 return QualType(); 10591 10592 assert(!Type.isNull() && "composite type for <=> has not been set"); 10593 10594 return S.CheckComparisonCategoryType( 10595 *getComparisonCategoryForBuiltinCmp(Type), Loc); 10596 } 10597 10598 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 10599 ExprResult &RHS, 10600 SourceLocation Loc, 10601 BinaryOperatorKind Opc) { 10602 if (Opc == BO_Cmp) 10603 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 10604 10605 // C99 6.5.8p3 / C99 6.5.9p4 10606 QualType Type = S.UsualArithmeticConversions(LHS, RHS); 10607 if (LHS.isInvalid() || RHS.isInvalid()) 10608 return QualType(); 10609 if (Type.isNull()) 10610 return S.InvalidOperands(Loc, LHS, RHS); 10611 assert(Type->isArithmeticType() || Type->isEnumeralType()); 10612 10613 checkEnumComparison(S, Loc, LHS.get(), RHS.get()); 10614 10615 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 10616 return S.InvalidOperands(Loc, LHS, RHS); 10617 10618 // Check for comparisons of floating point operands using != and ==. 10619 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 10620 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 10621 10622 // The result of comparisons is 'bool' in C++, 'int' in C. 10623 return S.Context.getLogicalOperationType(); 10624 } 10625 10626 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 10627 if (!NullE.get()->getType()->isAnyPointerType()) 10628 return; 10629 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 10630 if (!E.get()->getType()->isAnyPointerType() && 10631 E.get()->isNullPointerConstant(Context, 10632 Expr::NPC_ValueDependentIsNotNull) == 10633 Expr::NPCK_ZeroExpression) { 10634 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 10635 if (CL->getValue() == 0) 10636 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 10637 << NullValue 10638 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 10639 NullValue ? "NULL" : "(void *)0"); 10640 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 10641 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 10642 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 10643 if (T == Context.CharTy) 10644 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 10645 << NullValue 10646 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 10647 NullValue ? "NULL" : "(void *)0"); 10648 } 10649 } 10650 } 10651 10652 // C99 6.5.8, C++ [expr.rel] 10653 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 10654 SourceLocation Loc, 10655 BinaryOperatorKind Opc) { 10656 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 10657 bool IsThreeWay = Opc == BO_Cmp; 10658 auto IsAnyPointerType = [](ExprResult E) { 10659 QualType Ty = E.get()->getType(); 10660 return Ty->isPointerType() || Ty->isMemberPointerType(); 10661 }; 10662 10663 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 10664 // type, array-to-pointer, ..., conversions are performed on both operands to 10665 // bring them to their composite type. 10666 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 10667 // any type-related checks. 10668 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 10669 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10670 if (LHS.isInvalid()) 10671 return QualType(); 10672 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10673 if (RHS.isInvalid()) 10674 return QualType(); 10675 } else { 10676 LHS = DefaultLvalueConversion(LHS.get()); 10677 if (LHS.isInvalid()) 10678 return QualType(); 10679 RHS = DefaultLvalueConversion(RHS.get()); 10680 if (RHS.isInvalid()) 10681 return QualType(); 10682 } 10683 10684 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 10685 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 10686 CheckPtrComparisonWithNullChar(LHS, RHS); 10687 CheckPtrComparisonWithNullChar(RHS, LHS); 10688 } 10689 10690 // Handle vector comparisons separately. 10691 if (LHS.get()->getType()->isVectorType() || 10692 RHS.get()->getType()->isVectorType()) 10693 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 10694 10695 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 10696 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 10697 10698 QualType LHSType = LHS.get()->getType(); 10699 QualType RHSType = RHS.get()->getType(); 10700 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 10701 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 10702 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 10703 10704 const Expr::NullPointerConstantKind LHSNullKind = 10705 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 10706 const Expr::NullPointerConstantKind RHSNullKind = 10707 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 10708 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 10709 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 10710 10711 auto computeResultTy = [&]() { 10712 if (Opc != BO_Cmp) 10713 return Context.getLogicalOperationType(); 10714 assert(getLangOpts().CPlusPlus); 10715 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 10716 10717 QualType CompositeTy = LHS.get()->getType(); 10718 assert(!CompositeTy->isReferenceType()); 10719 10720 Optional<ComparisonCategoryType> CCT = 10721 getComparisonCategoryForBuiltinCmp(CompositeTy); 10722 if (!CCT) 10723 return InvalidOperands(Loc, LHS, RHS); 10724 10725 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { 10726 // P0946R0: Comparisons between a null pointer constant and an object 10727 // pointer result in std::strong_equality 10728 // FIXME: Reject this, consistent with P1959R0 + P0946R0. 10729 CCT = ComparisonCategoryType::StrongEquality; 10730 } 10731 10732 return CheckComparisonCategoryType(*CCT, Loc); 10733 }; 10734 10735 if (!IsRelational && LHSIsNull != RHSIsNull) { 10736 bool IsEquality = Opc == BO_EQ; 10737 if (RHSIsNull) 10738 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 10739 RHS.get()->getSourceRange()); 10740 else 10741 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 10742 LHS.get()->getSourceRange()); 10743 } 10744 10745 if ((LHSType->isIntegerType() && !LHSIsNull) || 10746 (RHSType->isIntegerType() && !RHSIsNull)) { 10747 // Skip normal pointer conversion checks in this case; we have better 10748 // diagnostics for this below. 10749 } else if (getLangOpts().CPlusPlus) { 10750 // Equality comparison of a function pointer to a void pointer is invalid, 10751 // but we allow it as an extension. 10752 // FIXME: If we really want to allow this, should it be part of composite 10753 // pointer type computation so it works in conditionals too? 10754 if (!IsRelational && 10755 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 10756 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 10757 // This is a gcc extension compatibility comparison. 10758 // In a SFINAE context, we treat this as a hard error to maintain 10759 // conformance with the C++ standard. 10760 diagnoseFunctionPointerToVoidComparison( 10761 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 10762 10763 if (isSFINAEContext()) 10764 return QualType(); 10765 10766 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10767 return computeResultTy(); 10768 } 10769 10770 // C++ [expr.eq]p2: 10771 // If at least one operand is a pointer [...] bring them to their 10772 // composite pointer type. 10773 // C++ [expr.spaceship]p6 10774 // If at least one of the operands is of pointer type, [...] bring them 10775 // to their composite pointer type. 10776 // C++ [expr.rel]p2: 10777 // If both operands are pointers, [...] bring them to their composite 10778 // pointer type. 10779 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 10780 (IsRelational ? 2 : 1) && 10781 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 10782 RHSType->isObjCObjectPointerType()))) { 10783 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 10784 return QualType(); 10785 return computeResultTy(); 10786 } 10787 } else if (LHSType->isPointerType() && 10788 RHSType->isPointerType()) { // C99 6.5.8p2 10789 // All of the following pointer-related warnings are GCC extensions, except 10790 // when handling null pointer constants. 10791 QualType LCanPointeeTy = 10792 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 10793 QualType RCanPointeeTy = 10794 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 10795 10796 // C99 6.5.9p2 and C99 6.5.8p2 10797 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 10798 RCanPointeeTy.getUnqualifiedType())) { 10799 // Valid unless a relational comparison of function pointers 10800 if (IsRelational && LCanPointeeTy->isFunctionType()) { 10801 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 10802 << LHSType << RHSType << LHS.get()->getSourceRange() 10803 << RHS.get()->getSourceRange(); 10804 } 10805 } else if (!IsRelational && 10806 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 10807 // Valid unless comparison between non-null pointer and function pointer 10808 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 10809 && !LHSIsNull && !RHSIsNull) 10810 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 10811 /*isError*/false); 10812 } else { 10813 // Invalid 10814 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 10815 } 10816 if (LCanPointeeTy != RCanPointeeTy) { 10817 // Treat NULL constant as a special case in OpenCL. 10818 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 10819 const PointerType *LHSPtr = LHSType->castAs<PointerType>(); 10820 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->castAs<PointerType>())) { 10821 Diag(Loc, 10822 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10823 << LHSType << RHSType << 0 /* comparison */ 10824 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10825 } 10826 } 10827 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 10828 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 10829 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 10830 : CK_BitCast; 10831 if (LHSIsNull && !RHSIsNull) 10832 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 10833 else 10834 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 10835 } 10836 return computeResultTy(); 10837 } 10838 10839 if (getLangOpts().CPlusPlus) { 10840 // C++ [expr.eq]p4: 10841 // Two operands of type std::nullptr_t or one operand of type 10842 // std::nullptr_t and the other a null pointer constant compare equal. 10843 if (!IsRelational && LHSIsNull && RHSIsNull) { 10844 if (LHSType->isNullPtrType()) { 10845 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10846 return computeResultTy(); 10847 } 10848 if (RHSType->isNullPtrType()) { 10849 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10850 return computeResultTy(); 10851 } 10852 } 10853 10854 // Comparison of Objective-C pointers and block pointers against nullptr_t. 10855 // These aren't covered by the composite pointer type rules. 10856 if (!IsRelational && RHSType->isNullPtrType() && 10857 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 10858 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10859 return computeResultTy(); 10860 } 10861 if (!IsRelational && LHSType->isNullPtrType() && 10862 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 10863 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10864 return computeResultTy(); 10865 } 10866 10867 if (IsRelational && 10868 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 10869 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 10870 // HACK: Relational comparison of nullptr_t against a pointer type is 10871 // invalid per DR583, but we allow it within std::less<> and friends, 10872 // since otherwise common uses of it break. 10873 // FIXME: Consider removing this hack once LWG fixes std::less<> and 10874 // friends to have std::nullptr_t overload candidates. 10875 DeclContext *DC = CurContext; 10876 if (isa<FunctionDecl>(DC)) 10877 DC = DC->getParent(); 10878 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 10879 if (CTSD->isInStdNamespace() && 10880 llvm::StringSwitch<bool>(CTSD->getName()) 10881 .Cases("less", "less_equal", "greater", "greater_equal", true) 10882 .Default(false)) { 10883 if (RHSType->isNullPtrType()) 10884 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10885 else 10886 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10887 return computeResultTy(); 10888 } 10889 } 10890 } 10891 10892 // C++ [expr.eq]p2: 10893 // If at least one operand is a pointer to member, [...] bring them to 10894 // their composite pointer type. 10895 if (!IsRelational && 10896 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 10897 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 10898 return QualType(); 10899 else 10900 return computeResultTy(); 10901 } 10902 } 10903 10904 // Handle block pointer types. 10905 if (!IsRelational && LHSType->isBlockPointerType() && 10906 RHSType->isBlockPointerType()) { 10907 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 10908 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 10909 10910 if (!LHSIsNull && !RHSIsNull && 10911 !Context.typesAreCompatible(lpointee, rpointee)) { 10912 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 10913 << LHSType << RHSType << LHS.get()->getSourceRange() 10914 << RHS.get()->getSourceRange(); 10915 } 10916 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10917 return computeResultTy(); 10918 } 10919 10920 // Allow block pointers to be compared with null pointer constants. 10921 if (!IsRelational 10922 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 10923 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 10924 if (!LHSIsNull && !RHSIsNull) { 10925 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 10926 ->getPointeeType()->isVoidType()) 10927 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 10928 ->getPointeeType()->isVoidType()))) 10929 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 10930 << LHSType << RHSType << LHS.get()->getSourceRange() 10931 << RHS.get()->getSourceRange(); 10932 } 10933 if (LHSIsNull && !RHSIsNull) 10934 LHS = ImpCastExprToType(LHS.get(), RHSType, 10935 RHSType->isPointerType() ? CK_BitCast 10936 : CK_AnyPointerToBlockPointerCast); 10937 else 10938 RHS = ImpCastExprToType(RHS.get(), LHSType, 10939 LHSType->isPointerType() ? CK_BitCast 10940 : CK_AnyPointerToBlockPointerCast); 10941 return computeResultTy(); 10942 } 10943 10944 if (LHSType->isObjCObjectPointerType() || 10945 RHSType->isObjCObjectPointerType()) { 10946 const PointerType *LPT = LHSType->getAs<PointerType>(); 10947 const PointerType *RPT = RHSType->getAs<PointerType>(); 10948 if (LPT || RPT) { 10949 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 10950 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 10951 10952 if (!LPtrToVoid && !RPtrToVoid && 10953 !Context.typesAreCompatible(LHSType, RHSType)) { 10954 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 10955 /*isError*/false); 10956 } 10957 if (LHSIsNull && !RHSIsNull) { 10958 Expr *E = LHS.get(); 10959 if (getLangOpts().ObjCAutoRefCount) 10960 CheckObjCConversion(SourceRange(), RHSType, E, 10961 CCK_ImplicitConversion); 10962 LHS = ImpCastExprToType(E, RHSType, 10963 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 10964 } 10965 else { 10966 Expr *E = RHS.get(); 10967 if (getLangOpts().ObjCAutoRefCount) 10968 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 10969 /*Diagnose=*/true, 10970 /*DiagnoseCFAudited=*/false, Opc); 10971 RHS = ImpCastExprToType(E, LHSType, 10972 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 10973 } 10974 return computeResultTy(); 10975 } 10976 if (LHSType->isObjCObjectPointerType() && 10977 RHSType->isObjCObjectPointerType()) { 10978 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 10979 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 10980 /*isError*/false); 10981 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 10982 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 10983 10984 if (LHSIsNull && !RHSIsNull) 10985 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10986 else 10987 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10988 return computeResultTy(); 10989 } 10990 10991 if (!IsRelational && LHSType->isBlockPointerType() && 10992 RHSType->isBlockCompatibleObjCPointerType(Context)) { 10993 LHS = ImpCastExprToType(LHS.get(), RHSType, 10994 CK_BlockPointerToObjCPointerCast); 10995 return computeResultTy(); 10996 } else if (!IsRelational && 10997 LHSType->isBlockCompatibleObjCPointerType(Context) && 10998 RHSType->isBlockPointerType()) { 10999 RHS = ImpCastExprToType(RHS.get(), LHSType, 11000 CK_BlockPointerToObjCPointerCast); 11001 return computeResultTy(); 11002 } 11003 } 11004 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 11005 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 11006 unsigned DiagID = 0; 11007 bool isError = false; 11008 if (LangOpts.DebuggerSupport) { 11009 // Under a debugger, allow the comparison of pointers to integers, 11010 // since users tend to want to compare addresses. 11011 } else if ((LHSIsNull && LHSType->isIntegerType()) || 11012 (RHSIsNull && RHSType->isIntegerType())) { 11013 if (IsRelational) { 11014 isError = getLangOpts().CPlusPlus; 11015 DiagID = 11016 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 11017 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 11018 } 11019 } else if (getLangOpts().CPlusPlus) { 11020 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 11021 isError = true; 11022 } else if (IsRelational) 11023 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 11024 else 11025 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 11026 11027 if (DiagID) { 11028 Diag(Loc, DiagID) 11029 << LHSType << RHSType << LHS.get()->getSourceRange() 11030 << RHS.get()->getSourceRange(); 11031 if (isError) 11032 return QualType(); 11033 } 11034 11035 if (LHSType->isIntegerType()) 11036 LHS = ImpCastExprToType(LHS.get(), RHSType, 11037 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11038 else 11039 RHS = ImpCastExprToType(RHS.get(), LHSType, 11040 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11041 return computeResultTy(); 11042 } 11043 11044 // Handle block pointers. 11045 if (!IsRelational && RHSIsNull 11046 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 11047 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11048 return computeResultTy(); 11049 } 11050 if (!IsRelational && LHSIsNull 11051 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 11052 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11053 return computeResultTy(); 11054 } 11055 11056 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 11057 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 11058 return computeResultTy(); 11059 } 11060 11061 if (LHSType->isQueueT() && RHSType->isQueueT()) { 11062 return computeResultTy(); 11063 } 11064 11065 if (LHSIsNull && RHSType->isQueueT()) { 11066 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11067 return computeResultTy(); 11068 } 11069 11070 if (LHSType->isQueueT() && RHSIsNull) { 11071 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11072 return computeResultTy(); 11073 } 11074 } 11075 11076 return InvalidOperands(Loc, LHS, RHS); 11077 } 11078 11079 // Return a signed ext_vector_type that is of identical size and number of 11080 // elements. For floating point vectors, return an integer type of identical 11081 // size and number of elements. In the non ext_vector_type case, search from 11082 // the largest type to the smallest type to avoid cases where long long == long, 11083 // where long gets picked over long long. 11084 QualType Sema::GetSignedVectorType(QualType V) { 11085 const VectorType *VTy = V->castAs<VectorType>(); 11086 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 11087 11088 if (isa<ExtVectorType>(VTy)) { 11089 if (TypeSize == Context.getTypeSize(Context.CharTy)) 11090 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 11091 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 11092 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 11093 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 11094 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 11095 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 11096 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 11097 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 11098 "Unhandled vector element size in vector compare"); 11099 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 11100 } 11101 11102 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 11103 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 11104 VectorType::GenericVector); 11105 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 11106 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 11107 VectorType::GenericVector); 11108 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 11109 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 11110 VectorType::GenericVector); 11111 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 11112 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 11113 VectorType::GenericVector); 11114 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 11115 "Unhandled vector element size in vector compare"); 11116 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 11117 VectorType::GenericVector); 11118 } 11119 11120 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 11121 /// operates on extended vector types. Instead of producing an IntTy result, 11122 /// like a scalar comparison, a vector comparison produces a vector of integer 11123 /// types. 11124 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 11125 SourceLocation Loc, 11126 BinaryOperatorKind Opc) { 11127 // Check to make sure we're operating on vectors of the same type and width, 11128 // Allowing one side to be a scalar of element type. 11129 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 11130 /*AllowBothBool*/true, 11131 /*AllowBoolConversions*/getLangOpts().ZVector); 11132 if (vType.isNull()) 11133 return vType; 11134 11135 QualType LHSType = LHS.get()->getType(); 11136 11137 // If AltiVec, the comparison results in a numeric type, i.e. 11138 // bool for C++, int for C 11139 if (getLangOpts().AltiVec && 11140 vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 11141 return Context.getLogicalOperationType(); 11142 11143 // For non-floating point types, check for self-comparisons of the form 11144 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11145 // often indicate logic errors in the program. 11146 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11147 11148 // Check for comparisons of floating point operands using != and ==. 11149 if (BinaryOperator::isEqualityOp(Opc) && 11150 LHSType->hasFloatingRepresentation()) { 11151 assert(RHS.get()->getType()->hasFloatingRepresentation()); 11152 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11153 } 11154 11155 // Return a signed type for the vector. 11156 return GetSignedVectorType(vType); 11157 } 11158 11159 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 11160 const ExprResult &XorRHS, 11161 const SourceLocation Loc) { 11162 // Do not diagnose macros. 11163 if (Loc.isMacroID()) 11164 return; 11165 11166 bool Negative = false; 11167 bool ExplicitPlus = false; 11168 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 11169 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 11170 11171 if (!LHSInt) 11172 return; 11173 if (!RHSInt) { 11174 // Check negative literals. 11175 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 11176 UnaryOperatorKind Opc = UO->getOpcode(); 11177 if (Opc != UO_Minus && Opc != UO_Plus) 11178 return; 11179 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 11180 if (!RHSInt) 11181 return; 11182 Negative = (Opc == UO_Minus); 11183 ExplicitPlus = !Negative; 11184 } else { 11185 return; 11186 } 11187 } 11188 11189 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 11190 llvm::APInt RightSideValue = RHSInt->getValue(); 11191 if (LeftSideValue != 2 && LeftSideValue != 10) 11192 return; 11193 11194 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 11195 return; 11196 11197 CharSourceRange ExprRange = CharSourceRange::getCharRange( 11198 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 11199 llvm::StringRef ExprStr = 11200 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 11201 11202 CharSourceRange XorRange = 11203 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11204 llvm::StringRef XorStr = 11205 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 11206 // Do not diagnose if xor keyword/macro is used. 11207 if (XorStr == "xor") 11208 return; 11209 11210 std::string LHSStr = Lexer::getSourceText( 11211 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 11212 S.getSourceManager(), S.getLangOpts()); 11213 std::string RHSStr = Lexer::getSourceText( 11214 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 11215 S.getSourceManager(), S.getLangOpts()); 11216 11217 if (Negative) { 11218 RightSideValue = -RightSideValue; 11219 RHSStr = "-" + RHSStr; 11220 } else if (ExplicitPlus) { 11221 RHSStr = "+" + RHSStr; 11222 } 11223 11224 StringRef LHSStrRef = LHSStr; 11225 StringRef RHSStrRef = RHSStr; 11226 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 11227 // literals. 11228 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 11229 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 11230 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 11231 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 11232 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 11233 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 11234 LHSStrRef.find('\'') != StringRef::npos || 11235 RHSStrRef.find('\'') != StringRef::npos) 11236 return; 11237 11238 bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 11239 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 11240 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 11241 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 11242 std::string SuggestedExpr = "1 << " + RHSStr; 11243 bool Overflow = false; 11244 llvm::APInt One = (LeftSideValue - 1); 11245 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 11246 if (Overflow) { 11247 if (RightSideIntValue < 64) 11248 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 11249 << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr) 11250 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 11251 else if (RightSideIntValue == 64) 11252 S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true); 11253 else 11254 return; 11255 } else { 11256 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 11257 << ExprStr << XorValue.toString(10, true) << SuggestedExpr 11258 << PowValue.toString(10, true) 11259 << FixItHint::CreateReplacement( 11260 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 11261 } 11262 11263 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor; 11264 } else if (LeftSideValue == 10) { 11265 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 11266 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 11267 << ExprStr << XorValue.toString(10, true) << SuggestedValue 11268 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 11269 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor; 11270 } 11271 } 11272 11273 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 11274 SourceLocation Loc) { 11275 // Ensure that either both operands are of the same vector type, or 11276 // one operand is of a vector type and the other is of its element type. 11277 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 11278 /*AllowBothBool*/true, 11279 /*AllowBoolConversions*/false); 11280 if (vType.isNull()) 11281 return InvalidOperands(Loc, LHS, RHS); 11282 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 11283 !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation()) 11284 return InvalidOperands(Loc, LHS, RHS); 11285 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 11286 // usage of the logical operators && and || with vectors in C. This 11287 // check could be notionally dropped. 11288 if (!getLangOpts().CPlusPlus && 11289 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 11290 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 11291 11292 return GetSignedVectorType(LHS.get()->getType()); 11293 } 11294 11295 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 11296 SourceLocation Loc, 11297 BinaryOperatorKind Opc) { 11298 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11299 11300 bool IsCompAssign = 11301 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 11302 11303 if (LHS.get()->getType()->isVectorType() || 11304 RHS.get()->getType()->isVectorType()) { 11305 if (LHS.get()->getType()->hasIntegerRepresentation() && 11306 RHS.get()->getType()->hasIntegerRepresentation()) 11307 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 11308 /*AllowBothBool*/true, 11309 /*AllowBoolConversions*/getLangOpts().ZVector); 11310 return InvalidOperands(Loc, LHS, RHS); 11311 } 11312 11313 if (Opc == BO_And) 11314 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11315 11316 ExprResult LHSResult = LHS, RHSResult = RHS; 11317 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 11318 IsCompAssign); 11319 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 11320 return QualType(); 11321 LHS = LHSResult.get(); 11322 RHS = RHSResult.get(); 11323 11324 if (Opc == BO_Xor) 11325 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 11326 11327 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 11328 return compType; 11329 return InvalidOperands(Loc, LHS, RHS); 11330 } 11331 11332 // C99 6.5.[13,14] 11333 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 11334 SourceLocation Loc, 11335 BinaryOperatorKind Opc) { 11336 // Check vector operands differently. 11337 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 11338 return CheckVectorLogicalOperands(LHS, RHS, Loc); 11339 11340 bool EnumConstantInBoolContext = false; 11341 for (const ExprResult &HS : {LHS, RHS}) { 11342 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 11343 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 11344 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 11345 EnumConstantInBoolContext = true; 11346 } 11347 } 11348 11349 if (EnumConstantInBoolContext) 11350 Diag(Loc, diag::warn_enum_constant_in_bool_context); 11351 11352 // Diagnose cases where the user write a logical and/or but probably meant a 11353 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 11354 // is a constant. 11355 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 11356 !LHS.get()->getType()->isBooleanType() && 11357 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 11358 // Don't warn in macros or template instantiations. 11359 !Loc.isMacroID() && !inTemplateInstantiation()) { 11360 // If the RHS can be constant folded, and if it constant folds to something 11361 // that isn't 0 or 1 (which indicate a potential logical operation that 11362 // happened to fold to true/false) then warn. 11363 // Parens on the RHS are ignored. 11364 Expr::EvalResult EVResult; 11365 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 11366 llvm::APSInt Result = EVResult.Val.getInt(); 11367 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 11368 !RHS.get()->getExprLoc().isMacroID()) || 11369 (Result != 0 && Result != 1)) { 11370 Diag(Loc, diag::warn_logical_instead_of_bitwise) 11371 << RHS.get()->getSourceRange() 11372 << (Opc == BO_LAnd ? "&&" : "||"); 11373 // Suggest replacing the logical operator with the bitwise version 11374 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 11375 << (Opc == BO_LAnd ? "&" : "|") 11376 << FixItHint::CreateReplacement(SourceRange( 11377 Loc, getLocForEndOfToken(Loc)), 11378 Opc == BO_LAnd ? "&" : "|"); 11379 if (Opc == BO_LAnd) 11380 // Suggest replacing "Foo() && kNonZero" with "Foo()" 11381 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 11382 << FixItHint::CreateRemoval( 11383 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 11384 RHS.get()->getEndLoc())); 11385 } 11386 } 11387 } 11388 11389 if (!Context.getLangOpts().CPlusPlus) { 11390 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 11391 // not operate on the built-in scalar and vector float types. 11392 if (Context.getLangOpts().OpenCL && 11393 Context.getLangOpts().OpenCLVersion < 120) { 11394 if (LHS.get()->getType()->isFloatingType() || 11395 RHS.get()->getType()->isFloatingType()) 11396 return InvalidOperands(Loc, LHS, RHS); 11397 } 11398 11399 LHS = UsualUnaryConversions(LHS.get()); 11400 if (LHS.isInvalid()) 11401 return QualType(); 11402 11403 RHS = UsualUnaryConversions(RHS.get()); 11404 if (RHS.isInvalid()) 11405 return QualType(); 11406 11407 if (!LHS.get()->getType()->isScalarType() || 11408 !RHS.get()->getType()->isScalarType()) 11409 return InvalidOperands(Loc, LHS, RHS); 11410 11411 return Context.IntTy; 11412 } 11413 11414 // The following is safe because we only use this method for 11415 // non-overloadable operands. 11416 11417 // C++ [expr.log.and]p1 11418 // C++ [expr.log.or]p1 11419 // The operands are both contextually converted to type bool. 11420 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 11421 if (LHSRes.isInvalid()) 11422 return InvalidOperands(Loc, LHS, RHS); 11423 LHS = LHSRes; 11424 11425 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 11426 if (RHSRes.isInvalid()) 11427 return InvalidOperands(Loc, LHS, RHS); 11428 RHS = RHSRes; 11429 11430 // C++ [expr.log.and]p2 11431 // C++ [expr.log.or]p2 11432 // The result is a bool. 11433 return Context.BoolTy; 11434 } 11435 11436 static bool IsReadonlyMessage(Expr *E, Sema &S) { 11437 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 11438 if (!ME) return false; 11439 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 11440 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 11441 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 11442 if (!Base) return false; 11443 return Base->getMethodDecl() != nullptr; 11444 } 11445 11446 /// Is the given expression (which must be 'const') a reference to a 11447 /// variable which was originally non-const, but which has become 11448 /// 'const' due to being captured within a block? 11449 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 11450 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 11451 assert(E->isLValue() && E->getType().isConstQualified()); 11452 E = E->IgnoreParens(); 11453 11454 // Must be a reference to a declaration from an enclosing scope. 11455 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 11456 if (!DRE) return NCCK_None; 11457 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 11458 11459 // The declaration must be a variable which is not declared 'const'. 11460 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 11461 if (!var) return NCCK_None; 11462 if (var->getType().isConstQualified()) return NCCK_None; 11463 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 11464 11465 // Decide whether the first capture was for a block or a lambda. 11466 DeclContext *DC = S.CurContext, *Prev = nullptr; 11467 // Decide whether the first capture was for a block or a lambda. 11468 while (DC) { 11469 // For init-capture, it is possible that the variable belongs to the 11470 // template pattern of the current context. 11471 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 11472 if (var->isInitCapture() && 11473 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 11474 break; 11475 if (DC == var->getDeclContext()) 11476 break; 11477 Prev = DC; 11478 DC = DC->getParent(); 11479 } 11480 // Unless we have an init-capture, we've gone one step too far. 11481 if (!var->isInitCapture()) 11482 DC = Prev; 11483 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 11484 } 11485 11486 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 11487 Ty = Ty.getNonReferenceType(); 11488 if (IsDereference && Ty->isPointerType()) 11489 Ty = Ty->getPointeeType(); 11490 return !Ty.isConstQualified(); 11491 } 11492 11493 // Update err_typecheck_assign_const and note_typecheck_assign_const 11494 // when this enum is changed. 11495 enum { 11496 ConstFunction, 11497 ConstVariable, 11498 ConstMember, 11499 ConstMethod, 11500 NestedConstMember, 11501 ConstUnknown, // Keep as last element 11502 }; 11503 11504 /// Emit the "read-only variable not assignable" error and print notes to give 11505 /// more information about why the variable is not assignable, such as pointing 11506 /// to the declaration of a const variable, showing that a method is const, or 11507 /// that the function is returning a const reference. 11508 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 11509 SourceLocation Loc) { 11510 SourceRange ExprRange = E->getSourceRange(); 11511 11512 // Only emit one error on the first const found. All other consts will emit 11513 // a note to the error. 11514 bool DiagnosticEmitted = false; 11515 11516 // Track if the current expression is the result of a dereference, and if the 11517 // next checked expression is the result of a dereference. 11518 bool IsDereference = false; 11519 bool NextIsDereference = false; 11520 11521 // Loop to process MemberExpr chains. 11522 while (true) { 11523 IsDereference = NextIsDereference; 11524 11525 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 11526 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 11527 NextIsDereference = ME->isArrow(); 11528 const ValueDecl *VD = ME->getMemberDecl(); 11529 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 11530 // Mutable fields can be modified even if the class is const. 11531 if (Field->isMutable()) { 11532 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 11533 break; 11534 } 11535 11536 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 11537 if (!DiagnosticEmitted) { 11538 S.Diag(Loc, diag::err_typecheck_assign_const) 11539 << ExprRange << ConstMember << false /*static*/ << Field 11540 << Field->getType(); 11541 DiagnosticEmitted = true; 11542 } 11543 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11544 << ConstMember << false /*static*/ << Field << Field->getType() 11545 << Field->getSourceRange(); 11546 } 11547 E = ME->getBase(); 11548 continue; 11549 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 11550 if (VDecl->getType().isConstQualified()) { 11551 if (!DiagnosticEmitted) { 11552 S.Diag(Loc, diag::err_typecheck_assign_const) 11553 << ExprRange << ConstMember << true /*static*/ << VDecl 11554 << VDecl->getType(); 11555 DiagnosticEmitted = true; 11556 } 11557 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11558 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 11559 << VDecl->getSourceRange(); 11560 } 11561 // Static fields do not inherit constness from parents. 11562 break; 11563 } 11564 break; // End MemberExpr 11565 } else if (const ArraySubscriptExpr *ASE = 11566 dyn_cast<ArraySubscriptExpr>(E)) { 11567 E = ASE->getBase()->IgnoreParenImpCasts(); 11568 continue; 11569 } else if (const ExtVectorElementExpr *EVE = 11570 dyn_cast<ExtVectorElementExpr>(E)) { 11571 E = EVE->getBase()->IgnoreParenImpCasts(); 11572 continue; 11573 } 11574 break; 11575 } 11576 11577 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 11578 // Function calls 11579 const FunctionDecl *FD = CE->getDirectCallee(); 11580 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 11581 if (!DiagnosticEmitted) { 11582 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 11583 << ConstFunction << FD; 11584 DiagnosticEmitted = true; 11585 } 11586 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 11587 diag::note_typecheck_assign_const) 11588 << ConstFunction << FD << FD->getReturnType() 11589 << FD->getReturnTypeSourceRange(); 11590 } 11591 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11592 // Point to variable declaration. 11593 if (const ValueDecl *VD = DRE->getDecl()) { 11594 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 11595 if (!DiagnosticEmitted) { 11596 S.Diag(Loc, diag::err_typecheck_assign_const) 11597 << ExprRange << ConstVariable << VD << VD->getType(); 11598 DiagnosticEmitted = true; 11599 } 11600 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11601 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 11602 } 11603 } 11604 } else if (isa<CXXThisExpr>(E)) { 11605 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 11606 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 11607 if (MD->isConst()) { 11608 if (!DiagnosticEmitted) { 11609 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 11610 << ConstMethod << MD; 11611 DiagnosticEmitted = true; 11612 } 11613 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 11614 << ConstMethod << MD << MD->getSourceRange(); 11615 } 11616 } 11617 } 11618 } 11619 11620 if (DiagnosticEmitted) 11621 return; 11622 11623 // Can't determine a more specific message, so display the generic error. 11624 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 11625 } 11626 11627 enum OriginalExprKind { 11628 OEK_Variable, 11629 OEK_Member, 11630 OEK_LValue 11631 }; 11632 11633 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 11634 const RecordType *Ty, 11635 SourceLocation Loc, SourceRange Range, 11636 OriginalExprKind OEK, 11637 bool &DiagnosticEmitted) { 11638 std::vector<const RecordType *> RecordTypeList; 11639 RecordTypeList.push_back(Ty); 11640 unsigned NextToCheckIndex = 0; 11641 // We walk the record hierarchy breadth-first to ensure that we print 11642 // diagnostics in field nesting order. 11643 while (RecordTypeList.size() > NextToCheckIndex) { 11644 bool IsNested = NextToCheckIndex > 0; 11645 for (const FieldDecl *Field : 11646 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 11647 // First, check every field for constness. 11648 QualType FieldTy = Field->getType(); 11649 if (FieldTy.isConstQualified()) { 11650 if (!DiagnosticEmitted) { 11651 S.Diag(Loc, diag::err_typecheck_assign_const) 11652 << Range << NestedConstMember << OEK << VD 11653 << IsNested << Field; 11654 DiagnosticEmitted = true; 11655 } 11656 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 11657 << NestedConstMember << IsNested << Field 11658 << FieldTy << Field->getSourceRange(); 11659 } 11660 11661 // Then we append it to the list to check next in order. 11662 FieldTy = FieldTy.getCanonicalType(); 11663 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 11664 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) 11665 RecordTypeList.push_back(FieldRecTy); 11666 } 11667 } 11668 ++NextToCheckIndex; 11669 } 11670 } 11671 11672 /// Emit an error for the case where a record we are trying to assign to has a 11673 /// const-qualified field somewhere in its hierarchy. 11674 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 11675 SourceLocation Loc) { 11676 QualType Ty = E->getType(); 11677 assert(Ty->isRecordType() && "lvalue was not record?"); 11678 SourceRange Range = E->getSourceRange(); 11679 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 11680 bool DiagEmitted = false; 11681 11682 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 11683 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 11684 Range, OEK_Member, DiagEmitted); 11685 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11686 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 11687 Range, OEK_Variable, DiagEmitted); 11688 else 11689 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 11690 Range, OEK_LValue, DiagEmitted); 11691 if (!DiagEmitted) 11692 DiagnoseConstAssignment(S, E, Loc); 11693 } 11694 11695 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 11696 /// emit an error and return true. If so, return false. 11697 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 11698 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 11699 11700 S.CheckShadowingDeclModification(E, Loc); 11701 11702 SourceLocation OrigLoc = Loc; 11703 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 11704 &Loc); 11705 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 11706 IsLV = Expr::MLV_InvalidMessageExpression; 11707 if (IsLV == Expr::MLV_Valid) 11708 return false; 11709 11710 unsigned DiagID = 0; 11711 bool NeedType = false; 11712 switch (IsLV) { // C99 6.5.16p2 11713 case Expr::MLV_ConstQualified: 11714 // Use a specialized diagnostic when we're assigning to an object 11715 // from an enclosing function or block. 11716 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 11717 if (NCCK == NCCK_Block) 11718 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 11719 else 11720 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 11721 break; 11722 } 11723 11724 // In ARC, use some specialized diagnostics for occasions where we 11725 // infer 'const'. These are always pseudo-strong variables. 11726 if (S.getLangOpts().ObjCAutoRefCount) { 11727 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 11728 if (declRef && isa<VarDecl>(declRef->getDecl())) { 11729 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 11730 11731 // Use the normal diagnostic if it's pseudo-__strong but the 11732 // user actually wrote 'const'. 11733 if (var->isARCPseudoStrong() && 11734 (!var->getTypeSourceInfo() || 11735 !var->getTypeSourceInfo()->getType().isConstQualified())) { 11736 // There are three pseudo-strong cases: 11737 // - self 11738 ObjCMethodDecl *method = S.getCurMethodDecl(); 11739 if (method && var == method->getSelfDecl()) { 11740 DiagID = method->isClassMethod() 11741 ? diag::err_typecheck_arc_assign_self_class_method 11742 : diag::err_typecheck_arc_assign_self; 11743 11744 // - Objective-C externally_retained attribute. 11745 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 11746 isa<ParmVarDecl>(var)) { 11747 DiagID = diag::err_typecheck_arc_assign_externally_retained; 11748 11749 // - fast enumeration variables 11750 } else { 11751 DiagID = diag::err_typecheck_arr_assign_enumeration; 11752 } 11753 11754 SourceRange Assign; 11755 if (Loc != OrigLoc) 11756 Assign = SourceRange(OrigLoc, OrigLoc); 11757 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 11758 // We need to preserve the AST regardless, so migration tool 11759 // can do its job. 11760 return false; 11761 } 11762 } 11763 } 11764 11765 // If none of the special cases above are triggered, then this is a 11766 // simple const assignment. 11767 if (DiagID == 0) { 11768 DiagnoseConstAssignment(S, E, Loc); 11769 return true; 11770 } 11771 11772 break; 11773 case Expr::MLV_ConstAddrSpace: 11774 DiagnoseConstAssignment(S, E, Loc); 11775 return true; 11776 case Expr::MLV_ConstQualifiedField: 11777 DiagnoseRecursiveConstFields(S, E, Loc); 11778 return true; 11779 case Expr::MLV_ArrayType: 11780 case Expr::MLV_ArrayTemporary: 11781 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 11782 NeedType = true; 11783 break; 11784 case Expr::MLV_NotObjectType: 11785 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 11786 NeedType = true; 11787 break; 11788 case Expr::MLV_LValueCast: 11789 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 11790 break; 11791 case Expr::MLV_Valid: 11792 llvm_unreachable("did not take early return for MLV_Valid"); 11793 case Expr::MLV_InvalidExpression: 11794 case Expr::MLV_MemberFunction: 11795 case Expr::MLV_ClassTemporary: 11796 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 11797 break; 11798 case Expr::MLV_IncompleteType: 11799 case Expr::MLV_IncompleteVoidType: 11800 return S.RequireCompleteType(Loc, E->getType(), 11801 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 11802 case Expr::MLV_DuplicateVectorComponents: 11803 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 11804 break; 11805 case Expr::MLV_NoSetterProperty: 11806 llvm_unreachable("readonly properties should be processed differently"); 11807 case Expr::MLV_InvalidMessageExpression: 11808 DiagID = diag::err_readonly_message_assignment; 11809 break; 11810 case Expr::MLV_SubObjCPropertySetting: 11811 DiagID = diag::err_no_subobject_property_setting; 11812 break; 11813 } 11814 11815 SourceRange Assign; 11816 if (Loc != OrigLoc) 11817 Assign = SourceRange(OrigLoc, OrigLoc); 11818 if (NeedType) 11819 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 11820 else 11821 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 11822 return true; 11823 } 11824 11825 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 11826 SourceLocation Loc, 11827 Sema &Sema) { 11828 if (Sema.inTemplateInstantiation()) 11829 return; 11830 if (Sema.isUnevaluatedContext()) 11831 return; 11832 if (Loc.isInvalid() || Loc.isMacroID()) 11833 return; 11834 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 11835 return; 11836 11837 // C / C++ fields 11838 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 11839 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 11840 if (ML && MR) { 11841 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 11842 return; 11843 const ValueDecl *LHSDecl = 11844 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 11845 const ValueDecl *RHSDecl = 11846 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 11847 if (LHSDecl != RHSDecl) 11848 return; 11849 if (LHSDecl->getType().isVolatileQualified()) 11850 return; 11851 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 11852 if (RefTy->getPointeeType().isVolatileQualified()) 11853 return; 11854 11855 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 11856 } 11857 11858 // Objective-C instance variables 11859 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 11860 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 11861 if (OL && OR && OL->getDecl() == OR->getDecl()) { 11862 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 11863 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 11864 if (RL && RR && RL->getDecl() == RR->getDecl()) 11865 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 11866 } 11867 } 11868 11869 // C99 6.5.16.1 11870 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 11871 SourceLocation Loc, 11872 QualType CompoundType) { 11873 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 11874 11875 // Verify that LHS is a modifiable lvalue, and emit error if not. 11876 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 11877 return QualType(); 11878 11879 QualType LHSType = LHSExpr->getType(); 11880 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 11881 CompoundType; 11882 // OpenCL v1.2 s6.1.1.1 p2: 11883 // The half data type can only be used to declare a pointer to a buffer that 11884 // contains half values 11885 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 11886 LHSType->isHalfType()) { 11887 Diag(Loc, diag::err_opencl_half_load_store) << 1 11888 << LHSType.getUnqualifiedType(); 11889 return QualType(); 11890 } 11891 11892 AssignConvertType ConvTy; 11893 if (CompoundType.isNull()) { 11894 Expr *RHSCheck = RHS.get(); 11895 11896 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 11897 11898 QualType LHSTy(LHSType); 11899 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 11900 if (RHS.isInvalid()) 11901 return QualType(); 11902 // Special case of NSObject attributes on c-style pointer types. 11903 if (ConvTy == IncompatiblePointer && 11904 ((Context.isObjCNSObjectType(LHSType) && 11905 RHSType->isObjCObjectPointerType()) || 11906 (Context.isObjCNSObjectType(RHSType) && 11907 LHSType->isObjCObjectPointerType()))) 11908 ConvTy = Compatible; 11909 11910 if (ConvTy == Compatible && 11911 LHSType->isObjCObjectType()) 11912 Diag(Loc, diag::err_objc_object_assignment) 11913 << LHSType; 11914 11915 // If the RHS is a unary plus or minus, check to see if they = and + are 11916 // right next to each other. If so, the user may have typo'd "x =+ 4" 11917 // instead of "x += 4". 11918 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 11919 RHSCheck = ICE->getSubExpr(); 11920 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 11921 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 11922 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 11923 // Only if the two operators are exactly adjacent. 11924 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 11925 // And there is a space or other character before the subexpr of the 11926 // unary +/-. We don't want to warn on "x=-1". 11927 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 11928 UO->getSubExpr()->getBeginLoc().isFileID()) { 11929 Diag(Loc, diag::warn_not_compound_assign) 11930 << (UO->getOpcode() == UO_Plus ? "+" : "-") 11931 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 11932 } 11933 } 11934 11935 if (ConvTy == Compatible) { 11936 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 11937 // Warn about retain cycles where a block captures the LHS, but 11938 // not if the LHS is a simple variable into which the block is 11939 // being stored...unless that variable can be captured by reference! 11940 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 11941 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 11942 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 11943 checkRetainCycles(LHSExpr, RHS.get()); 11944 } 11945 11946 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 11947 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 11948 // It is safe to assign a weak reference into a strong variable. 11949 // Although this code can still have problems: 11950 // id x = self.weakProp; 11951 // id y = self.weakProp; 11952 // we do not warn to warn spuriously when 'x' and 'y' are on separate 11953 // paths through the function. This should be revisited if 11954 // -Wrepeated-use-of-weak is made flow-sensitive. 11955 // For ObjCWeak only, we do not warn if the assign is to a non-weak 11956 // variable, which will be valid for the current autorelease scope. 11957 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 11958 RHS.get()->getBeginLoc())) 11959 getCurFunction()->markSafeWeakUse(RHS.get()); 11960 11961 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 11962 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 11963 } 11964 } 11965 } else { 11966 // Compound assignment "x += y" 11967 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 11968 } 11969 11970 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 11971 RHS.get(), AA_Assigning)) 11972 return QualType(); 11973 11974 CheckForNullPointerDereference(*this, LHSExpr); 11975 11976 if (getLangOpts().CPlusPlus2a && LHSType.isVolatileQualified()) { 11977 if (CompoundType.isNull()) { 11978 // C++2a [expr.ass]p5: 11979 // A simple-assignment whose left operand is of a volatile-qualified 11980 // type is deprecated unless the assignment is either a discarded-value 11981 // expression or an unevaluated operand 11982 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 11983 } else { 11984 // C++2a [expr.ass]p6: 11985 // [Compound-assignment] expressions are deprecated if E1 has 11986 // volatile-qualified type 11987 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 11988 } 11989 } 11990 11991 // C99 6.5.16p3: The type of an assignment expression is the type of the 11992 // left operand unless the left operand has qualified type, in which case 11993 // it is the unqualified version of the type of the left operand. 11994 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 11995 // is converted to the type of the assignment expression (above). 11996 // C++ 5.17p1: the type of the assignment expression is that of its left 11997 // operand. 11998 return (getLangOpts().CPlusPlus 11999 ? LHSType : LHSType.getUnqualifiedType()); 12000 } 12001 12002 // Only ignore explicit casts to void. 12003 static bool IgnoreCommaOperand(const Expr *E) { 12004 E = E->IgnoreParens(); 12005 12006 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 12007 if (CE->getCastKind() == CK_ToVoid) { 12008 return true; 12009 } 12010 12011 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 12012 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 12013 CE->getSubExpr()->getType()->isDependentType()) { 12014 return true; 12015 } 12016 } 12017 12018 return false; 12019 } 12020 12021 // Look for instances where it is likely the comma operator is confused with 12022 // another operator. There is a whitelist of acceptable expressions for the 12023 // left hand side of the comma operator, otherwise emit a warning. 12024 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 12025 // No warnings in macros 12026 if (Loc.isMacroID()) 12027 return; 12028 12029 // Don't warn in template instantiations. 12030 if (inTemplateInstantiation()) 12031 return; 12032 12033 // Scope isn't fine-grained enough to whitelist the specific cases, so 12034 // instead, skip more than needed, then call back into here with the 12035 // CommaVisitor in SemaStmt.cpp. 12036 // The whitelisted locations are the initialization and increment portions 12037 // of a for loop. The additional checks are on the condition of 12038 // if statements, do/while loops, and for loops. 12039 // Differences in scope flags for C89 mode requires the extra logic. 12040 const unsigned ForIncrementFlags = 12041 getLangOpts().C99 || getLangOpts().CPlusPlus 12042 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 12043 : Scope::ContinueScope | Scope::BreakScope; 12044 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 12045 const unsigned ScopeFlags = getCurScope()->getFlags(); 12046 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 12047 (ScopeFlags & ForInitFlags) == ForInitFlags) 12048 return; 12049 12050 // If there are multiple comma operators used together, get the RHS of the 12051 // of the comma operator as the LHS. 12052 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 12053 if (BO->getOpcode() != BO_Comma) 12054 break; 12055 LHS = BO->getRHS(); 12056 } 12057 12058 // Only allow some expressions on LHS to not warn. 12059 if (IgnoreCommaOperand(LHS)) 12060 return; 12061 12062 Diag(Loc, diag::warn_comma_operator); 12063 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 12064 << LHS->getSourceRange() 12065 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 12066 LangOpts.CPlusPlus ? "static_cast<void>(" 12067 : "(void)(") 12068 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 12069 ")"); 12070 } 12071 12072 // C99 6.5.17 12073 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 12074 SourceLocation Loc) { 12075 LHS = S.CheckPlaceholderExpr(LHS.get()); 12076 RHS = S.CheckPlaceholderExpr(RHS.get()); 12077 if (LHS.isInvalid() || RHS.isInvalid()) 12078 return QualType(); 12079 12080 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 12081 // operands, but not unary promotions. 12082 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 12083 12084 // So we treat the LHS as a ignored value, and in C++ we allow the 12085 // containing site to determine what should be done with the RHS. 12086 LHS = S.IgnoredValueConversions(LHS.get()); 12087 if (LHS.isInvalid()) 12088 return QualType(); 12089 12090 S.DiagnoseUnusedExprResult(LHS.get()); 12091 12092 if (!S.getLangOpts().CPlusPlus) { 12093 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 12094 if (RHS.isInvalid()) 12095 return QualType(); 12096 if (!RHS.get()->getType()->isVoidType()) 12097 S.RequireCompleteType(Loc, RHS.get()->getType(), 12098 diag::err_incomplete_type); 12099 } 12100 12101 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 12102 S.DiagnoseCommaOperator(LHS.get(), Loc); 12103 12104 return RHS.get()->getType(); 12105 } 12106 12107 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 12108 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 12109 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 12110 ExprValueKind &VK, 12111 ExprObjectKind &OK, 12112 SourceLocation OpLoc, 12113 bool IsInc, bool IsPrefix) { 12114 if (Op->isTypeDependent()) 12115 return S.Context.DependentTy; 12116 12117 QualType ResType = Op->getType(); 12118 // Atomic types can be used for increment / decrement where the non-atomic 12119 // versions can, so ignore the _Atomic() specifier for the purpose of 12120 // checking. 12121 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 12122 ResType = ResAtomicType->getValueType(); 12123 12124 assert(!ResType.isNull() && "no type for increment/decrement expression"); 12125 12126 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 12127 // Decrement of bool is not allowed. 12128 if (!IsInc) { 12129 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 12130 return QualType(); 12131 } 12132 // Increment of bool sets it to true, but is deprecated. 12133 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 12134 : diag::warn_increment_bool) 12135 << Op->getSourceRange(); 12136 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 12137 // Error on enum increments and decrements in C++ mode 12138 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 12139 return QualType(); 12140 } else if (ResType->isRealType()) { 12141 // OK! 12142 } else if (ResType->isPointerType()) { 12143 // C99 6.5.2.4p2, 6.5.6p2 12144 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 12145 return QualType(); 12146 } else if (ResType->isObjCObjectPointerType()) { 12147 // On modern runtimes, ObjC pointer arithmetic is forbidden. 12148 // Otherwise, we just need a complete type. 12149 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 12150 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 12151 return QualType(); 12152 } else if (ResType->isAnyComplexType()) { 12153 // C99 does not support ++/-- on complex types, we allow as an extension. 12154 S.Diag(OpLoc, diag::ext_integer_increment_complex) 12155 << ResType << Op->getSourceRange(); 12156 } else if (ResType->isPlaceholderType()) { 12157 ExprResult PR = S.CheckPlaceholderExpr(Op); 12158 if (PR.isInvalid()) return QualType(); 12159 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 12160 IsInc, IsPrefix); 12161 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 12162 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 12163 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 12164 (ResType->castAs<VectorType>()->getVectorKind() != 12165 VectorType::AltiVecBool)) { 12166 // The z vector extensions allow ++ and -- for non-bool vectors. 12167 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 12168 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 12169 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 12170 } else { 12171 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 12172 << ResType << int(IsInc) << Op->getSourceRange(); 12173 return QualType(); 12174 } 12175 // At this point, we know we have a real, complex or pointer type. 12176 // Now make sure the operand is a modifiable lvalue. 12177 if (CheckForModifiableLvalue(Op, OpLoc, S)) 12178 return QualType(); 12179 if (S.getLangOpts().CPlusPlus2a && ResType.isVolatileQualified()) { 12180 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 12181 // An operand with volatile-qualified type is deprecated 12182 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 12183 << IsInc << ResType; 12184 } 12185 // In C++, a prefix increment is the same type as the operand. Otherwise 12186 // (in C or with postfix), the increment is the unqualified type of the 12187 // operand. 12188 if (IsPrefix && S.getLangOpts().CPlusPlus) { 12189 VK = VK_LValue; 12190 OK = Op->getObjectKind(); 12191 return ResType; 12192 } else { 12193 VK = VK_RValue; 12194 return ResType.getUnqualifiedType(); 12195 } 12196 } 12197 12198 12199 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 12200 /// This routine allows us to typecheck complex/recursive expressions 12201 /// where the declaration is needed for type checking. We only need to 12202 /// handle cases when the expression references a function designator 12203 /// or is an lvalue. Here are some examples: 12204 /// - &(x) => x 12205 /// - &*****f => f for f a function designator. 12206 /// - &s.xx => s 12207 /// - &s.zz[1].yy -> s, if zz is an array 12208 /// - *(x + 1) -> x, if x is an array 12209 /// - &"123"[2] -> 0 12210 /// - & __real__ x -> x 12211 static ValueDecl *getPrimaryDecl(Expr *E) { 12212 switch (E->getStmtClass()) { 12213 case Stmt::DeclRefExprClass: 12214 return cast<DeclRefExpr>(E)->getDecl(); 12215 case Stmt::MemberExprClass: 12216 // If this is an arrow operator, the address is an offset from 12217 // the base's value, so the object the base refers to is 12218 // irrelevant. 12219 if (cast<MemberExpr>(E)->isArrow()) 12220 return nullptr; 12221 // Otherwise, the expression refers to a part of the base 12222 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 12223 case Stmt::ArraySubscriptExprClass: { 12224 // FIXME: This code shouldn't be necessary! We should catch the implicit 12225 // promotion of register arrays earlier. 12226 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 12227 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 12228 if (ICE->getSubExpr()->getType()->isArrayType()) 12229 return getPrimaryDecl(ICE->getSubExpr()); 12230 } 12231 return nullptr; 12232 } 12233 case Stmt::UnaryOperatorClass: { 12234 UnaryOperator *UO = cast<UnaryOperator>(E); 12235 12236 switch(UO->getOpcode()) { 12237 case UO_Real: 12238 case UO_Imag: 12239 case UO_Extension: 12240 return getPrimaryDecl(UO->getSubExpr()); 12241 default: 12242 return nullptr; 12243 } 12244 } 12245 case Stmt::ParenExprClass: 12246 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 12247 case Stmt::ImplicitCastExprClass: 12248 // If the result of an implicit cast is an l-value, we care about 12249 // the sub-expression; otherwise, the result here doesn't matter. 12250 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 12251 default: 12252 return nullptr; 12253 } 12254 } 12255 12256 namespace { 12257 enum { 12258 AO_Bit_Field = 0, 12259 AO_Vector_Element = 1, 12260 AO_Property_Expansion = 2, 12261 AO_Register_Variable = 3, 12262 AO_No_Error = 4 12263 }; 12264 } 12265 /// Diagnose invalid operand for address of operations. 12266 /// 12267 /// \param Type The type of operand which cannot have its address taken. 12268 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 12269 Expr *E, unsigned Type) { 12270 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 12271 } 12272 12273 /// CheckAddressOfOperand - The operand of & must be either a function 12274 /// designator or an lvalue designating an object. If it is an lvalue, the 12275 /// object cannot be declared with storage class register or be a bit field. 12276 /// Note: The usual conversions are *not* applied to the operand of the & 12277 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 12278 /// In C++, the operand might be an overloaded function name, in which case 12279 /// we allow the '&' but retain the overloaded-function type. 12280 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 12281 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 12282 if (PTy->getKind() == BuiltinType::Overload) { 12283 Expr *E = OrigOp.get()->IgnoreParens(); 12284 if (!isa<OverloadExpr>(E)) { 12285 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 12286 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 12287 << OrigOp.get()->getSourceRange(); 12288 return QualType(); 12289 } 12290 12291 OverloadExpr *Ovl = cast<OverloadExpr>(E); 12292 if (isa<UnresolvedMemberExpr>(Ovl)) 12293 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 12294 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 12295 << OrigOp.get()->getSourceRange(); 12296 return QualType(); 12297 } 12298 12299 return Context.OverloadTy; 12300 } 12301 12302 if (PTy->getKind() == BuiltinType::UnknownAny) 12303 return Context.UnknownAnyTy; 12304 12305 if (PTy->getKind() == BuiltinType::BoundMember) { 12306 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 12307 << OrigOp.get()->getSourceRange(); 12308 return QualType(); 12309 } 12310 12311 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 12312 if (OrigOp.isInvalid()) return QualType(); 12313 } 12314 12315 if (OrigOp.get()->isTypeDependent()) 12316 return Context.DependentTy; 12317 12318 assert(!OrigOp.get()->getType()->isPlaceholderType()); 12319 12320 // Make sure to ignore parentheses in subsequent checks 12321 Expr *op = OrigOp.get()->IgnoreParens(); 12322 12323 // In OpenCL captures for blocks called as lambda functions 12324 // are located in the private address space. Blocks used in 12325 // enqueue_kernel can be located in a different address space 12326 // depending on a vendor implementation. Thus preventing 12327 // taking an address of the capture to avoid invalid AS casts. 12328 if (LangOpts.OpenCL) { 12329 auto* VarRef = dyn_cast<DeclRefExpr>(op); 12330 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 12331 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 12332 return QualType(); 12333 } 12334 } 12335 12336 if (getLangOpts().C99) { 12337 // Implement C99-only parts of addressof rules. 12338 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 12339 if (uOp->getOpcode() == UO_Deref) 12340 // Per C99 6.5.3.2, the address of a deref always returns a valid result 12341 // (assuming the deref expression is valid). 12342 return uOp->getSubExpr()->getType(); 12343 } 12344 // Technically, there should be a check for array subscript 12345 // expressions here, but the result of one is always an lvalue anyway. 12346 } 12347 ValueDecl *dcl = getPrimaryDecl(op); 12348 12349 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 12350 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 12351 op->getBeginLoc())) 12352 return QualType(); 12353 12354 Expr::LValueClassification lval = op->ClassifyLValue(Context); 12355 unsigned AddressOfError = AO_No_Error; 12356 12357 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 12358 bool sfinae = (bool)isSFINAEContext(); 12359 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 12360 : diag::ext_typecheck_addrof_temporary) 12361 << op->getType() << op->getSourceRange(); 12362 if (sfinae) 12363 return QualType(); 12364 // Materialize the temporary as an lvalue so that we can take its address. 12365 OrigOp = op = 12366 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 12367 } else if (isa<ObjCSelectorExpr>(op)) { 12368 return Context.getPointerType(op->getType()); 12369 } else if (lval == Expr::LV_MemberFunction) { 12370 // If it's an instance method, make a member pointer. 12371 // The expression must have exactly the form &A::foo. 12372 12373 // If the underlying expression isn't a decl ref, give up. 12374 if (!isa<DeclRefExpr>(op)) { 12375 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 12376 << OrigOp.get()->getSourceRange(); 12377 return QualType(); 12378 } 12379 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 12380 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 12381 12382 // The id-expression was parenthesized. 12383 if (OrigOp.get() != DRE) { 12384 Diag(OpLoc, diag::err_parens_pointer_member_function) 12385 << OrigOp.get()->getSourceRange(); 12386 12387 // The method was named without a qualifier. 12388 } else if (!DRE->getQualifier()) { 12389 if (MD->getParent()->getName().empty()) 12390 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 12391 << op->getSourceRange(); 12392 else { 12393 SmallString<32> Str; 12394 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 12395 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 12396 << op->getSourceRange() 12397 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 12398 } 12399 } 12400 12401 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 12402 if (isa<CXXDestructorDecl>(MD)) 12403 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 12404 12405 QualType MPTy = Context.getMemberPointerType( 12406 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 12407 // Under the MS ABI, lock down the inheritance model now. 12408 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 12409 (void)isCompleteType(OpLoc, MPTy); 12410 return MPTy; 12411 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 12412 // C99 6.5.3.2p1 12413 // The operand must be either an l-value or a function designator 12414 if (!op->getType()->isFunctionType()) { 12415 // Use a special diagnostic for loads from property references. 12416 if (isa<PseudoObjectExpr>(op)) { 12417 AddressOfError = AO_Property_Expansion; 12418 } else { 12419 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 12420 << op->getType() << op->getSourceRange(); 12421 return QualType(); 12422 } 12423 } 12424 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 12425 // The operand cannot be a bit-field 12426 AddressOfError = AO_Bit_Field; 12427 } else if (op->getObjectKind() == OK_VectorComponent) { 12428 // The operand cannot be an element of a vector 12429 AddressOfError = AO_Vector_Element; 12430 } else if (dcl) { // C99 6.5.3.2p1 12431 // We have an lvalue with a decl. Make sure the decl is not declared 12432 // with the register storage-class specifier. 12433 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 12434 // in C++ it is not error to take address of a register 12435 // variable (c++03 7.1.1P3) 12436 if (vd->getStorageClass() == SC_Register && 12437 !getLangOpts().CPlusPlus) { 12438 AddressOfError = AO_Register_Variable; 12439 } 12440 } else if (isa<MSPropertyDecl>(dcl)) { 12441 AddressOfError = AO_Property_Expansion; 12442 } else if (isa<FunctionTemplateDecl>(dcl)) { 12443 return Context.OverloadTy; 12444 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 12445 // Okay: we can take the address of a field. 12446 // Could be a pointer to member, though, if there is an explicit 12447 // scope qualifier for the class. 12448 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 12449 DeclContext *Ctx = dcl->getDeclContext(); 12450 if (Ctx && Ctx->isRecord()) { 12451 if (dcl->getType()->isReferenceType()) { 12452 Diag(OpLoc, 12453 diag::err_cannot_form_pointer_to_member_of_reference_type) 12454 << dcl->getDeclName() << dcl->getType(); 12455 return QualType(); 12456 } 12457 12458 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 12459 Ctx = Ctx->getParent(); 12460 12461 QualType MPTy = Context.getMemberPointerType( 12462 op->getType(), 12463 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 12464 // Under the MS ABI, lock down the inheritance model now. 12465 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 12466 (void)isCompleteType(OpLoc, MPTy); 12467 return MPTy; 12468 } 12469 } 12470 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 12471 !isa<BindingDecl>(dcl)) 12472 llvm_unreachable("Unknown/unexpected decl type"); 12473 } 12474 12475 if (AddressOfError != AO_No_Error) { 12476 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 12477 return QualType(); 12478 } 12479 12480 if (lval == Expr::LV_IncompleteVoidType) { 12481 // Taking the address of a void variable is technically illegal, but we 12482 // allow it in cases which are otherwise valid. 12483 // Example: "extern void x; void* y = &x;". 12484 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 12485 } 12486 12487 // If the operand has type "type", the result has type "pointer to type". 12488 if (op->getType()->isObjCObjectType()) 12489 return Context.getObjCObjectPointerType(op->getType()); 12490 12491 CheckAddressOfPackedMember(op); 12492 12493 return Context.getPointerType(op->getType()); 12494 } 12495 12496 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 12497 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 12498 if (!DRE) 12499 return; 12500 const Decl *D = DRE->getDecl(); 12501 if (!D) 12502 return; 12503 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 12504 if (!Param) 12505 return; 12506 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 12507 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 12508 return; 12509 if (FunctionScopeInfo *FD = S.getCurFunction()) 12510 if (!FD->ModifiedNonNullParams.count(Param)) 12511 FD->ModifiedNonNullParams.insert(Param); 12512 } 12513 12514 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 12515 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 12516 SourceLocation OpLoc) { 12517 if (Op->isTypeDependent()) 12518 return S.Context.DependentTy; 12519 12520 ExprResult ConvResult = S.UsualUnaryConversions(Op); 12521 if (ConvResult.isInvalid()) 12522 return QualType(); 12523 Op = ConvResult.get(); 12524 QualType OpTy = Op->getType(); 12525 QualType Result; 12526 12527 if (isa<CXXReinterpretCastExpr>(Op)) { 12528 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 12529 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 12530 Op->getSourceRange()); 12531 } 12532 12533 if (const PointerType *PT = OpTy->getAs<PointerType>()) 12534 { 12535 Result = PT->getPointeeType(); 12536 } 12537 else if (const ObjCObjectPointerType *OPT = 12538 OpTy->getAs<ObjCObjectPointerType>()) 12539 Result = OPT->getPointeeType(); 12540 else { 12541 ExprResult PR = S.CheckPlaceholderExpr(Op); 12542 if (PR.isInvalid()) return QualType(); 12543 if (PR.get() != Op) 12544 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 12545 } 12546 12547 if (Result.isNull()) { 12548 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 12549 << OpTy << Op->getSourceRange(); 12550 return QualType(); 12551 } 12552 12553 // Note that per both C89 and C99, indirection is always legal, even if Result 12554 // is an incomplete type or void. It would be possible to warn about 12555 // dereferencing a void pointer, but it's completely well-defined, and such a 12556 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 12557 // for pointers to 'void' but is fine for any other pointer type: 12558 // 12559 // C++ [expr.unary.op]p1: 12560 // [...] the expression to which [the unary * operator] is applied shall 12561 // be a pointer to an object type, or a pointer to a function type 12562 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 12563 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 12564 << OpTy << Op->getSourceRange(); 12565 12566 // Dereferences are usually l-values... 12567 VK = VK_LValue; 12568 12569 // ...except that certain expressions are never l-values in C. 12570 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 12571 VK = VK_RValue; 12572 12573 return Result; 12574 } 12575 12576 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 12577 BinaryOperatorKind Opc; 12578 switch (Kind) { 12579 default: llvm_unreachable("Unknown binop!"); 12580 case tok::periodstar: Opc = BO_PtrMemD; break; 12581 case tok::arrowstar: Opc = BO_PtrMemI; break; 12582 case tok::star: Opc = BO_Mul; break; 12583 case tok::slash: Opc = BO_Div; break; 12584 case tok::percent: Opc = BO_Rem; break; 12585 case tok::plus: Opc = BO_Add; break; 12586 case tok::minus: Opc = BO_Sub; break; 12587 case tok::lessless: Opc = BO_Shl; break; 12588 case tok::greatergreater: Opc = BO_Shr; break; 12589 case tok::lessequal: Opc = BO_LE; break; 12590 case tok::less: Opc = BO_LT; break; 12591 case tok::greaterequal: Opc = BO_GE; break; 12592 case tok::greater: Opc = BO_GT; break; 12593 case tok::exclaimequal: Opc = BO_NE; break; 12594 case tok::equalequal: Opc = BO_EQ; break; 12595 case tok::spaceship: Opc = BO_Cmp; break; 12596 case tok::amp: Opc = BO_And; break; 12597 case tok::caret: Opc = BO_Xor; break; 12598 case tok::pipe: Opc = BO_Or; break; 12599 case tok::ampamp: Opc = BO_LAnd; break; 12600 case tok::pipepipe: Opc = BO_LOr; break; 12601 case tok::equal: Opc = BO_Assign; break; 12602 case tok::starequal: Opc = BO_MulAssign; break; 12603 case tok::slashequal: Opc = BO_DivAssign; break; 12604 case tok::percentequal: Opc = BO_RemAssign; break; 12605 case tok::plusequal: Opc = BO_AddAssign; break; 12606 case tok::minusequal: Opc = BO_SubAssign; break; 12607 case tok::lesslessequal: Opc = BO_ShlAssign; break; 12608 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 12609 case tok::ampequal: Opc = BO_AndAssign; break; 12610 case tok::caretequal: Opc = BO_XorAssign; break; 12611 case tok::pipeequal: Opc = BO_OrAssign; break; 12612 case tok::comma: Opc = BO_Comma; break; 12613 } 12614 return Opc; 12615 } 12616 12617 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 12618 tok::TokenKind Kind) { 12619 UnaryOperatorKind Opc; 12620 switch (Kind) { 12621 default: llvm_unreachable("Unknown unary op!"); 12622 case tok::plusplus: Opc = UO_PreInc; break; 12623 case tok::minusminus: Opc = UO_PreDec; break; 12624 case tok::amp: Opc = UO_AddrOf; break; 12625 case tok::star: Opc = UO_Deref; break; 12626 case tok::plus: Opc = UO_Plus; break; 12627 case tok::minus: Opc = UO_Minus; break; 12628 case tok::tilde: Opc = UO_Not; break; 12629 case tok::exclaim: Opc = UO_LNot; break; 12630 case tok::kw___real: Opc = UO_Real; break; 12631 case tok::kw___imag: Opc = UO_Imag; break; 12632 case tok::kw___extension__: Opc = UO_Extension; break; 12633 } 12634 return Opc; 12635 } 12636 12637 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 12638 /// This warning suppressed in the event of macro expansions. 12639 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 12640 SourceLocation OpLoc, bool IsBuiltin) { 12641 if (S.inTemplateInstantiation()) 12642 return; 12643 if (S.isUnevaluatedContext()) 12644 return; 12645 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 12646 return; 12647 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 12648 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 12649 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 12650 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 12651 if (!LHSDeclRef || !RHSDeclRef || 12652 LHSDeclRef->getLocation().isMacroID() || 12653 RHSDeclRef->getLocation().isMacroID()) 12654 return; 12655 const ValueDecl *LHSDecl = 12656 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 12657 const ValueDecl *RHSDecl = 12658 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 12659 if (LHSDecl != RHSDecl) 12660 return; 12661 if (LHSDecl->getType().isVolatileQualified()) 12662 return; 12663 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 12664 if (RefTy->getPointeeType().isVolatileQualified()) 12665 return; 12666 12667 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 12668 : diag::warn_self_assignment_overloaded) 12669 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 12670 << RHSExpr->getSourceRange(); 12671 } 12672 12673 /// Check if a bitwise-& is performed on an Objective-C pointer. This 12674 /// is usually indicative of introspection within the Objective-C pointer. 12675 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 12676 SourceLocation OpLoc) { 12677 if (!S.getLangOpts().ObjC) 12678 return; 12679 12680 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 12681 const Expr *LHS = L.get(); 12682 const Expr *RHS = R.get(); 12683 12684 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 12685 ObjCPointerExpr = LHS; 12686 OtherExpr = RHS; 12687 } 12688 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 12689 ObjCPointerExpr = RHS; 12690 OtherExpr = LHS; 12691 } 12692 12693 // This warning is deliberately made very specific to reduce false 12694 // positives with logic that uses '&' for hashing. This logic mainly 12695 // looks for code trying to introspect into tagged pointers, which 12696 // code should generally never do. 12697 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 12698 unsigned Diag = diag::warn_objc_pointer_masking; 12699 // Determine if we are introspecting the result of performSelectorXXX. 12700 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 12701 // Special case messages to -performSelector and friends, which 12702 // can return non-pointer values boxed in a pointer value. 12703 // Some clients may wish to silence warnings in this subcase. 12704 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 12705 Selector S = ME->getSelector(); 12706 StringRef SelArg0 = S.getNameForSlot(0); 12707 if (SelArg0.startswith("performSelector")) 12708 Diag = diag::warn_objc_pointer_masking_performSelector; 12709 } 12710 12711 S.Diag(OpLoc, Diag) 12712 << ObjCPointerExpr->getSourceRange(); 12713 } 12714 } 12715 12716 static NamedDecl *getDeclFromExpr(Expr *E) { 12717 if (!E) 12718 return nullptr; 12719 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 12720 return DRE->getDecl(); 12721 if (auto *ME = dyn_cast<MemberExpr>(E)) 12722 return ME->getMemberDecl(); 12723 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 12724 return IRE->getDecl(); 12725 return nullptr; 12726 } 12727 12728 // This helper function promotes a binary operator's operands (which are of a 12729 // half vector type) to a vector of floats and then truncates the result to 12730 // a vector of either half or short. 12731 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 12732 BinaryOperatorKind Opc, QualType ResultTy, 12733 ExprValueKind VK, ExprObjectKind OK, 12734 bool IsCompAssign, SourceLocation OpLoc, 12735 FPOptions FPFeatures) { 12736 auto &Context = S.getASTContext(); 12737 assert((isVector(ResultTy, Context.HalfTy) || 12738 isVector(ResultTy, Context.ShortTy)) && 12739 "Result must be a vector of half or short"); 12740 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 12741 isVector(RHS.get()->getType(), Context.HalfTy) && 12742 "both operands expected to be a half vector"); 12743 12744 RHS = convertVector(RHS.get(), Context.FloatTy, S); 12745 QualType BinOpResTy = RHS.get()->getType(); 12746 12747 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 12748 // change BinOpResTy to a vector of ints. 12749 if (isVector(ResultTy, Context.ShortTy)) 12750 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 12751 12752 if (IsCompAssign) 12753 return new (Context) CompoundAssignOperator( 12754 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy, 12755 OpLoc, FPFeatures); 12756 12757 LHS = convertVector(LHS.get(), Context.FloatTy, S); 12758 auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy, 12759 VK, OK, OpLoc, FPFeatures); 12760 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 12761 } 12762 12763 static std::pair<ExprResult, ExprResult> 12764 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 12765 Expr *RHSExpr) { 12766 ExprResult LHS = LHSExpr, RHS = RHSExpr; 12767 if (!S.getLangOpts().CPlusPlus) { 12768 // C cannot handle TypoExpr nodes on either side of a binop because it 12769 // doesn't handle dependent types properly, so make sure any TypoExprs have 12770 // been dealt with before checking the operands. 12771 LHS = S.CorrectDelayedTyposInExpr(LHS); 12772 RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) { 12773 if (Opc != BO_Assign) 12774 return ExprResult(E); 12775 // Avoid correcting the RHS to the same Expr as the LHS. 12776 Decl *D = getDeclFromExpr(E); 12777 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 12778 }); 12779 } 12780 return std::make_pair(LHS, RHS); 12781 } 12782 12783 /// Returns true if conversion between vectors of halfs and vectors of floats 12784 /// is needed. 12785 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 12786 QualType SrcType) { 12787 return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType && 12788 !Ctx.getTargetInfo().useFP16ConversionIntrinsics() && 12789 isVector(SrcType, Ctx.HalfTy); 12790 } 12791 12792 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 12793 /// operator @p Opc at location @c TokLoc. This routine only supports 12794 /// built-in operations; ActOnBinOp handles overloaded operators. 12795 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 12796 BinaryOperatorKind Opc, 12797 Expr *LHSExpr, Expr *RHSExpr) { 12798 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 12799 // The syntax only allows initializer lists on the RHS of assignment, 12800 // so we don't need to worry about accepting invalid code for 12801 // non-assignment operators. 12802 // C++11 5.17p9: 12803 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 12804 // of x = {} is x = T(). 12805 InitializationKind Kind = InitializationKind::CreateDirectList( 12806 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 12807 InitializedEntity Entity = 12808 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 12809 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 12810 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 12811 if (Init.isInvalid()) 12812 return Init; 12813 RHSExpr = Init.get(); 12814 } 12815 12816 ExprResult LHS = LHSExpr, RHS = RHSExpr; 12817 QualType ResultTy; // Result type of the binary operator. 12818 // The following two variables are used for compound assignment operators 12819 QualType CompLHSTy; // Type of LHS after promotions for computation 12820 QualType CompResultTy; // Type of computation result 12821 ExprValueKind VK = VK_RValue; 12822 ExprObjectKind OK = OK_Ordinary; 12823 bool ConvertHalfVec = false; 12824 12825 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 12826 if (!LHS.isUsable() || !RHS.isUsable()) 12827 return ExprError(); 12828 12829 if (getLangOpts().OpenCL) { 12830 QualType LHSTy = LHSExpr->getType(); 12831 QualType RHSTy = RHSExpr->getType(); 12832 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 12833 // the ATOMIC_VAR_INIT macro. 12834 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 12835 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 12836 if (BO_Assign == Opc) 12837 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 12838 else 12839 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 12840 return ExprError(); 12841 } 12842 12843 // OpenCL special types - image, sampler, pipe, and blocks are to be used 12844 // only with a builtin functions and therefore should be disallowed here. 12845 if (LHSTy->isImageType() || RHSTy->isImageType() || 12846 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 12847 LHSTy->isPipeType() || RHSTy->isPipeType() || 12848 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 12849 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 12850 return ExprError(); 12851 } 12852 } 12853 12854 // Diagnose operations on the unsupported types for OpenMP device compilation. 12855 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) { 12856 if (Opc != BO_Assign && Opc != BO_Comma) { 12857 checkOpenMPDeviceExpr(LHSExpr); 12858 checkOpenMPDeviceExpr(RHSExpr); 12859 } 12860 } 12861 12862 switch (Opc) { 12863 case BO_Assign: 12864 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 12865 if (getLangOpts().CPlusPlus && 12866 LHS.get()->getObjectKind() != OK_ObjCProperty) { 12867 VK = LHS.get()->getValueKind(); 12868 OK = LHS.get()->getObjectKind(); 12869 } 12870 if (!ResultTy.isNull()) { 12871 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 12872 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 12873 12874 // Avoid copying a block to the heap if the block is assigned to a local 12875 // auto variable that is declared in the same scope as the block. This 12876 // optimization is unsafe if the local variable is declared in an outer 12877 // scope. For example: 12878 // 12879 // BlockTy b; 12880 // { 12881 // b = ^{...}; 12882 // } 12883 // // It is unsafe to invoke the block here if it wasn't copied to the 12884 // // heap. 12885 // b(); 12886 12887 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 12888 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 12889 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 12890 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 12891 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 12892 12893 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 12894 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 12895 NTCUC_Assignment, NTCUK_Copy); 12896 } 12897 RecordModifiableNonNullParam(*this, LHS.get()); 12898 break; 12899 case BO_PtrMemD: 12900 case BO_PtrMemI: 12901 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 12902 Opc == BO_PtrMemI); 12903 break; 12904 case BO_Mul: 12905 case BO_Div: 12906 ConvertHalfVec = true; 12907 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 12908 Opc == BO_Div); 12909 break; 12910 case BO_Rem: 12911 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 12912 break; 12913 case BO_Add: 12914 ConvertHalfVec = true; 12915 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 12916 break; 12917 case BO_Sub: 12918 ConvertHalfVec = true; 12919 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 12920 break; 12921 case BO_Shl: 12922 case BO_Shr: 12923 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 12924 break; 12925 case BO_LE: 12926 case BO_LT: 12927 case BO_GE: 12928 case BO_GT: 12929 ConvertHalfVec = true; 12930 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12931 break; 12932 case BO_EQ: 12933 case BO_NE: 12934 ConvertHalfVec = true; 12935 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12936 break; 12937 case BO_Cmp: 12938 ConvertHalfVec = true; 12939 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12940 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 12941 break; 12942 case BO_And: 12943 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 12944 LLVM_FALLTHROUGH; 12945 case BO_Xor: 12946 case BO_Or: 12947 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 12948 break; 12949 case BO_LAnd: 12950 case BO_LOr: 12951 ConvertHalfVec = true; 12952 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 12953 break; 12954 case BO_MulAssign: 12955 case BO_DivAssign: 12956 ConvertHalfVec = true; 12957 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 12958 Opc == BO_DivAssign); 12959 CompLHSTy = CompResultTy; 12960 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12961 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12962 break; 12963 case BO_RemAssign: 12964 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 12965 CompLHSTy = CompResultTy; 12966 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12967 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12968 break; 12969 case BO_AddAssign: 12970 ConvertHalfVec = true; 12971 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 12972 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12973 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12974 break; 12975 case BO_SubAssign: 12976 ConvertHalfVec = true; 12977 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 12978 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12979 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12980 break; 12981 case BO_ShlAssign: 12982 case BO_ShrAssign: 12983 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 12984 CompLHSTy = CompResultTy; 12985 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12986 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12987 break; 12988 case BO_AndAssign: 12989 case BO_OrAssign: // fallthrough 12990 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 12991 LLVM_FALLTHROUGH; 12992 case BO_XorAssign: 12993 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 12994 CompLHSTy = CompResultTy; 12995 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12996 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12997 break; 12998 case BO_Comma: 12999 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 13000 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 13001 VK = RHS.get()->getValueKind(); 13002 OK = RHS.get()->getObjectKind(); 13003 } 13004 break; 13005 } 13006 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 13007 return ExprError(); 13008 13009 if (ResultTy->isRealFloatingType() && 13010 (getLangOpts().getFPRoundingMode() != LangOptions::FPR_ToNearest || 13011 getLangOpts().getFPExceptionMode() != LangOptions::FPE_Ignore)) 13012 // Mark the current function as usng floating point constrained intrinsics 13013 if (FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 13014 F->setUsesFPIntrin(true); 13015 } 13016 13017 // Some of the binary operations require promoting operands of half vector to 13018 // float vectors and truncating the result back to half vector. For now, we do 13019 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 13020 // arm64). 13021 assert(isVector(RHS.get()->getType(), Context.HalfTy) == 13022 isVector(LHS.get()->getType(), Context.HalfTy) && 13023 "both sides are half vectors or neither sides are"); 13024 ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context, 13025 LHS.get()->getType()); 13026 13027 // Check for array bounds violations for both sides of the BinaryOperator 13028 CheckArrayAccess(LHS.get()); 13029 CheckArrayAccess(RHS.get()); 13030 13031 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 13032 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 13033 &Context.Idents.get("object_setClass"), 13034 SourceLocation(), LookupOrdinaryName); 13035 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 13036 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 13037 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 13038 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 13039 "object_setClass(") 13040 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 13041 ",") 13042 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 13043 } 13044 else 13045 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 13046 } 13047 else if (const ObjCIvarRefExpr *OIRE = 13048 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 13049 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 13050 13051 // Opc is not a compound assignment if CompResultTy is null. 13052 if (CompResultTy.isNull()) { 13053 if (ConvertHalfVec) 13054 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 13055 OpLoc, FPFeatures); 13056 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 13057 OK, OpLoc, FPFeatures); 13058 } 13059 13060 // Handle compound assignments. 13061 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 13062 OK_ObjCProperty) { 13063 VK = VK_LValue; 13064 OK = LHS.get()->getObjectKind(); 13065 } 13066 13067 if (ConvertHalfVec) 13068 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 13069 OpLoc, FPFeatures); 13070 13071 return new (Context) CompoundAssignOperator( 13072 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 13073 OpLoc, FPFeatures); 13074 } 13075 13076 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 13077 /// operators are mixed in a way that suggests that the programmer forgot that 13078 /// comparison operators have higher precedence. The most typical example of 13079 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 13080 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 13081 SourceLocation OpLoc, Expr *LHSExpr, 13082 Expr *RHSExpr) { 13083 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 13084 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 13085 13086 // Check that one of the sides is a comparison operator and the other isn't. 13087 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 13088 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 13089 if (isLeftComp == isRightComp) 13090 return; 13091 13092 // Bitwise operations are sometimes used as eager logical ops. 13093 // Don't diagnose this. 13094 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 13095 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 13096 if (isLeftBitwise || isRightBitwise) 13097 return; 13098 13099 SourceRange DiagRange = isLeftComp 13100 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 13101 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 13102 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 13103 SourceRange ParensRange = 13104 isLeftComp 13105 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 13106 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 13107 13108 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 13109 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 13110 SuggestParentheses(Self, OpLoc, 13111 Self.PDiag(diag::note_precedence_silence) << OpStr, 13112 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 13113 SuggestParentheses(Self, OpLoc, 13114 Self.PDiag(diag::note_precedence_bitwise_first) 13115 << BinaryOperator::getOpcodeStr(Opc), 13116 ParensRange); 13117 } 13118 13119 /// It accepts a '&&' expr that is inside a '||' one. 13120 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 13121 /// in parentheses. 13122 static void 13123 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 13124 BinaryOperator *Bop) { 13125 assert(Bop->getOpcode() == BO_LAnd); 13126 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 13127 << Bop->getSourceRange() << OpLoc; 13128 SuggestParentheses(Self, Bop->getOperatorLoc(), 13129 Self.PDiag(diag::note_precedence_silence) 13130 << Bop->getOpcodeStr(), 13131 Bop->getSourceRange()); 13132 } 13133 13134 /// Returns true if the given expression can be evaluated as a constant 13135 /// 'true'. 13136 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 13137 bool Res; 13138 return !E->isValueDependent() && 13139 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 13140 } 13141 13142 /// Returns true if the given expression can be evaluated as a constant 13143 /// 'false'. 13144 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 13145 bool Res; 13146 return !E->isValueDependent() && 13147 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 13148 } 13149 13150 /// Look for '&&' in the left hand of a '||' expr. 13151 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 13152 Expr *LHSExpr, Expr *RHSExpr) { 13153 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 13154 if (Bop->getOpcode() == BO_LAnd) { 13155 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 13156 if (EvaluatesAsFalse(S, RHSExpr)) 13157 return; 13158 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 13159 if (!EvaluatesAsTrue(S, Bop->getLHS())) 13160 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 13161 } else if (Bop->getOpcode() == BO_LOr) { 13162 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 13163 // If it's "a || b && 1 || c" we didn't warn earlier for 13164 // "a || b && 1", but warn now. 13165 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 13166 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 13167 } 13168 } 13169 } 13170 } 13171 13172 /// Look for '&&' in the right hand of a '||' expr. 13173 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 13174 Expr *LHSExpr, Expr *RHSExpr) { 13175 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 13176 if (Bop->getOpcode() == BO_LAnd) { 13177 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 13178 if (EvaluatesAsFalse(S, LHSExpr)) 13179 return; 13180 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 13181 if (!EvaluatesAsTrue(S, Bop->getRHS())) 13182 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 13183 } 13184 } 13185 } 13186 13187 /// Look for bitwise op in the left or right hand of a bitwise op with 13188 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 13189 /// the '&' expression in parentheses. 13190 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 13191 SourceLocation OpLoc, Expr *SubExpr) { 13192 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 13193 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 13194 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 13195 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 13196 << Bop->getSourceRange() << OpLoc; 13197 SuggestParentheses(S, Bop->getOperatorLoc(), 13198 S.PDiag(diag::note_precedence_silence) 13199 << Bop->getOpcodeStr(), 13200 Bop->getSourceRange()); 13201 } 13202 } 13203 } 13204 13205 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 13206 Expr *SubExpr, StringRef Shift) { 13207 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 13208 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 13209 StringRef Op = Bop->getOpcodeStr(); 13210 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 13211 << Bop->getSourceRange() << OpLoc << Shift << Op; 13212 SuggestParentheses(S, Bop->getOperatorLoc(), 13213 S.PDiag(diag::note_precedence_silence) << Op, 13214 Bop->getSourceRange()); 13215 } 13216 } 13217 } 13218 13219 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 13220 Expr *LHSExpr, Expr *RHSExpr) { 13221 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 13222 if (!OCE) 13223 return; 13224 13225 FunctionDecl *FD = OCE->getDirectCallee(); 13226 if (!FD || !FD->isOverloadedOperator()) 13227 return; 13228 13229 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 13230 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 13231 return; 13232 13233 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 13234 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 13235 << (Kind == OO_LessLess); 13236 SuggestParentheses(S, OCE->getOperatorLoc(), 13237 S.PDiag(diag::note_precedence_silence) 13238 << (Kind == OO_LessLess ? "<<" : ">>"), 13239 OCE->getSourceRange()); 13240 SuggestParentheses( 13241 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 13242 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 13243 } 13244 13245 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 13246 /// precedence. 13247 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 13248 SourceLocation OpLoc, Expr *LHSExpr, 13249 Expr *RHSExpr){ 13250 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 13251 if (BinaryOperator::isBitwiseOp(Opc)) 13252 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 13253 13254 // Diagnose "arg1 & arg2 | arg3" 13255 if ((Opc == BO_Or || Opc == BO_Xor) && 13256 !OpLoc.isMacroID()/* Don't warn in macros. */) { 13257 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 13258 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 13259 } 13260 13261 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 13262 // We don't warn for 'assert(a || b && "bad")' since this is safe. 13263 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 13264 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 13265 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 13266 } 13267 13268 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 13269 || Opc == BO_Shr) { 13270 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 13271 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 13272 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 13273 } 13274 13275 // Warn on overloaded shift operators and comparisons, such as: 13276 // cout << 5 == 4; 13277 if (BinaryOperator::isComparisonOp(Opc)) 13278 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 13279 } 13280 13281 // Binary Operators. 'Tok' is the token for the operator. 13282 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 13283 tok::TokenKind Kind, 13284 Expr *LHSExpr, Expr *RHSExpr) { 13285 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 13286 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 13287 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 13288 13289 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 13290 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 13291 13292 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 13293 } 13294 13295 /// Build an overloaded binary operator expression in the given scope. 13296 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 13297 BinaryOperatorKind Opc, 13298 Expr *LHS, Expr *RHS) { 13299 switch (Opc) { 13300 case BO_Assign: 13301 case BO_DivAssign: 13302 case BO_RemAssign: 13303 case BO_SubAssign: 13304 case BO_AndAssign: 13305 case BO_OrAssign: 13306 case BO_XorAssign: 13307 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 13308 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 13309 break; 13310 default: 13311 break; 13312 } 13313 13314 // Find all of the overloaded operators visible from this 13315 // point. We perform both an operator-name lookup from the local 13316 // scope and an argument-dependent lookup based on the types of 13317 // the arguments. 13318 UnresolvedSet<16> Functions; 13319 OverloadedOperatorKind OverOp 13320 = BinaryOperator::getOverloadedOperator(Opc); 13321 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 13322 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 13323 RHS->getType(), Functions); 13324 13325 // In C++20 onwards, we may have a second operator to look up. 13326 if (S.getLangOpts().CPlusPlus2a) { 13327 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 13328 S.LookupOverloadedOperatorName(ExtraOp, Sc, LHS->getType(), 13329 RHS->getType(), Functions); 13330 } 13331 13332 // Build the (potentially-overloaded, potentially-dependent) 13333 // binary operation. 13334 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 13335 } 13336 13337 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 13338 BinaryOperatorKind Opc, 13339 Expr *LHSExpr, Expr *RHSExpr) { 13340 ExprResult LHS, RHS; 13341 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 13342 if (!LHS.isUsable() || !RHS.isUsable()) 13343 return ExprError(); 13344 LHSExpr = LHS.get(); 13345 RHSExpr = RHS.get(); 13346 13347 // We want to end up calling one of checkPseudoObjectAssignment 13348 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 13349 // both expressions are overloadable or either is type-dependent), 13350 // or CreateBuiltinBinOp (in any other case). We also want to get 13351 // any placeholder types out of the way. 13352 13353 // Handle pseudo-objects in the LHS. 13354 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 13355 // Assignments with a pseudo-object l-value need special analysis. 13356 if (pty->getKind() == BuiltinType::PseudoObject && 13357 BinaryOperator::isAssignmentOp(Opc)) 13358 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 13359 13360 // Don't resolve overloads if the other type is overloadable. 13361 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 13362 // We can't actually test that if we still have a placeholder, 13363 // though. Fortunately, none of the exceptions we see in that 13364 // code below are valid when the LHS is an overload set. Note 13365 // that an overload set can be dependently-typed, but it never 13366 // instantiates to having an overloadable type. 13367 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 13368 if (resolvedRHS.isInvalid()) return ExprError(); 13369 RHSExpr = resolvedRHS.get(); 13370 13371 if (RHSExpr->isTypeDependent() || 13372 RHSExpr->getType()->isOverloadableType()) 13373 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13374 } 13375 13376 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 13377 // template, diagnose the missing 'template' keyword instead of diagnosing 13378 // an invalid use of a bound member function. 13379 // 13380 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 13381 // to C++1z [over.over]/1.4, but we already checked for that case above. 13382 if (Opc == BO_LT && inTemplateInstantiation() && 13383 (pty->getKind() == BuiltinType::BoundMember || 13384 pty->getKind() == BuiltinType::Overload)) { 13385 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 13386 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 13387 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 13388 return isa<FunctionTemplateDecl>(ND); 13389 })) { 13390 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 13391 : OE->getNameLoc(), 13392 diag::err_template_kw_missing) 13393 << OE->getName().getAsString() << ""; 13394 return ExprError(); 13395 } 13396 } 13397 13398 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 13399 if (LHS.isInvalid()) return ExprError(); 13400 LHSExpr = LHS.get(); 13401 } 13402 13403 // Handle pseudo-objects in the RHS. 13404 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 13405 // An overload in the RHS can potentially be resolved by the type 13406 // being assigned to. 13407 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 13408 if (getLangOpts().CPlusPlus && 13409 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 13410 LHSExpr->getType()->isOverloadableType())) 13411 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13412 13413 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 13414 } 13415 13416 // Don't resolve overloads if the other type is overloadable. 13417 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 13418 LHSExpr->getType()->isOverloadableType()) 13419 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13420 13421 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 13422 if (!resolvedRHS.isUsable()) return ExprError(); 13423 RHSExpr = resolvedRHS.get(); 13424 } 13425 13426 if (getLangOpts().CPlusPlus) { 13427 // If either expression is type-dependent, always build an 13428 // overloaded op. 13429 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 13430 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13431 13432 // Otherwise, build an overloaded op if either expression has an 13433 // overloadable type. 13434 if (LHSExpr->getType()->isOverloadableType() || 13435 RHSExpr->getType()->isOverloadableType()) 13436 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13437 } 13438 13439 // Build a built-in binary operation. 13440 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 13441 } 13442 13443 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 13444 if (T.isNull() || T->isDependentType()) 13445 return false; 13446 13447 if (!T->isPromotableIntegerType()) 13448 return true; 13449 13450 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 13451 } 13452 13453 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 13454 UnaryOperatorKind Opc, 13455 Expr *InputExpr) { 13456 ExprResult Input = InputExpr; 13457 ExprValueKind VK = VK_RValue; 13458 ExprObjectKind OK = OK_Ordinary; 13459 QualType resultType; 13460 bool CanOverflow = false; 13461 13462 bool ConvertHalfVec = false; 13463 if (getLangOpts().OpenCL) { 13464 QualType Ty = InputExpr->getType(); 13465 // The only legal unary operation for atomics is '&'. 13466 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 13467 // OpenCL special types - image, sampler, pipe, and blocks are to be used 13468 // only with a builtin functions and therefore should be disallowed here. 13469 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 13470 || Ty->isBlockPointerType())) { 13471 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13472 << InputExpr->getType() 13473 << Input.get()->getSourceRange()); 13474 } 13475 } 13476 // Diagnose operations on the unsupported types for OpenMP device compilation. 13477 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) { 13478 if (UnaryOperator::isIncrementDecrementOp(Opc) || 13479 UnaryOperator::isArithmeticOp(Opc)) 13480 checkOpenMPDeviceExpr(InputExpr); 13481 } 13482 13483 switch (Opc) { 13484 case UO_PreInc: 13485 case UO_PreDec: 13486 case UO_PostInc: 13487 case UO_PostDec: 13488 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 13489 OpLoc, 13490 Opc == UO_PreInc || 13491 Opc == UO_PostInc, 13492 Opc == UO_PreInc || 13493 Opc == UO_PreDec); 13494 CanOverflow = isOverflowingIntegerType(Context, resultType); 13495 break; 13496 case UO_AddrOf: 13497 resultType = CheckAddressOfOperand(Input, OpLoc); 13498 CheckAddressOfNoDeref(InputExpr); 13499 RecordModifiableNonNullParam(*this, InputExpr); 13500 break; 13501 case UO_Deref: { 13502 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 13503 if (Input.isInvalid()) return ExprError(); 13504 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 13505 break; 13506 } 13507 case UO_Plus: 13508 case UO_Minus: 13509 CanOverflow = Opc == UO_Minus && 13510 isOverflowingIntegerType(Context, Input.get()->getType()); 13511 Input = UsualUnaryConversions(Input.get()); 13512 if (Input.isInvalid()) return ExprError(); 13513 // Unary plus and minus require promoting an operand of half vector to a 13514 // float vector and truncating the result back to a half vector. For now, we 13515 // do this only when HalfArgsAndReturns is set (that is, when the target is 13516 // arm or arm64). 13517 ConvertHalfVec = 13518 needsConversionOfHalfVec(true, Context, Input.get()->getType()); 13519 13520 // If the operand is a half vector, promote it to a float vector. 13521 if (ConvertHalfVec) 13522 Input = convertVector(Input.get(), Context.FloatTy, *this); 13523 resultType = Input.get()->getType(); 13524 if (resultType->isDependentType()) 13525 break; 13526 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 13527 break; 13528 else if (resultType->isVectorType() && 13529 // The z vector extensions don't allow + or - with bool vectors. 13530 (!Context.getLangOpts().ZVector || 13531 resultType->castAs<VectorType>()->getVectorKind() != 13532 VectorType::AltiVecBool)) 13533 break; 13534 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 13535 Opc == UO_Plus && 13536 resultType->isPointerType()) 13537 break; 13538 13539 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13540 << resultType << Input.get()->getSourceRange()); 13541 13542 case UO_Not: // bitwise complement 13543 Input = UsualUnaryConversions(Input.get()); 13544 if (Input.isInvalid()) 13545 return ExprError(); 13546 resultType = Input.get()->getType(); 13547 if (resultType->isDependentType()) 13548 break; 13549 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 13550 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 13551 // C99 does not support '~' for complex conjugation. 13552 Diag(OpLoc, diag::ext_integer_complement_complex) 13553 << resultType << Input.get()->getSourceRange(); 13554 else if (resultType->hasIntegerRepresentation()) 13555 break; 13556 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 13557 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 13558 // on vector float types. 13559 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 13560 if (!T->isIntegerType()) 13561 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13562 << resultType << Input.get()->getSourceRange()); 13563 } else { 13564 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13565 << resultType << Input.get()->getSourceRange()); 13566 } 13567 break; 13568 13569 case UO_LNot: // logical negation 13570 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 13571 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 13572 if (Input.isInvalid()) return ExprError(); 13573 resultType = Input.get()->getType(); 13574 13575 // Though we still have to promote half FP to float... 13576 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 13577 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 13578 resultType = Context.FloatTy; 13579 } 13580 13581 if (resultType->isDependentType()) 13582 break; 13583 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 13584 // C99 6.5.3.3p1: ok, fallthrough; 13585 if (Context.getLangOpts().CPlusPlus) { 13586 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 13587 // operand contextually converted to bool. 13588 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 13589 ScalarTypeToBooleanCastKind(resultType)); 13590 } else if (Context.getLangOpts().OpenCL && 13591 Context.getLangOpts().OpenCLVersion < 120) { 13592 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 13593 // operate on scalar float types. 13594 if (!resultType->isIntegerType() && !resultType->isPointerType()) 13595 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13596 << resultType << Input.get()->getSourceRange()); 13597 } 13598 } else if (resultType->isExtVectorType()) { 13599 if (Context.getLangOpts().OpenCL && 13600 Context.getLangOpts().OpenCLVersion < 120 && 13601 !Context.getLangOpts().OpenCLCPlusPlus) { 13602 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 13603 // operate on vector float types. 13604 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 13605 if (!T->isIntegerType()) 13606 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13607 << resultType << Input.get()->getSourceRange()); 13608 } 13609 // Vector logical not returns the signed variant of the operand type. 13610 resultType = GetSignedVectorType(resultType); 13611 break; 13612 } else { 13613 // FIXME: GCC's vector extension permits the usage of '!' with a vector 13614 // type in C++. We should allow that here too. 13615 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13616 << resultType << Input.get()->getSourceRange()); 13617 } 13618 13619 // LNot always has type int. C99 6.5.3.3p5. 13620 // In C++, it's bool. C++ 5.3.1p8 13621 resultType = Context.getLogicalOperationType(); 13622 break; 13623 case UO_Real: 13624 case UO_Imag: 13625 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 13626 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 13627 // complex l-values to ordinary l-values and all other values to r-values. 13628 if (Input.isInvalid()) return ExprError(); 13629 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 13630 if (Input.get()->getValueKind() != VK_RValue && 13631 Input.get()->getObjectKind() == OK_Ordinary) 13632 VK = Input.get()->getValueKind(); 13633 } else if (!getLangOpts().CPlusPlus) { 13634 // In C, a volatile scalar is read by __imag. In C++, it is not. 13635 Input = DefaultLvalueConversion(Input.get()); 13636 } 13637 break; 13638 case UO_Extension: 13639 resultType = Input.get()->getType(); 13640 VK = Input.get()->getValueKind(); 13641 OK = Input.get()->getObjectKind(); 13642 break; 13643 case UO_Coawait: 13644 // It's unnecessary to represent the pass-through operator co_await in the 13645 // AST; just return the input expression instead. 13646 assert(!Input.get()->getType()->isDependentType() && 13647 "the co_await expression must be non-dependant before " 13648 "building operator co_await"); 13649 return Input; 13650 } 13651 if (resultType.isNull() || Input.isInvalid()) 13652 return ExprError(); 13653 13654 // Check for array bounds violations in the operand of the UnaryOperator, 13655 // except for the '*' and '&' operators that have to be handled specially 13656 // by CheckArrayAccess (as there are special cases like &array[arraysize] 13657 // that are explicitly defined as valid by the standard). 13658 if (Opc != UO_AddrOf && Opc != UO_Deref) 13659 CheckArrayAccess(Input.get()); 13660 13661 auto *UO = new (Context) 13662 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow); 13663 13664 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 13665 !isa<ArrayType>(UO->getType().getDesugaredType(Context))) 13666 ExprEvalContexts.back().PossibleDerefs.insert(UO); 13667 13668 // Convert the result back to a half vector. 13669 if (ConvertHalfVec) 13670 return convertVector(UO, Context.HalfTy, *this); 13671 return UO; 13672 } 13673 13674 /// Determine whether the given expression is a qualified member 13675 /// access expression, of a form that could be turned into a pointer to member 13676 /// with the address-of operator. 13677 bool Sema::isQualifiedMemberAccess(Expr *E) { 13678 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13679 if (!DRE->getQualifier()) 13680 return false; 13681 13682 ValueDecl *VD = DRE->getDecl(); 13683 if (!VD->isCXXClassMember()) 13684 return false; 13685 13686 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 13687 return true; 13688 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 13689 return Method->isInstance(); 13690 13691 return false; 13692 } 13693 13694 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 13695 if (!ULE->getQualifier()) 13696 return false; 13697 13698 for (NamedDecl *D : ULE->decls()) { 13699 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 13700 if (Method->isInstance()) 13701 return true; 13702 } else { 13703 // Overload set does not contain methods. 13704 break; 13705 } 13706 } 13707 13708 return false; 13709 } 13710 13711 return false; 13712 } 13713 13714 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 13715 UnaryOperatorKind Opc, Expr *Input) { 13716 // First things first: handle placeholders so that the 13717 // overloaded-operator check considers the right type. 13718 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 13719 // Increment and decrement of pseudo-object references. 13720 if (pty->getKind() == BuiltinType::PseudoObject && 13721 UnaryOperator::isIncrementDecrementOp(Opc)) 13722 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 13723 13724 // extension is always a builtin operator. 13725 if (Opc == UO_Extension) 13726 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13727 13728 // & gets special logic for several kinds of placeholder. 13729 // The builtin code knows what to do. 13730 if (Opc == UO_AddrOf && 13731 (pty->getKind() == BuiltinType::Overload || 13732 pty->getKind() == BuiltinType::UnknownAny || 13733 pty->getKind() == BuiltinType::BoundMember)) 13734 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13735 13736 // Anything else needs to be handled now. 13737 ExprResult Result = CheckPlaceholderExpr(Input); 13738 if (Result.isInvalid()) return ExprError(); 13739 Input = Result.get(); 13740 } 13741 13742 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 13743 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 13744 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 13745 // Find all of the overloaded operators visible from this 13746 // point. We perform both an operator-name lookup from the local 13747 // scope and an argument-dependent lookup based on the types of 13748 // the arguments. 13749 UnresolvedSet<16> Functions; 13750 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 13751 if (S && OverOp != OO_None) 13752 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 13753 Functions); 13754 13755 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 13756 } 13757 13758 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13759 } 13760 13761 // Unary Operators. 'Tok' is the token for the operator. 13762 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 13763 tok::TokenKind Op, Expr *Input) { 13764 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 13765 } 13766 13767 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 13768 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 13769 LabelDecl *TheDecl) { 13770 TheDecl->markUsed(Context); 13771 // Create the AST node. The address of a label always has type 'void*'. 13772 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 13773 Context.getPointerType(Context.VoidTy)); 13774 } 13775 13776 void Sema::ActOnStartStmtExpr() { 13777 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 13778 } 13779 13780 void Sema::ActOnStmtExprError() { 13781 // Note that function is also called by TreeTransform when leaving a 13782 // StmtExpr scope without rebuilding anything. 13783 13784 DiscardCleanupsInEvaluationContext(); 13785 PopExpressionEvaluationContext(); 13786 } 13787 13788 ExprResult 13789 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 13790 SourceLocation RPLoc) { // "({..})" 13791 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 13792 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 13793 13794 if (hasAnyUnrecoverableErrorsInThisFunction()) 13795 DiscardCleanupsInEvaluationContext(); 13796 assert(!Cleanup.exprNeedsCleanups() && 13797 "cleanups within StmtExpr not correctly bound!"); 13798 PopExpressionEvaluationContext(); 13799 13800 // FIXME: there are a variety of strange constraints to enforce here, for 13801 // example, it is not possible to goto into a stmt expression apparently. 13802 // More semantic analysis is needed. 13803 13804 // If there are sub-stmts in the compound stmt, take the type of the last one 13805 // as the type of the stmtexpr. 13806 QualType Ty = Context.VoidTy; 13807 bool StmtExprMayBindToTemp = false; 13808 if (!Compound->body_empty()) { 13809 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 13810 if (const auto *LastStmt = 13811 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 13812 if (const Expr *Value = LastStmt->getExprStmt()) { 13813 StmtExprMayBindToTemp = true; 13814 Ty = Value->getType(); 13815 } 13816 } 13817 } 13818 13819 // FIXME: Check that expression type is complete/non-abstract; statement 13820 // expressions are not lvalues. 13821 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 13822 if (StmtExprMayBindToTemp) 13823 return MaybeBindToTemporary(ResStmtExpr); 13824 return ResStmtExpr; 13825 } 13826 13827 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 13828 if (ER.isInvalid()) 13829 return ExprError(); 13830 13831 // Do function/array conversion on the last expression, but not 13832 // lvalue-to-rvalue. However, initialize an unqualified type. 13833 ER = DefaultFunctionArrayConversion(ER.get()); 13834 if (ER.isInvalid()) 13835 return ExprError(); 13836 Expr *E = ER.get(); 13837 13838 if (E->isTypeDependent()) 13839 return E; 13840 13841 // In ARC, if the final expression ends in a consume, splice 13842 // the consume out and bind it later. In the alternate case 13843 // (when dealing with a retainable type), the result 13844 // initialization will create a produce. In both cases the 13845 // result will be +1, and we'll need to balance that out with 13846 // a bind. 13847 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 13848 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 13849 return Cast->getSubExpr(); 13850 13851 // FIXME: Provide a better location for the initialization. 13852 return PerformCopyInitialization( 13853 InitializedEntity::InitializeStmtExprResult( 13854 E->getBeginLoc(), E->getType().getUnqualifiedType()), 13855 SourceLocation(), E); 13856 } 13857 13858 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 13859 TypeSourceInfo *TInfo, 13860 ArrayRef<OffsetOfComponent> Components, 13861 SourceLocation RParenLoc) { 13862 QualType ArgTy = TInfo->getType(); 13863 bool Dependent = ArgTy->isDependentType(); 13864 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 13865 13866 // We must have at least one component that refers to the type, and the first 13867 // one is known to be a field designator. Verify that the ArgTy represents 13868 // a struct/union/class. 13869 if (!Dependent && !ArgTy->isRecordType()) 13870 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 13871 << ArgTy << TypeRange); 13872 13873 // Type must be complete per C99 7.17p3 because a declaring a variable 13874 // with an incomplete type would be ill-formed. 13875 if (!Dependent 13876 && RequireCompleteType(BuiltinLoc, ArgTy, 13877 diag::err_offsetof_incomplete_type, TypeRange)) 13878 return ExprError(); 13879 13880 bool DidWarnAboutNonPOD = false; 13881 QualType CurrentType = ArgTy; 13882 SmallVector<OffsetOfNode, 4> Comps; 13883 SmallVector<Expr*, 4> Exprs; 13884 for (const OffsetOfComponent &OC : Components) { 13885 if (OC.isBrackets) { 13886 // Offset of an array sub-field. TODO: Should we allow vector elements? 13887 if (!CurrentType->isDependentType()) { 13888 const ArrayType *AT = Context.getAsArrayType(CurrentType); 13889 if(!AT) 13890 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 13891 << CurrentType); 13892 CurrentType = AT->getElementType(); 13893 } else 13894 CurrentType = Context.DependentTy; 13895 13896 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 13897 if (IdxRval.isInvalid()) 13898 return ExprError(); 13899 Expr *Idx = IdxRval.get(); 13900 13901 // The expression must be an integral expression. 13902 // FIXME: An integral constant expression? 13903 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 13904 !Idx->getType()->isIntegerType()) 13905 return ExprError( 13906 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 13907 << Idx->getSourceRange()); 13908 13909 // Record this array index. 13910 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 13911 Exprs.push_back(Idx); 13912 continue; 13913 } 13914 13915 // Offset of a field. 13916 if (CurrentType->isDependentType()) { 13917 // We have the offset of a field, but we can't look into the dependent 13918 // type. Just record the identifier of the field. 13919 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 13920 CurrentType = Context.DependentTy; 13921 continue; 13922 } 13923 13924 // We need to have a complete type to look into. 13925 if (RequireCompleteType(OC.LocStart, CurrentType, 13926 diag::err_offsetof_incomplete_type)) 13927 return ExprError(); 13928 13929 // Look for the designated field. 13930 const RecordType *RC = CurrentType->getAs<RecordType>(); 13931 if (!RC) 13932 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 13933 << CurrentType); 13934 RecordDecl *RD = RC->getDecl(); 13935 13936 // C++ [lib.support.types]p5: 13937 // The macro offsetof accepts a restricted set of type arguments in this 13938 // International Standard. type shall be a POD structure or a POD union 13939 // (clause 9). 13940 // C++11 [support.types]p4: 13941 // If type is not a standard-layout class (Clause 9), the results are 13942 // undefined. 13943 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 13944 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 13945 unsigned DiagID = 13946 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 13947 : diag::ext_offsetof_non_pod_type; 13948 13949 if (!IsSafe && !DidWarnAboutNonPOD && 13950 DiagRuntimeBehavior(BuiltinLoc, nullptr, 13951 PDiag(DiagID) 13952 << SourceRange(Components[0].LocStart, OC.LocEnd) 13953 << CurrentType)) 13954 DidWarnAboutNonPOD = true; 13955 } 13956 13957 // Look for the field. 13958 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 13959 LookupQualifiedName(R, RD); 13960 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 13961 IndirectFieldDecl *IndirectMemberDecl = nullptr; 13962 if (!MemberDecl) { 13963 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 13964 MemberDecl = IndirectMemberDecl->getAnonField(); 13965 } 13966 13967 if (!MemberDecl) 13968 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 13969 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 13970 OC.LocEnd)); 13971 13972 // C99 7.17p3: 13973 // (If the specified member is a bit-field, the behavior is undefined.) 13974 // 13975 // We diagnose this as an error. 13976 if (MemberDecl->isBitField()) { 13977 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 13978 << MemberDecl->getDeclName() 13979 << SourceRange(BuiltinLoc, RParenLoc); 13980 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 13981 return ExprError(); 13982 } 13983 13984 RecordDecl *Parent = MemberDecl->getParent(); 13985 if (IndirectMemberDecl) 13986 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 13987 13988 // If the member was found in a base class, introduce OffsetOfNodes for 13989 // the base class indirections. 13990 CXXBasePaths Paths; 13991 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 13992 Paths)) { 13993 if (Paths.getDetectedVirtual()) { 13994 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 13995 << MemberDecl->getDeclName() 13996 << SourceRange(BuiltinLoc, RParenLoc); 13997 return ExprError(); 13998 } 13999 14000 CXXBasePath &Path = Paths.front(); 14001 for (const CXXBasePathElement &B : Path) 14002 Comps.push_back(OffsetOfNode(B.Base)); 14003 } 14004 14005 if (IndirectMemberDecl) { 14006 for (auto *FI : IndirectMemberDecl->chain()) { 14007 assert(isa<FieldDecl>(FI)); 14008 Comps.push_back(OffsetOfNode(OC.LocStart, 14009 cast<FieldDecl>(FI), OC.LocEnd)); 14010 } 14011 } else 14012 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 14013 14014 CurrentType = MemberDecl->getType().getNonReferenceType(); 14015 } 14016 14017 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 14018 Comps, Exprs, RParenLoc); 14019 } 14020 14021 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 14022 SourceLocation BuiltinLoc, 14023 SourceLocation TypeLoc, 14024 ParsedType ParsedArgTy, 14025 ArrayRef<OffsetOfComponent> Components, 14026 SourceLocation RParenLoc) { 14027 14028 TypeSourceInfo *ArgTInfo; 14029 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 14030 if (ArgTy.isNull()) 14031 return ExprError(); 14032 14033 if (!ArgTInfo) 14034 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 14035 14036 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 14037 } 14038 14039 14040 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 14041 Expr *CondExpr, 14042 Expr *LHSExpr, Expr *RHSExpr, 14043 SourceLocation RPLoc) { 14044 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 14045 14046 ExprValueKind VK = VK_RValue; 14047 ExprObjectKind OK = OK_Ordinary; 14048 QualType resType; 14049 bool ValueDependent = false; 14050 bool CondIsTrue = false; 14051 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 14052 resType = Context.DependentTy; 14053 ValueDependent = true; 14054 } else { 14055 // The conditional expression is required to be a constant expression. 14056 llvm::APSInt condEval(32); 14057 ExprResult CondICE 14058 = VerifyIntegerConstantExpression(CondExpr, &condEval, 14059 diag::err_typecheck_choose_expr_requires_constant, false); 14060 if (CondICE.isInvalid()) 14061 return ExprError(); 14062 CondExpr = CondICE.get(); 14063 CondIsTrue = condEval.getZExtValue(); 14064 14065 // If the condition is > zero, then the AST type is the same as the LHSExpr. 14066 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 14067 14068 resType = ActiveExpr->getType(); 14069 ValueDependent = ActiveExpr->isValueDependent(); 14070 VK = ActiveExpr->getValueKind(); 14071 OK = ActiveExpr->getObjectKind(); 14072 } 14073 14074 return new (Context) 14075 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 14076 CondIsTrue, resType->isDependentType(), ValueDependent); 14077 } 14078 14079 //===----------------------------------------------------------------------===// 14080 // Clang Extensions. 14081 //===----------------------------------------------------------------------===// 14082 14083 /// ActOnBlockStart - This callback is invoked when a block literal is started. 14084 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 14085 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 14086 14087 if (LangOpts.CPlusPlus) { 14088 MangleNumberingContext *MCtx; 14089 Decl *ManglingContextDecl; 14090 std::tie(MCtx, ManglingContextDecl) = 14091 getCurrentMangleNumberContext(Block->getDeclContext()); 14092 if (MCtx) { 14093 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 14094 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 14095 } 14096 } 14097 14098 PushBlockScope(CurScope, Block); 14099 CurContext->addDecl(Block); 14100 if (CurScope) 14101 PushDeclContext(CurScope, Block); 14102 else 14103 CurContext = Block; 14104 14105 getCurBlock()->HasImplicitReturnType = true; 14106 14107 // Enter a new evaluation context to insulate the block from any 14108 // cleanups from the enclosing full-expression. 14109 PushExpressionEvaluationContext( 14110 ExpressionEvaluationContext::PotentiallyEvaluated); 14111 } 14112 14113 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 14114 Scope *CurScope) { 14115 assert(ParamInfo.getIdentifier() == nullptr && 14116 "block-id should have no identifier!"); 14117 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext); 14118 BlockScopeInfo *CurBlock = getCurBlock(); 14119 14120 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 14121 QualType T = Sig->getType(); 14122 14123 // FIXME: We should allow unexpanded parameter packs here, but that would, 14124 // in turn, make the block expression contain unexpanded parameter packs. 14125 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 14126 // Drop the parameters. 14127 FunctionProtoType::ExtProtoInfo EPI; 14128 EPI.HasTrailingReturn = false; 14129 EPI.TypeQuals.addConst(); 14130 T = Context.getFunctionType(Context.DependentTy, None, EPI); 14131 Sig = Context.getTrivialTypeSourceInfo(T); 14132 } 14133 14134 // GetTypeForDeclarator always produces a function type for a block 14135 // literal signature. Furthermore, it is always a FunctionProtoType 14136 // unless the function was written with a typedef. 14137 assert(T->isFunctionType() && 14138 "GetTypeForDeclarator made a non-function block signature"); 14139 14140 // Look for an explicit signature in that function type. 14141 FunctionProtoTypeLoc ExplicitSignature; 14142 14143 if ((ExplicitSignature = Sig->getTypeLoc() 14144 .getAsAdjusted<FunctionProtoTypeLoc>())) { 14145 14146 // Check whether that explicit signature was synthesized by 14147 // GetTypeForDeclarator. If so, don't save that as part of the 14148 // written signature. 14149 if (ExplicitSignature.getLocalRangeBegin() == 14150 ExplicitSignature.getLocalRangeEnd()) { 14151 // This would be much cheaper if we stored TypeLocs instead of 14152 // TypeSourceInfos. 14153 TypeLoc Result = ExplicitSignature.getReturnLoc(); 14154 unsigned Size = Result.getFullDataSize(); 14155 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 14156 Sig->getTypeLoc().initializeFullCopy(Result, Size); 14157 14158 ExplicitSignature = FunctionProtoTypeLoc(); 14159 } 14160 } 14161 14162 CurBlock->TheDecl->setSignatureAsWritten(Sig); 14163 CurBlock->FunctionType = T; 14164 14165 const FunctionType *Fn = T->getAs<FunctionType>(); 14166 QualType RetTy = Fn->getReturnType(); 14167 bool isVariadic = 14168 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 14169 14170 CurBlock->TheDecl->setIsVariadic(isVariadic); 14171 14172 // Context.DependentTy is used as a placeholder for a missing block 14173 // return type. TODO: what should we do with declarators like: 14174 // ^ * { ... } 14175 // If the answer is "apply template argument deduction".... 14176 if (RetTy != Context.DependentTy) { 14177 CurBlock->ReturnType = RetTy; 14178 CurBlock->TheDecl->setBlockMissingReturnType(false); 14179 CurBlock->HasImplicitReturnType = false; 14180 } 14181 14182 // Push block parameters from the declarator if we had them. 14183 SmallVector<ParmVarDecl*, 8> Params; 14184 if (ExplicitSignature) { 14185 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 14186 ParmVarDecl *Param = ExplicitSignature.getParam(I); 14187 if (Param->getIdentifier() == nullptr && 14188 !Param->isImplicit() && 14189 !Param->isInvalidDecl() && 14190 !getLangOpts().CPlusPlus) 14191 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 14192 Params.push_back(Param); 14193 } 14194 14195 // Fake up parameter variables if we have a typedef, like 14196 // ^ fntype { ... } 14197 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 14198 for (const auto &I : Fn->param_types()) { 14199 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 14200 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 14201 Params.push_back(Param); 14202 } 14203 } 14204 14205 // Set the parameters on the block decl. 14206 if (!Params.empty()) { 14207 CurBlock->TheDecl->setParams(Params); 14208 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 14209 /*CheckParameterNames=*/false); 14210 } 14211 14212 // Finally we can process decl attributes. 14213 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 14214 14215 // Put the parameter variables in scope. 14216 for (auto AI : CurBlock->TheDecl->parameters()) { 14217 AI->setOwningFunction(CurBlock->TheDecl); 14218 14219 // If this has an identifier, add it to the scope stack. 14220 if (AI->getIdentifier()) { 14221 CheckShadow(CurBlock->TheScope, AI); 14222 14223 PushOnScopeChains(AI, CurBlock->TheScope); 14224 } 14225 } 14226 } 14227 14228 /// ActOnBlockError - If there is an error parsing a block, this callback 14229 /// is invoked to pop the information about the block from the action impl. 14230 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 14231 // Leave the expression-evaluation context. 14232 DiscardCleanupsInEvaluationContext(); 14233 PopExpressionEvaluationContext(); 14234 14235 // Pop off CurBlock, handle nested blocks. 14236 PopDeclContext(); 14237 PopFunctionScopeInfo(); 14238 } 14239 14240 /// ActOnBlockStmtExpr - This is called when the body of a block statement 14241 /// literal was successfully completed. ^(int x){...} 14242 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 14243 Stmt *Body, Scope *CurScope) { 14244 // If blocks are disabled, emit an error. 14245 if (!LangOpts.Blocks) 14246 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 14247 14248 // Leave the expression-evaluation context. 14249 if (hasAnyUnrecoverableErrorsInThisFunction()) 14250 DiscardCleanupsInEvaluationContext(); 14251 assert(!Cleanup.exprNeedsCleanups() && 14252 "cleanups within block not correctly bound!"); 14253 PopExpressionEvaluationContext(); 14254 14255 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 14256 BlockDecl *BD = BSI->TheDecl; 14257 14258 if (BSI->HasImplicitReturnType) 14259 deduceClosureReturnType(*BSI); 14260 14261 QualType RetTy = Context.VoidTy; 14262 if (!BSI->ReturnType.isNull()) 14263 RetTy = BSI->ReturnType; 14264 14265 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 14266 QualType BlockTy; 14267 14268 // If the user wrote a function type in some form, try to use that. 14269 if (!BSI->FunctionType.isNull()) { 14270 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 14271 14272 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 14273 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 14274 14275 // Turn protoless block types into nullary block types. 14276 if (isa<FunctionNoProtoType>(FTy)) { 14277 FunctionProtoType::ExtProtoInfo EPI; 14278 EPI.ExtInfo = Ext; 14279 BlockTy = Context.getFunctionType(RetTy, None, EPI); 14280 14281 // Otherwise, if we don't need to change anything about the function type, 14282 // preserve its sugar structure. 14283 } else if (FTy->getReturnType() == RetTy && 14284 (!NoReturn || FTy->getNoReturnAttr())) { 14285 BlockTy = BSI->FunctionType; 14286 14287 // Otherwise, make the minimal modifications to the function type. 14288 } else { 14289 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 14290 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 14291 EPI.TypeQuals = Qualifiers(); 14292 EPI.ExtInfo = Ext; 14293 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 14294 } 14295 14296 // If we don't have a function type, just build one from nothing. 14297 } else { 14298 FunctionProtoType::ExtProtoInfo EPI; 14299 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 14300 BlockTy = Context.getFunctionType(RetTy, None, EPI); 14301 } 14302 14303 DiagnoseUnusedParameters(BD->parameters()); 14304 BlockTy = Context.getBlockPointerType(BlockTy); 14305 14306 // If needed, diagnose invalid gotos and switches in the block. 14307 if (getCurFunction()->NeedsScopeChecking() && 14308 !PP.isCodeCompletionEnabled()) 14309 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 14310 14311 BD->setBody(cast<CompoundStmt>(Body)); 14312 14313 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 14314 DiagnoseUnguardedAvailabilityViolations(BD); 14315 14316 // Try to apply the named return value optimization. We have to check again 14317 // if we can do this, though, because blocks keep return statements around 14318 // to deduce an implicit return type. 14319 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 14320 !BD->isDependentContext()) 14321 computeNRVO(Body, BSI); 14322 14323 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 14324 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 14325 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 14326 NTCUK_Destruct|NTCUK_Copy); 14327 14328 PopDeclContext(); 14329 14330 // Pop the block scope now but keep it alive to the end of this function. 14331 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14332 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 14333 14334 // Set the captured variables on the block. 14335 SmallVector<BlockDecl::Capture, 4> Captures; 14336 for (Capture &Cap : BSI->Captures) { 14337 if (Cap.isInvalid() || Cap.isThisCapture()) 14338 continue; 14339 14340 VarDecl *Var = Cap.getVariable(); 14341 Expr *CopyExpr = nullptr; 14342 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 14343 if (const RecordType *Record = 14344 Cap.getCaptureType()->getAs<RecordType>()) { 14345 // The capture logic needs the destructor, so make sure we mark it. 14346 // Usually this is unnecessary because most local variables have 14347 // their destructors marked at declaration time, but parameters are 14348 // an exception because it's technically only the call site that 14349 // actually requires the destructor. 14350 if (isa<ParmVarDecl>(Var)) 14351 FinalizeVarWithDestructor(Var, Record); 14352 14353 // Enter a separate potentially-evaluated context while building block 14354 // initializers to isolate their cleanups from those of the block 14355 // itself. 14356 // FIXME: Is this appropriate even when the block itself occurs in an 14357 // unevaluated operand? 14358 EnterExpressionEvaluationContext EvalContext( 14359 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 14360 14361 SourceLocation Loc = Cap.getLocation(); 14362 14363 ExprResult Result = BuildDeclarationNameExpr( 14364 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 14365 14366 // According to the blocks spec, the capture of a variable from 14367 // the stack requires a const copy constructor. This is not true 14368 // of the copy/move done to move a __block variable to the heap. 14369 if (!Result.isInvalid() && 14370 !Result.get()->getType().isConstQualified()) { 14371 Result = ImpCastExprToType(Result.get(), 14372 Result.get()->getType().withConst(), 14373 CK_NoOp, VK_LValue); 14374 } 14375 14376 if (!Result.isInvalid()) { 14377 Result = PerformCopyInitialization( 14378 InitializedEntity::InitializeBlock(Var->getLocation(), 14379 Cap.getCaptureType(), false), 14380 Loc, Result.get()); 14381 } 14382 14383 // Build a full-expression copy expression if initialization 14384 // succeeded and used a non-trivial constructor. Recover from 14385 // errors by pretending that the copy isn't necessary. 14386 if (!Result.isInvalid() && 14387 !cast<CXXConstructExpr>(Result.get())->getConstructor() 14388 ->isTrivial()) { 14389 Result = MaybeCreateExprWithCleanups(Result); 14390 CopyExpr = Result.get(); 14391 } 14392 } 14393 } 14394 14395 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 14396 CopyExpr); 14397 Captures.push_back(NewCap); 14398 } 14399 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 14400 14401 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 14402 14403 // If the block isn't obviously global, i.e. it captures anything at 14404 // all, then we need to do a few things in the surrounding context: 14405 if (Result->getBlockDecl()->hasCaptures()) { 14406 // First, this expression has a new cleanup object. 14407 ExprCleanupObjects.push_back(Result->getBlockDecl()); 14408 Cleanup.setExprNeedsCleanups(true); 14409 14410 // It also gets a branch-protected scope if any of the captured 14411 // variables needs destruction. 14412 for (const auto &CI : Result->getBlockDecl()->captures()) { 14413 const VarDecl *var = CI.getVariable(); 14414 if (var->getType().isDestructedType() != QualType::DK_none) { 14415 setFunctionHasBranchProtectedScope(); 14416 break; 14417 } 14418 } 14419 } 14420 14421 if (getCurFunction()) 14422 getCurFunction()->addBlock(BD); 14423 14424 return Result; 14425 } 14426 14427 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 14428 SourceLocation RPLoc) { 14429 TypeSourceInfo *TInfo; 14430 GetTypeFromParser(Ty, &TInfo); 14431 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 14432 } 14433 14434 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 14435 Expr *E, TypeSourceInfo *TInfo, 14436 SourceLocation RPLoc) { 14437 Expr *OrigExpr = E; 14438 bool IsMS = false; 14439 14440 // CUDA device code does not support varargs. 14441 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 14442 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 14443 CUDAFunctionTarget T = IdentifyCUDATarget(F); 14444 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 14445 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 14446 } 14447 } 14448 14449 // NVPTX does not support va_arg expression. 14450 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 14451 Context.getTargetInfo().getTriple().isNVPTX()) 14452 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 14453 14454 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 14455 // as Microsoft ABI on an actual Microsoft platform, where 14456 // __builtin_ms_va_list and __builtin_va_list are the same.) 14457 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 14458 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 14459 QualType MSVaListType = Context.getBuiltinMSVaListType(); 14460 if (Context.hasSameType(MSVaListType, E->getType())) { 14461 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 14462 return ExprError(); 14463 IsMS = true; 14464 } 14465 } 14466 14467 // Get the va_list type 14468 QualType VaListType = Context.getBuiltinVaListType(); 14469 if (!IsMS) { 14470 if (VaListType->isArrayType()) { 14471 // Deal with implicit array decay; for example, on x86-64, 14472 // va_list is an array, but it's supposed to decay to 14473 // a pointer for va_arg. 14474 VaListType = Context.getArrayDecayedType(VaListType); 14475 // Make sure the input expression also decays appropriately. 14476 ExprResult Result = UsualUnaryConversions(E); 14477 if (Result.isInvalid()) 14478 return ExprError(); 14479 E = Result.get(); 14480 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 14481 // If va_list is a record type and we are compiling in C++ mode, 14482 // check the argument using reference binding. 14483 InitializedEntity Entity = InitializedEntity::InitializeParameter( 14484 Context, Context.getLValueReferenceType(VaListType), false); 14485 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 14486 if (Init.isInvalid()) 14487 return ExprError(); 14488 E = Init.getAs<Expr>(); 14489 } else { 14490 // Otherwise, the va_list argument must be an l-value because 14491 // it is modified by va_arg. 14492 if (!E->isTypeDependent() && 14493 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 14494 return ExprError(); 14495 } 14496 } 14497 14498 if (!IsMS && !E->isTypeDependent() && 14499 !Context.hasSameType(VaListType, E->getType())) 14500 return ExprError( 14501 Diag(E->getBeginLoc(), 14502 diag::err_first_argument_to_va_arg_not_of_type_va_list) 14503 << OrigExpr->getType() << E->getSourceRange()); 14504 14505 if (!TInfo->getType()->isDependentType()) { 14506 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 14507 diag::err_second_parameter_to_va_arg_incomplete, 14508 TInfo->getTypeLoc())) 14509 return ExprError(); 14510 14511 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 14512 TInfo->getType(), 14513 diag::err_second_parameter_to_va_arg_abstract, 14514 TInfo->getTypeLoc())) 14515 return ExprError(); 14516 14517 if (!TInfo->getType().isPODType(Context)) { 14518 Diag(TInfo->getTypeLoc().getBeginLoc(), 14519 TInfo->getType()->isObjCLifetimeType() 14520 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 14521 : diag::warn_second_parameter_to_va_arg_not_pod) 14522 << TInfo->getType() 14523 << TInfo->getTypeLoc().getSourceRange(); 14524 } 14525 14526 // Check for va_arg where arguments of the given type will be promoted 14527 // (i.e. this va_arg is guaranteed to have undefined behavior). 14528 QualType PromoteType; 14529 if (TInfo->getType()->isPromotableIntegerType()) { 14530 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 14531 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 14532 PromoteType = QualType(); 14533 } 14534 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 14535 PromoteType = Context.DoubleTy; 14536 if (!PromoteType.isNull()) 14537 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 14538 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 14539 << TInfo->getType() 14540 << PromoteType 14541 << TInfo->getTypeLoc().getSourceRange()); 14542 } 14543 14544 QualType T = TInfo->getType().getNonLValueExprType(Context); 14545 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 14546 } 14547 14548 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 14549 // The type of __null will be int or long, depending on the size of 14550 // pointers on the target. 14551 QualType Ty; 14552 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 14553 if (pw == Context.getTargetInfo().getIntWidth()) 14554 Ty = Context.IntTy; 14555 else if (pw == Context.getTargetInfo().getLongWidth()) 14556 Ty = Context.LongTy; 14557 else if (pw == Context.getTargetInfo().getLongLongWidth()) 14558 Ty = Context.LongLongTy; 14559 else { 14560 llvm_unreachable("I don't know size of pointer!"); 14561 } 14562 14563 return new (Context) GNUNullExpr(Ty, TokenLoc); 14564 } 14565 14566 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 14567 SourceLocation BuiltinLoc, 14568 SourceLocation RPLoc) { 14569 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); 14570 } 14571 14572 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 14573 SourceLocation BuiltinLoc, 14574 SourceLocation RPLoc, 14575 DeclContext *ParentContext) { 14576 return new (Context) 14577 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); 14578 } 14579 14580 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 14581 bool Diagnose) { 14582 if (!getLangOpts().ObjC) 14583 return false; 14584 14585 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 14586 if (!PT) 14587 return false; 14588 14589 if (!PT->isObjCIdType()) { 14590 // Check if the destination is the 'NSString' interface. 14591 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 14592 if (!ID || !ID->getIdentifier()->isStr("NSString")) 14593 return false; 14594 } 14595 14596 // Ignore any parens, implicit casts (should only be 14597 // array-to-pointer decays), and not-so-opaque values. The last is 14598 // important for making this trigger for property assignments. 14599 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 14600 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 14601 if (OV->getSourceExpr()) 14602 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 14603 14604 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 14605 if (!SL || !SL->isAscii()) 14606 return false; 14607 if (Diagnose) { 14608 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 14609 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 14610 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 14611 } 14612 return true; 14613 } 14614 14615 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 14616 const Expr *SrcExpr) { 14617 if (!DstType->isFunctionPointerType() || 14618 !SrcExpr->getType()->isFunctionType()) 14619 return false; 14620 14621 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 14622 if (!DRE) 14623 return false; 14624 14625 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 14626 if (!FD) 14627 return false; 14628 14629 return !S.checkAddressOfFunctionIsAvailable(FD, 14630 /*Complain=*/true, 14631 SrcExpr->getBeginLoc()); 14632 } 14633 14634 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 14635 SourceLocation Loc, 14636 QualType DstType, QualType SrcType, 14637 Expr *SrcExpr, AssignmentAction Action, 14638 bool *Complained) { 14639 if (Complained) 14640 *Complained = false; 14641 14642 // Decode the result (notice that AST's are still created for extensions). 14643 bool CheckInferredResultType = false; 14644 bool isInvalid = false; 14645 unsigned DiagKind = 0; 14646 FixItHint Hint; 14647 ConversionFixItGenerator ConvHints; 14648 bool MayHaveConvFixit = false; 14649 bool MayHaveFunctionDiff = false; 14650 const ObjCInterfaceDecl *IFace = nullptr; 14651 const ObjCProtocolDecl *PDecl = nullptr; 14652 14653 switch (ConvTy) { 14654 case Compatible: 14655 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 14656 return false; 14657 14658 case PointerToInt: 14659 DiagKind = diag::ext_typecheck_convert_pointer_int; 14660 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14661 MayHaveConvFixit = true; 14662 break; 14663 case IntToPointer: 14664 DiagKind = diag::ext_typecheck_convert_int_pointer; 14665 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14666 MayHaveConvFixit = true; 14667 break; 14668 case IncompatiblePointer: 14669 if (Action == AA_Passing_CFAudited) 14670 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 14671 else if (SrcType->isFunctionPointerType() && 14672 DstType->isFunctionPointerType()) 14673 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 14674 else 14675 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 14676 14677 CheckInferredResultType = DstType->isObjCObjectPointerType() && 14678 SrcType->isObjCObjectPointerType(); 14679 if (Hint.isNull() && !CheckInferredResultType) { 14680 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14681 } 14682 else if (CheckInferredResultType) { 14683 SrcType = SrcType.getUnqualifiedType(); 14684 DstType = DstType.getUnqualifiedType(); 14685 } 14686 MayHaveConvFixit = true; 14687 break; 14688 case IncompatiblePointerSign: 14689 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 14690 break; 14691 case FunctionVoidPointer: 14692 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 14693 break; 14694 case IncompatiblePointerDiscardsQualifiers: { 14695 // Perform array-to-pointer decay if necessary. 14696 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 14697 14698 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 14699 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 14700 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 14701 DiagKind = diag::err_typecheck_incompatible_address_space; 14702 break; 14703 14704 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 14705 DiagKind = diag::err_typecheck_incompatible_ownership; 14706 break; 14707 } 14708 14709 llvm_unreachable("unknown error case for discarding qualifiers!"); 14710 // fallthrough 14711 } 14712 case CompatiblePointerDiscardsQualifiers: 14713 // If the qualifiers lost were because we were applying the 14714 // (deprecated) C++ conversion from a string literal to a char* 14715 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 14716 // Ideally, this check would be performed in 14717 // checkPointerTypesForAssignment. However, that would require a 14718 // bit of refactoring (so that the second argument is an 14719 // expression, rather than a type), which should be done as part 14720 // of a larger effort to fix checkPointerTypesForAssignment for 14721 // C++ semantics. 14722 if (getLangOpts().CPlusPlus && 14723 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 14724 return false; 14725 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 14726 break; 14727 case IncompatibleNestedPointerQualifiers: 14728 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 14729 break; 14730 case IncompatibleNestedPointerAddressSpaceMismatch: 14731 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 14732 break; 14733 case IntToBlockPointer: 14734 DiagKind = diag::err_int_to_block_pointer; 14735 break; 14736 case IncompatibleBlockPointer: 14737 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 14738 break; 14739 case IncompatibleObjCQualifiedId: { 14740 if (SrcType->isObjCQualifiedIdType()) { 14741 const ObjCObjectPointerType *srcOPT = 14742 SrcType->castAs<ObjCObjectPointerType>(); 14743 for (auto *srcProto : srcOPT->quals()) { 14744 PDecl = srcProto; 14745 break; 14746 } 14747 if (const ObjCInterfaceType *IFaceT = 14748 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 14749 IFace = IFaceT->getDecl(); 14750 } 14751 else if (DstType->isObjCQualifiedIdType()) { 14752 const ObjCObjectPointerType *dstOPT = 14753 DstType->castAs<ObjCObjectPointerType>(); 14754 for (auto *dstProto : dstOPT->quals()) { 14755 PDecl = dstProto; 14756 break; 14757 } 14758 if (const ObjCInterfaceType *IFaceT = 14759 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 14760 IFace = IFaceT->getDecl(); 14761 } 14762 DiagKind = diag::warn_incompatible_qualified_id; 14763 break; 14764 } 14765 case IncompatibleVectors: 14766 DiagKind = diag::warn_incompatible_vectors; 14767 break; 14768 case IncompatibleObjCWeakRef: 14769 DiagKind = diag::err_arc_weak_unavailable_assign; 14770 break; 14771 case Incompatible: 14772 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 14773 if (Complained) 14774 *Complained = true; 14775 return true; 14776 } 14777 14778 DiagKind = diag::err_typecheck_convert_incompatible; 14779 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14780 MayHaveConvFixit = true; 14781 isInvalid = true; 14782 MayHaveFunctionDiff = true; 14783 break; 14784 } 14785 14786 QualType FirstType, SecondType; 14787 switch (Action) { 14788 case AA_Assigning: 14789 case AA_Initializing: 14790 // The destination type comes first. 14791 FirstType = DstType; 14792 SecondType = SrcType; 14793 break; 14794 14795 case AA_Returning: 14796 case AA_Passing: 14797 case AA_Passing_CFAudited: 14798 case AA_Converting: 14799 case AA_Sending: 14800 case AA_Casting: 14801 // The source type comes first. 14802 FirstType = SrcType; 14803 SecondType = DstType; 14804 break; 14805 } 14806 14807 PartialDiagnostic FDiag = PDiag(DiagKind); 14808 if (Action == AA_Passing_CFAudited) 14809 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 14810 else 14811 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 14812 14813 // If we can fix the conversion, suggest the FixIts. 14814 assert(ConvHints.isNull() || Hint.isNull()); 14815 if (!ConvHints.isNull()) { 14816 for (FixItHint &H : ConvHints.Hints) 14817 FDiag << H; 14818 } else { 14819 FDiag << Hint; 14820 } 14821 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 14822 14823 if (MayHaveFunctionDiff) 14824 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 14825 14826 Diag(Loc, FDiag); 14827 if (DiagKind == diag::warn_incompatible_qualified_id && 14828 PDecl && IFace && !IFace->hasDefinition()) 14829 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 14830 << IFace << PDecl; 14831 14832 if (SecondType == Context.OverloadTy) 14833 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 14834 FirstType, /*TakingAddress=*/true); 14835 14836 if (CheckInferredResultType) 14837 EmitRelatedResultTypeNote(SrcExpr); 14838 14839 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 14840 EmitRelatedResultTypeNoteForReturn(DstType); 14841 14842 if (Complained) 14843 *Complained = true; 14844 return isInvalid; 14845 } 14846 14847 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 14848 llvm::APSInt *Result) { 14849 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 14850 public: 14851 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 14852 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 14853 } 14854 } Diagnoser; 14855 14856 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 14857 } 14858 14859 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 14860 llvm::APSInt *Result, 14861 unsigned DiagID, 14862 bool AllowFold) { 14863 class IDDiagnoser : public VerifyICEDiagnoser { 14864 unsigned DiagID; 14865 14866 public: 14867 IDDiagnoser(unsigned DiagID) 14868 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 14869 14870 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 14871 S.Diag(Loc, DiagID) << SR; 14872 } 14873 } Diagnoser(DiagID); 14874 14875 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 14876 } 14877 14878 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 14879 SourceRange SR) { 14880 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 14881 } 14882 14883 ExprResult 14884 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 14885 VerifyICEDiagnoser &Diagnoser, 14886 bool AllowFold) { 14887 SourceLocation DiagLoc = E->getBeginLoc(); 14888 14889 if (getLangOpts().CPlusPlus11) { 14890 // C++11 [expr.const]p5: 14891 // If an expression of literal class type is used in a context where an 14892 // integral constant expression is required, then that class type shall 14893 // have a single non-explicit conversion function to an integral or 14894 // unscoped enumeration type 14895 ExprResult Converted; 14896 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 14897 public: 14898 CXX11ConvertDiagnoser(bool Silent) 14899 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 14900 Silent, true) {} 14901 14902 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 14903 QualType T) override { 14904 return S.Diag(Loc, diag::err_ice_not_integral) << T; 14905 } 14906 14907 SemaDiagnosticBuilder diagnoseIncomplete( 14908 Sema &S, SourceLocation Loc, QualType T) override { 14909 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 14910 } 14911 14912 SemaDiagnosticBuilder diagnoseExplicitConv( 14913 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 14914 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 14915 } 14916 14917 SemaDiagnosticBuilder noteExplicitConv( 14918 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 14919 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 14920 << ConvTy->isEnumeralType() << ConvTy; 14921 } 14922 14923 SemaDiagnosticBuilder diagnoseAmbiguous( 14924 Sema &S, SourceLocation Loc, QualType T) override { 14925 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 14926 } 14927 14928 SemaDiagnosticBuilder noteAmbiguous( 14929 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 14930 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 14931 << ConvTy->isEnumeralType() << ConvTy; 14932 } 14933 14934 SemaDiagnosticBuilder diagnoseConversion( 14935 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 14936 llvm_unreachable("conversion functions are permitted"); 14937 } 14938 } ConvertDiagnoser(Diagnoser.Suppress); 14939 14940 Converted = PerformContextualImplicitConversion(DiagLoc, E, 14941 ConvertDiagnoser); 14942 if (Converted.isInvalid()) 14943 return Converted; 14944 E = Converted.get(); 14945 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 14946 return ExprError(); 14947 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 14948 // An ICE must be of integral or unscoped enumeration type. 14949 if (!Diagnoser.Suppress) 14950 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 14951 return ExprError(); 14952 } 14953 14954 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 14955 // in the non-ICE case. 14956 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 14957 if (Result) 14958 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 14959 if (!isa<ConstantExpr>(E)) 14960 E = ConstantExpr::Create(Context, E); 14961 return E; 14962 } 14963 14964 Expr::EvalResult EvalResult; 14965 SmallVector<PartialDiagnosticAt, 8> Notes; 14966 EvalResult.Diag = &Notes; 14967 14968 // Try to evaluate the expression, and produce diagnostics explaining why it's 14969 // not a constant expression as a side-effect. 14970 bool Folded = 14971 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 14972 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 14973 14974 if (!isa<ConstantExpr>(E)) 14975 E = ConstantExpr::Create(Context, E, EvalResult.Val); 14976 14977 // In C++11, we can rely on diagnostics being produced for any expression 14978 // which is not a constant expression. If no diagnostics were produced, then 14979 // this is a constant expression. 14980 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 14981 if (Result) 14982 *Result = EvalResult.Val.getInt(); 14983 return E; 14984 } 14985 14986 // If our only note is the usual "invalid subexpression" note, just point 14987 // the caret at its location rather than producing an essentially 14988 // redundant note. 14989 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 14990 diag::note_invalid_subexpr_in_const_expr) { 14991 DiagLoc = Notes[0].first; 14992 Notes.clear(); 14993 } 14994 14995 if (!Folded || !AllowFold) { 14996 if (!Diagnoser.Suppress) { 14997 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 14998 for (const PartialDiagnosticAt &Note : Notes) 14999 Diag(Note.first, Note.second); 15000 } 15001 15002 return ExprError(); 15003 } 15004 15005 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 15006 for (const PartialDiagnosticAt &Note : Notes) 15007 Diag(Note.first, Note.second); 15008 15009 if (Result) 15010 *Result = EvalResult.Val.getInt(); 15011 return E; 15012 } 15013 15014 namespace { 15015 // Handle the case where we conclude a expression which we speculatively 15016 // considered to be unevaluated is actually evaluated. 15017 class TransformToPE : public TreeTransform<TransformToPE> { 15018 typedef TreeTransform<TransformToPE> BaseTransform; 15019 15020 public: 15021 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 15022 15023 // Make sure we redo semantic analysis 15024 bool AlwaysRebuild() { return true; } 15025 bool ReplacingOriginal() { return true; } 15026 15027 // We need to special-case DeclRefExprs referring to FieldDecls which 15028 // are not part of a member pointer formation; normal TreeTransforming 15029 // doesn't catch this case because of the way we represent them in the AST. 15030 // FIXME: This is a bit ugly; is it really the best way to handle this 15031 // case? 15032 // 15033 // Error on DeclRefExprs referring to FieldDecls. 15034 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 15035 if (isa<FieldDecl>(E->getDecl()) && 15036 !SemaRef.isUnevaluatedContext()) 15037 return SemaRef.Diag(E->getLocation(), 15038 diag::err_invalid_non_static_member_use) 15039 << E->getDecl() << E->getSourceRange(); 15040 15041 return BaseTransform::TransformDeclRefExpr(E); 15042 } 15043 15044 // Exception: filter out member pointer formation 15045 ExprResult TransformUnaryOperator(UnaryOperator *E) { 15046 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 15047 return E; 15048 15049 return BaseTransform::TransformUnaryOperator(E); 15050 } 15051 15052 // The body of a lambda-expression is in a separate expression evaluation 15053 // context so never needs to be transformed. 15054 // FIXME: Ideally we wouldn't transform the closure type either, and would 15055 // just recreate the capture expressions and lambda expression. 15056 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 15057 return SkipLambdaBody(E, Body); 15058 } 15059 }; 15060 } 15061 15062 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 15063 assert(isUnevaluatedContext() && 15064 "Should only transform unevaluated expressions"); 15065 ExprEvalContexts.back().Context = 15066 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 15067 if (isUnevaluatedContext()) 15068 return E; 15069 return TransformToPE(*this).TransformExpr(E); 15070 } 15071 15072 void 15073 Sema::PushExpressionEvaluationContext( 15074 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 15075 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 15076 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 15077 LambdaContextDecl, ExprContext); 15078 Cleanup.reset(); 15079 if (!MaybeODRUseExprs.empty()) 15080 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 15081 } 15082 15083 void 15084 Sema::PushExpressionEvaluationContext( 15085 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 15086 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 15087 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 15088 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 15089 } 15090 15091 namespace { 15092 15093 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 15094 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 15095 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 15096 if (E->getOpcode() == UO_Deref) 15097 return CheckPossibleDeref(S, E->getSubExpr()); 15098 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 15099 return CheckPossibleDeref(S, E->getBase()); 15100 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 15101 return CheckPossibleDeref(S, E->getBase()); 15102 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 15103 QualType Inner; 15104 QualType Ty = E->getType(); 15105 if (const auto *Ptr = Ty->getAs<PointerType>()) 15106 Inner = Ptr->getPointeeType(); 15107 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 15108 Inner = Arr->getElementType(); 15109 else 15110 return nullptr; 15111 15112 if (Inner->hasAttr(attr::NoDeref)) 15113 return E; 15114 } 15115 return nullptr; 15116 } 15117 15118 } // namespace 15119 15120 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 15121 for (const Expr *E : Rec.PossibleDerefs) { 15122 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 15123 if (DeclRef) { 15124 const ValueDecl *Decl = DeclRef->getDecl(); 15125 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 15126 << Decl->getName() << E->getSourceRange(); 15127 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 15128 } else { 15129 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 15130 << E->getSourceRange(); 15131 } 15132 } 15133 Rec.PossibleDerefs.clear(); 15134 } 15135 15136 /// Check whether E, which is either a discarded-value expression or an 15137 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 15138 /// and if so, remove it from the list of volatile-qualified assignments that 15139 /// we are going to warn are deprecated. 15140 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 15141 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus2a) 15142 return; 15143 15144 // Note: ignoring parens here is not justified by the standard rules, but 15145 // ignoring parentheses seems like a more reasonable approach, and this only 15146 // drives a deprecation warning so doesn't affect conformance. 15147 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 15148 if (BO->getOpcode() == BO_Assign) { 15149 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 15150 LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()), 15151 LHSs.end()); 15152 } 15153 } 15154 } 15155 15156 void Sema::PopExpressionEvaluationContext() { 15157 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 15158 unsigned NumTypos = Rec.NumTypos; 15159 15160 if (!Rec.Lambdas.empty()) { 15161 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 15162 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() || 15163 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) { 15164 unsigned D; 15165 if (Rec.isUnevaluated()) { 15166 // C++11 [expr.prim.lambda]p2: 15167 // A lambda-expression shall not appear in an unevaluated operand 15168 // (Clause 5). 15169 D = diag::err_lambda_unevaluated_operand; 15170 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 15171 // C++1y [expr.const]p2: 15172 // A conditional-expression e is a core constant expression unless the 15173 // evaluation of e, following the rules of the abstract machine, would 15174 // evaluate [...] a lambda-expression. 15175 D = diag::err_lambda_in_constant_expression; 15176 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 15177 // C++17 [expr.prim.lamda]p2: 15178 // A lambda-expression shall not appear [...] in a template-argument. 15179 D = diag::err_lambda_in_invalid_context; 15180 } else 15181 llvm_unreachable("Couldn't infer lambda error message."); 15182 15183 for (const auto *L : Rec.Lambdas) 15184 Diag(L->getBeginLoc(), D); 15185 } 15186 } 15187 15188 WarnOnPendingNoDerefs(Rec); 15189 15190 // Warn on any volatile-qualified simple-assignments that are not discarded- 15191 // value expressions nor unevaluated operands (those cases get removed from 15192 // this list by CheckUnusedVolatileAssignment). 15193 for (auto *BO : Rec.VolatileAssignmentLHSs) 15194 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 15195 << BO->getType(); 15196 15197 // When are coming out of an unevaluated context, clear out any 15198 // temporaries that we may have created as part of the evaluation of 15199 // the expression in that context: they aren't relevant because they 15200 // will never be constructed. 15201 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 15202 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 15203 ExprCleanupObjects.end()); 15204 Cleanup = Rec.ParentCleanup; 15205 CleanupVarDeclMarking(); 15206 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 15207 // Otherwise, merge the contexts together. 15208 } else { 15209 Cleanup.mergeFrom(Rec.ParentCleanup); 15210 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 15211 Rec.SavedMaybeODRUseExprs.end()); 15212 } 15213 15214 // Pop the current expression evaluation context off the stack. 15215 ExprEvalContexts.pop_back(); 15216 15217 // The global expression evaluation context record is never popped. 15218 ExprEvalContexts.back().NumTypos += NumTypos; 15219 } 15220 15221 void Sema::DiscardCleanupsInEvaluationContext() { 15222 ExprCleanupObjects.erase( 15223 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 15224 ExprCleanupObjects.end()); 15225 Cleanup.reset(); 15226 MaybeODRUseExprs.clear(); 15227 } 15228 15229 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 15230 ExprResult Result = CheckPlaceholderExpr(E); 15231 if (Result.isInvalid()) 15232 return ExprError(); 15233 E = Result.get(); 15234 if (!E->getType()->isVariablyModifiedType()) 15235 return E; 15236 return TransformToPotentiallyEvaluated(E); 15237 } 15238 15239 /// Are we in a context that is potentially constant evaluated per C++20 15240 /// [expr.const]p12? 15241 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 15242 /// C++2a [expr.const]p12: 15243 // An expression or conversion is potentially constant evaluated if it is 15244 switch (SemaRef.ExprEvalContexts.back().Context) { 15245 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 15246 // -- a manifestly constant-evaluated expression, 15247 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 15248 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 15249 case Sema::ExpressionEvaluationContext::DiscardedStatement: 15250 // -- a potentially-evaluated expression, 15251 case Sema::ExpressionEvaluationContext::UnevaluatedList: 15252 // -- an immediate subexpression of a braced-init-list, 15253 15254 // -- [FIXME] an expression of the form & cast-expression that occurs 15255 // within a templated entity 15256 // -- a subexpression of one of the above that is not a subexpression of 15257 // a nested unevaluated operand. 15258 return true; 15259 15260 case Sema::ExpressionEvaluationContext::Unevaluated: 15261 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 15262 // Expressions in this context are never evaluated. 15263 return false; 15264 } 15265 llvm_unreachable("Invalid context"); 15266 } 15267 15268 /// Return true if this function has a calling convention that requires mangling 15269 /// in the size of the parameter pack. 15270 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 15271 // These manglings don't do anything on non-Windows or non-x86 platforms, so 15272 // we don't need parameter type sizes. 15273 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 15274 if (!TT.isOSWindows() || (TT.getArch() != llvm::Triple::x86 && 15275 TT.getArch() != llvm::Triple::x86_64)) 15276 return false; 15277 15278 // If this is C++ and this isn't an extern "C" function, parameters do not 15279 // need to be complete. In this case, C++ mangling will apply, which doesn't 15280 // use the size of the parameters. 15281 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 15282 return false; 15283 15284 // Stdcall, fastcall, and vectorcall need this special treatment. 15285 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 15286 switch (CC) { 15287 case CC_X86StdCall: 15288 case CC_X86FastCall: 15289 case CC_X86VectorCall: 15290 return true; 15291 default: 15292 break; 15293 } 15294 return false; 15295 } 15296 15297 /// Require that all of the parameter types of function be complete. Normally, 15298 /// parameter types are only required to be complete when a function is called 15299 /// or defined, but to mangle functions with certain calling conventions, the 15300 /// mangler needs to know the size of the parameter list. In this situation, 15301 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 15302 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 15303 /// result in a linker error. Clang doesn't implement this behavior, and instead 15304 /// attempts to error at compile time. 15305 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 15306 SourceLocation Loc) { 15307 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 15308 FunctionDecl *FD; 15309 ParmVarDecl *Param; 15310 15311 public: 15312 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 15313 : FD(FD), Param(Param) {} 15314 15315 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 15316 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 15317 StringRef CCName; 15318 switch (CC) { 15319 case CC_X86StdCall: 15320 CCName = "stdcall"; 15321 break; 15322 case CC_X86FastCall: 15323 CCName = "fastcall"; 15324 break; 15325 case CC_X86VectorCall: 15326 CCName = "vectorcall"; 15327 break; 15328 default: 15329 llvm_unreachable("CC does not need mangling"); 15330 } 15331 15332 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 15333 << Param->getDeclName() << FD->getDeclName() << CCName; 15334 } 15335 }; 15336 15337 for (ParmVarDecl *Param : FD->parameters()) { 15338 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 15339 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 15340 } 15341 } 15342 15343 namespace { 15344 enum class OdrUseContext { 15345 /// Declarations in this context are not odr-used. 15346 None, 15347 /// Declarations in this context are formally odr-used, but this is a 15348 /// dependent context. 15349 Dependent, 15350 /// Declarations in this context are odr-used but not actually used (yet). 15351 FormallyOdrUsed, 15352 /// Declarations in this context are used. 15353 Used 15354 }; 15355 } 15356 15357 /// Are we within a context in which references to resolved functions or to 15358 /// variables result in odr-use? 15359 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 15360 OdrUseContext Result; 15361 15362 switch (SemaRef.ExprEvalContexts.back().Context) { 15363 case Sema::ExpressionEvaluationContext::Unevaluated: 15364 case Sema::ExpressionEvaluationContext::UnevaluatedList: 15365 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 15366 return OdrUseContext::None; 15367 15368 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 15369 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 15370 Result = OdrUseContext::Used; 15371 break; 15372 15373 case Sema::ExpressionEvaluationContext::DiscardedStatement: 15374 Result = OdrUseContext::FormallyOdrUsed; 15375 break; 15376 15377 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 15378 // A default argument formally results in odr-use, but doesn't actually 15379 // result in a use in any real sense until it itself is used. 15380 Result = OdrUseContext::FormallyOdrUsed; 15381 break; 15382 } 15383 15384 if (SemaRef.CurContext->isDependentContext()) 15385 return OdrUseContext::Dependent; 15386 15387 return Result; 15388 } 15389 15390 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 15391 return Func->isConstexpr() && 15392 (Func->isImplicitlyInstantiable() || !Func->isUserProvided()); 15393 } 15394 15395 /// Mark a function referenced, and check whether it is odr-used 15396 /// (C++ [basic.def.odr]p2, C99 6.9p3) 15397 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 15398 bool MightBeOdrUse) { 15399 assert(Func && "No function?"); 15400 15401 Func->setReferenced(); 15402 15403 // Recursive functions aren't really used until they're used from some other 15404 // context. 15405 bool IsRecursiveCall = CurContext == Func; 15406 15407 // C++11 [basic.def.odr]p3: 15408 // A function whose name appears as a potentially-evaluated expression is 15409 // odr-used if it is the unique lookup result or the selected member of a 15410 // set of overloaded functions [...]. 15411 // 15412 // We (incorrectly) mark overload resolution as an unevaluated context, so we 15413 // can just check that here. 15414 OdrUseContext OdrUse = 15415 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 15416 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 15417 OdrUse = OdrUseContext::FormallyOdrUsed; 15418 15419 // Trivial default constructors and destructors are never actually used. 15420 // FIXME: What about other special members? 15421 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 15422 OdrUse == OdrUseContext::Used) { 15423 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 15424 if (Constructor->isDefaultConstructor()) 15425 OdrUse = OdrUseContext::FormallyOdrUsed; 15426 if (isa<CXXDestructorDecl>(Func)) 15427 OdrUse = OdrUseContext::FormallyOdrUsed; 15428 } 15429 15430 // C++20 [expr.const]p12: 15431 // A function [...] is needed for constant evaluation if it is [...] a 15432 // constexpr function that is named by an expression that is potentially 15433 // constant evaluated 15434 bool NeededForConstantEvaluation = 15435 isPotentiallyConstantEvaluatedContext(*this) && 15436 isImplicitlyDefinableConstexprFunction(Func); 15437 15438 // Determine whether we require a function definition to exist, per 15439 // C++11 [temp.inst]p3: 15440 // Unless a function template specialization has been explicitly 15441 // instantiated or explicitly specialized, the function template 15442 // specialization is implicitly instantiated when the specialization is 15443 // referenced in a context that requires a function definition to exist. 15444 // C++20 [temp.inst]p7: 15445 // The existence of a definition of a [...] function is considered to 15446 // affect the semantics of the program if the [...] function is needed for 15447 // constant evaluation by an expression 15448 // C++20 [basic.def.odr]p10: 15449 // Every program shall contain exactly one definition of every non-inline 15450 // function or variable that is odr-used in that program outside of a 15451 // discarded statement 15452 // C++20 [special]p1: 15453 // The implementation will implicitly define [defaulted special members] 15454 // if they are odr-used or needed for constant evaluation. 15455 // 15456 // Note that we skip the implicit instantiation of templates that are only 15457 // used in unused default arguments or by recursive calls to themselves. 15458 // This is formally non-conforming, but seems reasonable in practice. 15459 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 15460 NeededForConstantEvaluation); 15461 15462 // C++14 [temp.expl.spec]p6: 15463 // If a template [...] is explicitly specialized then that specialization 15464 // shall be declared before the first use of that specialization that would 15465 // cause an implicit instantiation to take place, in every translation unit 15466 // in which such a use occurs 15467 if (NeedDefinition && 15468 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 15469 Func->getMemberSpecializationInfo())) 15470 checkSpecializationVisibility(Loc, Func); 15471 15472 // C++14 [except.spec]p17: 15473 // An exception-specification is considered to be needed when: 15474 // - the function is odr-used or, if it appears in an unevaluated operand, 15475 // would be odr-used if the expression were potentially-evaluated; 15476 // 15477 // Note, we do this even if MightBeOdrUse is false. That indicates that the 15478 // function is a pure virtual function we're calling, and in that case the 15479 // function was selected by overload resolution and we need to resolve its 15480 // exception specification for a different reason. 15481 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 15482 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 15483 ResolveExceptionSpec(Loc, FPT); 15484 15485 if (getLangOpts().CUDA) 15486 CheckCUDACall(Loc, Func); 15487 15488 // If we need a definition, try to create one. 15489 if (NeedDefinition && !Func->getBody()) { 15490 runWithSufficientStackSpace(Loc, [&] { 15491 if (CXXConstructorDecl *Constructor = 15492 dyn_cast<CXXConstructorDecl>(Func)) { 15493 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 15494 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 15495 if (Constructor->isDefaultConstructor()) { 15496 if (Constructor->isTrivial() && 15497 !Constructor->hasAttr<DLLExportAttr>()) 15498 return; 15499 DefineImplicitDefaultConstructor(Loc, Constructor); 15500 } else if (Constructor->isCopyConstructor()) { 15501 DefineImplicitCopyConstructor(Loc, Constructor); 15502 } else if (Constructor->isMoveConstructor()) { 15503 DefineImplicitMoveConstructor(Loc, Constructor); 15504 } 15505 } else if (Constructor->getInheritedConstructor()) { 15506 DefineInheritingConstructor(Loc, Constructor); 15507 } 15508 } else if (CXXDestructorDecl *Destructor = 15509 dyn_cast<CXXDestructorDecl>(Func)) { 15510 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 15511 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 15512 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 15513 return; 15514 DefineImplicitDestructor(Loc, Destructor); 15515 } 15516 if (Destructor->isVirtual() && getLangOpts().AppleKext) 15517 MarkVTableUsed(Loc, Destructor->getParent()); 15518 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 15519 if (MethodDecl->isOverloadedOperator() && 15520 MethodDecl->getOverloadedOperator() == OO_Equal) { 15521 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 15522 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 15523 if (MethodDecl->isCopyAssignmentOperator()) 15524 DefineImplicitCopyAssignment(Loc, MethodDecl); 15525 else if (MethodDecl->isMoveAssignmentOperator()) 15526 DefineImplicitMoveAssignment(Loc, MethodDecl); 15527 } 15528 } else if (isa<CXXConversionDecl>(MethodDecl) && 15529 MethodDecl->getParent()->isLambda()) { 15530 CXXConversionDecl *Conversion = 15531 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 15532 if (Conversion->isLambdaToBlockPointerConversion()) 15533 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 15534 else 15535 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 15536 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 15537 MarkVTableUsed(Loc, MethodDecl->getParent()); 15538 } 15539 15540 if (Func->isDefaulted() && !Func->isDeleted()) { 15541 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); 15542 if (DCK != DefaultedComparisonKind::None) 15543 DefineDefaultedComparison(Loc, Func, DCK); 15544 } 15545 15546 // Implicit instantiation of function templates and member functions of 15547 // class templates. 15548 if (Func->isImplicitlyInstantiable()) { 15549 TemplateSpecializationKind TSK = 15550 Func->getTemplateSpecializationKindForInstantiation(); 15551 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 15552 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 15553 if (FirstInstantiation) { 15554 PointOfInstantiation = Loc; 15555 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 15556 } else if (TSK != TSK_ImplicitInstantiation) { 15557 // Use the point of use as the point of instantiation, instead of the 15558 // point of explicit instantiation (which we track as the actual point 15559 // of instantiation). This gives better backtraces in diagnostics. 15560 PointOfInstantiation = Loc; 15561 } 15562 15563 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 15564 Func->isConstexpr()) { 15565 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 15566 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 15567 CodeSynthesisContexts.size()) 15568 PendingLocalImplicitInstantiations.push_back( 15569 std::make_pair(Func, PointOfInstantiation)); 15570 else if (Func->isConstexpr()) 15571 // Do not defer instantiations of constexpr functions, to avoid the 15572 // expression evaluator needing to call back into Sema if it sees a 15573 // call to such a function. 15574 InstantiateFunctionDefinition(PointOfInstantiation, Func); 15575 else { 15576 Func->setInstantiationIsPending(true); 15577 PendingInstantiations.push_back( 15578 std::make_pair(Func, PointOfInstantiation)); 15579 // Notify the consumer that a function was implicitly instantiated. 15580 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 15581 } 15582 } 15583 } else { 15584 // Walk redefinitions, as some of them may be instantiable. 15585 for (auto i : Func->redecls()) { 15586 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 15587 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 15588 } 15589 } 15590 }); 15591 } 15592 15593 // If this is the first "real" use, act on that. 15594 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 15595 // Keep track of used but undefined functions. 15596 if (!Func->isDefined()) { 15597 if (mightHaveNonExternalLinkage(Func)) 15598 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 15599 else if (Func->getMostRecentDecl()->isInlined() && 15600 !LangOpts.GNUInline && 15601 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 15602 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 15603 else if (isExternalWithNoLinkageType(Func)) 15604 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 15605 } 15606 15607 // Some x86 Windows calling conventions mangle the size of the parameter 15608 // pack into the name. Computing the size of the parameters requires the 15609 // parameter types to be complete. Check that now. 15610 if (funcHasParameterSizeMangling(*this, Func)) 15611 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 15612 15613 Func->markUsed(Context); 15614 } 15615 15616 if (LangOpts.OpenMP) { 15617 markOpenMPDeclareVariantFuncsReferenced(Loc, Func, MightBeOdrUse); 15618 if (LangOpts.OpenMPIsDevice) 15619 checkOpenMPDeviceFunction(Loc, Func); 15620 else 15621 checkOpenMPHostFunction(Loc, Func); 15622 } 15623 } 15624 15625 /// Directly mark a variable odr-used. Given a choice, prefer to use 15626 /// MarkVariableReferenced since it does additional checks and then 15627 /// calls MarkVarDeclODRUsed. 15628 /// If the variable must be captured: 15629 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 15630 /// - else capture it in the DeclContext that maps to the 15631 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 15632 static void 15633 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 15634 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 15635 // Keep track of used but undefined variables. 15636 // FIXME: We shouldn't suppress this warning for static data members. 15637 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 15638 (!Var->isExternallyVisible() || Var->isInline() || 15639 SemaRef.isExternalWithNoLinkageType(Var)) && 15640 !(Var->isStaticDataMember() && Var->hasInit())) { 15641 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 15642 if (old.isInvalid()) 15643 old = Loc; 15644 } 15645 QualType CaptureType, DeclRefType; 15646 if (SemaRef.LangOpts.OpenMP) 15647 SemaRef.tryCaptureOpenMPLambdas(Var); 15648 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 15649 /*EllipsisLoc*/ SourceLocation(), 15650 /*BuildAndDiagnose*/ true, 15651 CaptureType, DeclRefType, 15652 FunctionScopeIndexToStopAt); 15653 15654 Var->markUsed(SemaRef.Context); 15655 } 15656 15657 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 15658 SourceLocation Loc, 15659 unsigned CapturingScopeIndex) { 15660 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 15661 } 15662 15663 static void 15664 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 15665 ValueDecl *var, DeclContext *DC) { 15666 DeclContext *VarDC = var->getDeclContext(); 15667 15668 // If the parameter still belongs to the translation unit, then 15669 // we're actually just using one parameter in the declaration of 15670 // the next. 15671 if (isa<ParmVarDecl>(var) && 15672 isa<TranslationUnitDecl>(VarDC)) 15673 return; 15674 15675 // For C code, don't diagnose about capture if we're not actually in code 15676 // right now; it's impossible to write a non-constant expression outside of 15677 // function context, so we'll get other (more useful) diagnostics later. 15678 // 15679 // For C++, things get a bit more nasty... it would be nice to suppress this 15680 // diagnostic for certain cases like using a local variable in an array bound 15681 // for a member of a local class, but the correct predicate is not obvious. 15682 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 15683 return; 15684 15685 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 15686 unsigned ContextKind = 3; // unknown 15687 if (isa<CXXMethodDecl>(VarDC) && 15688 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 15689 ContextKind = 2; 15690 } else if (isa<FunctionDecl>(VarDC)) { 15691 ContextKind = 0; 15692 } else if (isa<BlockDecl>(VarDC)) { 15693 ContextKind = 1; 15694 } 15695 15696 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 15697 << var << ValueKind << ContextKind << VarDC; 15698 S.Diag(var->getLocation(), diag::note_entity_declared_at) 15699 << var; 15700 15701 // FIXME: Add additional diagnostic info about class etc. which prevents 15702 // capture. 15703 } 15704 15705 15706 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 15707 bool &SubCapturesAreNested, 15708 QualType &CaptureType, 15709 QualType &DeclRefType) { 15710 // Check whether we've already captured it. 15711 if (CSI->CaptureMap.count(Var)) { 15712 // If we found a capture, any subcaptures are nested. 15713 SubCapturesAreNested = true; 15714 15715 // Retrieve the capture type for this variable. 15716 CaptureType = CSI->getCapture(Var).getCaptureType(); 15717 15718 // Compute the type of an expression that refers to this variable. 15719 DeclRefType = CaptureType.getNonReferenceType(); 15720 15721 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 15722 // are mutable in the sense that user can change their value - they are 15723 // private instances of the captured declarations. 15724 const Capture &Cap = CSI->getCapture(Var); 15725 if (Cap.isCopyCapture() && 15726 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 15727 !(isa<CapturedRegionScopeInfo>(CSI) && 15728 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 15729 DeclRefType.addConst(); 15730 return true; 15731 } 15732 return false; 15733 } 15734 15735 // Only block literals, captured statements, and lambda expressions can 15736 // capture; other scopes don't work. 15737 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 15738 SourceLocation Loc, 15739 const bool Diagnose, Sema &S) { 15740 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 15741 return getLambdaAwareParentOfDeclContext(DC); 15742 else if (Var->hasLocalStorage()) { 15743 if (Diagnose) 15744 diagnoseUncapturableValueReference(S, Loc, Var, DC); 15745 } 15746 return nullptr; 15747 } 15748 15749 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 15750 // certain types of variables (unnamed, variably modified types etc.) 15751 // so check for eligibility. 15752 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 15753 SourceLocation Loc, 15754 const bool Diagnose, Sema &S) { 15755 15756 bool IsBlock = isa<BlockScopeInfo>(CSI); 15757 bool IsLambda = isa<LambdaScopeInfo>(CSI); 15758 15759 // Lambdas are not allowed to capture unnamed variables 15760 // (e.g. anonymous unions). 15761 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 15762 // assuming that's the intent. 15763 if (IsLambda && !Var->getDeclName()) { 15764 if (Diagnose) { 15765 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 15766 S.Diag(Var->getLocation(), diag::note_declared_at); 15767 } 15768 return false; 15769 } 15770 15771 // Prohibit variably-modified types in blocks; they're difficult to deal with. 15772 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 15773 if (Diagnose) { 15774 S.Diag(Loc, diag::err_ref_vm_type); 15775 S.Diag(Var->getLocation(), diag::note_previous_decl) 15776 << Var->getDeclName(); 15777 } 15778 return false; 15779 } 15780 // Prohibit structs with flexible array members too. 15781 // We cannot capture what is in the tail end of the struct. 15782 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 15783 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 15784 if (Diagnose) { 15785 if (IsBlock) 15786 S.Diag(Loc, diag::err_ref_flexarray_type); 15787 else 15788 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 15789 << Var->getDeclName(); 15790 S.Diag(Var->getLocation(), diag::note_previous_decl) 15791 << Var->getDeclName(); 15792 } 15793 return false; 15794 } 15795 } 15796 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 15797 // Lambdas and captured statements are not allowed to capture __block 15798 // variables; they don't support the expected semantics. 15799 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 15800 if (Diagnose) { 15801 S.Diag(Loc, diag::err_capture_block_variable) 15802 << Var->getDeclName() << !IsLambda; 15803 S.Diag(Var->getLocation(), diag::note_previous_decl) 15804 << Var->getDeclName(); 15805 } 15806 return false; 15807 } 15808 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 15809 if (S.getLangOpts().OpenCL && IsBlock && 15810 Var->getType()->isBlockPointerType()) { 15811 if (Diagnose) 15812 S.Diag(Loc, diag::err_opencl_block_ref_block); 15813 return false; 15814 } 15815 15816 return true; 15817 } 15818 15819 // Returns true if the capture by block was successful. 15820 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 15821 SourceLocation Loc, 15822 const bool BuildAndDiagnose, 15823 QualType &CaptureType, 15824 QualType &DeclRefType, 15825 const bool Nested, 15826 Sema &S, bool Invalid) { 15827 bool ByRef = false; 15828 15829 // Blocks are not allowed to capture arrays, excepting OpenCL. 15830 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 15831 // (decayed to pointers). 15832 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 15833 if (BuildAndDiagnose) { 15834 S.Diag(Loc, diag::err_ref_array_type); 15835 S.Diag(Var->getLocation(), diag::note_previous_decl) 15836 << Var->getDeclName(); 15837 Invalid = true; 15838 } else { 15839 return false; 15840 } 15841 } 15842 15843 // Forbid the block-capture of autoreleasing variables. 15844 if (!Invalid && 15845 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 15846 if (BuildAndDiagnose) { 15847 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 15848 << /*block*/ 0; 15849 S.Diag(Var->getLocation(), diag::note_previous_decl) 15850 << Var->getDeclName(); 15851 Invalid = true; 15852 } else { 15853 return false; 15854 } 15855 } 15856 15857 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 15858 if (const auto *PT = CaptureType->getAs<PointerType>()) { 15859 QualType PointeeTy = PT->getPointeeType(); 15860 15861 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 15862 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 15863 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 15864 if (BuildAndDiagnose) { 15865 SourceLocation VarLoc = Var->getLocation(); 15866 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 15867 S.Diag(VarLoc, diag::note_declare_parameter_strong); 15868 } 15869 } 15870 } 15871 15872 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 15873 if (HasBlocksAttr || CaptureType->isReferenceType() || 15874 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 15875 // Block capture by reference does not change the capture or 15876 // declaration reference types. 15877 ByRef = true; 15878 } else { 15879 // Block capture by copy introduces 'const'. 15880 CaptureType = CaptureType.getNonReferenceType().withConst(); 15881 DeclRefType = CaptureType; 15882 } 15883 15884 // Actually capture the variable. 15885 if (BuildAndDiagnose) 15886 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 15887 CaptureType, Invalid); 15888 15889 return !Invalid; 15890 } 15891 15892 15893 /// Capture the given variable in the captured region. 15894 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 15895 VarDecl *Var, 15896 SourceLocation Loc, 15897 const bool BuildAndDiagnose, 15898 QualType &CaptureType, 15899 QualType &DeclRefType, 15900 const bool RefersToCapturedVariable, 15901 Sema &S, bool Invalid) { 15902 // By default, capture variables by reference. 15903 bool ByRef = true; 15904 // Using an LValue reference type is consistent with Lambdas (see below). 15905 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 15906 if (S.isOpenMPCapturedDecl(Var)) { 15907 bool HasConst = DeclRefType.isConstQualified(); 15908 DeclRefType = DeclRefType.getUnqualifiedType(); 15909 // Don't lose diagnostics about assignments to const. 15910 if (HasConst) 15911 DeclRefType.addConst(); 15912 } 15913 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 15914 RSI->OpenMPCaptureLevel); 15915 } 15916 15917 if (ByRef) 15918 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 15919 else 15920 CaptureType = DeclRefType; 15921 15922 // Actually capture the variable. 15923 if (BuildAndDiagnose) 15924 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 15925 Loc, SourceLocation(), CaptureType, Invalid); 15926 15927 return !Invalid; 15928 } 15929 15930 /// Capture the given variable in the lambda. 15931 static bool captureInLambda(LambdaScopeInfo *LSI, 15932 VarDecl *Var, 15933 SourceLocation Loc, 15934 const bool BuildAndDiagnose, 15935 QualType &CaptureType, 15936 QualType &DeclRefType, 15937 const bool RefersToCapturedVariable, 15938 const Sema::TryCaptureKind Kind, 15939 SourceLocation EllipsisLoc, 15940 const bool IsTopScope, 15941 Sema &S, bool Invalid) { 15942 // Determine whether we are capturing by reference or by value. 15943 bool ByRef = false; 15944 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 15945 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 15946 } else { 15947 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 15948 } 15949 15950 // Compute the type of the field that will capture this variable. 15951 if (ByRef) { 15952 // C++11 [expr.prim.lambda]p15: 15953 // An entity is captured by reference if it is implicitly or 15954 // explicitly captured but not captured by copy. It is 15955 // unspecified whether additional unnamed non-static data 15956 // members are declared in the closure type for entities 15957 // captured by reference. 15958 // 15959 // FIXME: It is not clear whether we want to build an lvalue reference 15960 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 15961 // to do the former, while EDG does the latter. Core issue 1249 will 15962 // clarify, but for now we follow GCC because it's a more permissive and 15963 // easily defensible position. 15964 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 15965 } else { 15966 // C++11 [expr.prim.lambda]p14: 15967 // For each entity captured by copy, an unnamed non-static 15968 // data member is declared in the closure type. The 15969 // declaration order of these members is unspecified. The type 15970 // of such a data member is the type of the corresponding 15971 // captured entity if the entity is not a reference to an 15972 // object, or the referenced type otherwise. [Note: If the 15973 // captured entity is a reference to a function, the 15974 // corresponding data member is also a reference to a 15975 // function. - end note ] 15976 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 15977 if (!RefType->getPointeeType()->isFunctionType()) 15978 CaptureType = RefType->getPointeeType(); 15979 } 15980 15981 // Forbid the lambda copy-capture of autoreleasing variables. 15982 if (!Invalid && 15983 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 15984 if (BuildAndDiagnose) { 15985 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 15986 S.Diag(Var->getLocation(), diag::note_previous_decl) 15987 << Var->getDeclName(); 15988 Invalid = true; 15989 } else { 15990 return false; 15991 } 15992 } 15993 15994 // Make sure that by-copy captures are of a complete and non-abstract type. 15995 if (!Invalid && BuildAndDiagnose) { 15996 if (!CaptureType->isDependentType() && 15997 S.RequireCompleteType(Loc, CaptureType, 15998 diag::err_capture_of_incomplete_type, 15999 Var->getDeclName())) 16000 Invalid = true; 16001 else if (S.RequireNonAbstractType(Loc, CaptureType, 16002 diag::err_capture_of_abstract_type)) 16003 Invalid = true; 16004 } 16005 } 16006 16007 // Compute the type of a reference to this captured variable. 16008 if (ByRef) 16009 DeclRefType = CaptureType.getNonReferenceType(); 16010 else { 16011 // C++ [expr.prim.lambda]p5: 16012 // The closure type for a lambda-expression has a public inline 16013 // function call operator [...]. This function call operator is 16014 // declared const (9.3.1) if and only if the lambda-expression's 16015 // parameter-declaration-clause is not followed by mutable. 16016 DeclRefType = CaptureType.getNonReferenceType(); 16017 if (!LSI->Mutable && !CaptureType->isReferenceType()) 16018 DeclRefType.addConst(); 16019 } 16020 16021 // Add the capture. 16022 if (BuildAndDiagnose) 16023 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 16024 Loc, EllipsisLoc, CaptureType, Invalid); 16025 16026 return !Invalid; 16027 } 16028 16029 bool Sema::tryCaptureVariable( 16030 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 16031 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 16032 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 16033 // An init-capture is notionally from the context surrounding its 16034 // declaration, but its parent DC is the lambda class. 16035 DeclContext *VarDC = Var->getDeclContext(); 16036 if (Var->isInitCapture()) 16037 VarDC = VarDC->getParent(); 16038 16039 DeclContext *DC = CurContext; 16040 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 16041 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 16042 // We need to sync up the Declaration Context with the 16043 // FunctionScopeIndexToStopAt 16044 if (FunctionScopeIndexToStopAt) { 16045 unsigned FSIndex = FunctionScopes.size() - 1; 16046 while (FSIndex != MaxFunctionScopesIndex) { 16047 DC = getLambdaAwareParentOfDeclContext(DC); 16048 --FSIndex; 16049 } 16050 } 16051 16052 16053 // If the variable is declared in the current context, there is no need to 16054 // capture it. 16055 if (VarDC == DC) return true; 16056 16057 // Capture global variables if it is required to use private copy of this 16058 // variable. 16059 bool IsGlobal = !Var->hasLocalStorage(); 16060 if (IsGlobal && 16061 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 16062 MaxFunctionScopesIndex))) 16063 return true; 16064 Var = Var->getCanonicalDecl(); 16065 16066 // Walk up the stack to determine whether we can capture the variable, 16067 // performing the "simple" checks that don't depend on type. We stop when 16068 // we've either hit the declared scope of the variable or find an existing 16069 // capture of that variable. We start from the innermost capturing-entity 16070 // (the DC) and ensure that all intervening capturing-entities 16071 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 16072 // declcontext can either capture the variable or have already captured 16073 // the variable. 16074 CaptureType = Var->getType(); 16075 DeclRefType = CaptureType.getNonReferenceType(); 16076 bool Nested = false; 16077 bool Explicit = (Kind != TryCapture_Implicit); 16078 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 16079 do { 16080 // Only block literals, captured statements, and lambda expressions can 16081 // capture; other scopes don't work. 16082 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 16083 ExprLoc, 16084 BuildAndDiagnose, 16085 *this); 16086 // We need to check for the parent *first* because, if we *have* 16087 // private-captured a global variable, we need to recursively capture it in 16088 // intermediate blocks, lambdas, etc. 16089 if (!ParentDC) { 16090 if (IsGlobal) { 16091 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 16092 break; 16093 } 16094 return true; 16095 } 16096 16097 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 16098 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 16099 16100 16101 // Check whether we've already captured it. 16102 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 16103 DeclRefType)) { 16104 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 16105 break; 16106 } 16107 // If we are instantiating a generic lambda call operator body, 16108 // we do not want to capture new variables. What was captured 16109 // during either a lambdas transformation or initial parsing 16110 // should be used. 16111 if (isGenericLambdaCallOperatorSpecialization(DC)) { 16112 if (BuildAndDiagnose) { 16113 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 16114 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 16115 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 16116 Diag(Var->getLocation(), diag::note_previous_decl) 16117 << Var->getDeclName(); 16118 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 16119 } else 16120 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 16121 } 16122 return true; 16123 } 16124 16125 // Try to capture variable-length arrays types. 16126 if (Var->getType()->isVariablyModifiedType()) { 16127 // We're going to walk down into the type and look for VLA 16128 // expressions. 16129 QualType QTy = Var->getType(); 16130 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 16131 QTy = PVD->getOriginalType(); 16132 captureVariablyModifiedType(Context, QTy, CSI); 16133 } 16134 16135 if (getLangOpts().OpenMP) { 16136 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 16137 // OpenMP private variables should not be captured in outer scope, so 16138 // just break here. Similarly, global variables that are captured in a 16139 // target region should not be captured outside the scope of the region. 16140 if (RSI->CapRegionKind == CR_OpenMP) { 16141 bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel); 16142 // If the variable is private (i.e. not captured) and has variably 16143 // modified type, we still need to capture the type for correct 16144 // codegen in all regions, associated with the construct. Currently, 16145 // it is captured in the innermost captured region only. 16146 if (IsOpenMPPrivateDecl && Var->getType()->isVariablyModifiedType()) { 16147 QualType QTy = Var->getType(); 16148 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 16149 QTy = PVD->getOriginalType(); 16150 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 16151 I < E; ++I) { 16152 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 16153 FunctionScopes[FunctionScopesIndex - I]); 16154 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 16155 "Wrong number of captured regions associated with the " 16156 "OpenMP construct."); 16157 captureVariablyModifiedType(Context, QTy, OuterRSI); 16158 } 16159 } 16160 bool IsTargetCap = !IsOpenMPPrivateDecl && 16161 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 16162 // When we detect target captures we are looking from inside the 16163 // target region, therefore we need to propagate the capture from the 16164 // enclosing region. Therefore, the capture is not initially nested. 16165 if (IsTargetCap) 16166 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 16167 16168 if (IsTargetCap || IsOpenMPPrivateDecl) { 16169 Nested = !IsTargetCap; 16170 DeclRefType = DeclRefType.getUnqualifiedType(); 16171 CaptureType = Context.getLValueReferenceType(DeclRefType); 16172 break; 16173 } 16174 } 16175 } 16176 } 16177 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 16178 // No capture-default, and this is not an explicit capture 16179 // so cannot capture this variable. 16180 if (BuildAndDiagnose) { 16181 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 16182 Diag(Var->getLocation(), diag::note_previous_decl) 16183 << Var->getDeclName(); 16184 if (cast<LambdaScopeInfo>(CSI)->Lambda) 16185 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(), 16186 diag::note_lambda_decl); 16187 // FIXME: If we error out because an outer lambda can not implicitly 16188 // capture a variable that an inner lambda explicitly captures, we 16189 // should have the inner lambda do the explicit capture - because 16190 // it makes for cleaner diagnostics later. This would purely be done 16191 // so that the diagnostic does not misleadingly claim that a variable 16192 // can not be captured by a lambda implicitly even though it is captured 16193 // explicitly. Suggestion: 16194 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 16195 // at the function head 16196 // - cache the StartingDeclContext - this must be a lambda 16197 // - captureInLambda in the innermost lambda the variable. 16198 } 16199 return true; 16200 } 16201 16202 FunctionScopesIndex--; 16203 DC = ParentDC; 16204 Explicit = false; 16205 } while (!VarDC->Equals(DC)); 16206 16207 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 16208 // computing the type of the capture at each step, checking type-specific 16209 // requirements, and adding captures if requested. 16210 // If the variable had already been captured previously, we start capturing 16211 // at the lambda nested within that one. 16212 bool Invalid = false; 16213 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 16214 ++I) { 16215 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 16216 16217 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 16218 // certain types of variables (unnamed, variably modified types etc.) 16219 // so check for eligibility. 16220 if (!Invalid) 16221 Invalid = 16222 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 16223 16224 // After encountering an error, if we're actually supposed to capture, keep 16225 // capturing in nested contexts to suppress any follow-on diagnostics. 16226 if (Invalid && !BuildAndDiagnose) 16227 return true; 16228 16229 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 16230 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 16231 DeclRefType, Nested, *this, Invalid); 16232 Nested = true; 16233 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 16234 Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose, 16235 CaptureType, DeclRefType, Nested, 16236 *this, Invalid); 16237 Nested = true; 16238 } else { 16239 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 16240 Invalid = 16241 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 16242 DeclRefType, Nested, Kind, EllipsisLoc, 16243 /*IsTopScope*/ I == N - 1, *this, Invalid); 16244 Nested = true; 16245 } 16246 16247 if (Invalid && !BuildAndDiagnose) 16248 return true; 16249 } 16250 return Invalid; 16251 } 16252 16253 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 16254 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 16255 QualType CaptureType; 16256 QualType DeclRefType; 16257 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 16258 /*BuildAndDiagnose=*/true, CaptureType, 16259 DeclRefType, nullptr); 16260 } 16261 16262 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 16263 QualType CaptureType; 16264 QualType DeclRefType; 16265 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 16266 /*BuildAndDiagnose=*/false, CaptureType, 16267 DeclRefType, nullptr); 16268 } 16269 16270 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 16271 QualType CaptureType; 16272 QualType DeclRefType; 16273 16274 // Determine whether we can capture this variable. 16275 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 16276 /*BuildAndDiagnose=*/false, CaptureType, 16277 DeclRefType, nullptr)) 16278 return QualType(); 16279 16280 return DeclRefType; 16281 } 16282 16283 namespace { 16284 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 16285 // The produced TemplateArgumentListInfo* points to data stored within this 16286 // object, so should only be used in contexts where the pointer will not be 16287 // used after the CopiedTemplateArgs object is destroyed. 16288 class CopiedTemplateArgs { 16289 bool HasArgs; 16290 TemplateArgumentListInfo TemplateArgStorage; 16291 public: 16292 template<typename RefExpr> 16293 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 16294 if (HasArgs) 16295 E->copyTemplateArgumentsInto(TemplateArgStorage); 16296 } 16297 operator TemplateArgumentListInfo*() 16298 #ifdef __has_cpp_attribute 16299 #if __has_cpp_attribute(clang::lifetimebound) 16300 [[clang::lifetimebound]] 16301 #endif 16302 #endif 16303 { 16304 return HasArgs ? &TemplateArgStorage : nullptr; 16305 } 16306 }; 16307 } 16308 16309 /// Walk the set of potential results of an expression and mark them all as 16310 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 16311 /// 16312 /// \return A new expression if we found any potential results, ExprEmpty() if 16313 /// not, and ExprError() if we diagnosed an error. 16314 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 16315 NonOdrUseReason NOUR) { 16316 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 16317 // an object that satisfies the requirements for appearing in a 16318 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 16319 // is immediately applied." This function handles the lvalue-to-rvalue 16320 // conversion part. 16321 // 16322 // If we encounter a node that claims to be an odr-use but shouldn't be, we 16323 // transform it into the relevant kind of non-odr-use node and rebuild the 16324 // tree of nodes leading to it. 16325 // 16326 // This is a mini-TreeTransform that only transforms a restricted subset of 16327 // nodes (and only certain operands of them). 16328 16329 // Rebuild a subexpression. 16330 auto Rebuild = [&](Expr *Sub) { 16331 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 16332 }; 16333 16334 // Check whether a potential result satisfies the requirements of NOUR. 16335 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 16336 // Any entity other than a VarDecl is always odr-used whenever it's named 16337 // in a potentially-evaluated expression. 16338 auto *VD = dyn_cast<VarDecl>(D); 16339 if (!VD) 16340 return true; 16341 16342 // C++2a [basic.def.odr]p4: 16343 // A variable x whose name appears as a potentially-evalauted expression 16344 // e is odr-used by e unless 16345 // -- x is a reference that is usable in constant expressions, or 16346 // -- x is a variable of non-reference type that is usable in constant 16347 // expressions and has no mutable subobjects, and e is an element of 16348 // the set of potential results of an expression of 16349 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 16350 // conversion is applied, or 16351 // -- x is a variable of non-reference type, and e is an element of the 16352 // set of potential results of a discarded-value expression to which 16353 // the lvalue-to-rvalue conversion is not applied 16354 // 16355 // We check the first bullet and the "potentially-evaluated" condition in 16356 // BuildDeclRefExpr. We check the type requirements in the second bullet 16357 // in CheckLValueToRValueConversionOperand below. 16358 switch (NOUR) { 16359 case NOUR_None: 16360 case NOUR_Unevaluated: 16361 llvm_unreachable("unexpected non-odr-use-reason"); 16362 16363 case NOUR_Constant: 16364 // Constant references were handled when they were built. 16365 if (VD->getType()->isReferenceType()) 16366 return true; 16367 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 16368 if (RD->hasMutableFields()) 16369 return true; 16370 if (!VD->isUsableInConstantExpressions(S.Context)) 16371 return true; 16372 break; 16373 16374 case NOUR_Discarded: 16375 if (VD->getType()->isReferenceType()) 16376 return true; 16377 break; 16378 } 16379 return false; 16380 }; 16381 16382 // Mark that this expression does not constitute an odr-use. 16383 auto MarkNotOdrUsed = [&] { 16384 S.MaybeODRUseExprs.erase(E); 16385 if (LambdaScopeInfo *LSI = S.getCurLambda()) 16386 LSI->markVariableExprAsNonODRUsed(E); 16387 }; 16388 16389 // C++2a [basic.def.odr]p2: 16390 // The set of potential results of an expression e is defined as follows: 16391 switch (E->getStmtClass()) { 16392 // -- If e is an id-expression, ... 16393 case Expr::DeclRefExprClass: { 16394 auto *DRE = cast<DeclRefExpr>(E); 16395 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 16396 break; 16397 16398 // Rebuild as a non-odr-use DeclRefExpr. 16399 MarkNotOdrUsed(); 16400 return DeclRefExpr::Create( 16401 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 16402 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 16403 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 16404 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 16405 } 16406 16407 case Expr::FunctionParmPackExprClass: { 16408 auto *FPPE = cast<FunctionParmPackExpr>(E); 16409 // If any of the declarations in the pack is odr-used, then the expression 16410 // as a whole constitutes an odr-use. 16411 for (VarDecl *D : *FPPE) 16412 if (IsPotentialResultOdrUsed(D)) 16413 return ExprEmpty(); 16414 16415 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 16416 // nothing cares about whether we marked this as an odr-use, but it might 16417 // be useful for non-compiler tools. 16418 MarkNotOdrUsed(); 16419 break; 16420 } 16421 16422 // -- If e is a subscripting operation with an array operand... 16423 case Expr::ArraySubscriptExprClass: { 16424 auto *ASE = cast<ArraySubscriptExpr>(E); 16425 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 16426 if (!OldBase->getType()->isArrayType()) 16427 break; 16428 ExprResult Base = Rebuild(OldBase); 16429 if (!Base.isUsable()) 16430 return Base; 16431 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 16432 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 16433 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 16434 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 16435 ASE->getRBracketLoc()); 16436 } 16437 16438 case Expr::MemberExprClass: { 16439 auto *ME = cast<MemberExpr>(E); 16440 // -- If e is a class member access expression [...] naming a non-static 16441 // data member... 16442 if (isa<FieldDecl>(ME->getMemberDecl())) { 16443 ExprResult Base = Rebuild(ME->getBase()); 16444 if (!Base.isUsable()) 16445 return Base; 16446 return MemberExpr::Create( 16447 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 16448 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 16449 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 16450 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 16451 ME->getObjectKind(), ME->isNonOdrUse()); 16452 } 16453 16454 if (ME->getMemberDecl()->isCXXInstanceMember()) 16455 break; 16456 16457 // -- If e is a class member access expression naming a static data member, 16458 // ... 16459 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 16460 break; 16461 16462 // Rebuild as a non-odr-use MemberExpr. 16463 MarkNotOdrUsed(); 16464 return MemberExpr::Create( 16465 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 16466 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 16467 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 16468 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 16469 return ExprEmpty(); 16470 } 16471 16472 case Expr::BinaryOperatorClass: { 16473 auto *BO = cast<BinaryOperator>(E); 16474 Expr *LHS = BO->getLHS(); 16475 Expr *RHS = BO->getRHS(); 16476 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 16477 if (BO->getOpcode() == BO_PtrMemD) { 16478 ExprResult Sub = Rebuild(LHS); 16479 if (!Sub.isUsable()) 16480 return Sub; 16481 LHS = Sub.get(); 16482 // -- If e is a comma expression, ... 16483 } else if (BO->getOpcode() == BO_Comma) { 16484 ExprResult Sub = Rebuild(RHS); 16485 if (!Sub.isUsable()) 16486 return Sub; 16487 RHS = Sub.get(); 16488 } else { 16489 break; 16490 } 16491 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 16492 LHS, RHS); 16493 } 16494 16495 // -- If e has the form (e1)... 16496 case Expr::ParenExprClass: { 16497 auto *PE = cast<ParenExpr>(E); 16498 ExprResult Sub = Rebuild(PE->getSubExpr()); 16499 if (!Sub.isUsable()) 16500 return Sub; 16501 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 16502 } 16503 16504 // -- If e is a glvalue conditional expression, ... 16505 // We don't apply this to a binary conditional operator. FIXME: Should we? 16506 case Expr::ConditionalOperatorClass: { 16507 auto *CO = cast<ConditionalOperator>(E); 16508 ExprResult LHS = Rebuild(CO->getLHS()); 16509 if (LHS.isInvalid()) 16510 return ExprError(); 16511 ExprResult RHS = Rebuild(CO->getRHS()); 16512 if (RHS.isInvalid()) 16513 return ExprError(); 16514 if (!LHS.isUsable() && !RHS.isUsable()) 16515 return ExprEmpty(); 16516 if (!LHS.isUsable()) 16517 LHS = CO->getLHS(); 16518 if (!RHS.isUsable()) 16519 RHS = CO->getRHS(); 16520 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 16521 CO->getCond(), LHS.get(), RHS.get()); 16522 } 16523 16524 // [Clang extension] 16525 // -- If e has the form __extension__ e1... 16526 case Expr::UnaryOperatorClass: { 16527 auto *UO = cast<UnaryOperator>(E); 16528 if (UO->getOpcode() != UO_Extension) 16529 break; 16530 ExprResult Sub = Rebuild(UO->getSubExpr()); 16531 if (!Sub.isUsable()) 16532 return Sub; 16533 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 16534 Sub.get()); 16535 } 16536 16537 // [Clang extension] 16538 // -- If e has the form _Generic(...), the set of potential results is the 16539 // union of the sets of potential results of the associated expressions. 16540 case Expr::GenericSelectionExprClass: { 16541 auto *GSE = cast<GenericSelectionExpr>(E); 16542 16543 SmallVector<Expr *, 4> AssocExprs; 16544 bool AnyChanged = false; 16545 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 16546 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 16547 if (AssocExpr.isInvalid()) 16548 return ExprError(); 16549 if (AssocExpr.isUsable()) { 16550 AssocExprs.push_back(AssocExpr.get()); 16551 AnyChanged = true; 16552 } else { 16553 AssocExprs.push_back(OrigAssocExpr); 16554 } 16555 } 16556 16557 return AnyChanged ? S.CreateGenericSelectionExpr( 16558 GSE->getGenericLoc(), GSE->getDefaultLoc(), 16559 GSE->getRParenLoc(), GSE->getControllingExpr(), 16560 GSE->getAssocTypeSourceInfos(), AssocExprs) 16561 : ExprEmpty(); 16562 } 16563 16564 // [Clang extension] 16565 // -- If e has the form __builtin_choose_expr(...), the set of potential 16566 // results is the union of the sets of potential results of the 16567 // second and third subexpressions. 16568 case Expr::ChooseExprClass: { 16569 auto *CE = cast<ChooseExpr>(E); 16570 16571 ExprResult LHS = Rebuild(CE->getLHS()); 16572 if (LHS.isInvalid()) 16573 return ExprError(); 16574 16575 ExprResult RHS = Rebuild(CE->getLHS()); 16576 if (RHS.isInvalid()) 16577 return ExprError(); 16578 16579 if (!LHS.get() && !RHS.get()) 16580 return ExprEmpty(); 16581 if (!LHS.isUsable()) 16582 LHS = CE->getLHS(); 16583 if (!RHS.isUsable()) 16584 RHS = CE->getRHS(); 16585 16586 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 16587 RHS.get(), CE->getRParenLoc()); 16588 } 16589 16590 // Step through non-syntactic nodes. 16591 case Expr::ConstantExprClass: { 16592 auto *CE = cast<ConstantExpr>(E); 16593 ExprResult Sub = Rebuild(CE->getSubExpr()); 16594 if (!Sub.isUsable()) 16595 return Sub; 16596 return ConstantExpr::Create(S.Context, Sub.get()); 16597 } 16598 16599 // We could mostly rely on the recursive rebuilding to rebuild implicit 16600 // casts, but not at the top level, so rebuild them here. 16601 case Expr::ImplicitCastExprClass: { 16602 auto *ICE = cast<ImplicitCastExpr>(E); 16603 // Only step through the narrow set of cast kinds we expect to encounter. 16604 // Anything else suggests we've left the region in which potential results 16605 // can be found. 16606 switch (ICE->getCastKind()) { 16607 case CK_NoOp: 16608 case CK_DerivedToBase: 16609 case CK_UncheckedDerivedToBase: { 16610 ExprResult Sub = Rebuild(ICE->getSubExpr()); 16611 if (!Sub.isUsable()) 16612 return Sub; 16613 CXXCastPath Path(ICE->path()); 16614 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 16615 ICE->getValueKind(), &Path); 16616 } 16617 16618 default: 16619 break; 16620 } 16621 break; 16622 } 16623 16624 default: 16625 break; 16626 } 16627 16628 // Can't traverse through this node. Nothing to do. 16629 return ExprEmpty(); 16630 } 16631 16632 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 16633 // Check whether the operand is or contains an object of non-trivial C union 16634 // type. 16635 if (E->getType().isVolatileQualified() && 16636 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 16637 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 16638 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 16639 Sema::NTCUC_LValueToRValueVolatile, 16640 NTCUK_Destruct|NTCUK_Copy); 16641 16642 // C++2a [basic.def.odr]p4: 16643 // [...] an expression of non-volatile-qualified non-class type to which 16644 // the lvalue-to-rvalue conversion is applied [...] 16645 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 16646 return E; 16647 16648 ExprResult Result = 16649 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 16650 if (Result.isInvalid()) 16651 return ExprError(); 16652 return Result.get() ? Result : E; 16653 } 16654 16655 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 16656 Res = CorrectDelayedTyposInExpr(Res); 16657 16658 if (!Res.isUsable()) 16659 return Res; 16660 16661 // If a constant-expression is a reference to a variable where we delay 16662 // deciding whether it is an odr-use, just assume we will apply the 16663 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 16664 // (a non-type template argument), we have special handling anyway. 16665 return CheckLValueToRValueConversionOperand(Res.get()); 16666 } 16667 16668 void Sema::CleanupVarDeclMarking() { 16669 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 16670 // call. 16671 MaybeODRUseExprSet LocalMaybeODRUseExprs; 16672 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 16673 16674 for (Expr *E : LocalMaybeODRUseExprs) { 16675 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 16676 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 16677 DRE->getLocation(), *this); 16678 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 16679 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 16680 *this); 16681 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 16682 for (VarDecl *VD : *FP) 16683 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 16684 } else { 16685 llvm_unreachable("Unexpected expression"); 16686 } 16687 } 16688 16689 assert(MaybeODRUseExprs.empty() && 16690 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 16691 } 16692 16693 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 16694 VarDecl *Var, Expr *E) { 16695 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 16696 isa<FunctionParmPackExpr>(E)) && 16697 "Invalid Expr argument to DoMarkVarDeclReferenced"); 16698 Var->setReferenced(); 16699 16700 if (Var->isInvalidDecl()) 16701 return; 16702 16703 auto *MSI = Var->getMemberSpecializationInfo(); 16704 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 16705 : Var->getTemplateSpecializationKind(); 16706 16707 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 16708 bool UsableInConstantExpr = 16709 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 16710 16711 // C++20 [expr.const]p12: 16712 // A variable [...] is needed for constant evaluation if it is [...] a 16713 // variable whose name appears as a potentially constant evaluated 16714 // expression that is either a contexpr variable or is of non-volatile 16715 // const-qualified integral type or of reference type 16716 bool NeededForConstantEvaluation = 16717 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 16718 16719 bool NeedDefinition = 16720 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 16721 16722 VarTemplateSpecializationDecl *VarSpec = 16723 dyn_cast<VarTemplateSpecializationDecl>(Var); 16724 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 16725 "Can't instantiate a partial template specialization."); 16726 16727 // If this might be a member specialization of a static data member, check 16728 // the specialization is visible. We already did the checks for variable 16729 // template specializations when we created them. 16730 if (NeedDefinition && TSK != TSK_Undeclared && 16731 !isa<VarTemplateSpecializationDecl>(Var)) 16732 SemaRef.checkSpecializationVisibility(Loc, Var); 16733 16734 // Perform implicit instantiation of static data members, static data member 16735 // templates of class templates, and variable template specializations. Delay 16736 // instantiations of variable templates, except for those that could be used 16737 // in a constant expression. 16738 if (NeedDefinition && isTemplateInstantiation(TSK)) { 16739 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 16740 // instantiation declaration if a variable is usable in a constant 16741 // expression (among other cases). 16742 bool TryInstantiating = 16743 TSK == TSK_ImplicitInstantiation || 16744 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 16745 16746 if (TryInstantiating) { 16747 SourceLocation PointOfInstantiation = 16748 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 16749 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 16750 if (FirstInstantiation) { 16751 PointOfInstantiation = Loc; 16752 if (MSI) 16753 MSI->setPointOfInstantiation(PointOfInstantiation); 16754 else 16755 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 16756 } 16757 16758 bool InstantiationDependent = false; 16759 bool IsNonDependent = 16760 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 16761 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 16762 : true; 16763 16764 // Do not instantiate specializations that are still type-dependent. 16765 if (IsNonDependent) { 16766 if (UsableInConstantExpr) { 16767 // Do not defer instantiations of variables that could be used in a 16768 // constant expression. 16769 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 16770 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 16771 }); 16772 } else if (FirstInstantiation || 16773 isa<VarTemplateSpecializationDecl>(Var)) { 16774 // FIXME: For a specialization of a variable template, we don't 16775 // distinguish between "declaration and type implicitly instantiated" 16776 // and "implicit instantiation of definition requested", so we have 16777 // no direct way to avoid enqueueing the pending instantiation 16778 // multiple times. 16779 SemaRef.PendingInstantiations 16780 .push_back(std::make_pair(Var, PointOfInstantiation)); 16781 } 16782 } 16783 } 16784 } 16785 16786 // C++2a [basic.def.odr]p4: 16787 // A variable x whose name appears as a potentially-evaluated expression e 16788 // is odr-used by e unless 16789 // -- x is a reference that is usable in constant expressions 16790 // -- x is a variable of non-reference type that is usable in constant 16791 // expressions and has no mutable subobjects [FIXME], and e is an 16792 // element of the set of potential results of an expression of 16793 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 16794 // conversion is applied 16795 // -- x is a variable of non-reference type, and e is an element of the set 16796 // of potential results of a discarded-value expression to which the 16797 // lvalue-to-rvalue conversion is not applied [FIXME] 16798 // 16799 // We check the first part of the second bullet here, and 16800 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 16801 // FIXME: To get the third bullet right, we need to delay this even for 16802 // variables that are not usable in constant expressions. 16803 16804 // If we already know this isn't an odr-use, there's nothing more to do. 16805 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 16806 if (DRE->isNonOdrUse()) 16807 return; 16808 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 16809 if (ME->isNonOdrUse()) 16810 return; 16811 16812 switch (OdrUse) { 16813 case OdrUseContext::None: 16814 assert((!E || isa<FunctionParmPackExpr>(E)) && 16815 "missing non-odr-use marking for unevaluated decl ref"); 16816 break; 16817 16818 case OdrUseContext::FormallyOdrUsed: 16819 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 16820 // behavior. 16821 break; 16822 16823 case OdrUseContext::Used: 16824 // If we might later find that this expression isn't actually an odr-use, 16825 // delay the marking. 16826 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 16827 SemaRef.MaybeODRUseExprs.insert(E); 16828 else 16829 MarkVarDeclODRUsed(Var, Loc, SemaRef); 16830 break; 16831 16832 case OdrUseContext::Dependent: 16833 // If this is a dependent context, we don't need to mark variables as 16834 // odr-used, but we may still need to track them for lambda capture. 16835 // FIXME: Do we also need to do this inside dependent typeid expressions 16836 // (which are modeled as unevaluated at this point)? 16837 const bool RefersToEnclosingScope = 16838 (SemaRef.CurContext != Var->getDeclContext() && 16839 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 16840 if (RefersToEnclosingScope) { 16841 LambdaScopeInfo *const LSI = 16842 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 16843 if (LSI && (!LSI->CallOperator || 16844 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 16845 // If a variable could potentially be odr-used, defer marking it so 16846 // until we finish analyzing the full expression for any 16847 // lvalue-to-rvalue 16848 // or discarded value conversions that would obviate odr-use. 16849 // Add it to the list of potential captures that will be analyzed 16850 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 16851 // unless the variable is a reference that was initialized by a constant 16852 // expression (this will never need to be captured or odr-used). 16853 // 16854 // FIXME: We can simplify this a lot after implementing P0588R1. 16855 assert(E && "Capture variable should be used in an expression."); 16856 if (!Var->getType()->isReferenceType() || 16857 !Var->isUsableInConstantExpressions(SemaRef.Context)) 16858 LSI->addPotentialCapture(E->IgnoreParens()); 16859 } 16860 } 16861 break; 16862 } 16863 } 16864 16865 /// Mark a variable referenced, and check whether it is odr-used 16866 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 16867 /// used directly for normal expressions referring to VarDecl. 16868 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 16869 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 16870 } 16871 16872 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 16873 Decl *D, Expr *E, bool MightBeOdrUse) { 16874 if (SemaRef.isInOpenMPDeclareTargetContext()) 16875 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 16876 16877 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 16878 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 16879 return; 16880 } 16881 16882 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 16883 16884 // If this is a call to a method via a cast, also mark the method in the 16885 // derived class used in case codegen can devirtualize the call. 16886 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 16887 if (!ME) 16888 return; 16889 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 16890 if (!MD) 16891 return; 16892 // Only attempt to devirtualize if this is truly a virtual call. 16893 bool IsVirtualCall = MD->isVirtual() && 16894 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 16895 if (!IsVirtualCall) 16896 return; 16897 16898 // If it's possible to devirtualize the call, mark the called function 16899 // referenced. 16900 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 16901 ME->getBase(), SemaRef.getLangOpts().AppleKext); 16902 if (DM) 16903 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 16904 } 16905 16906 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 16907 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 16908 // TODO: update this with DR# once a defect report is filed. 16909 // C++11 defect. The address of a pure member should not be an ODR use, even 16910 // if it's a qualified reference. 16911 bool OdrUse = true; 16912 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 16913 if (Method->isVirtual() && 16914 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 16915 OdrUse = false; 16916 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 16917 } 16918 16919 /// Perform reference-marking and odr-use handling for a MemberExpr. 16920 void Sema::MarkMemberReferenced(MemberExpr *E) { 16921 // C++11 [basic.def.odr]p2: 16922 // A non-overloaded function whose name appears as a potentially-evaluated 16923 // expression or a member of a set of candidate functions, if selected by 16924 // overload resolution when referred to from a potentially-evaluated 16925 // expression, is odr-used, unless it is a pure virtual function and its 16926 // name is not explicitly qualified. 16927 bool MightBeOdrUse = true; 16928 if (E->performsVirtualDispatch(getLangOpts())) { 16929 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 16930 if (Method->isPure()) 16931 MightBeOdrUse = false; 16932 } 16933 SourceLocation Loc = 16934 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 16935 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 16936 } 16937 16938 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 16939 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 16940 for (VarDecl *VD : *E) 16941 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true); 16942 } 16943 16944 /// Perform marking for a reference to an arbitrary declaration. It 16945 /// marks the declaration referenced, and performs odr-use checking for 16946 /// functions and variables. This method should not be used when building a 16947 /// normal expression which refers to a variable. 16948 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 16949 bool MightBeOdrUse) { 16950 if (MightBeOdrUse) { 16951 if (auto *VD = dyn_cast<VarDecl>(D)) { 16952 MarkVariableReferenced(Loc, VD); 16953 return; 16954 } 16955 } 16956 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 16957 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 16958 return; 16959 } 16960 D->setReferenced(); 16961 } 16962 16963 namespace { 16964 // Mark all of the declarations used by a type as referenced. 16965 // FIXME: Not fully implemented yet! We need to have a better understanding 16966 // of when we're entering a context we should not recurse into. 16967 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 16968 // TreeTransforms rebuilding the type in a new context. Rather than 16969 // duplicating the TreeTransform logic, we should consider reusing it here. 16970 // Currently that causes problems when rebuilding LambdaExprs. 16971 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 16972 Sema &S; 16973 SourceLocation Loc; 16974 16975 public: 16976 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 16977 16978 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 16979 16980 bool TraverseTemplateArgument(const TemplateArgument &Arg); 16981 }; 16982 } 16983 16984 bool MarkReferencedDecls::TraverseTemplateArgument( 16985 const TemplateArgument &Arg) { 16986 { 16987 // A non-type template argument is a constant-evaluated context. 16988 EnterExpressionEvaluationContext Evaluated( 16989 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 16990 if (Arg.getKind() == TemplateArgument::Declaration) { 16991 if (Decl *D = Arg.getAsDecl()) 16992 S.MarkAnyDeclReferenced(Loc, D, true); 16993 } else if (Arg.getKind() == TemplateArgument::Expression) { 16994 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 16995 } 16996 } 16997 16998 return Inherited::TraverseTemplateArgument(Arg); 16999 } 17000 17001 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 17002 MarkReferencedDecls Marker(*this, Loc); 17003 Marker.TraverseType(T); 17004 } 17005 17006 namespace { 17007 /// Helper class that marks all of the declarations referenced by 17008 /// potentially-evaluated subexpressions as "referenced". 17009 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 17010 Sema &S; 17011 bool SkipLocalVariables; 17012 17013 public: 17014 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 17015 17016 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 17017 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 17018 17019 void VisitDeclRefExpr(DeclRefExpr *E) { 17020 // If we were asked not to visit local variables, don't. 17021 if (SkipLocalVariables) { 17022 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 17023 if (VD->hasLocalStorage()) 17024 return; 17025 } 17026 17027 S.MarkDeclRefReferenced(E); 17028 } 17029 17030 void VisitMemberExpr(MemberExpr *E) { 17031 S.MarkMemberReferenced(E); 17032 Inherited::VisitMemberExpr(E); 17033 } 17034 17035 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 17036 S.MarkFunctionReferenced( 17037 E->getBeginLoc(), 17038 const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor())); 17039 Visit(E->getSubExpr()); 17040 } 17041 17042 void VisitCXXNewExpr(CXXNewExpr *E) { 17043 if (E->getOperatorNew()) 17044 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew()); 17045 if (E->getOperatorDelete()) 17046 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete()); 17047 Inherited::VisitCXXNewExpr(E); 17048 } 17049 17050 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 17051 if (E->getOperatorDelete()) 17052 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete()); 17053 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 17054 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 17055 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 17056 S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record)); 17057 } 17058 17059 Inherited::VisitCXXDeleteExpr(E); 17060 } 17061 17062 void VisitCXXConstructExpr(CXXConstructExpr *E) { 17063 S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor()); 17064 Inherited::VisitCXXConstructExpr(E); 17065 } 17066 17067 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 17068 Visit(E->getExpr()); 17069 } 17070 }; 17071 } 17072 17073 /// Mark any declarations that appear within this expression or any 17074 /// potentially-evaluated subexpressions as "referenced". 17075 /// 17076 /// \param SkipLocalVariables If true, don't mark local variables as 17077 /// 'referenced'. 17078 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 17079 bool SkipLocalVariables) { 17080 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 17081 } 17082 17083 /// Emit a diagnostic that describes an effect on the run-time behavior 17084 /// of the program being compiled. 17085 /// 17086 /// This routine emits the given diagnostic when the code currently being 17087 /// type-checked is "potentially evaluated", meaning that there is a 17088 /// possibility that the code will actually be executable. Code in sizeof() 17089 /// expressions, code used only during overload resolution, etc., are not 17090 /// potentially evaluated. This routine will suppress such diagnostics or, 17091 /// in the absolutely nutty case of potentially potentially evaluated 17092 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 17093 /// later. 17094 /// 17095 /// This routine should be used for all diagnostics that describe the run-time 17096 /// behavior of a program, such as passing a non-POD value through an ellipsis. 17097 /// Failure to do so will likely result in spurious diagnostics or failures 17098 /// during overload resolution or within sizeof/alignof/typeof/typeid. 17099 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 17100 const PartialDiagnostic &PD) { 17101 switch (ExprEvalContexts.back().Context) { 17102 case ExpressionEvaluationContext::Unevaluated: 17103 case ExpressionEvaluationContext::UnevaluatedList: 17104 case ExpressionEvaluationContext::UnevaluatedAbstract: 17105 case ExpressionEvaluationContext::DiscardedStatement: 17106 // The argument will never be evaluated, so don't complain. 17107 break; 17108 17109 case ExpressionEvaluationContext::ConstantEvaluated: 17110 // Relevant diagnostics should be produced by constant evaluation. 17111 break; 17112 17113 case ExpressionEvaluationContext::PotentiallyEvaluated: 17114 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 17115 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 17116 FunctionScopes.back()->PossiblyUnreachableDiags. 17117 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 17118 return true; 17119 } 17120 17121 // The initializer of a constexpr variable or of the first declaration of a 17122 // static data member is not syntactically a constant evaluated constant, 17123 // but nonetheless is always required to be a constant expression, so we 17124 // can skip diagnosing. 17125 // FIXME: Using the mangling context here is a hack. 17126 if (auto *VD = dyn_cast_or_null<VarDecl>( 17127 ExprEvalContexts.back().ManglingContextDecl)) { 17128 if (VD->isConstexpr() || 17129 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 17130 break; 17131 // FIXME: For any other kind of variable, we should build a CFG for its 17132 // initializer and check whether the context in question is reachable. 17133 } 17134 17135 Diag(Loc, PD); 17136 return true; 17137 } 17138 17139 return false; 17140 } 17141 17142 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 17143 const PartialDiagnostic &PD) { 17144 return DiagRuntimeBehavior( 17145 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 17146 } 17147 17148 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 17149 CallExpr *CE, FunctionDecl *FD) { 17150 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 17151 return false; 17152 17153 // If we're inside a decltype's expression, don't check for a valid return 17154 // type or construct temporaries until we know whether this is the last call. 17155 if (ExprEvalContexts.back().ExprContext == 17156 ExpressionEvaluationContextRecord::EK_Decltype) { 17157 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 17158 return false; 17159 } 17160 17161 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 17162 FunctionDecl *FD; 17163 CallExpr *CE; 17164 17165 public: 17166 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 17167 : FD(FD), CE(CE) { } 17168 17169 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 17170 if (!FD) { 17171 S.Diag(Loc, diag::err_call_incomplete_return) 17172 << T << CE->getSourceRange(); 17173 return; 17174 } 17175 17176 S.Diag(Loc, diag::err_call_function_incomplete_return) 17177 << CE->getSourceRange() << FD->getDeclName() << T; 17178 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 17179 << FD->getDeclName(); 17180 } 17181 } Diagnoser(FD, CE); 17182 17183 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 17184 return true; 17185 17186 return false; 17187 } 17188 17189 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 17190 // will prevent this condition from triggering, which is what we want. 17191 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 17192 SourceLocation Loc; 17193 17194 unsigned diagnostic = diag::warn_condition_is_assignment; 17195 bool IsOrAssign = false; 17196 17197 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 17198 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 17199 return; 17200 17201 IsOrAssign = Op->getOpcode() == BO_OrAssign; 17202 17203 // Greylist some idioms by putting them into a warning subcategory. 17204 if (ObjCMessageExpr *ME 17205 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 17206 Selector Sel = ME->getSelector(); 17207 17208 // self = [<foo> init...] 17209 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 17210 diagnostic = diag::warn_condition_is_idiomatic_assignment; 17211 17212 // <foo> = [<bar> nextObject] 17213 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 17214 diagnostic = diag::warn_condition_is_idiomatic_assignment; 17215 } 17216 17217 Loc = Op->getOperatorLoc(); 17218 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 17219 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 17220 return; 17221 17222 IsOrAssign = Op->getOperator() == OO_PipeEqual; 17223 Loc = Op->getOperatorLoc(); 17224 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 17225 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 17226 else { 17227 // Not an assignment. 17228 return; 17229 } 17230 17231 Diag(Loc, diagnostic) << E->getSourceRange(); 17232 17233 SourceLocation Open = E->getBeginLoc(); 17234 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 17235 Diag(Loc, diag::note_condition_assign_silence) 17236 << FixItHint::CreateInsertion(Open, "(") 17237 << FixItHint::CreateInsertion(Close, ")"); 17238 17239 if (IsOrAssign) 17240 Diag(Loc, diag::note_condition_or_assign_to_comparison) 17241 << FixItHint::CreateReplacement(Loc, "!="); 17242 else 17243 Diag(Loc, diag::note_condition_assign_to_comparison) 17244 << FixItHint::CreateReplacement(Loc, "=="); 17245 } 17246 17247 /// Redundant parentheses over an equality comparison can indicate 17248 /// that the user intended an assignment used as condition. 17249 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 17250 // Don't warn if the parens came from a macro. 17251 SourceLocation parenLoc = ParenE->getBeginLoc(); 17252 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 17253 return; 17254 // Don't warn for dependent expressions. 17255 if (ParenE->isTypeDependent()) 17256 return; 17257 17258 Expr *E = ParenE->IgnoreParens(); 17259 17260 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 17261 if (opE->getOpcode() == BO_EQ && 17262 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 17263 == Expr::MLV_Valid) { 17264 SourceLocation Loc = opE->getOperatorLoc(); 17265 17266 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 17267 SourceRange ParenERange = ParenE->getSourceRange(); 17268 Diag(Loc, diag::note_equality_comparison_silence) 17269 << FixItHint::CreateRemoval(ParenERange.getBegin()) 17270 << FixItHint::CreateRemoval(ParenERange.getEnd()); 17271 Diag(Loc, diag::note_equality_comparison_to_assign) 17272 << FixItHint::CreateReplacement(Loc, "="); 17273 } 17274 } 17275 17276 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 17277 bool IsConstexpr) { 17278 DiagnoseAssignmentAsCondition(E); 17279 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 17280 DiagnoseEqualityWithExtraParens(parenE); 17281 17282 ExprResult result = CheckPlaceholderExpr(E); 17283 if (result.isInvalid()) return ExprError(); 17284 E = result.get(); 17285 17286 if (!E->isTypeDependent()) { 17287 if (getLangOpts().CPlusPlus) 17288 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 17289 17290 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 17291 if (ERes.isInvalid()) 17292 return ExprError(); 17293 E = ERes.get(); 17294 17295 QualType T = E->getType(); 17296 if (!T->isScalarType()) { // C99 6.8.4.1p1 17297 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 17298 << T << E->getSourceRange(); 17299 return ExprError(); 17300 } 17301 CheckBoolLikeConversion(E, Loc); 17302 } 17303 17304 return E; 17305 } 17306 17307 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 17308 Expr *SubExpr, ConditionKind CK) { 17309 // Empty conditions are valid in for-statements. 17310 if (!SubExpr) 17311 return ConditionResult(); 17312 17313 ExprResult Cond; 17314 switch (CK) { 17315 case ConditionKind::Boolean: 17316 Cond = CheckBooleanCondition(Loc, SubExpr); 17317 break; 17318 17319 case ConditionKind::ConstexprIf: 17320 Cond = CheckBooleanCondition(Loc, SubExpr, true); 17321 break; 17322 17323 case ConditionKind::Switch: 17324 Cond = CheckSwitchCondition(Loc, SubExpr); 17325 break; 17326 } 17327 if (Cond.isInvalid()) 17328 return ConditionError(); 17329 17330 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 17331 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 17332 if (!FullExpr.get()) 17333 return ConditionError(); 17334 17335 return ConditionResult(*this, nullptr, FullExpr, 17336 CK == ConditionKind::ConstexprIf); 17337 } 17338 17339 namespace { 17340 /// A visitor for rebuilding a call to an __unknown_any expression 17341 /// to have an appropriate type. 17342 struct RebuildUnknownAnyFunction 17343 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 17344 17345 Sema &S; 17346 17347 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 17348 17349 ExprResult VisitStmt(Stmt *S) { 17350 llvm_unreachable("unexpected statement!"); 17351 } 17352 17353 ExprResult VisitExpr(Expr *E) { 17354 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 17355 << E->getSourceRange(); 17356 return ExprError(); 17357 } 17358 17359 /// Rebuild an expression which simply semantically wraps another 17360 /// expression which it shares the type and value kind of. 17361 template <class T> ExprResult rebuildSugarExpr(T *E) { 17362 ExprResult SubResult = Visit(E->getSubExpr()); 17363 if (SubResult.isInvalid()) return ExprError(); 17364 17365 Expr *SubExpr = SubResult.get(); 17366 E->setSubExpr(SubExpr); 17367 E->setType(SubExpr->getType()); 17368 E->setValueKind(SubExpr->getValueKind()); 17369 assert(E->getObjectKind() == OK_Ordinary); 17370 return E; 17371 } 17372 17373 ExprResult VisitParenExpr(ParenExpr *E) { 17374 return rebuildSugarExpr(E); 17375 } 17376 17377 ExprResult VisitUnaryExtension(UnaryOperator *E) { 17378 return rebuildSugarExpr(E); 17379 } 17380 17381 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 17382 ExprResult SubResult = Visit(E->getSubExpr()); 17383 if (SubResult.isInvalid()) return ExprError(); 17384 17385 Expr *SubExpr = SubResult.get(); 17386 E->setSubExpr(SubExpr); 17387 E->setType(S.Context.getPointerType(SubExpr->getType())); 17388 assert(E->getValueKind() == VK_RValue); 17389 assert(E->getObjectKind() == OK_Ordinary); 17390 return E; 17391 } 17392 17393 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 17394 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 17395 17396 E->setType(VD->getType()); 17397 17398 assert(E->getValueKind() == VK_RValue); 17399 if (S.getLangOpts().CPlusPlus && 17400 !(isa<CXXMethodDecl>(VD) && 17401 cast<CXXMethodDecl>(VD)->isInstance())) 17402 E->setValueKind(VK_LValue); 17403 17404 return E; 17405 } 17406 17407 ExprResult VisitMemberExpr(MemberExpr *E) { 17408 return resolveDecl(E, E->getMemberDecl()); 17409 } 17410 17411 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 17412 return resolveDecl(E, E->getDecl()); 17413 } 17414 }; 17415 } 17416 17417 /// Given a function expression of unknown-any type, try to rebuild it 17418 /// to have a function type. 17419 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 17420 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 17421 if (Result.isInvalid()) return ExprError(); 17422 return S.DefaultFunctionArrayConversion(Result.get()); 17423 } 17424 17425 namespace { 17426 /// A visitor for rebuilding an expression of type __unknown_anytype 17427 /// into one which resolves the type directly on the referring 17428 /// expression. Strict preservation of the original source 17429 /// structure is not a goal. 17430 struct RebuildUnknownAnyExpr 17431 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 17432 17433 Sema &S; 17434 17435 /// The current destination type. 17436 QualType DestType; 17437 17438 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 17439 : S(S), DestType(CastType) {} 17440 17441 ExprResult VisitStmt(Stmt *S) { 17442 llvm_unreachable("unexpected statement!"); 17443 } 17444 17445 ExprResult VisitExpr(Expr *E) { 17446 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 17447 << E->getSourceRange(); 17448 return ExprError(); 17449 } 17450 17451 ExprResult VisitCallExpr(CallExpr *E); 17452 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 17453 17454 /// Rebuild an expression which simply semantically wraps another 17455 /// expression which it shares the type and value kind of. 17456 template <class T> ExprResult rebuildSugarExpr(T *E) { 17457 ExprResult SubResult = Visit(E->getSubExpr()); 17458 if (SubResult.isInvalid()) return ExprError(); 17459 Expr *SubExpr = SubResult.get(); 17460 E->setSubExpr(SubExpr); 17461 E->setType(SubExpr->getType()); 17462 E->setValueKind(SubExpr->getValueKind()); 17463 assert(E->getObjectKind() == OK_Ordinary); 17464 return E; 17465 } 17466 17467 ExprResult VisitParenExpr(ParenExpr *E) { 17468 return rebuildSugarExpr(E); 17469 } 17470 17471 ExprResult VisitUnaryExtension(UnaryOperator *E) { 17472 return rebuildSugarExpr(E); 17473 } 17474 17475 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 17476 const PointerType *Ptr = DestType->getAs<PointerType>(); 17477 if (!Ptr) { 17478 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 17479 << E->getSourceRange(); 17480 return ExprError(); 17481 } 17482 17483 if (isa<CallExpr>(E->getSubExpr())) { 17484 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 17485 << E->getSourceRange(); 17486 return ExprError(); 17487 } 17488 17489 assert(E->getValueKind() == VK_RValue); 17490 assert(E->getObjectKind() == OK_Ordinary); 17491 E->setType(DestType); 17492 17493 // Build the sub-expression as if it were an object of the pointee type. 17494 DestType = Ptr->getPointeeType(); 17495 ExprResult SubResult = Visit(E->getSubExpr()); 17496 if (SubResult.isInvalid()) return ExprError(); 17497 E->setSubExpr(SubResult.get()); 17498 return E; 17499 } 17500 17501 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 17502 17503 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 17504 17505 ExprResult VisitMemberExpr(MemberExpr *E) { 17506 return resolveDecl(E, E->getMemberDecl()); 17507 } 17508 17509 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 17510 return resolveDecl(E, E->getDecl()); 17511 } 17512 }; 17513 } 17514 17515 /// Rebuilds a call expression which yielded __unknown_anytype. 17516 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 17517 Expr *CalleeExpr = E->getCallee(); 17518 17519 enum FnKind { 17520 FK_MemberFunction, 17521 FK_FunctionPointer, 17522 FK_BlockPointer 17523 }; 17524 17525 FnKind Kind; 17526 QualType CalleeType = CalleeExpr->getType(); 17527 if (CalleeType == S.Context.BoundMemberTy) { 17528 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 17529 Kind = FK_MemberFunction; 17530 CalleeType = Expr::findBoundMemberType(CalleeExpr); 17531 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 17532 CalleeType = Ptr->getPointeeType(); 17533 Kind = FK_FunctionPointer; 17534 } else { 17535 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 17536 Kind = FK_BlockPointer; 17537 } 17538 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 17539 17540 // Verify that this is a legal result type of a function. 17541 if (DestType->isArrayType() || DestType->isFunctionType()) { 17542 unsigned diagID = diag::err_func_returning_array_function; 17543 if (Kind == FK_BlockPointer) 17544 diagID = diag::err_block_returning_array_function; 17545 17546 S.Diag(E->getExprLoc(), diagID) 17547 << DestType->isFunctionType() << DestType; 17548 return ExprError(); 17549 } 17550 17551 // Otherwise, go ahead and set DestType as the call's result. 17552 E->setType(DestType.getNonLValueExprType(S.Context)); 17553 E->setValueKind(Expr::getValueKindForType(DestType)); 17554 assert(E->getObjectKind() == OK_Ordinary); 17555 17556 // Rebuild the function type, replacing the result type with DestType. 17557 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 17558 if (Proto) { 17559 // __unknown_anytype(...) is a special case used by the debugger when 17560 // it has no idea what a function's signature is. 17561 // 17562 // We want to build this call essentially under the K&R 17563 // unprototyped rules, but making a FunctionNoProtoType in C++ 17564 // would foul up all sorts of assumptions. However, we cannot 17565 // simply pass all arguments as variadic arguments, nor can we 17566 // portably just call the function under a non-variadic type; see 17567 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 17568 // However, it turns out that in practice it is generally safe to 17569 // call a function declared as "A foo(B,C,D);" under the prototype 17570 // "A foo(B,C,D,...);". The only known exception is with the 17571 // Windows ABI, where any variadic function is implicitly cdecl 17572 // regardless of its normal CC. Therefore we change the parameter 17573 // types to match the types of the arguments. 17574 // 17575 // This is a hack, but it is far superior to moving the 17576 // corresponding target-specific code from IR-gen to Sema/AST. 17577 17578 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 17579 SmallVector<QualType, 8> ArgTypes; 17580 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 17581 ArgTypes.reserve(E->getNumArgs()); 17582 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 17583 Expr *Arg = E->getArg(i); 17584 QualType ArgType = Arg->getType(); 17585 if (E->isLValue()) { 17586 ArgType = S.Context.getLValueReferenceType(ArgType); 17587 } else if (E->isXValue()) { 17588 ArgType = S.Context.getRValueReferenceType(ArgType); 17589 } 17590 ArgTypes.push_back(ArgType); 17591 } 17592 ParamTypes = ArgTypes; 17593 } 17594 DestType = S.Context.getFunctionType(DestType, ParamTypes, 17595 Proto->getExtProtoInfo()); 17596 } else { 17597 DestType = S.Context.getFunctionNoProtoType(DestType, 17598 FnType->getExtInfo()); 17599 } 17600 17601 // Rebuild the appropriate pointer-to-function type. 17602 switch (Kind) { 17603 case FK_MemberFunction: 17604 // Nothing to do. 17605 break; 17606 17607 case FK_FunctionPointer: 17608 DestType = S.Context.getPointerType(DestType); 17609 break; 17610 17611 case FK_BlockPointer: 17612 DestType = S.Context.getBlockPointerType(DestType); 17613 break; 17614 } 17615 17616 // Finally, we can recurse. 17617 ExprResult CalleeResult = Visit(CalleeExpr); 17618 if (!CalleeResult.isUsable()) return ExprError(); 17619 E->setCallee(CalleeResult.get()); 17620 17621 // Bind a temporary if necessary. 17622 return S.MaybeBindToTemporary(E); 17623 } 17624 17625 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 17626 // Verify that this is a legal result type of a call. 17627 if (DestType->isArrayType() || DestType->isFunctionType()) { 17628 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 17629 << DestType->isFunctionType() << DestType; 17630 return ExprError(); 17631 } 17632 17633 // Rewrite the method result type if available. 17634 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 17635 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 17636 Method->setReturnType(DestType); 17637 } 17638 17639 // Change the type of the message. 17640 E->setType(DestType.getNonReferenceType()); 17641 E->setValueKind(Expr::getValueKindForType(DestType)); 17642 17643 return S.MaybeBindToTemporary(E); 17644 } 17645 17646 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 17647 // The only case we should ever see here is a function-to-pointer decay. 17648 if (E->getCastKind() == CK_FunctionToPointerDecay) { 17649 assert(E->getValueKind() == VK_RValue); 17650 assert(E->getObjectKind() == OK_Ordinary); 17651 17652 E->setType(DestType); 17653 17654 // Rebuild the sub-expression as the pointee (function) type. 17655 DestType = DestType->castAs<PointerType>()->getPointeeType(); 17656 17657 ExprResult Result = Visit(E->getSubExpr()); 17658 if (!Result.isUsable()) return ExprError(); 17659 17660 E->setSubExpr(Result.get()); 17661 return E; 17662 } else if (E->getCastKind() == CK_LValueToRValue) { 17663 assert(E->getValueKind() == VK_RValue); 17664 assert(E->getObjectKind() == OK_Ordinary); 17665 17666 assert(isa<BlockPointerType>(E->getType())); 17667 17668 E->setType(DestType); 17669 17670 // The sub-expression has to be a lvalue reference, so rebuild it as such. 17671 DestType = S.Context.getLValueReferenceType(DestType); 17672 17673 ExprResult Result = Visit(E->getSubExpr()); 17674 if (!Result.isUsable()) return ExprError(); 17675 17676 E->setSubExpr(Result.get()); 17677 return E; 17678 } else { 17679 llvm_unreachable("Unhandled cast type!"); 17680 } 17681 } 17682 17683 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 17684 ExprValueKind ValueKind = VK_LValue; 17685 QualType Type = DestType; 17686 17687 // We know how to make this work for certain kinds of decls: 17688 17689 // - functions 17690 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 17691 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 17692 DestType = Ptr->getPointeeType(); 17693 ExprResult Result = resolveDecl(E, VD); 17694 if (Result.isInvalid()) return ExprError(); 17695 return S.ImpCastExprToType(Result.get(), Type, 17696 CK_FunctionToPointerDecay, VK_RValue); 17697 } 17698 17699 if (!Type->isFunctionType()) { 17700 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 17701 << VD << E->getSourceRange(); 17702 return ExprError(); 17703 } 17704 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 17705 // We must match the FunctionDecl's type to the hack introduced in 17706 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 17707 // type. See the lengthy commentary in that routine. 17708 QualType FDT = FD->getType(); 17709 const FunctionType *FnType = FDT->castAs<FunctionType>(); 17710 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 17711 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 17712 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 17713 SourceLocation Loc = FD->getLocation(); 17714 FunctionDecl *NewFD = FunctionDecl::Create( 17715 S.Context, FD->getDeclContext(), Loc, Loc, 17716 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 17717 SC_None, false /*isInlineSpecified*/, FD->hasPrototype(), 17718 /*ConstexprKind*/ CSK_unspecified); 17719 17720 if (FD->getQualifier()) 17721 NewFD->setQualifierInfo(FD->getQualifierLoc()); 17722 17723 SmallVector<ParmVarDecl*, 16> Params; 17724 for (const auto &AI : FT->param_types()) { 17725 ParmVarDecl *Param = 17726 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 17727 Param->setScopeInfo(0, Params.size()); 17728 Params.push_back(Param); 17729 } 17730 NewFD->setParams(Params); 17731 DRE->setDecl(NewFD); 17732 VD = DRE->getDecl(); 17733 } 17734 } 17735 17736 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 17737 if (MD->isInstance()) { 17738 ValueKind = VK_RValue; 17739 Type = S.Context.BoundMemberTy; 17740 } 17741 17742 // Function references aren't l-values in C. 17743 if (!S.getLangOpts().CPlusPlus) 17744 ValueKind = VK_RValue; 17745 17746 // - variables 17747 } else if (isa<VarDecl>(VD)) { 17748 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 17749 Type = RefTy->getPointeeType(); 17750 } else if (Type->isFunctionType()) { 17751 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 17752 << VD << E->getSourceRange(); 17753 return ExprError(); 17754 } 17755 17756 // - nothing else 17757 } else { 17758 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 17759 << VD << E->getSourceRange(); 17760 return ExprError(); 17761 } 17762 17763 // Modifying the declaration like this is friendly to IR-gen but 17764 // also really dangerous. 17765 VD->setType(DestType); 17766 E->setType(Type); 17767 E->setValueKind(ValueKind); 17768 return E; 17769 } 17770 17771 /// Check a cast of an unknown-any type. We intentionally only 17772 /// trigger this for C-style casts. 17773 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 17774 Expr *CastExpr, CastKind &CastKind, 17775 ExprValueKind &VK, CXXCastPath &Path) { 17776 // The type we're casting to must be either void or complete. 17777 if (!CastType->isVoidType() && 17778 RequireCompleteType(TypeRange.getBegin(), CastType, 17779 diag::err_typecheck_cast_to_incomplete)) 17780 return ExprError(); 17781 17782 // Rewrite the casted expression from scratch. 17783 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 17784 if (!result.isUsable()) return ExprError(); 17785 17786 CastExpr = result.get(); 17787 VK = CastExpr->getValueKind(); 17788 CastKind = CK_NoOp; 17789 17790 return CastExpr; 17791 } 17792 17793 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 17794 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 17795 } 17796 17797 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 17798 Expr *arg, QualType ¶mType) { 17799 // If the syntactic form of the argument is not an explicit cast of 17800 // any sort, just do default argument promotion. 17801 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 17802 if (!castArg) { 17803 ExprResult result = DefaultArgumentPromotion(arg); 17804 if (result.isInvalid()) return ExprError(); 17805 paramType = result.get()->getType(); 17806 return result; 17807 } 17808 17809 // Otherwise, use the type that was written in the explicit cast. 17810 assert(!arg->hasPlaceholderType()); 17811 paramType = castArg->getTypeAsWritten(); 17812 17813 // Copy-initialize a parameter of that type. 17814 InitializedEntity entity = 17815 InitializedEntity::InitializeParameter(Context, paramType, 17816 /*consumed*/ false); 17817 return PerformCopyInitialization(entity, callLoc, arg); 17818 } 17819 17820 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 17821 Expr *orig = E; 17822 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 17823 while (true) { 17824 E = E->IgnoreParenImpCasts(); 17825 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 17826 E = call->getCallee(); 17827 diagID = diag::err_uncasted_call_of_unknown_any; 17828 } else { 17829 break; 17830 } 17831 } 17832 17833 SourceLocation loc; 17834 NamedDecl *d; 17835 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 17836 loc = ref->getLocation(); 17837 d = ref->getDecl(); 17838 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 17839 loc = mem->getMemberLoc(); 17840 d = mem->getMemberDecl(); 17841 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 17842 diagID = diag::err_uncasted_call_of_unknown_any; 17843 loc = msg->getSelectorStartLoc(); 17844 d = msg->getMethodDecl(); 17845 if (!d) { 17846 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 17847 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 17848 << orig->getSourceRange(); 17849 return ExprError(); 17850 } 17851 } else { 17852 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 17853 << E->getSourceRange(); 17854 return ExprError(); 17855 } 17856 17857 S.Diag(loc, diagID) << d << orig->getSourceRange(); 17858 17859 // Never recoverable. 17860 return ExprError(); 17861 } 17862 17863 /// Check for operands with placeholder types and complain if found. 17864 /// Returns ExprError() if there was an error and no recovery was possible. 17865 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 17866 if (!getLangOpts().CPlusPlus) { 17867 // C cannot handle TypoExpr nodes on either side of a binop because it 17868 // doesn't handle dependent types properly, so make sure any TypoExprs have 17869 // been dealt with before checking the operands. 17870 ExprResult Result = CorrectDelayedTyposInExpr(E); 17871 if (!Result.isUsable()) return ExprError(); 17872 E = Result.get(); 17873 } 17874 17875 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 17876 if (!placeholderType) return E; 17877 17878 switch (placeholderType->getKind()) { 17879 17880 // Overloaded expressions. 17881 case BuiltinType::Overload: { 17882 // Try to resolve a single function template specialization. 17883 // This is obligatory. 17884 ExprResult Result = E; 17885 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 17886 return Result; 17887 17888 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 17889 // leaves Result unchanged on failure. 17890 Result = E; 17891 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) 17892 return Result; 17893 17894 // If that failed, try to recover with a call. 17895 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 17896 /*complain*/ true); 17897 return Result; 17898 } 17899 17900 // Bound member functions. 17901 case BuiltinType::BoundMember: { 17902 ExprResult result = E; 17903 const Expr *BME = E->IgnoreParens(); 17904 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 17905 // Try to give a nicer diagnostic if it is a bound member that we recognize. 17906 if (isa<CXXPseudoDestructorExpr>(BME)) { 17907 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 17908 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 17909 if (ME->getMemberNameInfo().getName().getNameKind() == 17910 DeclarationName::CXXDestructorName) 17911 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 17912 } 17913 tryToRecoverWithCall(result, PD, 17914 /*complain*/ true); 17915 return result; 17916 } 17917 17918 // ARC unbridged casts. 17919 case BuiltinType::ARCUnbridgedCast: { 17920 Expr *realCast = stripARCUnbridgedCast(E); 17921 diagnoseARCUnbridgedCast(realCast); 17922 return realCast; 17923 } 17924 17925 // Expressions of unknown type. 17926 case BuiltinType::UnknownAny: 17927 return diagnoseUnknownAnyExpr(*this, E); 17928 17929 // Pseudo-objects. 17930 case BuiltinType::PseudoObject: 17931 return checkPseudoObjectRValue(E); 17932 17933 case BuiltinType::BuiltinFn: { 17934 // Accept __noop without parens by implicitly converting it to a call expr. 17935 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 17936 if (DRE) { 17937 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 17938 if (FD->getBuiltinID() == Builtin::BI__noop) { 17939 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 17940 CK_BuiltinFnToFnPtr) 17941 .get(); 17942 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 17943 VK_RValue, SourceLocation()); 17944 } 17945 } 17946 17947 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 17948 return ExprError(); 17949 } 17950 17951 // Expressions of unknown type. 17952 case BuiltinType::OMPArraySection: 17953 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 17954 return ExprError(); 17955 17956 // Everything else should be impossible. 17957 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 17958 case BuiltinType::Id: 17959 #include "clang/Basic/OpenCLImageTypes.def" 17960 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 17961 case BuiltinType::Id: 17962 #include "clang/Basic/OpenCLExtensionTypes.def" 17963 #define SVE_TYPE(Name, Id, SingletonId) \ 17964 case BuiltinType::Id: 17965 #include "clang/Basic/AArch64SVEACLETypes.def" 17966 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 17967 #define PLACEHOLDER_TYPE(Id, SingletonId) 17968 #include "clang/AST/BuiltinTypes.def" 17969 break; 17970 } 17971 17972 llvm_unreachable("invalid placeholder type!"); 17973 } 17974 17975 bool Sema::CheckCaseExpression(Expr *E) { 17976 if (E->isTypeDependent()) 17977 return true; 17978 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 17979 return E->getType()->isIntegralOrEnumerationType(); 17980 return false; 17981 } 17982 17983 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 17984 ExprResult 17985 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 17986 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 17987 "Unknown Objective-C Boolean value!"); 17988 QualType BoolT = Context.ObjCBuiltinBoolTy; 17989 if (!Context.getBOOLDecl()) { 17990 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 17991 Sema::LookupOrdinaryName); 17992 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 17993 NamedDecl *ND = Result.getFoundDecl(); 17994 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 17995 Context.setBOOLDecl(TD); 17996 } 17997 } 17998 if (Context.getBOOLDecl()) 17999 BoolT = Context.getBOOLType(); 18000 return new (Context) 18001 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 18002 } 18003 18004 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 18005 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 18006 SourceLocation RParen) { 18007 18008 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 18009 18010 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 18011 return Spec.getPlatform() == Platform; 18012 }); 18013 18014 VersionTuple Version; 18015 if (Spec != AvailSpecs.end()) 18016 Version = Spec->getVersion(); 18017 18018 // The use of `@available` in the enclosing function should be analyzed to 18019 // warn when it's used inappropriately (i.e. not if(@available)). 18020 if (getCurFunctionOrMethodDecl()) 18021 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 18022 else if (getCurBlock() || getCurLambda()) 18023 getCurFunction()->HasPotentialAvailabilityViolations = true; 18024 18025 return new (Context) 18026 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 18027 } 18028