1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements semantic analysis for expressions. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "TreeTransform.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/ASTMutationListener.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/DeclObjC.h" 21 #include "clang/AST/DeclTemplate.h" 22 #include "clang/AST/EvaluatedExprVisitor.h" 23 #include "clang/AST/Expr.h" 24 #include "clang/AST/ExprCXX.h" 25 #include "clang/AST/ExprObjC.h" 26 #include "clang/AST/ExprOpenMP.h" 27 #include "clang/AST/RecursiveASTVisitor.h" 28 #include "clang/AST/TypeLoc.h" 29 #include "clang/Basic/PartialDiagnostic.h" 30 #include "clang/Basic/SourceManager.h" 31 #include "clang/Basic/TargetInfo.h" 32 #include "clang/Lex/LiteralSupport.h" 33 #include "clang/Lex/Preprocessor.h" 34 #include "clang/Sema/AnalysisBasedWarnings.h" 35 #include "clang/Sema/DeclSpec.h" 36 #include "clang/Sema/DelayedDiagnostic.h" 37 #include "clang/Sema/Designator.h" 38 #include "clang/Sema/Initialization.h" 39 #include "clang/Sema/Lookup.h" 40 #include "clang/Sema/ParsedTemplate.h" 41 #include "clang/Sema/Scope.h" 42 #include "clang/Sema/ScopeInfo.h" 43 #include "clang/Sema/SemaFixItUtils.h" 44 #include "clang/Sema/SemaInternal.h" 45 #include "clang/Sema/Template.h" 46 #include "llvm/Support/ConvertUTF.h" 47 using namespace clang; 48 using namespace sema; 49 50 /// \brief Determine whether the use of this declaration is valid, without 51 /// emitting diagnostics. 52 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 53 // See if this is an auto-typed variable whose initializer we are parsing. 54 if (ParsingInitForAutoVars.count(D)) 55 return false; 56 57 // See if this is a deleted function. 58 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 59 if (FD->isDeleted()) 60 return false; 61 62 // If the function has a deduced return type, and we can't deduce it, 63 // then we can't use it either. 64 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 65 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 66 return false; 67 } 68 69 // See if this function is unavailable. 70 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 71 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 72 return false; 73 74 return true; 75 } 76 77 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 78 // Warn if this is used but marked unused. 79 if (const auto *A = D->getAttr<UnusedAttr>()) { 80 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 81 // should diagnose them. 82 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused) { 83 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 84 if (DC && !DC->hasAttr<UnusedAttr>()) 85 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 86 } 87 } 88 } 89 90 /// \brief Emit a note explaining that this function is deleted. 91 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 92 assert(Decl->isDeleted()); 93 94 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 95 96 if (Method && Method->isDeleted() && Method->isDefaulted()) { 97 // If the method was explicitly defaulted, point at that declaration. 98 if (!Method->isImplicit()) 99 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 100 101 // Try to diagnose why this special member function was implicitly 102 // deleted. This might fail, if that reason no longer applies. 103 CXXSpecialMember CSM = getSpecialMember(Method); 104 if (CSM != CXXInvalid) 105 ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true); 106 107 return; 108 } 109 110 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 111 if (Ctor && Ctor->isInheritingConstructor()) 112 return NoteDeletedInheritingConstructor(Ctor); 113 114 Diag(Decl->getLocation(), diag::note_availability_specified_here) 115 << Decl << true; 116 } 117 118 /// \brief Determine whether a FunctionDecl was ever declared with an 119 /// explicit storage class. 120 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 121 for (auto I : D->redecls()) { 122 if (I->getStorageClass() != SC_None) 123 return true; 124 } 125 return false; 126 } 127 128 /// \brief Check whether we're in an extern inline function and referring to a 129 /// variable or function with internal linkage (C11 6.7.4p3). 130 /// 131 /// This is only a warning because we used to silently accept this code, but 132 /// in many cases it will not behave correctly. This is not enabled in C++ mode 133 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 134 /// and so while there may still be user mistakes, most of the time we can't 135 /// prove that there are errors. 136 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 137 const NamedDecl *D, 138 SourceLocation Loc) { 139 // This is disabled under C++; there are too many ways for this to fire in 140 // contexts where the warning is a false positive, or where it is technically 141 // correct but benign. 142 if (S.getLangOpts().CPlusPlus) 143 return; 144 145 // Check if this is an inlined function or method. 146 FunctionDecl *Current = S.getCurFunctionDecl(); 147 if (!Current) 148 return; 149 if (!Current->isInlined()) 150 return; 151 if (!Current->isExternallyVisible()) 152 return; 153 154 // Check if the decl has internal linkage. 155 if (D->getFormalLinkage() != InternalLinkage) 156 return; 157 158 // Downgrade from ExtWarn to Extension if 159 // (1) the supposedly external inline function is in the main file, 160 // and probably won't be included anywhere else. 161 // (2) the thing we're referencing is a pure function. 162 // (3) the thing we're referencing is another inline function. 163 // This last can give us false negatives, but it's better than warning on 164 // wrappers for simple C library functions. 165 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 166 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 167 if (!DowngradeWarning && UsedFn) 168 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 169 170 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 171 : diag::ext_internal_in_extern_inline) 172 << /*IsVar=*/!UsedFn << D; 173 174 S.MaybeSuggestAddingStaticToDecl(Current); 175 176 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 177 << D; 178 } 179 180 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 181 const FunctionDecl *First = Cur->getFirstDecl(); 182 183 // Suggest "static" on the function, if possible. 184 if (!hasAnyExplicitStorageClass(First)) { 185 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 186 Diag(DeclBegin, diag::note_convert_inline_to_static) 187 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 188 } 189 } 190 191 /// \brief Determine whether the use of this declaration is valid, and 192 /// emit any corresponding diagnostics. 193 /// 194 /// This routine diagnoses various problems with referencing 195 /// declarations that can occur when using a declaration. For example, 196 /// it might warn if a deprecated or unavailable declaration is being 197 /// used, or produce an error (and return true) if a C++0x deleted 198 /// function is being used. 199 /// 200 /// \returns true if there was an error (this declaration cannot be 201 /// referenced), false otherwise. 202 /// 203 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 204 const ObjCInterfaceDecl *UnknownObjCClass, 205 bool ObjCPropertyAccess, 206 bool AvoidPartialAvailabilityChecks) { 207 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 208 // If there were any diagnostics suppressed by template argument deduction, 209 // emit them now. 210 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 211 if (Pos != SuppressedDiagnostics.end()) { 212 for (const PartialDiagnosticAt &Suppressed : Pos->second) 213 Diag(Suppressed.first, Suppressed.second); 214 215 // Clear out the list of suppressed diagnostics, so that we don't emit 216 // them again for this specialization. However, we don't obsolete this 217 // entry from the table, because we want to avoid ever emitting these 218 // diagnostics again. 219 Pos->second.clear(); 220 } 221 222 // C++ [basic.start.main]p3: 223 // The function 'main' shall not be used within a program. 224 if (cast<FunctionDecl>(D)->isMain()) 225 Diag(Loc, diag::ext_main_used); 226 } 227 228 // See if this is an auto-typed variable whose initializer we are parsing. 229 if (ParsingInitForAutoVars.count(D)) { 230 if (isa<BindingDecl>(D)) { 231 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 232 << D->getDeclName(); 233 } else { 234 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 235 << D->getDeclName() << cast<VarDecl>(D)->getType(); 236 } 237 return true; 238 } 239 240 // See if this is a deleted function. 241 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 242 if (FD->isDeleted()) { 243 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 244 if (Ctor && Ctor->isInheritingConstructor()) 245 Diag(Loc, diag::err_deleted_inherited_ctor_use) 246 << Ctor->getParent() 247 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 248 else 249 Diag(Loc, diag::err_deleted_function_use); 250 NoteDeletedFunction(FD); 251 return true; 252 } 253 254 // If the function has a deduced return type, and we can't deduce it, 255 // then we can't use it either. 256 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 257 DeduceReturnType(FD, Loc)) 258 return true; 259 260 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 261 return true; 262 } 263 264 auto getReferencedObjCProp = [](const NamedDecl *D) -> 265 const ObjCPropertyDecl * { 266 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 267 return MD->findPropertyDecl(); 268 return nullptr; 269 }; 270 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 271 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 272 return true; 273 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 274 return true; 275 } 276 277 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 278 // Only the variables omp_in and omp_out are allowed in the combiner. 279 // Only the variables omp_priv and omp_orig are allowed in the 280 // initializer-clause. 281 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 282 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 283 isa<VarDecl>(D)) { 284 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 285 << getCurFunction()->HasOMPDeclareReductionCombiner; 286 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 287 return true; 288 } 289 290 DiagnoseAvailabilityOfDecl(D, Loc, UnknownObjCClass, ObjCPropertyAccess, 291 AvoidPartialAvailabilityChecks); 292 293 DiagnoseUnusedOfDecl(*this, D, Loc); 294 295 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 296 297 return false; 298 } 299 300 /// \brief Retrieve the message suffix that should be added to a 301 /// diagnostic complaining about the given function being deleted or 302 /// unavailable. 303 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 304 std::string Message; 305 if (FD->getAvailability(&Message)) 306 return ": " + Message; 307 308 return std::string(); 309 } 310 311 /// DiagnoseSentinelCalls - This routine checks whether a call or 312 /// message-send is to a declaration with the sentinel attribute, and 313 /// if so, it checks that the requirements of the sentinel are 314 /// satisfied. 315 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 316 ArrayRef<Expr *> Args) { 317 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 318 if (!attr) 319 return; 320 321 // The number of formal parameters of the declaration. 322 unsigned numFormalParams; 323 324 // The kind of declaration. This is also an index into a %select in 325 // the diagnostic. 326 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 327 328 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 329 numFormalParams = MD->param_size(); 330 calleeType = CT_Method; 331 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 332 numFormalParams = FD->param_size(); 333 calleeType = CT_Function; 334 } else if (isa<VarDecl>(D)) { 335 QualType type = cast<ValueDecl>(D)->getType(); 336 const FunctionType *fn = nullptr; 337 if (const PointerType *ptr = type->getAs<PointerType>()) { 338 fn = ptr->getPointeeType()->getAs<FunctionType>(); 339 if (!fn) return; 340 calleeType = CT_Function; 341 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 342 fn = ptr->getPointeeType()->castAs<FunctionType>(); 343 calleeType = CT_Block; 344 } else { 345 return; 346 } 347 348 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 349 numFormalParams = proto->getNumParams(); 350 } else { 351 numFormalParams = 0; 352 } 353 } else { 354 return; 355 } 356 357 // "nullPos" is the number of formal parameters at the end which 358 // effectively count as part of the variadic arguments. This is 359 // useful if you would prefer to not have *any* formal parameters, 360 // but the language forces you to have at least one. 361 unsigned nullPos = attr->getNullPos(); 362 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 363 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 364 365 // The number of arguments which should follow the sentinel. 366 unsigned numArgsAfterSentinel = attr->getSentinel(); 367 368 // If there aren't enough arguments for all the formal parameters, 369 // the sentinel, and the args after the sentinel, complain. 370 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 371 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 372 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 373 return; 374 } 375 376 // Otherwise, find the sentinel expression. 377 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 378 if (!sentinelExpr) return; 379 if (sentinelExpr->isValueDependent()) return; 380 if (Context.isSentinelNullExpr(sentinelExpr)) return; 381 382 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 383 // or 'NULL' if those are actually defined in the context. Only use 384 // 'nil' for ObjC methods, where it's much more likely that the 385 // variadic arguments form a list of object pointers. 386 SourceLocation MissingNilLoc 387 = getLocForEndOfToken(sentinelExpr->getLocEnd()); 388 std::string NullValue; 389 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 390 NullValue = "nil"; 391 else if (getLangOpts().CPlusPlus11) 392 NullValue = "nullptr"; 393 else if (PP.isMacroDefined("NULL")) 394 NullValue = "NULL"; 395 else 396 NullValue = "(void*) 0"; 397 398 if (MissingNilLoc.isInvalid()) 399 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 400 else 401 Diag(MissingNilLoc, diag::warn_missing_sentinel) 402 << int(calleeType) 403 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 404 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 405 } 406 407 SourceRange Sema::getExprRange(Expr *E) const { 408 return E ? E->getSourceRange() : SourceRange(); 409 } 410 411 //===----------------------------------------------------------------------===// 412 // Standard Promotions and Conversions 413 //===----------------------------------------------------------------------===// 414 415 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 416 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 417 // Handle any placeholder expressions which made it here. 418 if (E->getType()->isPlaceholderType()) { 419 ExprResult result = CheckPlaceholderExpr(E); 420 if (result.isInvalid()) return ExprError(); 421 E = result.get(); 422 } 423 424 QualType Ty = E->getType(); 425 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 426 427 if (Ty->isFunctionType()) { 428 // If we are here, we are not calling a function but taking 429 // its address (which is not allowed in OpenCL v1.0 s6.8.a.3). 430 if (getLangOpts().OpenCL) { 431 if (Diagnose) 432 Diag(E->getExprLoc(), diag::err_opencl_taking_function_address); 433 return ExprError(); 434 } 435 436 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 437 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 438 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 439 return ExprError(); 440 441 E = ImpCastExprToType(E, Context.getPointerType(Ty), 442 CK_FunctionToPointerDecay).get(); 443 } else if (Ty->isArrayType()) { 444 // In C90 mode, arrays only promote to pointers if the array expression is 445 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 446 // type 'array of type' is converted to an expression that has type 'pointer 447 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 448 // that has type 'array of type' ...". The relevant change is "an lvalue" 449 // (C90) to "an expression" (C99). 450 // 451 // C++ 4.2p1: 452 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 453 // T" can be converted to an rvalue of type "pointer to T". 454 // 455 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 456 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 457 CK_ArrayToPointerDecay).get(); 458 } 459 return E; 460 } 461 462 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 463 // Check to see if we are dereferencing a null pointer. If so, 464 // and if not volatile-qualified, this is undefined behavior that the 465 // optimizer will delete, so warn about it. People sometimes try to use this 466 // to get a deterministic trap and are surprised by clang's behavior. This 467 // only handles the pattern "*null", which is a very syntactic check. 468 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 469 if (UO->getOpcode() == UO_Deref && 470 UO->getSubExpr()->IgnoreParenCasts()-> 471 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 472 !UO->getType().isVolatileQualified()) { 473 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 474 S.PDiag(diag::warn_indirection_through_null) 475 << UO->getSubExpr()->getSourceRange()); 476 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 477 S.PDiag(diag::note_indirection_through_null)); 478 } 479 } 480 481 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 482 SourceLocation AssignLoc, 483 const Expr* RHS) { 484 const ObjCIvarDecl *IV = OIRE->getDecl(); 485 if (!IV) 486 return; 487 488 DeclarationName MemberName = IV->getDeclName(); 489 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 490 if (!Member || !Member->isStr("isa")) 491 return; 492 493 const Expr *Base = OIRE->getBase(); 494 QualType BaseType = Base->getType(); 495 if (OIRE->isArrow()) 496 BaseType = BaseType->getPointeeType(); 497 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 498 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 499 ObjCInterfaceDecl *ClassDeclared = nullptr; 500 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 501 if (!ClassDeclared->getSuperClass() 502 && (*ClassDeclared->ivar_begin()) == IV) { 503 if (RHS) { 504 NamedDecl *ObjectSetClass = 505 S.LookupSingleName(S.TUScope, 506 &S.Context.Idents.get("object_setClass"), 507 SourceLocation(), S.LookupOrdinaryName); 508 if (ObjectSetClass) { 509 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd()); 510 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 511 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 512 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 513 AssignLoc), ",") << 514 FixItHint::CreateInsertion(RHSLocEnd, ")"); 515 } 516 else 517 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 518 } else { 519 NamedDecl *ObjectGetClass = 520 S.LookupSingleName(S.TUScope, 521 &S.Context.Idents.get("object_getClass"), 522 SourceLocation(), S.LookupOrdinaryName); 523 if (ObjectGetClass) 524 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 525 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 526 FixItHint::CreateReplacement( 527 SourceRange(OIRE->getOpLoc(), 528 OIRE->getLocEnd()), ")"); 529 else 530 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 531 } 532 S.Diag(IV->getLocation(), diag::note_ivar_decl); 533 } 534 } 535 } 536 537 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 538 // Handle any placeholder expressions which made it here. 539 if (E->getType()->isPlaceholderType()) { 540 ExprResult result = CheckPlaceholderExpr(E); 541 if (result.isInvalid()) return ExprError(); 542 E = result.get(); 543 } 544 545 // C++ [conv.lval]p1: 546 // A glvalue of a non-function, non-array type T can be 547 // converted to a prvalue. 548 if (!E->isGLValue()) return E; 549 550 QualType T = E->getType(); 551 assert(!T.isNull() && "r-value conversion on typeless expression?"); 552 553 // We don't want to throw lvalue-to-rvalue casts on top of 554 // expressions of certain types in C++. 555 if (getLangOpts().CPlusPlus && 556 (E->getType() == Context.OverloadTy || 557 T->isDependentType() || 558 T->isRecordType())) 559 return E; 560 561 // The C standard is actually really unclear on this point, and 562 // DR106 tells us what the result should be but not why. It's 563 // generally best to say that void types just doesn't undergo 564 // lvalue-to-rvalue at all. Note that expressions of unqualified 565 // 'void' type are never l-values, but qualified void can be. 566 if (T->isVoidType()) 567 return E; 568 569 // OpenCL usually rejects direct accesses to values of 'half' type. 570 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 571 T->isHalfType()) { 572 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 573 << 0 << T; 574 return ExprError(); 575 } 576 577 CheckForNullPointerDereference(*this, E); 578 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 579 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 580 &Context.Idents.get("object_getClass"), 581 SourceLocation(), LookupOrdinaryName); 582 if (ObjectGetClass) 583 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 584 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 585 FixItHint::CreateReplacement( 586 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 587 else 588 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 589 } 590 else if (const ObjCIvarRefExpr *OIRE = 591 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 592 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 593 594 // C++ [conv.lval]p1: 595 // [...] If T is a non-class type, the type of the prvalue is the 596 // cv-unqualified version of T. Otherwise, the type of the 597 // rvalue is T. 598 // 599 // C99 6.3.2.1p2: 600 // If the lvalue has qualified type, the value has the unqualified 601 // version of the type of the lvalue; otherwise, the value has the 602 // type of the lvalue. 603 if (T.hasQualifiers()) 604 T = T.getUnqualifiedType(); 605 606 // Under the MS ABI, lock down the inheritance model now. 607 if (T->isMemberPointerType() && 608 Context.getTargetInfo().getCXXABI().isMicrosoft()) 609 (void)isCompleteType(E->getExprLoc(), T); 610 611 UpdateMarkingForLValueToRValue(E); 612 613 // Loading a __weak object implicitly retains the value, so we need a cleanup to 614 // balance that. 615 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 616 Cleanup.setExprNeedsCleanups(true); 617 618 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 619 nullptr, VK_RValue); 620 621 // C11 6.3.2.1p2: 622 // ... if the lvalue has atomic type, the value has the non-atomic version 623 // of the type of the lvalue ... 624 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 625 T = Atomic->getValueType().getUnqualifiedType(); 626 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 627 nullptr, VK_RValue); 628 } 629 630 return Res; 631 } 632 633 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 634 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 635 if (Res.isInvalid()) 636 return ExprError(); 637 Res = DefaultLvalueConversion(Res.get()); 638 if (Res.isInvalid()) 639 return ExprError(); 640 return Res; 641 } 642 643 /// CallExprUnaryConversions - a special case of an unary conversion 644 /// performed on a function designator of a call expression. 645 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 646 QualType Ty = E->getType(); 647 ExprResult Res = E; 648 // Only do implicit cast for a function type, but not for a pointer 649 // to function type. 650 if (Ty->isFunctionType()) { 651 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 652 CK_FunctionToPointerDecay).get(); 653 if (Res.isInvalid()) 654 return ExprError(); 655 } 656 Res = DefaultLvalueConversion(Res.get()); 657 if (Res.isInvalid()) 658 return ExprError(); 659 return Res.get(); 660 } 661 662 /// UsualUnaryConversions - Performs various conversions that are common to most 663 /// operators (C99 6.3). The conversions of array and function types are 664 /// sometimes suppressed. For example, the array->pointer conversion doesn't 665 /// apply if the array is an argument to the sizeof or address (&) operators. 666 /// In these instances, this routine should *not* be called. 667 ExprResult Sema::UsualUnaryConversions(Expr *E) { 668 // First, convert to an r-value. 669 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 670 if (Res.isInvalid()) 671 return ExprError(); 672 E = Res.get(); 673 674 QualType Ty = E->getType(); 675 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 676 677 // Half FP have to be promoted to float unless it is natively supported 678 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 679 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 680 681 // Try to perform integral promotions if the object has a theoretically 682 // promotable type. 683 if (Ty->isIntegralOrUnscopedEnumerationType()) { 684 // C99 6.3.1.1p2: 685 // 686 // The following may be used in an expression wherever an int or 687 // unsigned int may be used: 688 // - an object or expression with an integer type whose integer 689 // conversion rank is less than or equal to the rank of int 690 // and unsigned int. 691 // - A bit-field of type _Bool, int, signed int, or unsigned int. 692 // 693 // If an int can represent all values of the original type, the 694 // value is converted to an int; otherwise, it is converted to an 695 // unsigned int. These are called the integer promotions. All 696 // other types are unchanged by the integer promotions. 697 698 QualType PTy = Context.isPromotableBitField(E); 699 if (!PTy.isNull()) { 700 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 701 return E; 702 } 703 if (Ty->isPromotableIntegerType()) { 704 QualType PT = Context.getPromotedIntegerType(Ty); 705 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 706 return E; 707 } 708 } 709 return E; 710 } 711 712 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 713 /// do not have a prototype. Arguments that have type float or __fp16 714 /// are promoted to double. All other argument types are converted by 715 /// UsualUnaryConversions(). 716 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 717 QualType Ty = E->getType(); 718 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 719 720 ExprResult Res = UsualUnaryConversions(E); 721 if (Res.isInvalid()) 722 return ExprError(); 723 E = Res.get(); 724 725 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to 726 // double. 727 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 728 if (BTy && (BTy->getKind() == BuiltinType::Half || 729 BTy->getKind() == BuiltinType::Float)) { 730 if (getLangOpts().OpenCL && 731 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 732 if (BTy->getKind() == BuiltinType::Half) { 733 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 734 } 735 } else { 736 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 737 } 738 } 739 740 // C++ performs lvalue-to-rvalue conversion as a default argument 741 // promotion, even on class types, but note: 742 // C++11 [conv.lval]p2: 743 // When an lvalue-to-rvalue conversion occurs in an unevaluated 744 // operand or a subexpression thereof the value contained in the 745 // referenced object is not accessed. Otherwise, if the glvalue 746 // has a class type, the conversion copy-initializes a temporary 747 // of type T from the glvalue and the result of the conversion 748 // is a prvalue for the temporary. 749 // FIXME: add some way to gate this entire thing for correctness in 750 // potentially potentially evaluated contexts. 751 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 752 ExprResult Temp = PerformCopyInitialization( 753 InitializedEntity::InitializeTemporary(E->getType()), 754 E->getExprLoc(), E); 755 if (Temp.isInvalid()) 756 return ExprError(); 757 E = Temp.get(); 758 } 759 760 return E; 761 } 762 763 /// Determine the degree of POD-ness for an expression. 764 /// Incomplete types are considered POD, since this check can be performed 765 /// when we're in an unevaluated context. 766 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 767 if (Ty->isIncompleteType()) { 768 // C++11 [expr.call]p7: 769 // After these conversions, if the argument does not have arithmetic, 770 // enumeration, pointer, pointer to member, or class type, the program 771 // is ill-formed. 772 // 773 // Since we've already performed array-to-pointer and function-to-pointer 774 // decay, the only such type in C++ is cv void. This also handles 775 // initializer lists as variadic arguments. 776 if (Ty->isVoidType()) 777 return VAK_Invalid; 778 779 if (Ty->isObjCObjectType()) 780 return VAK_Invalid; 781 return VAK_Valid; 782 } 783 784 if (Ty.isCXX98PODType(Context)) 785 return VAK_Valid; 786 787 // C++11 [expr.call]p7: 788 // Passing a potentially-evaluated argument of class type (Clause 9) 789 // having a non-trivial copy constructor, a non-trivial move constructor, 790 // or a non-trivial destructor, with no corresponding parameter, 791 // is conditionally-supported with implementation-defined semantics. 792 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 793 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 794 if (!Record->hasNonTrivialCopyConstructor() && 795 !Record->hasNonTrivialMoveConstructor() && 796 !Record->hasNonTrivialDestructor()) 797 return VAK_ValidInCXX11; 798 799 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 800 return VAK_Valid; 801 802 if (Ty->isObjCObjectType()) 803 return VAK_Invalid; 804 805 if (getLangOpts().MSVCCompat) 806 return VAK_MSVCUndefined; 807 808 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 809 // permitted to reject them. We should consider doing so. 810 return VAK_Undefined; 811 } 812 813 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 814 // Don't allow one to pass an Objective-C interface to a vararg. 815 const QualType &Ty = E->getType(); 816 VarArgKind VAK = isValidVarArgType(Ty); 817 818 // Complain about passing non-POD types through varargs. 819 switch (VAK) { 820 case VAK_ValidInCXX11: 821 DiagRuntimeBehavior( 822 E->getLocStart(), nullptr, 823 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 824 << Ty << CT); 825 // Fall through. 826 case VAK_Valid: 827 if (Ty->isRecordType()) { 828 // This is unlikely to be what the user intended. If the class has a 829 // 'c_str' member function, the user probably meant to call that. 830 DiagRuntimeBehavior(E->getLocStart(), nullptr, 831 PDiag(diag::warn_pass_class_arg_to_vararg) 832 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 833 } 834 break; 835 836 case VAK_Undefined: 837 case VAK_MSVCUndefined: 838 DiagRuntimeBehavior( 839 E->getLocStart(), nullptr, 840 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 841 << getLangOpts().CPlusPlus11 << Ty << CT); 842 break; 843 844 case VAK_Invalid: 845 if (Ty->isObjCObjectType()) 846 DiagRuntimeBehavior( 847 E->getLocStart(), nullptr, 848 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 849 << Ty << CT); 850 else 851 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg) 852 << isa<InitListExpr>(E) << Ty << CT; 853 break; 854 } 855 } 856 857 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 858 /// will create a trap if the resulting type is not a POD type. 859 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 860 FunctionDecl *FDecl) { 861 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 862 // Strip the unbridged-cast placeholder expression off, if applicable. 863 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 864 (CT == VariadicMethod || 865 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 866 E = stripARCUnbridgedCast(E); 867 868 // Otherwise, do normal placeholder checking. 869 } else { 870 ExprResult ExprRes = CheckPlaceholderExpr(E); 871 if (ExprRes.isInvalid()) 872 return ExprError(); 873 E = ExprRes.get(); 874 } 875 } 876 877 ExprResult ExprRes = DefaultArgumentPromotion(E); 878 if (ExprRes.isInvalid()) 879 return ExprError(); 880 E = ExprRes.get(); 881 882 // Diagnostics regarding non-POD argument types are 883 // emitted along with format string checking in Sema::CheckFunctionCall(). 884 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 885 // Turn this into a trap. 886 CXXScopeSpec SS; 887 SourceLocation TemplateKWLoc; 888 UnqualifiedId Name; 889 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 890 E->getLocStart()); 891 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 892 Name, true, false); 893 if (TrapFn.isInvalid()) 894 return ExprError(); 895 896 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 897 E->getLocStart(), None, 898 E->getLocEnd()); 899 if (Call.isInvalid()) 900 return ExprError(); 901 902 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 903 Call.get(), E); 904 if (Comma.isInvalid()) 905 return ExprError(); 906 return Comma.get(); 907 } 908 909 if (!getLangOpts().CPlusPlus && 910 RequireCompleteType(E->getExprLoc(), E->getType(), 911 diag::err_call_incomplete_argument)) 912 return ExprError(); 913 914 return E; 915 } 916 917 /// \brief Converts an integer to complex float type. Helper function of 918 /// UsualArithmeticConversions() 919 /// 920 /// \return false if the integer expression is an integer type and is 921 /// successfully converted to the complex type. 922 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 923 ExprResult &ComplexExpr, 924 QualType IntTy, 925 QualType ComplexTy, 926 bool SkipCast) { 927 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 928 if (SkipCast) return false; 929 if (IntTy->isIntegerType()) { 930 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 931 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 932 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 933 CK_FloatingRealToComplex); 934 } else { 935 assert(IntTy->isComplexIntegerType()); 936 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 937 CK_IntegralComplexToFloatingComplex); 938 } 939 return false; 940 } 941 942 /// \brief Handle arithmetic conversion with complex types. Helper function of 943 /// UsualArithmeticConversions() 944 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 945 ExprResult &RHS, QualType LHSType, 946 QualType RHSType, 947 bool IsCompAssign) { 948 // if we have an integer operand, the result is the complex type. 949 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 950 /*skipCast*/false)) 951 return LHSType; 952 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 953 /*skipCast*/IsCompAssign)) 954 return RHSType; 955 956 // This handles complex/complex, complex/float, or float/complex. 957 // When both operands are complex, the shorter operand is converted to the 958 // type of the longer, and that is the type of the result. This corresponds 959 // to what is done when combining two real floating-point operands. 960 // The fun begins when size promotion occur across type domains. 961 // From H&S 6.3.4: When one operand is complex and the other is a real 962 // floating-point type, the less precise type is converted, within it's 963 // real or complex domain, to the precision of the other type. For example, 964 // when combining a "long double" with a "double _Complex", the 965 // "double _Complex" is promoted to "long double _Complex". 966 967 // Compute the rank of the two types, regardless of whether they are complex. 968 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 969 970 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 971 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 972 QualType LHSElementType = 973 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 974 QualType RHSElementType = 975 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 976 977 QualType ResultType = S.Context.getComplexType(LHSElementType); 978 if (Order < 0) { 979 // Promote the precision of the LHS if not an assignment. 980 ResultType = S.Context.getComplexType(RHSElementType); 981 if (!IsCompAssign) { 982 if (LHSComplexType) 983 LHS = 984 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 985 else 986 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 987 } 988 } else if (Order > 0) { 989 // Promote the precision of the RHS. 990 if (RHSComplexType) 991 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 992 else 993 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 994 } 995 return ResultType; 996 } 997 998 /// \brief Handle arithmetic conversion from integer to float. Helper function 999 /// of UsualArithmeticConversions() 1000 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1001 ExprResult &IntExpr, 1002 QualType FloatTy, QualType IntTy, 1003 bool ConvertFloat, bool ConvertInt) { 1004 if (IntTy->isIntegerType()) { 1005 if (ConvertInt) 1006 // Convert intExpr to the lhs floating point type. 1007 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1008 CK_IntegralToFloating); 1009 return FloatTy; 1010 } 1011 1012 // Convert both sides to the appropriate complex float. 1013 assert(IntTy->isComplexIntegerType()); 1014 QualType result = S.Context.getComplexType(FloatTy); 1015 1016 // _Complex int -> _Complex float 1017 if (ConvertInt) 1018 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1019 CK_IntegralComplexToFloatingComplex); 1020 1021 // float -> _Complex float 1022 if (ConvertFloat) 1023 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1024 CK_FloatingRealToComplex); 1025 1026 return result; 1027 } 1028 1029 /// \brief Handle arithmethic conversion with floating point types. Helper 1030 /// function of UsualArithmeticConversions() 1031 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1032 ExprResult &RHS, QualType LHSType, 1033 QualType RHSType, bool IsCompAssign) { 1034 bool LHSFloat = LHSType->isRealFloatingType(); 1035 bool RHSFloat = RHSType->isRealFloatingType(); 1036 1037 // If we have two real floating types, convert the smaller operand 1038 // to the bigger result. 1039 if (LHSFloat && RHSFloat) { 1040 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1041 if (order > 0) { 1042 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1043 return LHSType; 1044 } 1045 1046 assert(order < 0 && "illegal float comparison"); 1047 if (!IsCompAssign) 1048 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1049 return RHSType; 1050 } 1051 1052 if (LHSFloat) { 1053 // Half FP has to be promoted to float unless it is natively supported 1054 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1055 LHSType = S.Context.FloatTy; 1056 1057 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1058 /*convertFloat=*/!IsCompAssign, 1059 /*convertInt=*/ true); 1060 } 1061 assert(RHSFloat); 1062 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1063 /*convertInt=*/ true, 1064 /*convertFloat=*/!IsCompAssign); 1065 } 1066 1067 /// \brief Diagnose attempts to convert between __float128 and long double if 1068 /// there is no support for such conversion. Helper function of 1069 /// UsualArithmeticConversions(). 1070 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1071 QualType RHSType) { 1072 /* No issue converting if at least one of the types is not a floating point 1073 type or the two types have the same rank. 1074 */ 1075 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1076 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1077 return false; 1078 1079 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1080 "The remaining types must be floating point types."); 1081 1082 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1083 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1084 1085 QualType LHSElemType = LHSComplex ? 1086 LHSComplex->getElementType() : LHSType; 1087 QualType RHSElemType = RHSComplex ? 1088 RHSComplex->getElementType() : RHSType; 1089 1090 // No issue if the two types have the same representation 1091 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1092 &S.Context.getFloatTypeSemantics(RHSElemType)) 1093 return false; 1094 1095 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1096 RHSElemType == S.Context.LongDoubleTy); 1097 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1098 RHSElemType == S.Context.Float128Ty); 1099 1100 /* We've handled the situation where __float128 and long double have the same 1101 representation. The only other allowable conversion is if long double is 1102 really just double. 1103 */ 1104 return Float128AndLongDouble && 1105 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) != 1106 &llvm::APFloat::IEEEdouble()); 1107 } 1108 1109 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1110 1111 namespace { 1112 /// These helper callbacks are placed in an anonymous namespace to 1113 /// permit their use as function template parameters. 1114 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1115 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1116 } 1117 1118 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1119 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1120 CK_IntegralComplexCast); 1121 } 1122 } 1123 1124 /// \brief Handle integer arithmetic conversions. Helper function of 1125 /// UsualArithmeticConversions() 1126 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1127 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1128 ExprResult &RHS, QualType LHSType, 1129 QualType RHSType, bool IsCompAssign) { 1130 // The rules for this case are in C99 6.3.1.8 1131 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1132 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1133 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1134 if (LHSSigned == RHSSigned) { 1135 // Same signedness; use the higher-ranked type 1136 if (order >= 0) { 1137 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1138 return LHSType; 1139 } else if (!IsCompAssign) 1140 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1141 return RHSType; 1142 } else if (order != (LHSSigned ? 1 : -1)) { 1143 // The unsigned type has greater than or equal rank to the 1144 // signed type, so use the unsigned type 1145 if (RHSSigned) { 1146 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1147 return LHSType; 1148 } else if (!IsCompAssign) 1149 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1150 return RHSType; 1151 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1152 // The two types are different widths; if we are here, that 1153 // means the signed type is larger than the unsigned type, so 1154 // use the signed type. 1155 if (LHSSigned) { 1156 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1157 return LHSType; 1158 } else if (!IsCompAssign) 1159 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1160 return RHSType; 1161 } else { 1162 // The signed type is higher-ranked than the unsigned type, 1163 // but isn't actually any bigger (like unsigned int and long 1164 // on most 32-bit systems). Use the unsigned type corresponding 1165 // to the signed type. 1166 QualType result = 1167 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1168 RHS = (*doRHSCast)(S, RHS.get(), result); 1169 if (!IsCompAssign) 1170 LHS = (*doLHSCast)(S, LHS.get(), result); 1171 return result; 1172 } 1173 } 1174 1175 /// \brief Handle conversions with GCC complex int extension. Helper function 1176 /// of UsualArithmeticConversions() 1177 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1178 ExprResult &RHS, QualType LHSType, 1179 QualType RHSType, 1180 bool IsCompAssign) { 1181 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1182 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1183 1184 if (LHSComplexInt && RHSComplexInt) { 1185 QualType LHSEltType = LHSComplexInt->getElementType(); 1186 QualType RHSEltType = RHSComplexInt->getElementType(); 1187 QualType ScalarType = 1188 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1189 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1190 1191 return S.Context.getComplexType(ScalarType); 1192 } 1193 1194 if (LHSComplexInt) { 1195 QualType LHSEltType = LHSComplexInt->getElementType(); 1196 QualType ScalarType = 1197 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1198 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1199 QualType ComplexType = S.Context.getComplexType(ScalarType); 1200 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1201 CK_IntegralRealToComplex); 1202 1203 return ComplexType; 1204 } 1205 1206 assert(RHSComplexInt); 1207 1208 QualType RHSEltType = RHSComplexInt->getElementType(); 1209 QualType ScalarType = 1210 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1211 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1212 QualType ComplexType = S.Context.getComplexType(ScalarType); 1213 1214 if (!IsCompAssign) 1215 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1216 CK_IntegralRealToComplex); 1217 return ComplexType; 1218 } 1219 1220 /// UsualArithmeticConversions - Performs various conversions that are common to 1221 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1222 /// routine returns the first non-arithmetic type found. The client is 1223 /// responsible for emitting appropriate error diagnostics. 1224 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1225 bool IsCompAssign) { 1226 if (!IsCompAssign) { 1227 LHS = UsualUnaryConversions(LHS.get()); 1228 if (LHS.isInvalid()) 1229 return QualType(); 1230 } 1231 1232 RHS = UsualUnaryConversions(RHS.get()); 1233 if (RHS.isInvalid()) 1234 return QualType(); 1235 1236 // For conversion purposes, we ignore any qualifiers. 1237 // For example, "const float" and "float" are equivalent. 1238 QualType LHSType = 1239 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1240 QualType RHSType = 1241 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1242 1243 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1244 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1245 LHSType = AtomicLHS->getValueType(); 1246 1247 // If both types are identical, no conversion is needed. 1248 if (LHSType == RHSType) 1249 return LHSType; 1250 1251 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1252 // The caller can deal with this (e.g. pointer + int). 1253 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1254 return QualType(); 1255 1256 // Apply unary and bitfield promotions to the LHS's type. 1257 QualType LHSUnpromotedType = LHSType; 1258 if (LHSType->isPromotableIntegerType()) 1259 LHSType = Context.getPromotedIntegerType(LHSType); 1260 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1261 if (!LHSBitfieldPromoteTy.isNull()) 1262 LHSType = LHSBitfieldPromoteTy; 1263 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1264 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1265 1266 // If both types are identical, no conversion is needed. 1267 if (LHSType == RHSType) 1268 return LHSType; 1269 1270 // At this point, we have two different arithmetic types. 1271 1272 // Diagnose attempts to convert between __float128 and long double where 1273 // such conversions currently can't be handled. 1274 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1275 return QualType(); 1276 1277 // Handle complex types first (C99 6.3.1.8p1). 1278 if (LHSType->isComplexType() || RHSType->isComplexType()) 1279 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1280 IsCompAssign); 1281 1282 // Now handle "real" floating types (i.e. float, double, long double). 1283 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1284 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1285 IsCompAssign); 1286 1287 // Handle GCC complex int extension. 1288 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1289 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1290 IsCompAssign); 1291 1292 // Finally, we have two differing integer types. 1293 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1294 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1295 } 1296 1297 1298 //===----------------------------------------------------------------------===// 1299 // Semantic Analysis for various Expression Types 1300 //===----------------------------------------------------------------------===// 1301 1302 1303 ExprResult 1304 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1305 SourceLocation DefaultLoc, 1306 SourceLocation RParenLoc, 1307 Expr *ControllingExpr, 1308 ArrayRef<ParsedType> ArgTypes, 1309 ArrayRef<Expr *> ArgExprs) { 1310 unsigned NumAssocs = ArgTypes.size(); 1311 assert(NumAssocs == ArgExprs.size()); 1312 1313 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1314 for (unsigned i = 0; i < NumAssocs; ++i) { 1315 if (ArgTypes[i]) 1316 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1317 else 1318 Types[i] = nullptr; 1319 } 1320 1321 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1322 ControllingExpr, 1323 llvm::makeArrayRef(Types, NumAssocs), 1324 ArgExprs); 1325 delete [] Types; 1326 return ER; 1327 } 1328 1329 ExprResult 1330 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1331 SourceLocation DefaultLoc, 1332 SourceLocation RParenLoc, 1333 Expr *ControllingExpr, 1334 ArrayRef<TypeSourceInfo *> Types, 1335 ArrayRef<Expr *> Exprs) { 1336 unsigned NumAssocs = Types.size(); 1337 assert(NumAssocs == Exprs.size()); 1338 1339 // Decay and strip qualifiers for the controlling expression type, and handle 1340 // placeholder type replacement. See committee discussion from WG14 DR423. 1341 { 1342 EnterExpressionEvaluationContext Unevaluated( 1343 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1344 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1345 if (R.isInvalid()) 1346 return ExprError(); 1347 ControllingExpr = R.get(); 1348 } 1349 1350 // The controlling expression is an unevaluated operand, so side effects are 1351 // likely unintended. 1352 if (!inTemplateInstantiation() && 1353 ControllingExpr->HasSideEffects(Context, false)) 1354 Diag(ControllingExpr->getExprLoc(), 1355 diag::warn_side_effects_unevaluated_context); 1356 1357 bool TypeErrorFound = false, 1358 IsResultDependent = ControllingExpr->isTypeDependent(), 1359 ContainsUnexpandedParameterPack 1360 = ControllingExpr->containsUnexpandedParameterPack(); 1361 1362 for (unsigned i = 0; i < NumAssocs; ++i) { 1363 if (Exprs[i]->containsUnexpandedParameterPack()) 1364 ContainsUnexpandedParameterPack = true; 1365 1366 if (Types[i]) { 1367 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1368 ContainsUnexpandedParameterPack = true; 1369 1370 if (Types[i]->getType()->isDependentType()) { 1371 IsResultDependent = true; 1372 } else { 1373 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1374 // complete object type other than a variably modified type." 1375 unsigned D = 0; 1376 if (Types[i]->getType()->isIncompleteType()) 1377 D = diag::err_assoc_type_incomplete; 1378 else if (!Types[i]->getType()->isObjectType()) 1379 D = diag::err_assoc_type_nonobject; 1380 else if (Types[i]->getType()->isVariablyModifiedType()) 1381 D = diag::err_assoc_type_variably_modified; 1382 1383 if (D != 0) { 1384 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1385 << Types[i]->getTypeLoc().getSourceRange() 1386 << Types[i]->getType(); 1387 TypeErrorFound = true; 1388 } 1389 1390 // C11 6.5.1.1p2 "No two generic associations in the same generic 1391 // selection shall specify compatible types." 1392 for (unsigned j = i+1; j < NumAssocs; ++j) 1393 if (Types[j] && !Types[j]->getType()->isDependentType() && 1394 Context.typesAreCompatible(Types[i]->getType(), 1395 Types[j]->getType())) { 1396 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1397 diag::err_assoc_compatible_types) 1398 << Types[j]->getTypeLoc().getSourceRange() 1399 << Types[j]->getType() 1400 << Types[i]->getType(); 1401 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1402 diag::note_compat_assoc) 1403 << Types[i]->getTypeLoc().getSourceRange() 1404 << Types[i]->getType(); 1405 TypeErrorFound = true; 1406 } 1407 } 1408 } 1409 } 1410 if (TypeErrorFound) 1411 return ExprError(); 1412 1413 // If we determined that the generic selection is result-dependent, don't 1414 // try to compute the result expression. 1415 if (IsResultDependent) 1416 return new (Context) GenericSelectionExpr( 1417 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1418 ContainsUnexpandedParameterPack); 1419 1420 SmallVector<unsigned, 1> CompatIndices; 1421 unsigned DefaultIndex = -1U; 1422 for (unsigned i = 0; i < NumAssocs; ++i) { 1423 if (!Types[i]) 1424 DefaultIndex = i; 1425 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1426 Types[i]->getType())) 1427 CompatIndices.push_back(i); 1428 } 1429 1430 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1431 // type compatible with at most one of the types named in its generic 1432 // association list." 1433 if (CompatIndices.size() > 1) { 1434 // We strip parens here because the controlling expression is typically 1435 // parenthesized in macro definitions. 1436 ControllingExpr = ControllingExpr->IgnoreParens(); 1437 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1438 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1439 << (unsigned) CompatIndices.size(); 1440 for (unsigned I : CompatIndices) { 1441 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1442 diag::note_compat_assoc) 1443 << Types[I]->getTypeLoc().getSourceRange() 1444 << Types[I]->getType(); 1445 } 1446 return ExprError(); 1447 } 1448 1449 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1450 // its controlling expression shall have type compatible with exactly one of 1451 // the types named in its generic association list." 1452 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1453 // We strip parens here because the controlling expression is typically 1454 // parenthesized in macro definitions. 1455 ControllingExpr = ControllingExpr->IgnoreParens(); 1456 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1457 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1458 return ExprError(); 1459 } 1460 1461 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1462 // type name that is compatible with the type of the controlling expression, 1463 // then the result expression of the generic selection is the expression 1464 // in that generic association. Otherwise, the result expression of the 1465 // generic selection is the expression in the default generic association." 1466 unsigned ResultIndex = 1467 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1468 1469 return new (Context) GenericSelectionExpr( 1470 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1471 ContainsUnexpandedParameterPack, ResultIndex); 1472 } 1473 1474 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1475 /// location of the token and the offset of the ud-suffix within it. 1476 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1477 unsigned Offset) { 1478 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1479 S.getLangOpts()); 1480 } 1481 1482 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1483 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1484 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1485 IdentifierInfo *UDSuffix, 1486 SourceLocation UDSuffixLoc, 1487 ArrayRef<Expr*> Args, 1488 SourceLocation LitEndLoc) { 1489 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1490 1491 QualType ArgTy[2]; 1492 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1493 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1494 if (ArgTy[ArgIdx]->isArrayType()) 1495 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1496 } 1497 1498 DeclarationName OpName = 1499 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1500 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1501 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1502 1503 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1504 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1505 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1506 /*AllowStringTemplate*/ false, 1507 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1508 return ExprError(); 1509 1510 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1511 } 1512 1513 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1514 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1515 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1516 /// multiple tokens. However, the common case is that StringToks points to one 1517 /// string. 1518 /// 1519 ExprResult 1520 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1521 assert(!StringToks.empty() && "Must have at least one string!"); 1522 1523 StringLiteralParser Literal(StringToks, PP); 1524 if (Literal.hadError) 1525 return ExprError(); 1526 1527 SmallVector<SourceLocation, 4> StringTokLocs; 1528 for (const Token &Tok : StringToks) 1529 StringTokLocs.push_back(Tok.getLocation()); 1530 1531 QualType CharTy = Context.CharTy; 1532 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1533 if (Literal.isWide()) { 1534 CharTy = Context.getWideCharType(); 1535 Kind = StringLiteral::Wide; 1536 } else if (Literal.isUTF8()) { 1537 Kind = StringLiteral::UTF8; 1538 } else if (Literal.isUTF16()) { 1539 CharTy = Context.Char16Ty; 1540 Kind = StringLiteral::UTF16; 1541 } else if (Literal.isUTF32()) { 1542 CharTy = Context.Char32Ty; 1543 Kind = StringLiteral::UTF32; 1544 } else if (Literal.isPascal()) { 1545 CharTy = Context.UnsignedCharTy; 1546 } 1547 1548 QualType CharTyConst = CharTy; 1549 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1550 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1551 CharTyConst.addConst(); 1552 1553 // Get an array type for the string, according to C99 6.4.5. This includes 1554 // the nul terminator character as well as the string length for pascal 1555 // strings. 1556 QualType StrTy = Context.getConstantArrayType(CharTyConst, 1557 llvm::APInt(32, Literal.GetNumStringChars()+1), 1558 ArrayType::Normal, 0); 1559 1560 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 1561 if (getLangOpts().OpenCL) { 1562 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant); 1563 } 1564 1565 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1566 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1567 Kind, Literal.Pascal, StrTy, 1568 &StringTokLocs[0], 1569 StringTokLocs.size()); 1570 if (Literal.getUDSuffix().empty()) 1571 return Lit; 1572 1573 // We're building a user-defined literal. 1574 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1575 SourceLocation UDSuffixLoc = 1576 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1577 Literal.getUDSuffixOffset()); 1578 1579 // Make sure we're allowed user-defined literals here. 1580 if (!UDLScope) 1581 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1582 1583 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1584 // operator "" X (str, len) 1585 QualType SizeType = Context.getSizeType(); 1586 1587 DeclarationName OpName = 1588 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1589 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1590 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1591 1592 QualType ArgTy[] = { 1593 Context.getArrayDecayedType(StrTy), SizeType 1594 }; 1595 1596 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1597 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1598 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1599 /*AllowStringTemplate*/ true, 1600 /*DiagnoseMissing*/ true)) { 1601 1602 case LOLR_Cooked: { 1603 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1604 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1605 StringTokLocs[0]); 1606 Expr *Args[] = { Lit, LenArg }; 1607 1608 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1609 } 1610 1611 case LOLR_StringTemplate: { 1612 TemplateArgumentListInfo ExplicitArgs; 1613 1614 unsigned CharBits = Context.getIntWidth(CharTy); 1615 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1616 llvm::APSInt Value(CharBits, CharIsUnsigned); 1617 1618 TemplateArgument TypeArg(CharTy); 1619 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1620 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1621 1622 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1623 Value = Lit->getCodeUnit(I); 1624 TemplateArgument Arg(Context, Value, CharTy); 1625 TemplateArgumentLocInfo ArgInfo; 1626 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1627 } 1628 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1629 &ExplicitArgs); 1630 } 1631 case LOLR_Raw: 1632 case LOLR_Template: 1633 case LOLR_ErrorNoDiagnostic: 1634 llvm_unreachable("unexpected literal operator lookup result"); 1635 case LOLR_Error: 1636 return ExprError(); 1637 } 1638 llvm_unreachable("unexpected literal operator lookup result"); 1639 } 1640 1641 ExprResult 1642 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1643 SourceLocation Loc, 1644 const CXXScopeSpec *SS) { 1645 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1646 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1647 } 1648 1649 /// BuildDeclRefExpr - Build an expression that references a 1650 /// declaration that does not require a closure capture. 1651 ExprResult 1652 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1653 const DeclarationNameInfo &NameInfo, 1654 const CXXScopeSpec *SS, NamedDecl *FoundD, 1655 const TemplateArgumentListInfo *TemplateArgs) { 1656 bool RefersToCapturedVariable = 1657 isa<VarDecl>(D) && 1658 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1659 1660 DeclRefExpr *E; 1661 if (isa<VarTemplateSpecializationDecl>(D)) { 1662 VarTemplateSpecializationDecl *VarSpec = 1663 cast<VarTemplateSpecializationDecl>(D); 1664 1665 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1666 : NestedNameSpecifierLoc(), 1667 VarSpec->getTemplateKeywordLoc(), D, 1668 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK, 1669 FoundD, TemplateArgs); 1670 } else { 1671 assert(!TemplateArgs && "No template arguments for non-variable" 1672 " template specialization references"); 1673 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1674 : NestedNameSpecifierLoc(), 1675 SourceLocation(), D, RefersToCapturedVariable, 1676 NameInfo, Ty, VK, FoundD); 1677 } 1678 1679 MarkDeclRefReferenced(E); 1680 1681 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1682 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && 1683 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart())) 1684 recordUseOfEvaluatedWeak(E); 1685 1686 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1687 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 1688 FD = IFD->getAnonField(); 1689 if (FD) { 1690 UnusedPrivateFields.remove(FD); 1691 // Just in case we're building an illegal pointer-to-member. 1692 if (FD->isBitField()) 1693 E->setObjectKind(OK_BitField); 1694 } 1695 1696 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1697 // designates a bit-field. 1698 if (auto *BD = dyn_cast<BindingDecl>(D)) 1699 if (auto *BE = BD->getBinding()) 1700 E->setObjectKind(BE->getObjectKind()); 1701 1702 return E; 1703 } 1704 1705 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1706 /// possibly a list of template arguments. 1707 /// 1708 /// If this produces template arguments, it is permitted to call 1709 /// DecomposeTemplateName. 1710 /// 1711 /// This actually loses a lot of source location information for 1712 /// non-standard name kinds; we should consider preserving that in 1713 /// some way. 1714 void 1715 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1716 TemplateArgumentListInfo &Buffer, 1717 DeclarationNameInfo &NameInfo, 1718 const TemplateArgumentListInfo *&TemplateArgs) { 1719 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1720 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1721 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1722 1723 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1724 Id.TemplateId->NumArgs); 1725 translateTemplateArguments(TemplateArgsPtr, Buffer); 1726 1727 TemplateName TName = Id.TemplateId->Template.get(); 1728 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1729 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1730 TemplateArgs = &Buffer; 1731 } else { 1732 NameInfo = GetNameFromUnqualifiedId(Id); 1733 TemplateArgs = nullptr; 1734 } 1735 } 1736 1737 static void emitEmptyLookupTypoDiagnostic( 1738 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1739 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1740 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1741 DeclContext *Ctx = 1742 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1743 if (!TC) { 1744 // Emit a special diagnostic for failed member lookups. 1745 // FIXME: computing the declaration context might fail here (?) 1746 if (Ctx) 1747 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1748 << SS.getRange(); 1749 else 1750 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1751 return; 1752 } 1753 1754 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1755 bool DroppedSpecifier = 1756 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1757 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1758 ? diag::note_implicit_param_decl 1759 : diag::note_previous_decl; 1760 if (!Ctx) 1761 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1762 SemaRef.PDiag(NoteID)); 1763 else 1764 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1765 << Typo << Ctx << DroppedSpecifier 1766 << SS.getRange(), 1767 SemaRef.PDiag(NoteID)); 1768 } 1769 1770 /// Diagnose an empty lookup. 1771 /// 1772 /// \return false if new lookup candidates were found 1773 bool 1774 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1775 std::unique_ptr<CorrectionCandidateCallback> CCC, 1776 TemplateArgumentListInfo *ExplicitTemplateArgs, 1777 ArrayRef<Expr *> Args, TypoExpr **Out) { 1778 DeclarationName Name = R.getLookupName(); 1779 1780 unsigned diagnostic = diag::err_undeclared_var_use; 1781 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1782 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1783 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1784 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1785 diagnostic = diag::err_undeclared_use; 1786 diagnostic_suggest = diag::err_undeclared_use_suggest; 1787 } 1788 1789 // If the original lookup was an unqualified lookup, fake an 1790 // unqualified lookup. This is useful when (for example) the 1791 // original lookup would not have found something because it was a 1792 // dependent name. 1793 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1794 while (DC) { 1795 if (isa<CXXRecordDecl>(DC)) { 1796 LookupQualifiedName(R, DC); 1797 1798 if (!R.empty()) { 1799 // Don't give errors about ambiguities in this lookup. 1800 R.suppressDiagnostics(); 1801 1802 // During a default argument instantiation the CurContext points 1803 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1804 // function parameter list, hence add an explicit check. 1805 bool isDefaultArgument = 1806 !CodeSynthesisContexts.empty() && 1807 CodeSynthesisContexts.back().Kind == 1808 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 1809 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1810 bool isInstance = CurMethod && 1811 CurMethod->isInstance() && 1812 DC == CurMethod->getParent() && !isDefaultArgument; 1813 1814 // Give a code modification hint to insert 'this->'. 1815 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1816 // Actually quite difficult! 1817 if (getLangOpts().MSVCCompat) 1818 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1819 if (isInstance) { 1820 Diag(R.getNameLoc(), diagnostic) << Name 1821 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1822 CheckCXXThisCapture(R.getNameLoc()); 1823 } else { 1824 Diag(R.getNameLoc(), diagnostic) << Name; 1825 } 1826 1827 // Do we really want to note all of these? 1828 for (NamedDecl *D : R) 1829 Diag(D->getLocation(), diag::note_dependent_var_use); 1830 1831 // Return true if we are inside a default argument instantiation 1832 // and the found name refers to an instance member function, otherwise 1833 // the function calling DiagnoseEmptyLookup will try to create an 1834 // implicit member call and this is wrong for default argument. 1835 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1836 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1837 return true; 1838 } 1839 1840 // Tell the callee to try to recover. 1841 return false; 1842 } 1843 1844 R.clear(); 1845 } 1846 1847 // In Microsoft mode, if we are performing lookup from within a friend 1848 // function definition declared at class scope then we must set 1849 // DC to the lexical parent to be able to search into the parent 1850 // class. 1851 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1852 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1853 DC->getLexicalParent()->isRecord()) 1854 DC = DC->getLexicalParent(); 1855 else 1856 DC = DC->getParent(); 1857 } 1858 1859 // We didn't find anything, so try to correct for a typo. 1860 TypoCorrection Corrected; 1861 if (S && Out) { 1862 SourceLocation TypoLoc = R.getNameLoc(); 1863 assert(!ExplicitTemplateArgs && 1864 "Diagnosing an empty lookup with explicit template args!"); 1865 *Out = CorrectTypoDelayed( 1866 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC), 1867 [=](const TypoCorrection &TC) { 1868 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 1869 diagnostic, diagnostic_suggest); 1870 }, 1871 nullptr, CTK_ErrorRecovery); 1872 if (*Out) 1873 return true; 1874 } else if (S && (Corrected = 1875 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, 1876 &SS, std::move(CCC), CTK_ErrorRecovery))) { 1877 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1878 bool DroppedSpecifier = 1879 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1880 R.setLookupName(Corrected.getCorrection()); 1881 1882 bool AcceptableWithRecovery = false; 1883 bool AcceptableWithoutRecovery = false; 1884 NamedDecl *ND = Corrected.getFoundDecl(); 1885 if (ND) { 1886 if (Corrected.isOverloaded()) { 1887 OverloadCandidateSet OCS(R.getNameLoc(), 1888 OverloadCandidateSet::CSK_Normal); 1889 OverloadCandidateSet::iterator Best; 1890 for (NamedDecl *CD : Corrected) { 1891 if (FunctionTemplateDecl *FTD = 1892 dyn_cast<FunctionTemplateDecl>(CD)) 1893 AddTemplateOverloadCandidate( 1894 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1895 Args, OCS); 1896 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 1897 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1898 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1899 Args, OCS); 1900 } 1901 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1902 case OR_Success: 1903 ND = Best->FoundDecl; 1904 Corrected.setCorrectionDecl(ND); 1905 break; 1906 default: 1907 // FIXME: Arbitrarily pick the first declaration for the note. 1908 Corrected.setCorrectionDecl(ND); 1909 break; 1910 } 1911 } 1912 R.addDecl(ND); 1913 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 1914 CXXRecordDecl *Record = nullptr; 1915 if (Corrected.getCorrectionSpecifier()) { 1916 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 1917 Record = Ty->getAsCXXRecordDecl(); 1918 } 1919 if (!Record) 1920 Record = cast<CXXRecordDecl>( 1921 ND->getDeclContext()->getRedeclContext()); 1922 R.setNamingClass(Record); 1923 } 1924 1925 auto *UnderlyingND = ND->getUnderlyingDecl(); 1926 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 1927 isa<FunctionTemplateDecl>(UnderlyingND); 1928 // FIXME: If we ended up with a typo for a type name or 1929 // Objective-C class name, we're in trouble because the parser 1930 // is in the wrong place to recover. Suggest the typo 1931 // correction, but don't make it a fix-it since we're not going 1932 // to recover well anyway. 1933 AcceptableWithoutRecovery = 1934 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND); 1935 } else { 1936 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1937 // because we aren't able to recover. 1938 AcceptableWithoutRecovery = true; 1939 } 1940 1941 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 1942 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 1943 ? diag::note_implicit_param_decl 1944 : diag::note_previous_decl; 1945 if (SS.isEmpty()) 1946 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 1947 PDiag(NoteID), AcceptableWithRecovery); 1948 else 1949 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 1950 << Name << computeDeclContext(SS, false) 1951 << DroppedSpecifier << SS.getRange(), 1952 PDiag(NoteID), AcceptableWithRecovery); 1953 1954 // Tell the callee whether to try to recover. 1955 return !AcceptableWithRecovery; 1956 } 1957 } 1958 R.clear(); 1959 1960 // Emit a special diagnostic for failed member lookups. 1961 // FIXME: computing the declaration context might fail here (?) 1962 if (!SS.isEmpty()) { 1963 Diag(R.getNameLoc(), diag::err_no_member) 1964 << Name << computeDeclContext(SS, false) 1965 << SS.getRange(); 1966 return true; 1967 } 1968 1969 // Give up, we can't recover. 1970 Diag(R.getNameLoc(), diagnostic) << Name; 1971 return true; 1972 } 1973 1974 /// In Microsoft mode, if we are inside a template class whose parent class has 1975 /// dependent base classes, and we can't resolve an unqualified identifier, then 1976 /// assume the identifier is a member of a dependent base class. We can only 1977 /// recover successfully in static methods, instance methods, and other contexts 1978 /// where 'this' is available. This doesn't precisely match MSVC's 1979 /// instantiation model, but it's close enough. 1980 static Expr * 1981 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 1982 DeclarationNameInfo &NameInfo, 1983 SourceLocation TemplateKWLoc, 1984 const TemplateArgumentListInfo *TemplateArgs) { 1985 // Only try to recover from lookup into dependent bases in static methods or 1986 // contexts where 'this' is available. 1987 QualType ThisType = S.getCurrentThisType(); 1988 const CXXRecordDecl *RD = nullptr; 1989 if (!ThisType.isNull()) 1990 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 1991 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 1992 RD = MD->getParent(); 1993 if (!RD || !RD->hasAnyDependentBases()) 1994 return nullptr; 1995 1996 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 1997 // is available, suggest inserting 'this->' as a fixit. 1998 SourceLocation Loc = NameInfo.getLoc(); 1999 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2000 DB << NameInfo.getName() << RD; 2001 2002 if (!ThisType.isNull()) { 2003 DB << FixItHint::CreateInsertion(Loc, "this->"); 2004 return CXXDependentScopeMemberExpr::Create( 2005 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2006 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2007 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 2008 } 2009 2010 // Synthesize a fake NNS that points to the derived class. This will 2011 // perform name lookup during template instantiation. 2012 CXXScopeSpec SS; 2013 auto *NNS = 2014 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2015 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2016 return DependentScopeDeclRefExpr::Create( 2017 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2018 TemplateArgs); 2019 } 2020 2021 ExprResult 2022 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2023 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2024 bool HasTrailingLParen, bool IsAddressOfOperand, 2025 std::unique_ptr<CorrectionCandidateCallback> CCC, 2026 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2027 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2028 "cannot be direct & operand and have a trailing lparen"); 2029 if (SS.isInvalid()) 2030 return ExprError(); 2031 2032 TemplateArgumentListInfo TemplateArgsBuffer; 2033 2034 // Decompose the UnqualifiedId into the following data. 2035 DeclarationNameInfo NameInfo; 2036 const TemplateArgumentListInfo *TemplateArgs; 2037 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2038 2039 DeclarationName Name = NameInfo.getName(); 2040 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2041 SourceLocation NameLoc = NameInfo.getLoc(); 2042 2043 if (II && II->isEditorPlaceholder()) { 2044 // FIXME: When typed placeholders are supported we can create a typed 2045 // placeholder expression node. 2046 return ExprError(); 2047 } 2048 2049 // C++ [temp.dep.expr]p3: 2050 // An id-expression is type-dependent if it contains: 2051 // -- an identifier that was declared with a dependent type, 2052 // (note: handled after lookup) 2053 // -- a template-id that is dependent, 2054 // (note: handled in BuildTemplateIdExpr) 2055 // -- a conversion-function-id that specifies a dependent type, 2056 // -- a nested-name-specifier that contains a class-name that 2057 // names a dependent type. 2058 // Determine whether this is a member of an unknown specialization; 2059 // we need to handle these differently. 2060 bool DependentID = false; 2061 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2062 Name.getCXXNameType()->isDependentType()) { 2063 DependentID = true; 2064 } else if (SS.isSet()) { 2065 if (DeclContext *DC = computeDeclContext(SS, false)) { 2066 if (RequireCompleteDeclContext(SS, DC)) 2067 return ExprError(); 2068 } else { 2069 DependentID = true; 2070 } 2071 } 2072 2073 if (DependentID) 2074 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2075 IsAddressOfOperand, TemplateArgs); 2076 2077 // Perform the required lookup. 2078 LookupResult R(*this, NameInfo, 2079 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 2080 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 2081 if (TemplateArgs) { 2082 // Lookup the template name again to correctly establish the context in 2083 // which it was found. This is really unfortunate as we already did the 2084 // lookup to determine that it was a template name in the first place. If 2085 // this becomes a performance hit, we can work harder to preserve those 2086 // results until we get here but it's likely not worth it. 2087 bool MemberOfUnknownSpecialization; 2088 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2089 MemberOfUnknownSpecialization); 2090 2091 if (MemberOfUnknownSpecialization || 2092 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2093 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2094 IsAddressOfOperand, TemplateArgs); 2095 } else { 2096 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2097 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2098 2099 // If the result might be in a dependent base class, this is a dependent 2100 // id-expression. 2101 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2102 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2103 IsAddressOfOperand, TemplateArgs); 2104 2105 // If this reference is in an Objective-C method, then we need to do 2106 // some special Objective-C lookup, too. 2107 if (IvarLookupFollowUp) { 2108 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2109 if (E.isInvalid()) 2110 return ExprError(); 2111 2112 if (Expr *Ex = E.getAs<Expr>()) 2113 return Ex; 2114 } 2115 } 2116 2117 if (R.isAmbiguous()) 2118 return ExprError(); 2119 2120 // This could be an implicitly declared function reference (legal in C90, 2121 // extension in C99, forbidden in C++). 2122 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2123 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2124 if (D) R.addDecl(D); 2125 } 2126 2127 // Determine whether this name might be a candidate for 2128 // argument-dependent lookup. 2129 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2130 2131 if (R.empty() && !ADL) { 2132 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2133 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2134 TemplateKWLoc, TemplateArgs)) 2135 return E; 2136 } 2137 2138 // Don't diagnose an empty lookup for inline assembly. 2139 if (IsInlineAsmIdentifier) 2140 return ExprError(); 2141 2142 // If this name wasn't predeclared and if this is not a function 2143 // call, diagnose the problem. 2144 TypoExpr *TE = nullptr; 2145 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2146 II, SS.isValid() ? SS.getScopeRep() : nullptr); 2147 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; 2148 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2149 "Typo correction callback misconfigured"); 2150 if (CCC) { 2151 // Make sure the callback knows what the typo being diagnosed is. 2152 CCC->setTypoName(II); 2153 if (SS.isValid()) 2154 CCC->setTypoNNS(SS.getScopeRep()); 2155 } 2156 if (DiagnoseEmptyLookup(S, SS, R, 2157 CCC ? std::move(CCC) : std::move(DefaultValidator), 2158 nullptr, None, &TE)) { 2159 if (TE && KeywordReplacement) { 2160 auto &State = getTypoExprState(TE); 2161 auto BestTC = State.Consumer->getNextCorrection(); 2162 if (BestTC.isKeyword()) { 2163 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2164 if (State.DiagHandler) 2165 State.DiagHandler(BestTC); 2166 KeywordReplacement->startToken(); 2167 KeywordReplacement->setKind(II->getTokenID()); 2168 KeywordReplacement->setIdentifierInfo(II); 2169 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2170 // Clean up the state associated with the TypoExpr, since it has 2171 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2172 clearDelayedTypo(TE); 2173 // Signal that a correction to a keyword was performed by returning a 2174 // valid-but-null ExprResult. 2175 return (Expr*)nullptr; 2176 } 2177 State.Consumer->resetCorrectionStream(); 2178 } 2179 return TE ? TE : ExprError(); 2180 } 2181 2182 assert(!R.empty() && 2183 "DiagnoseEmptyLookup returned false but added no results"); 2184 2185 // If we found an Objective-C instance variable, let 2186 // LookupInObjCMethod build the appropriate expression to 2187 // reference the ivar. 2188 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2189 R.clear(); 2190 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2191 // In a hopelessly buggy code, Objective-C instance variable 2192 // lookup fails and no expression will be built to reference it. 2193 if (!E.isInvalid() && !E.get()) 2194 return ExprError(); 2195 return E; 2196 } 2197 } 2198 2199 // This is guaranteed from this point on. 2200 assert(!R.empty() || ADL); 2201 2202 // Check whether this might be a C++ implicit instance member access. 2203 // C++ [class.mfct.non-static]p3: 2204 // When an id-expression that is not part of a class member access 2205 // syntax and not used to form a pointer to member is used in the 2206 // body of a non-static member function of class X, if name lookup 2207 // resolves the name in the id-expression to a non-static non-type 2208 // member of some class C, the id-expression is transformed into a 2209 // class member access expression using (*this) as the 2210 // postfix-expression to the left of the . operator. 2211 // 2212 // But we don't actually need to do this for '&' operands if R 2213 // resolved to a function or overloaded function set, because the 2214 // expression is ill-formed if it actually works out to be a 2215 // non-static member function: 2216 // 2217 // C++ [expr.ref]p4: 2218 // Otherwise, if E1.E2 refers to a non-static member function. . . 2219 // [t]he expression can be used only as the left-hand operand of a 2220 // member function call. 2221 // 2222 // There are other safeguards against such uses, but it's important 2223 // to get this right here so that we don't end up making a 2224 // spuriously dependent expression if we're inside a dependent 2225 // instance method. 2226 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2227 bool MightBeImplicitMember; 2228 if (!IsAddressOfOperand) 2229 MightBeImplicitMember = true; 2230 else if (!SS.isEmpty()) 2231 MightBeImplicitMember = false; 2232 else if (R.isOverloadedResult()) 2233 MightBeImplicitMember = false; 2234 else if (R.isUnresolvableResult()) 2235 MightBeImplicitMember = true; 2236 else 2237 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2238 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2239 isa<MSPropertyDecl>(R.getFoundDecl()); 2240 2241 if (MightBeImplicitMember) 2242 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2243 R, TemplateArgs, S); 2244 } 2245 2246 if (TemplateArgs || TemplateKWLoc.isValid()) { 2247 2248 // In C++1y, if this is a variable template id, then check it 2249 // in BuildTemplateIdExpr(). 2250 // The single lookup result must be a variable template declaration. 2251 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId && 2252 Id.TemplateId->Kind == TNK_Var_template) { 2253 assert(R.getAsSingle<VarTemplateDecl>() && 2254 "There should only be one declaration found."); 2255 } 2256 2257 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2258 } 2259 2260 return BuildDeclarationNameExpr(SS, R, ADL); 2261 } 2262 2263 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2264 /// declaration name, generally during template instantiation. 2265 /// There's a large number of things which don't need to be done along 2266 /// this path. 2267 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2268 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2269 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2270 DeclContext *DC = computeDeclContext(SS, false); 2271 if (!DC) 2272 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2273 NameInfo, /*TemplateArgs=*/nullptr); 2274 2275 if (RequireCompleteDeclContext(SS, DC)) 2276 return ExprError(); 2277 2278 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2279 LookupQualifiedName(R, DC); 2280 2281 if (R.isAmbiguous()) 2282 return ExprError(); 2283 2284 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2285 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2286 NameInfo, /*TemplateArgs=*/nullptr); 2287 2288 if (R.empty()) { 2289 Diag(NameInfo.getLoc(), diag::err_no_member) 2290 << NameInfo.getName() << DC << SS.getRange(); 2291 return ExprError(); 2292 } 2293 2294 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2295 // Diagnose a missing typename if this resolved unambiguously to a type in 2296 // a dependent context. If we can recover with a type, downgrade this to 2297 // a warning in Microsoft compatibility mode. 2298 unsigned DiagID = diag::err_typename_missing; 2299 if (RecoveryTSI && getLangOpts().MSVCCompat) 2300 DiagID = diag::ext_typename_missing; 2301 SourceLocation Loc = SS.getBeginLoc(); 2302 auto D = Diag(Loc, DiagID); 2303 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2304 << SourceRange(Loc, NameInfo.getEndLoc()); 2305 2306 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2307 // context. 2308 if (!RecoveryTSI) 2309 return ExprError(); 2310 2311 // Only issue the fixit if we're prepared to recover. 2312 D << FixItHint::CreateInsertion(Loc, "typename "); 2313 2314 // Recover by pretending this was an elaborated type. 2315 QualType Ty = Context.getTypeDeclType(TD); 2316 TypeLocBuilder TLB; 2317 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2318 2319 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2320 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2321 QTL.setElaboratedKeywordLoc(SourceLocation()); 2322 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2323 2324 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2325 2326 return ExprEmpty(); 2327 } 2328 2329 // Defend against this resolving to an implicit member access. We usually 2330 // won't get here if this might be a legitimate a class member (we end up in 2331 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2332 // a pointer-to-member or in an unevaluated context in C++11. 2333 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2334 return BuildPossibleImplicitMemberExpr(SS, 2335 /*TemplateKWLoc=*/SourceLocation(), 2336 R, /*TemplateArgs=*/nullptr, S); 2337 2338 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2339 } 2340 2341 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2342 /// detected that we're currently inside an ObjC method. Perform some 2343 /// additional lookup. 2344 /// 2345 /// Ideally, most of this would be done by lookup, but there's 2346 /// actually quite a lot of extra work involved. 2347 /// 2348 /// Returns a null sentinel to indicate trivial success. 2349 ExprResult 2350 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2351 IdentifierInfo *II, bool AllowBuiltinCreation) { 2352 SourceLocation Loc = Lookup.getNameLoc(); 2353 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2354 2355 // Check for error condition which is already reported. 2356 if (!CurMethod) 2357 return ExprError(); 2358 2359 // There are two cases to handle here. 1) scoped lookup could have failed, 2360 // in which case we should look for an ivar. 2) scoped lookup could have 2361 // found a decl, but that decl is outside the current instance method (i.e. 2362 // a global variable). In these two cases, we do a lookup for an ivar with 2363 // this name, if the lookup sucedes, we replace it our current decl. 2364 2365 // If we're in a class method, we don't normally want to look for 2366 // ivars. But if we don't find anything else, and there's an 2367 // ivar, that's an error. 2368 bool IsClassMethod = CurMethod->isClassMethod(); 2369 2370 bool LookForIvars; 2371 if (Lookup.empty()) 2372 LookForIvars = true; 2373 else if (IsClassMethod) 2374 LookForIvars = false; 2375 else 2376 LookForIvars = (Lookup.isSingleResult() && 2377 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2378 ObjCInterfaceDecl *IFace = nullptr; 2379 if (LookForIvars) { 2380 IFace = CurMethod->getClassInterface(); 2381 ObjCInterfaceDecl *ClassDeclared; 2382 ObjCIvarDecl *IV = nullptr; 2383 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2384 // Diagnose using an ivar in a class method. 2385 if (IsClassMethod) 2386 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2387 << IV->getDeclName()); 2388 2389 // If we're referencing an invalid decl, just return this as a silent 2390 // error node. The error diagnostic was already emitted on the decl. 2391 if (IV->isInvalidDecl()) 2392 return ExprError(); 2393 2394 // Check if referencing a field with __attribute__((deprecated)). 2395 if (DiagnoseUseOfDecl(IV, Loc)) 2396 return ExprError(); 2397 2398 // Diagnose the use of an ivar outside of the declaring class. 2399 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2400 !declaresSameEntity(ClassDeclared, IFace) && 2401 !getLangOpts().DebuggerSupport) 2402 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2403 2404 // FIXME: This should use a new expr for a direct reference, don't 2405 // turn this into Self->ivar, just return a BareIVarExpr or something. 2406 IdentifierInfo &II = Context.Idents.get("self"); 2407 UnqualifiedId SelfName; 2408 SelfName.setIdentifier(&II, SourceLocation()); 2409 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2410 CXXScopeSpec SelfScopeSpec; 2411 SourceLocation TemplateKWLoc; 2412 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2413 SelfName, false, false); 2414 if (SelfExpr.isInvalid()) 2415 return ExprError(); 2416 2417 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2418 if (SelfExpr.isInvalid()) 2419 return ExprError(); 2420 2421 MarkAnyDeclReferenced(Loc, IV, true); 2422 2423 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2424 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2425 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2426 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2427 2428 ObjCIvarRefExpr *Result = new (Context) 2429 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2430 IV->getLocation(), SelfExpr.get(), true, true); 2431 2432 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2433 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2434 recordUseOfEvaluatedWeak(Result); 2435 } 2436 if (getLangOpts().ObjCAutoRefCount) { 2437 if (CurContext->isClosure()) 2438 Diag(Loc, diag::warn_implicitly_retains_self) 2439 << FixItHint::CreateInsertion(Loc, "self->"); 2440 } 2441 2442 return Result; 2443 } 2444 } else if (CurMethod->isInstanceMethod()) { 2445 // We should warn if a local variable hides an ivar. 2446 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2447 ObjCInterfaceDecl *ClassDeclared; 2448 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2449 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2450 declaresSameEntity(IFace, ClassDeclared)) 2451 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2452 } 2453 } 2454 } else if (Lookup.isSingleResult() && 2455 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2456 // If accessing a stand-alone ivar in a class method, this is an error. 2457 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2458 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2459 << IV->getDeclName()); 2460 } 2461 2462 if (Lookup.empty() && II && AllowBuiltinCreation) { 2463 // FIXME. Consolidate this with similar code in LookupName. 2464 if (unsigned BuiltinID = II->getBuiltinID()) { 2465 if (!(getLangOpts().CPlusPlus && 2466 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2467 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2468 S, Lookup.isForRedeclaration(), 2469 Lookup.getNameLoc()); 2470 if (D) Lookup.addDecl(D); 2471 } 2472 } 2473 } 2474 // Sentinel value saying that we didn't do anything special. 2475 return ExprResult((Expr *)nullptr); 2476 } 2477 2478 /// \brief Cast a base object to a member's actual type. 2479 /// 2480 /// Logically this happens in three phases: 2481 /// 2482 /// * First we cast from the base type to the naming class. 2483 /// The naming class is the class into which we were looking 2484 /// when we found the member; it's the qualifier type if a 2485 /// qualifier was provided, and otherwise it's the base type. 2486 /// 2487 /// * Next we cast from the naming class to the declaring class. 2488 /// If the member we found was brought into a class's scope by 2489 /// a using declaration, this is that class; otherwise it's 2490 /// the class declaring the member. 2491 /// 2492 /// * Finally we cast from the declaring class to the "true" 2493 /// declaring class of the member. This conversion does not 2494 /// obey access control. 2495 ExprResult 2496 Sema::PerformObjectMemberConversion(Expr *From, 2497 NestedNameSpecifier *Qualifier, 2498 NamedDecl *FoundDecl, 2499 NamedDecl *Member) { 2500 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2501 if (!RD) 2502 return From; 2503 2504 QualType DestRecordType; 2505 QualType DestType; 2506 QualType FromRecordType; 2507 QualType FromType = From->getType(); 2508 bool PointerConversions = false; 2509 if (isa<FieldDecl>(Member)) { 2510 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2511 2512 if (FromType->getAs<PointerType>()) { 2513 DestType = Context.getPointerType(DestRecordType); 2514 FromRecordType = FromType->getPointeeType(); 2515 PointerConversions = true; 2516 } else { 2517 DestType = DestRecordType; 2518 FromRecordType = FromType; 2519 } 2520 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2521 if (Method->isStatic()) 2522 return From; 2523 2524 DestType = Method->getThisType(Context); 2525 DestRecordType = DestType->getPointeeType(); 2526 2527 if (FromType->getAs<PointerType>()) { 2528 FromRecordType = FromType->getPointeeType(); 2529 PointerConversions = true; 2530 } else { 2531 FromRecordType = FromType; 2532 DestType = DestRecordType; 2533 } 2534 } else { 2535 // No conversion necessary. 2536 return From; 2537 } 2538 2539 if (DestType->isDependentType() || FromType->isDependentType()) 2540 return From; 2541 2542 // If the unqualified types are the same, no conversion is necessary. 2543 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2544 return From; 2545 2546 SourceRange FromRange = From->getSourceRange(); 2547 SourceLocation FromLoc = FromRange.getBegin(); 2548 2549 ExprValueKind VK = From->getValueKind(); 2550 2551 // C++ [class.member.lookup]p8: 2552 // [...] Ambiguities can often be resolved by qualifying a name with its 2553 // class name. 2554 // 2555 // If the member was a qualified name and the qualified referred to a 2556 // specific base subobject type, we'll cast to that intermediate type 2557 // first and then to the object in which the member is declared. That allows 2558 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2559 // 2560 // class Base { public: int x; }; 2561 // class Derived1 : public Base { }; 2562 // class Derived2 : public Base { }; 2563 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2564 // 2565 // void VeryDerived::f() { 2566 // x = 17; // error: ambiguous base subobjects 2567 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2568 // } 2569 if (Qualifier && Qualifier->getAsType()) { 2570 QualType QType = QualType(Qualifier->getAsType(), 0); 2571 assert(QType->isRecordType() && "lookup done with non-record type"); 2572 2573 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2574 2575 // In C++98, the qualifier type doesn't actually have to be a base 2576 // type of the object type, in which case we just ignore it. 2577 // Otherwise build the appropriate casts. 2578 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2579 CXXCastPath BasePath; 2580 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2581 FromLoc, FromRange, &BasePath)) 2582 return ExprError(); 2583 2584 if (PointerConversions) 2585 QType = Context.getPointerType(QType); 2586 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2587 VK, &BasePath).get(); 2588 2589 FromType = QType; 2590 FromRecordType = QRecordType; 2591 2592 // If the qualifier type was the same as the destination type, 2593 // we're done. 2594 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2595 return From; 2596 } 2597 } 2598 2599 bool IgnoreAccess = false; 2600 2601 // If we actually found the member through a using declaration, cast 2602 // down to the using declaration's type. 2603 // 2604 // Pointer equality is fine here because only one declaration of a 2605 // class ever has member declarations. 2606 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2607 assert(isa<UsingShadowDecl>(FoundDecl)); 2608 QualType URecordType = Context.getTypeDeclType( 2609 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2610 2611 // We only need to do this if the naming-class to declaring-class 2612 // conversion is non-trivial. 2613 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2614 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2615 CXXCastPath BasePath; 2616 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2617 FromLoc, FromRange, &BasePath)) 2618 return ExprError(); 2619 2620 QualType UType = URecordType; 2621 if (PointerConversions) 2622 UType = Context.getPointerType(UType); 2623 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2624 VK, &BasePath).get(); 2625 FromType = UType; 2626 FromRecordType = URecordType; 2627 } 2628 2629 // We don't do access control for the conversion from the 2630 // declaring class to the true declaring class. 2631 IgnoreAccess = true; 2632 } 2633 2634 CXXCastPath BasePath; 2635 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2636 FromLoc, FromRange, &BasePath, 2637 IgnoreAccess)) 2638 return ExprError(); 2639 2640 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2641 VK, &BasePath); 2642 } 2643 2644 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2645 const LookupResult &R, 2646 bool HasTrailingLParen) { 2647 // Only when used directly as the postfix-expression of a call. 2648 if (!HasTrailingLParen) 2649 return false; 2650 2651 // Never if a scope specifier was provided. 2652 if (SS.isSet()) 2653 return false; 2654 2655 // Only in C++ or ObjC++. 2656 if (!getLangOpts().CPlusPlus) 2657 return false; 2658 2659 // Turn off ADL when we find certain kinds of declarations during 2660 // normal lookup: 2661 for (NamedDecl *D : R) { 2662 // C++0x [basic.lookup.argdep]p3: 2663 // -- a declaration of a class member 2664 // Since using decls preserve this property, we check this on the 2665 // original decl. 2666 if (D->isCXXClassMember()) 2667 return false; 2668 2669 // C++0x [basic.lookup.argdep]p3: 2670 // -- a block-scope function declaration that is not a 2671 // using-declaration 2672 // NOTE: we also trigger this for function templates (in fact, we 2673 // don't check the decl type at all, since all other decl types 2674 // turn off ADL anyway). 2675 if (isa<UsingShadowDecl>(D)) 2676 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2677 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2678 return false; 2679 2680 // C++0x [basic.lookup.argdep]p3: 2681 // -- a declaration that is neither a function or a function 2682 // template 2683 // And also for builtin functions. 2684 if (isa<FunctionDecl>(D)) { 2685 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2686 2687 // But also builtin functions. 2688 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2689 return false; 2690 } else if (!isa<FunctionTemplateDecl>(D)) 2691 return false; 2692 } 2693 2694 return true; 2695 } 2696 2697 2698 /// Diagnoses obvious problems with the use of the given declaration 2699 /// as an expression. This is only actually called for lookups that 2700 /// were not overloaded, and it doesn't promise that the declaration 2701 /// will in fact be used. 2702 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2703 if (D->isInvalidDecl()) 2704 return true; 2705 2706 if (isa<TypedefNameDecl>(D)) { 2707 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2708 return true; 2709 } 2710 2711 if (isa<ObjCInterfaceDecl>(D)) { 2712 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2713 return true; 2714 } 2715 2716 if (isa<NamespaceDecl>(D)) { 2717 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2718 return true; 2719 } 2720 2721 return false; 2722 } 2723 2724 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2725 LookupResult &R, bool NeedsADL, 2726 bool AcceptInvalidDecl) { 2727 // If this is a single, fully-resolved result and we don't need ADL, 2728 // just build an ordinary singleton decl ref. 2729 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2730 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2731 R.getRepresentativeDecl(), nullptr, 2732 AcceptInvalidDecl); 2733 2734 // We only need to check the declaration if there's exactly one 2735 // result, because in the overloaded case the results can only be 2736 // functions and function templates. 2737 if (R.isSingleResult() && 2738 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2739 return ExprError(); 2740 2741 // Otherwise, just build an unresolved lookup expression. Suppress 2742 // any lookup-related diagnostics; we'll hash these out later, when 2743 // we've picked a target. 2744 R.suppressDiagnostics(); 2745 2746 UnresolvedLookupExpr *ULE 2747 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2748 SS.getWithLocInContext(Context), 2749 R.getLookupNameInfo(), 2750 NeedsADL, R.isOverloadedResult(), 2751 R.begin(), R.end()); 2752 2753 return ULE; 2754 } 2755 2756 static void 2757 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 2758 ValueDecl *var, DeclContext *DC); 2759 2760 /// \brief Complete semantic analysis for a reference to the given declaration. 2761 ExprResult Sema::BuildDeclarationNameExpr( 2762 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2763 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2764 bool AcceptInvalidDecl) { 2765 assert(D && "Cannot refer to a NULL declaration"); 2766 assert(!isa<FunctionTemplateDecl>(D) && 2767 "Cannot refer unambiguously to a function template"); 2768 2769 SourceLocation Loc = NameInfo.getLoc(); 2770 if (CheckDeclInExpr(*this, Loc, D)) 2771 return ExprError(); 2772 2773 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2774 // Specifically diagnose references to class templates that are missing 2775 // a template argument list. 2776 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2777 << Template << SS.getRange(); 2778 Diag(Template->getLocation(), diag::note_template_decl_here); 2779 return ExprError(); 2780 } 2781 2782 // Make sure that we're referring to a value. 2783 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2784 if (!VD) { 2785 Diag(Loc, diag::err_ref_non_value) 2786 << D << SS.getRange(); 2787 Diag(D->getLocation(), diag::note_declared_at); 2788 return ExprError(); 2789 } 2790 2791 // Check whether this declaration can be used. Note that we suppress 2792 // this check when we're going to perform argument-dependent lookup 2793 // on this function name, because this might not be the function 2794 // that overload resolution actually selects. 2795 if (DiagnoseUseOfDecl(VD, Loc)) 2796 return ExprError(); 2797 2798 // Only create DeclRefExpr's for valid Decl's. 2799 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2800 return ExprError(); 2801 2802 // Handle members of anonymous structs and unions. If we got here, 2803 // and the reference is to a class member indirect field, then this 2804 // must be the subject of a pointer-to-member expression. 2805 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2806 if (!indirectField->isCXXClassMember()) 2807 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2808 indirectField); 2809 2810 { 2811 QualType type = VD->getType(); 2812 if (auto *FPT = type->getAs<FunctionProtoType>()) { 2813 // C++ [except.spec]p17: 2814 // An exception-specification is considered to be needed when: 2815 // - in an expression, the function is the unique lookup result or 2816 // the selected member of a set of overloaded functions. 2817 ResolveExceptionSpec(Loc, FPT); 2818 type = VD->getType(); 2819 } 2820 ExprValueKind valueKind = VK_RValue; 2821 2822 switch (D->getKind()) { 2823 // Ignore all the non-ValueDecl kinds. 2824 #define ABSTRACT_DECL(kind) 2825 #define VALUE(type, base) 2826 #define DECL(type, base) \ 2827 case Decl::type: 2828 #include "clang/AST/DeclNodes.inc" 2829 llvm_unreachable("invalid value decl kind"); 2830 2831 // These shouldn't make it here. 2832 case Decl::ObjCAtDefsField: 2833 case Decl::ObjCIvar: 2834 llvm_unreachable("forming non-member reference to ivar?"); 2835 2836 // Enum constants are always r-values and never references. 2837 // Unresolved using declarations are dependent. 2838 case Decl::EnumConstant: 2839 case Decl::UnresolvedUsingValue: 2840 case Decl::OMPDeclareReduction: 2841 valueKind = VK_RValue; 2842 break; 2843 2844 // Fields and indirect fields that got here must be for 2845 // pointer-to-member expressions; we just call them l-values for 2846 // internal consistency, because this subexpression doesn't really 2847 // exist in the high-level semantics. 2848 case Decl::Field: 2849 case Decl::IndirectField: 2850 assert(getLangOpts().CPlusPlus && 2851 "building reference to field in C?"); 2852 2853 // These can't have reference type in well-formed programs, but 2854 // for internal consistency we do this anyway. 2855 type = type.getNonReferenceType(); 2856 valueKind = VK_LValue; 2857 break; 2858 2859 // Non-type template parameters are either l-values or r-values 2860 // depending on the type. 2861 case Decl::NonTypeTemplateParm: { 2862 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2863 type = reftype->getPointeeType(); 2864 valueKind = VK_LValue; // even if the parameter is an r-value reference 2865 break; 2866 } 2867 2868 // For non-references, we need to strip qualifiers just in case 2869 // the template parameter was declared as 'const int' or whatever. 2870 valueKind = VK_RValue; 2871 type = type.getUnqualifiedType(); 2872 break; 2873 } 2874 2875 case Decl::Var: 2876 case Decl::VarTemplateSpecialization: 2877 case Decl::VarTemplatePartialSpecialization: 2878 case Decl::Decomposition: 2879 case Decl::OMPCapturedExpr: 2880 // In C, "extern void blah;" is valid and is an r-value. 2881 if (!getLangOpts().CPlusPlus && 2882 !type.hasQualifiers() && 2883 type->isVoidType()) { 2884 valueKind = VK_RValue; 2885 break; 2886 } 2887 // fallthrough 2888 2889 case Decl::ImplicitParam: 2890 case Decl::ParmVar: { 2891 // These are always l-values. 2892 valueKind = VK_LValue; 2893 type = type.getNonReferenceType(); 2894 2895 // FIXME: Does the addition of const really only apply in 2896 // potentially-evaluated contexts? Since the variable isn't actually 2897 // captured in an unevaluated context, it seems that the answer is no. 2898 if (!isUnevaluatedContext()) { 2899 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2900 if (!CapturedType.isNull()) 2901 type = CapturedType; 2902 } 2903 2904 break; 2905 } 2906 2907 case Decl::Binding: { 2908 // These are always lvalues. 2909 valueKind = VK_LValue; 2910 type = type.getNonReferenceType(); 2911 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 2912 // decides how that's supposed to work. 2913 auto *BD = cast<BindingDecl>(VD); 2914 if (BD->getDeclContext()->isFunctionOrMethod() && 2915 BD->getDeclContext() != CurContext) 2916 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 2917 break; 2918 } 2919 2920 case Decl::Function: { 2921 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2922 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2923 type = Context.BuiltinFnTy; 2924 valueKind = VK_RValue; 2925 break; 2926 } 2927 } 2928 2929 const FunctionType *fty = type->castAs<FunctionType>(); 2930 2931 // If we're referring to a function with an __unknown_anytype 2932 // result type, make the entire expression __unknown_anytype. 2933 if (fty->getReturnType() == Context.UnknownAnyTy) { 2934 type = Context.UnknownAnyTy; 2935 valueKind = VK_RValue; 2936 break; 2937 } 2938 2939 // Functions are l-values in C++. 2940 if (getLangOpts().CPlusPlus) { 2941 valueKind = VK_LValue; 2942 break; 2943 } 2944 2945 // C99 DR 316 says that, if a function type comes from a 2946 // function definition (without a prototype), that type is only 2947 // used for checking compatibility. Therefore, when referencing 2948 // the function, we pretend that we don't have the full function 2949 // type. 2950 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2951 isa<FunctionProtoType>(fty)) 2952 type = Context.getFunctionNoProtoType(fty->getReturnType(), 2953 fty->getExtInfo()); 2954 2955 // Functions are r-values in C. 2956 valueKind = VK_RValue; 2957 break; 2958 } 2959 2960 case Decl::CXXDeductionGuide: 2961 llvm_unreachable("building reference to deduction guide"); 2962 2963 case Decl::MSProperty: 2964 valueKind = VK_LValue; 2965 break; 2966 2967 case Decl::CXXMethod: 2968 // If we're referring to a method with an __unknown_anytype 2969 // result type, make the entire expression __unknown_anytype. 2970 // This should only be possible with a type written directly. 2971 if (const FunctionProtoType *proto 2972 = dyn_cast<FunctionProtoType>(VD->getType())) 2973 if (proto->getReturnType() == Context.UnknownAnyTy) { 2974 type = Context.UnknownAnyTy; 2975 valueKind = VK_RValue; 2976 break; 2977 } 2978 2979 // C++ methods are l-values if static, r-values if non-static. 2980 if (cast<CXXMethodDecl>(VD)->isStatic()) { 2981 valueKind = VK_LValue; 2982 break; 2983 } 2984 // fallthrough 2985 2986 case Decl::CXXConversion: 2987 case Decl::CXXDestructor: 2988 case Decl::CXXConstructor: 2989 valueKind = VK_RValue; 2990 break; 2991 } 2992 2993 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 2994 TemplateArgs); 2995 } 2996 } 2997 2998 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 2999 SmallString<32> &Target) { 3000 Target.resize(CharByteWidth * (Source.size() + 1)); 3001 char *ResultPtr = &Target[0]; 3002 const llvm::UTF8 *ErrorPtr; 3003 bool success = 3004 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3005 (void)success; 3006 assert(success); 3007 Target.resize(ResultPtr - &Target[0]); 3008 } 3009 3010 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3011 PredefinedExpr::IdentType IT) { 3012 // Pick the current block, lambda, captured statement or function. 3013 Decl *currentDecl = nullptr; 3014 if (const BlockScopeInfo *BSI = getCurBlock()) 3015 currentDecl = BSI->TheDecl; 3016 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3017 currentDecl = LSI->CallOperator; 3018 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3019 currentDecl = CSI->TheCapturedDecl; 3020 else 3021 currentDecl = getCurFunctionOrMethodDecl(); 3022 3023 if (!currentDecl) { 3024 Diag(Loc, diag::ext_predef_outside_function); 3025 currentDecl = Context.getTranslationUnitDecl(); 3026 } 3027 3028 QualType ResTy; 3029 StringLiteral *SL = nullptr; 3030 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3031 ResTy = Context.DependentTy; 3032 else { 3033 // Pre-defined identifiers are of type char[x], where x is the length of 3034 // the string. 3035 auto Str = PredefinedExpr::ComputeName(IT, currentDecl); 3036 unsigned Length = Str.length(); 3037 3038 llvm::APInt LengthI(32, Length + 1); 3039 if (IT == PredefinedExpr::LFunction) { 3040 ResTy = Context.WideCharTy.withConst(); 3041 SmallString<32> RawChars; 3042 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3043 Str, RawChars); 3044 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3045 /*IndexTypeQuals*/ 0); 3046 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3047 /*Pascal*/ false, ResTy, Loc); 3048 } else { 3049 ResTy = Context.CharTy.withConst(); 3050 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3051 /*IndexTypeQuals*/ 0); 3052 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3053 /*Pascal*/ false, ResTy, Loc); 3054 } 3055 } 3056 3057 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL); 3058 } 3059 3060 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3061 PredefinedExpr::IdentType IT; 3062 3063 switch (Kind) { 3064 default: llvm_unreachable("Unknown simple primary expr!"); 3065 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3066 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 3067 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 3068 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS] 3069 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 3070 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 3071 } 3072 3073 return BuildPredefinedExpr(Loc, IT); 3074 } 3075 3076 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3077 SmallString<16> CharBuffer; 3078 bool Invalid = false; 3079 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3080 if (Invalid) 3081 return ExprError(); 3082 3083 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3084 PP, Tok.getKind()); 3085 if (Literal.hadError()) 3086 return ExprError(); 3087 3088 QualType Ty; 3089 if (Literal.isWide()) 3090 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3091 else if (Literal.isUTF16()) 3092 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3093 else if (Literal.isUTF32()) 3094 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3095 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3096 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3097 else 3098 Ty = Context.CharTy; // 'x' -> char in C++ 3099 3100 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3101 if (Literal.isWide()) 3102 Kind = CharacterLiteral::Wide; 3103 else if (Literal.isUTF16()) 3104 Kind = CharacterLiteral::UTF16; 3105 else if (Literal.isUTF32()) 3106 Kind = CharacterLiteral::UTF32; 3107 else if (Literal.isUTF8()) 3108 Kind = CharacterLiteral::UTF8; 3109 3110 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3111 Tok.getLocation()); 3112 3113 if (Literal.getUDSuffix().empty()) 3114 return Lit; 3115 3116 // We're building a user-defined literal. 3117 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3118 SourceLocation UDSuffixLoc = 3119 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3120 3121 // Make sure we're allowed user-defined literals here. 3122 if (!UDLScope) 3123 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3124 3125 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3126 // operator "" X (ch) 3127 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3128 Lit, Tok.getLocation()); 3129 } 3130 3131 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3132 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3133 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3134 Context.IntTy, Loc); 3135 } 3136 3137 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3138 QualType Ty, SourceLocation Loc) { 3139 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3140 3141 using llvm::APFloat; 3142 APFloat Val(Format); 3143 3144 APFloat::opStatus result = Literal.GetFloatValue(Val); 3145 3146 // Overflow is always an error, but underflow is only an error if 3147 // we underflowed to zero (APFloat reports denormals as underflow). 3148 if ((result & APFloat::opOverflow) || 3149 ((result & APFloat::opUnderflow) && Val.isZero())) { 3150 unsigned diagnostic; 3151 SmallString<20> buffer; 3152 if (result & APFloat::opOverflow) { 3153 diagnostic = diag::warn_float_overflow; 3154 APFloat::getLargest(Format).toString(buffer); 3155 } else { 3156 diagnostic = diag::warn_float_underflow; 3157 APFloat::getSmallest(Format).toString(buffer); 3158 } 3159 3160 S.Diag(Loc, diagnostic) 3161 << Ty 3162 << StringRef(buffer.data(), buffer.size()); 3163 } 3164 3165 bool isExact = (result == APFloat::opOK); 3166 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3167 } 3168 3169 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3170 assert(E && "Invalid expression"); 3171 3172 if (E->isValueDependent()) 3173 return false; 3174 3175 QualType QT = E->getType(); 3176 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3177 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3178 return true; 3179 } 3180 3181 llvm::APSInt ValueAPS; 3182 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3183 3184 if (R.isInvalid()) 3185 return true; 3186 3187 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3188 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3189 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3190 << ValueAPS.toString(10) << ValueIsPositive; 3191 return true; 3192 } 3193 3194 return false; 3195 } 3196 3197 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3198 // Fast path for a single digit (which is quite common). A single digit 3199 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3200 if (Tok.getLength() == 1) { 3201 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3202 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3203 } 3204 3205 SmallString<128> SpellingBuffer; 3206 // NumericLiteralParser wants to overread by one character. Add padding to 3207 // the buffer in case the token is copied to the buffer. If getSpelling() 3208 // returns a StringRef to the memory buffer, it should have a null char at 3209 // the EOF, so it is also safe. 3210 SpellingBuffer.resize(Tok.getLength() + 1); 3211 3212 // Get the spelling of the token, which eliminates trigraphs, etc. 3213 bool Invalid = false; 3214 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3215 if (Invalid) 3216 return ExprError(); 3217 3218 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3219 if (Literal.hadError) 3220 return ExprError(); 3221 3222 if (Literal.hasUDSuffix()) { 3223 // We're building a user-defined literal. 3224 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3225 SourceLocation UDSuffixLoc = 3226 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3227 3228 // Make sure we're allowed user-defined literals here. 3229 if (!UDLScope) 3230 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3231 3232 QualType CookedTy; 3233 if (Literal.isFloatingLiteral()) { 3234 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3235 // long double, the literal is treated as a call of the form 3236 // operator "" X (f L) 3237 CookedTy = Context.LongDoubleTy; 3238 } else { 3239 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3240 // unsigned long long, the literal is treated as a call of the form 3241 // operator "" X (n ULL) 3242 CookedTy = Context.UnsignedLongLongTy; 3243 } 3244 3245 DeclarationName OpName = 3246 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3247 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3248 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3249 3250 SourceLocation TokLoc = Tok.getLocation(); 3251 3252 // Perform literal operator lookup to determine if we're building a raw 3253 // literal or a cooked one. 3254 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3255 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3256 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3257 /*AllowStringTemplate*/ false, 3258 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3259 case LOLR_ErrorNoDiagnostic: 3260 // Lookup failure for imaginary constants isn't fatal, there's still the 3261 // GNU extension producing _Complex types. 3262 break; 3263 case LOLR_Error: 3264 return ExprError(); 3265 case LOLR_Cooked: { 3266 Expr *Lit; 3267 if (Literal.isFloatingLiteral()) { 3268 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3269 } else { 3270 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3271 if (Literal.GetIntegerValue(ResultVal)) 3272 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3273 << /* Unsigned */ 1; 3274 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3275 Tok.getLocation()); 3276 } 3277 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3278 } 3279 3280 case LOLR_Raw: { 3281 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3282 // literal is treated as a call of the form 3283 // operator "" X ("n") 3284 unsigned Length = Literal.getUDSuffixOffset(); 3285 QualType StrTy = Context.getConstantArrayType( 3286 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 3287 ArrayType::Normal, 0); 3288 Expr *Lit = StringLiteral::Create( 3289 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3290 /*Pascal*/false, StrTy, &TokLoc, 1); 3291 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3292 } 3293 3294 case LOLR_Template: { 3295 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3296 // template), L is treated as a call fo the form 3297 // operator "" X <'c1', 'c2', ... 'ck'>() 3298 // where n is the source character sequence c1 c2 ... ck. 3299 TemplateArgumentListInfo ExplicitArgs; 3300 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3301 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3302 llvm::APSInt Value(CharBits, CharIsUnsigned); 3303 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3304 Value = TokSpelling[I]; 3305 TemplateArgument Arg(Context, Value, Context.CharTy); 3306 TemplateArgumentLocInfo ArgInfo; 3307 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3308 } 3309 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3310 &ExplicitArgs); 3311 } 3312 case LOLR_StringTemplate: 3313 llvm_unreachable("unexpected literal operator lookup result"); 3314 } 3315 } 3316 3317 Expr *Res; 3318 3319 if (Literal.isFloatingLiteral()) { 3320 QualType Ty; 3321 if (Literal.isHalf){ 3322 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3323 Ty = Context.HalfTy; 3324 else { 3325 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3326 return ExprError(); 3327 } 3328 } else if (Literal.isFloat) 3329 Ty = Context.FloatTy; 3330 else if (Literal.isLong) 3331 Ty = Context.LongDoubleTy; 3332 else if (Literal.isFloat128) 3333 Ty = Context.Float128Ty; 3334 else 3335 Ty = Context.DoubleTy; 3336 3337 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3338 3339 if (Ty == Context.DoubleTy) { 3340 if (getLangOpts().SinglePrecisionConstants) { 3341 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3342 if (BTy->getKind() != BuiltinType::Float) { 3343 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3344 } 3345 } else if (getLangOpts().OpenCL && 3346 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3347 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3348 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3349 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3350 } 3351 } 3352 } else if (!Literal.isIntegerLiteral()) { 3353 return ExprError(); 3354 } else { 3355 QualType Ty; 3356 3357 // 'long long' is a C99 or C++11 feature. 3358 if (!getLangOpts().C99 && Literal.isLongLong) { 3359 if (getLangOpts().CPlusPlus) 3360 Diag(Tok.getLocation(), 3361 getLangOpts().CPlusPlus11 ? 3362 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3363 else 3364 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3365 } 3366 3367 // Get the value in the widest-possible width. 3368 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3369 llvm::APInt ResultVal(MaxWidth, 0); 3370 3371 if (Literal.GetIntegerValue(ResultVal)) { 3372 // If this value didn't fit into uintmax_t, error and force to ull. 3373 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3374 << /* Unsigned */ 1; 3375 Ty = Context.UnsignedLongLongTy; 3376 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3377 "long long is not intmax_t?"); 3378 } else { 3379 // If this value fits into a ULL, try to figure out what else it fits into 3380 // according to the rules of C99 6.4.4.1p5. 3381 3382 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3383 // be an unsigned int. 3384 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3385 3386 // Check from smallest to largest, picking the smallest type we can. 3387 unsigned Width = 0; 3388 3389 // Microsoft specific integer suffixes are explicitly sized. 3390 if (Literal.MicrosoftInteger) { 3391 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3392 Width = 8; 3393 Ty = Context.CharTy; 3394 } else { 3395 Width = Literal.MicrosoftInteger; 3396 Ty = Context.getIntTypeForBitwidth(Width, 3397 /*Signed=*/!Literal.isUnsigned); 3398 } 3399 } 3400 3401 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3402 // Are int/unsigned possibilities? 3403 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3404 3405 // Does it fit in a unsigned int? 3406 if (ResultVal.isIntN(IntSize)) { 3407 // Does it fit in a signed int? 3408 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3409 Ty = Context.IntTy; 3410 else if (AllowUnsigned) 3411 Ty = Context.UnsignedIntTy; 3412 Width = IntSize; 3413 } 3414 } 3415 3416 // Are long/unsigned long possibilities? 3417 if (Ty.isNull() && !Literal.isLongLong) { 3418 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3419 3420 // Does it fit in a unsigned long? 3421 if (ResultVal.isIntN(LongSize)) { 3422 // Does it fit in a signed long? 3423 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3424 Ty = Context.LongTy; 3425 else if (AllowUnsigned) 3426 Ty = Context.UnsignedLongTy; 3427 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3428 // is compatible. 3429 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3430 const unsigned LongLongSize = 3431 Context.getTargetInfo().getLongLongWidth(); 3432 Diag(Tok.getLocation(), 3433 getLangOpts().CPlusPlus 3434 ? Literal.isLong 3435 ? diag::warn_old_implicitly_unsigned_long_cxx 3436 : /*C++98 UB*/ diag:: 3437 ext_old_implicitly_unsigned_long_cxx 3438 : diag::warn_old_implicitly_unsigned_long) 3439 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3440 : /*will be ill-formed*/ 1); 3441 Ty = Context.UnsignedLongTy; 3442 } 3443 Width = LongSize; 3444 } 3445 } 3446 3447 // Check long long if needed. 3448 if (Ty.isNull()) { 3449 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3450 3451 // Does it fit in a unsigned long long? 3452 if (ResultVal.isIntN(LongLongSize)) { 3453 // Does it fit in a signed long long? 3454 // To be compatible with MSVC, hex integer literals ending with the 3455 // LL or i64 suffix are always signed in Microsoft mode. 3456 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3457 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3458 Ty = Context.LongLongTy; 3459 else if (AllowUnsigned) 3460 Ty = Context.UnsignedLongLongTy; 3461 Width = LongLongSize; 3462 } 3463 } 3464 3465 // If we still couldn't decide a type, we probably have something that 3466 // does not fit in a signed long long, but has no U suffix. 3467 if (Ty.isNull()) { 3468 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3469 Ty = Context.UnsignedLongLongTy; 3470 Width = Context.getTargetInfo().getLongLongWidth(); 3471 } 3472 3473 if (ResultVal.getBitWidth() != Width) 3474 ResultVal = ResultVal.trunc(Width); 3475 } 3476 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3477 } 3478 3479 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3480 if (Literal.isImaginary) { 3481 Res = new (Context) ImaginaryLiteral(Res, 3482 Context.getComplexType(Res->getType())); 3483 3484 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3485 } 3486 return Res; 3487 } 3488 3489 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3490 assert(E && "ActOnParenExpr() missing expr"); 3491 return new (Context) ParenExpr(L, R, E); 3492 } 3493 3494 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3495 SourceLocation Loc, 3496 SourceRange ArgRange) { 3497 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3498 // scalar or vector data type argument..." 3499 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3500 // type (C99 6.2.5p18) or void. 3501 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3502 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3503 << T << ArgRange; 3504 return true; 3505 } 3506 3507 assert((T->isVoidType() || !T->isIncompleteType()) && 3508 "Scalar types should always be complete"); 3509 return false; 3510 } 3511 3512 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3513 SourceLocation Loc, 3514 SourceRange ArgRange, 3515 UnaryExprOrTypeTrait TraitKind) { 3516 // Invalid types must be hard errors for SFINAE in C++. 3517 if (S.LangOpts.CPlusPlus) 3518 return true; 3519 3520 // C99 6.5.3.4p1: 3521 if (T->isFunctionType() && 3522 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3523 // sizeof(function)/alignof(function) is allowed as an extension. 3524 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3525 << TraitKind << ArgRange; 3526 return false; 3527 } 3528 3529 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3530 // this is an error (OpenCL v1.1 s6.3.k) 3531 if (T->isVoidType()) { 3532 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3533 : diag::ext_sizeof_alignof_void_type; 3534 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3535 return false; 3536 } 3537 3538 return true; 3539 } 3540 3541 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3542 SourceLocation Loc, 3543 SourceRange ArgRange, 3544 UnaryExprOrTypeTrait TraitKind) { 3545 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3546 // runtime doesn't allow it. 3547 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3548 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3549 << T << (TraitKind == UETT_SizeOf) 3550 << ArgRange; 3551 return true; 3552 } 3553 3554 return false; 3555 } 3556 3557 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3558 /// pointer type is equal to T) and emit a warning if it is. 3559 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3560 Expr *E) { 3561 // Don't warn if the operation changed the type. 3562 if (T != E->getType()) 3563 return; 3564 3565 // Now look for array decays. 3566 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3567 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3568 return; 3569 3570 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3571 << ICE->getType() 3572 << ICE->getSubExpr()->getType(); 3573 } 3574 3575 /// \brief Check the constraints on expression operands to unary type expression 3576 /// and type traits. 3577 /// 3578 /// Completes any types necessary and validates the constraints on the operand 3579 /// expression. The logic mostly mirrors the type-based overload, but may modify 3580 /// the expression as it completes the type for that expression through template 3581 /// instantiation, etc. 3582 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3583 UnaryExprOrTypeTrait ExprKind) { 3584 QualType ExprTy = E->getType(); 3585 assert(!ExprTy->isReferenceType()); 3586 3587 if (ExprKind == UETT_VecStep) 3588 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3589 E->getSourceRange()); 3590 3591 // Whitelist some types as extensions 3592 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3593 E->getSourceRange(), ExprKind)) 3594 return false; 3595 3596 // 'alignof' applied to an expression only requires the base element type of 3597 // the expression to be complete. 'sizeof' requires the expression's type to 3598 // be complete (and will attempt to complete it if it's an array of unknown 3599 // bound). 3600 if (ExprKind == UETT_AlignOf) { 3601 if (RequireCompleteType(E->getExprLoc(), 3602 Context.getBaseElementType(E->getType()), 3603 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3604 E->getSourceRange())) 3605 return true; 3606 } else { 3607 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3608 ExprKind, E->getSourceRange())) 3609 return true; 3610 } 3611 3612 // Completing the expression's type may have changed it. 3613 ExprTy = E->getType(); 3614 assert(!ExprTy->isReferenceType()); 3615 3616 if (ExprTy->isFunctionType()) { 3617 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3618 << ExprKind << E->getSourceRange(); 3619 return true; 3620 } 3621 3622 // The operand for sizeof and alignof is in an unevaluated expression context, 3623 // so side effects could result in unintended consequences. 3624 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) && 3625 !inTemplateInstantiation() && E->HasSideEffects(Context, false)) 3626 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3627 3628 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3629 E->getSourceRange(), ExprKind)) 3630 return true; 3631 3632 if (ExprKind == UETT_SizeOf) { 3633 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3634 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3635 QualType OType = PVD->getOriginalType(); 3636 QualType Type = PVD->getType(); 3637 if (Type->isPointerType() && OType->isArrayType()) { 3638 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3639 << Type << OType; 3640 Diag(PVD->getLocation(), diag::note_declared_at); 3641 } 3642 } 3643 } 3644 3645 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3646 // decays into a pointer and returns an unintended result. This is most 3647 // likely a typo for "sizeof(array) op x". 3648 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3649 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3650 BO->getLHS()); 3651 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3652 BO->getRHS()); 3653 } 3654 } 3655 3656 return false; 3657 } 3658 3659 /// \brief Check the constraints on operands to unary expression and type 3660 /// traits. 3661 /// 3662 /// This will complete any types necessary, and validate the various constraints 3663 /// on those operands. 3664 /// 3665 /// The UsualUnaryConversions() function is *not* called by this routine. 3666 /// C99 6.3.2.1p[2-4] all state: 3667 /// Except when it is the operand of the sizeof operator ... 3668 /// 3669 /// C++ [expr.sizeof]p4 3670 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3671 /// standard conversions are not applied to the operand of sizeof. 3672 /// 3673 /// This policy is followed for all of the unary trait expressions. 3674 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3675 SourceLocation OpLoc, 3676 SourceRange ExprRange, 3677 UnaryExprOrTypeTrait ExprKind) { 3678 if (ExprType->isDependentType()) 3679 return false; 3680 3681 // C++ [expr.sizeof]p2: 3682 // When applied to a reference or a reference type, the result 3683 // is the size of the referenced type. 3684 // C++11 [expr.alignof]p3: 3685 // When alignof is applied to a reference type, the result 3686 // shall be the alignment of the referenced type. 3687 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3688 ExprType = Ref->getPointeeType(); 3689 3690 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3691 // When alignof or _Alignof is applied to an array type, the result 3692 // is the alignment of the element type. 3693 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign) 3694 ExprType = Context.getBaseElementType(ExprType); 3695 3696 if (ExprKind == UETT_VecStep) 3697 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3698 3699 // Whitelist some types as extensions 3700 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3701 ExprKind)) 3702 return false; 3703 3704 if (RequireCompleteType(OpLoc, ExprType, 3705 diag::err_sizeof_alignof_incomplete_type, 3706 ExprKind, ExprRange)) 3707 return true; 3708 3709 if (ExprType->isFunctionType()) { 3710 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3711 << ExprKind << ExprRange; 3712 return true; 3713 } 3714 3715 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3716 ExprKind)) 3717 return true; 3718 3719 return false; 3720 } 3721 3722 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3723 E = E->IgnoreParens(); 3724 3725 // Cannot know anything else if the expression is dependent. 3726 if (E->isTypeDependent()) 3727 return false; 3728 3729 if (E->getObjectKind() == OK_BitField) { 3730 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3731 << 1 << E->getSourceRange(); 3732 return true; 3733 } 3734 3735 ValueDecl *D = nullptr; 3736 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3737 D = DRE->getDecl(); 3738 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3739 D = ME->getMemberDecl(); 3740 } 3741 3742 // If it's a field, require the containing struct to have a 3743 // complete definition so that we can compute the layout. 3744 // 3745 // This can happen in C++11 onwards, either by naming the member 3746 // in a way that is not transformed into a member access expression 3747 // (in an unevaluated operand, for instance), or by naming the member 3748 // in a trailing-return-type. 3749 // 3750 // For the record, since __alignof__ on expressions is a GCC 3751 // extension, GCC seems to permit this but always gives the 3752 // nonsensical answer 0. 3753 // 3754 // We don't really need the layout here --- we could instead just 3755 // directly check for all the appropriate alignment-lowing 3756 // attributes --- but that would require duplicating a lot of 3757 // logic that just isn't worth duplicating for such a marginal 3758 // use-case. 3759 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3760 // Fast path this check, since we at least know the record has a 3761 // definition if we can find a member of it. 3762 if (!FD->getParent()->isCompleteDefinition()) { 3763 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3764 << E->getSourceRange(); 3765 return true; 3766 } 3767 3768 // Otherwise, if it's a field, and the field doesn't have 3769 // reference type, then it must have a complete type (or be a 3770 // flexible array member, which we explicitly want to 3771 // white-list anyway), which makes the following checks trivial. 3772 if (!FD->getType()->isReferenceType()) 3773 return false; 3774 } 3775 3776 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3777 } 3778 3779 bool Sema::CheckVecStepExpr(Expr *E) { 3780 E = E->IgnoreParens(); 3781 3782 // Cannot know anything else if the expression is dependent. 3783 if (E->isTypeDependent()) 3784 return false; 3785 3786 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3787 } 3788 3789 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 3790 CapturingScopeInfo *CSI) { 3791 assert(T->isVariablyModifiedType()); 3792 assert(CSI != nullptr); 3793 3794 // We're going to walk down into the type and look for VLA expressions. 3795 do { 3796 const Type *Ty = T.getTypePtr(); 3797 switch (Ty->getTypeClass()) { 3798 #define TYPE(Class, Base) 3799 #define ABSTRACT_TYPE(Class, Base) 3800 #define NON_CANONICAL_TYPE(Class, Base) 3801 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 3802 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 3803 #include "clang/AST/TypeNodes.def" 3804 T = QualType(); 3805 break; 3806 // These types are never variably-modified. 3807 case Type::Builtin: 3808 case Type::Complex: 3809 case Type::Vector: 3810 case Type::ExtVector: 3811 case Type::Record: 3812 case Type::Enum: 3813 case Type::Elaborated: 3814 case Type::TemplateSpecialization: 3815 case Type::ObjCObject: 3816 case Type::ObjCInterface: 3817 case Type::ObjCObjectPointer: 3818 case Type::ObjCTypeParam: 3819 case Type::Pipe: 3820 llvm_unreachable("type class is never variably-modified!"); 3821 case Type::Adjusted: 3822 T = cast<AdjustedType>(Ty)->getOriginalType(); 3823 break; 3824 case Type::Decayed: 3825 T = cast<DecayedType>(Ty)->getPointeeType(); 3826 break; 3827 case Type::Pointer: 3828 T = cast<PointerType>(Ty)->getPointeeType(); 3829 break; 3830 case Type::BlockPointer: 3831 T = cast<BlockPointerType>(Ty)->getPointeeType(); 3832 break; 3833 case Type::LValueReference: 3834 case Type::RValueReference: 3835 T = cast<ReferenceType>(Ty)->getPointeeType(); 3836 break; 3837 case Type::MemberPointer: 3838 T = cast<MemberPointerType>(Ty)->getPointeeType(); 3839 break; 3840 case Type::ConstantArray: 3841 case Type::IncompleteArray: 3842 // Losing element qualification here is fine. 3843 T = cast<ArrayType>(Ty)->getElementType(); 3844 break; 3845 case Type::VariableArray: { 3846 // Losing element qualification here is fine. 3847 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 3848 3849 // Unknown size indication requires no size computation. 3850 // Otherwise, evaluate and record it. 3851 if (auto Size = VAT->getSizeExpr()) { 3852 if (!CSI->isVLATypeCaptured(VAT)) { 3853 RecordDecl *CapRecord = nullptr; 3854 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 3855 CapRecord = LSI->Lambda; 3856 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 3857 CapRecord = CRSI->TheRecordDecl; 3858 } 3859 if (CapRecord) { 3860 auto ExprLoc = Size->getExprLoc(); 3861 auto SizeType = Context.getSizeType(); 3862 // Build the non-static data member. 3863 auto Field = 3864 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc, 3865 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 3866 /*BW*/ nullptr, /*Mutable*/ false, 3867 /*InitStyle*/ ICIS_NoInit); 3868 Field->setImplicit(true); 3869 Field->setAccess(AS_private); 3870 Field->setCapturedVLAType(VAT); 3871 CapRecord->addDecl(Field); 3872 3873 CSI->addVLATypeCapture(ExprLoc, SizeType); 3874 } 3875 } 3876 } 3877 T = VAT->getElementType(); 3878 break; 3879 } 3880 case Type::FunctionProto: 3881 case Type::FunctionNoProto: 3882 T = cast<FunctionType>(Ty)->getReturnType(); 3883 break; 3884 case Type::Paren: 3885 case Type::TypeOf: 3886 case Type::UnaryTransform: 3887 case Type::Attributed: 3888 case Type::SubstTemplateTypeParm: 3889 case Type::PackExpansion: 3890 // Keep walking after single level desugaring. 3891 T = T.getSingleStepDesugaredType(Context); 3892 break; 3893 case Type::Typedef: 3894 T = cast<TypedefType>(Ty)->desugar(); 3895 break; 3896 case Type::Decltype: 3897 T = cast<DecltypeType>(Ty)->desugar(); 3898 break; 3899 case Type::Auto: 3900 case Type::DeducedTemplateSpecialization: 3901 T = cast<DeducedType>(Ty)->getDeducedType(); 3902 break; 3903 case Type::TypeOfExpr: 3904 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 3905 break; 3906 case Type::Atomic: 3907 T = cast<AtomicType>(Ty)->getValueType(); 3908 break; 3909 } 3910 } while (!T.isNull() && T->isVariablyModifiedType()); 3911 } 3912 3913 /// \brief Build a sizeof or alignof expression given a type operand. 3914 ExprResult 3915 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3916 SourceLocation OpLoc, 3917 UnaryExprOrTypeTrait ExprKind, 3918 SourceRange R) { 3919 if (!TInfo) 3920 return ExprError(); 3921 3922 QualType T = TInfo->getType(); 3923 3924 if (!T->isDependentType() && 3925 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3926 return ExprError(); 3927 3928 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 3929 if (auto *TT = T->getAs<TypedefType>()) { 3930 for (auto I = FunctionScopes.rbegin(), 3931 E = std::prev(FunctionScopes.rend()); 3932 I != E; ++I) { 3933 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 3934 if (CSI == nullptr) 3935 break; 3936 DeclContext *DC = nullptr; 3937 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 3938 DC = LSI->CallOperator; 3939 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 3940 DC = CRSI->TheCapturedDecl; 3941 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 3942 DC = BSI->TheDecl; 3943 if (DC) { 3944 if (DC->containsDecl(TT->getDecl())) 3945 break; 3946 captureVariablyModifiedType(Context, T, CSI); 3947 } 3948 } 3949 } 3950 } 3951 3952 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3953 return new (Context) UnaryExprOrTypeTraitExpr( 3954 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 3955 } 3956 3957 /// \brief Build a sizeof or alignof expression given an expression 3958 /// operand. 3959 ExprResult 3960 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 3961 UnaryExprOrTypeTrait ExprKind) { 3962 ExprResult PE = CheckPlaceholderExpr(E); 3963 if (PE.isInvalid()) 3964 return ExprError(); 3965 3966 E = PE.get(); 3967 3968 // Verify that the operand is valid. 3969 bool isInvalid = false; 3970 if (E->isTypeDependent()) { 3971 // Delay type-checking for type-dependent expressions. 3972 } else if (ExprKind == UETT_AlignOf) { 3973 isInvalid = CheckAlignOfExpr(*this, E); 3974 } else if (ExprKind == UETT_VecStep) { 3975 isInvalid = CheckVecStepExpr(E); 3976 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 3977 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 3978 isInvalid = true; 3979 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 3980 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 3981 isInvalid = true; 3982 } else { 3983 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 3984 } 3985 3986 if (isInvalid) 3987 return ExprError(); 3988 3989 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 3990 PE = TransformToPotentiallyEvaluated(E); 3991 if (PE.isInvalid()) return ExprError(); 3992 E = PE.get(); 3993 } 3994 3995 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3996 return new (Context) UnaryExprOrTypeTraitExpr( 3997 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 3998 } 3999 4000 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4001 /// expr and the same for @c alignof and @c __alignof 4002 /// Note that the ArgRange is invalid if isType is false. 4003 ExprResult 4004 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4005 UnaryExprOrTypeTrait ExprKind, bool IsType, 4006 void *TyOrEx, SourceRange ArgRange) { 4007 // If error parsing type, ignore. 4008 if (!TyOrEx) return ExprError(); 4009 4010 if (IsType) { 4011 TypeSourceInfo *TInfo; 4012 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4013 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4014 } 4015 4016 Expr *ArgEx = (Expr *)TyOrEx; 4017 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4018 return Result; 4019 } 4020 4021 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4022 bool IsReal) { 4023 if (V.get()->isTypeDependent()) 4024 return S.Context.DependentTy; 4025 4026 // _Real and _Imag are only l-values for normal l-values. 4027 if (V.get()->getObjectKind() != OK_Ordinary) { 4028 V = S.DefaultLvalueConversion(V.get()); 4029 if (V.isInvalid()) 4030 return QualType(); 4031 } 4032 4033 // These operators return the element type of a complex type. 4034 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4035 return CT->getElementType(); 4036 4037 // Otherwise they pass through real integer and floating point types here. 4038 if (V.get()->getType()->isArithmeticType()) 4039 return V.get()->getType(); 4040 4041 // Test for placeholders. 4042 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4043 if (PR.isInvalid()) return QualType(); 4044 if (PR.get() != V.get()) { 4045 V = PR; 4046 return CheckRealImagOperand(S, V, Loc, IsReal); 4047 } 4048 4049 // Reject anything else. 4050 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4051 << (IsReal ? "__real" : "__imag"); 4052 return QualType(); 4053 } 4054 4055 4056 4057 ExprResult 4058 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4059 tok::TokenKind Kind, Expr *Input) { 4060 UnaryOperatorKind Opc; 4061 switch (Kind) { 4062 default: llvm_unreachable("Unknown unary op!"); 4063 case tok::plusplus: Opc = UO_PostInc; break; 4064 case tok::minusminus: Opc = UO_PostDec; break; 4065 } 4066 4067 // Since this might is a postfix expression, get rid of ParenListExprs. 4068 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4069 if (Result.isInvalid()) return ExprError(); 4070 Input = Result.get(); 4071 4072 return BuildUnaryOp(S, OpLoc, Opc, Input); 4073 } 4074 4075 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 4076 /// 4077 /// \return true on error 4078 static bool checkArithmeticOnObjCPointer(Sema &S, 4079 SourceLocation opLoc, 4080 Expr *op) { 4081 assert(op->getType()->isObjCObjectPointerType()); 4082 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4083 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4084 return false; 4085 4086 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4087 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4088 << op->getSourceRange(); 4089 return true; 4090 } 4091 4092 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4093 auto *BaseNoParens = Base->IgnoreParens(); 4094 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4095 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4096 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4097 } 4098 4099 ExprResult 4100 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4101 Expr *idx, SourceLocation rbLoc) { 4102 if (base && !base->getType().isNull() && 4103 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4104 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4105 /*Length=*/nullptr, rbLoc); 4106 4107 // Since this might be a postfix expression, get rid of ParenListExprs. 4108 if (isa<ParenListExpr>(base)) { 4109 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4110 if (result.isInvalid()) return ExprError(); 4111 base = result.get(); 4112 } 4113 4114 // Handle any non-overload placeholder types in the base and index 4115 // expressions. We can't handle overloads here because the other 4116 // operand might be an overloadable type, in which case the overload 4117 // resolution for the operator overload should get the first crack 4118 // at the overload. 4119 bool IsMSPropertySubscript = false; 4120 if (base->getType()->isNonOverloadPlaceholderType()) { 4121 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4122 if (!IsMSPropertySubscript) { 4123 ExprResult result = CheckPlaceholderExpr(base); 4124 if (result.isInvalid()) 4125 return ExprError(); 4126 base = result.get(); 4127 } 4128 } 4129 if (idx->getType()->isNonOverloadPlaceholderType()) { 4130 ExprResult result = CheckPlaceholderExpr(idx); 4131 if (result.isInvalid()) return ExprError(); 4132 idx = result.get(); 4133 } 4134 4135 // Build an unanalyzed expression if either operand is type-dependent. 4136 if (getLangOpts().CPlusPlus && 4137 (base->isTypeDependent() || idx->isTypeDependent())) { 4138 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4139 VK_LValue, OK_Ordinary, rbLoc); 4140 } 4141 4142 // MSDN, property (C++) 4143 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4144 // This attribute can also be used in the declaration of an empty array in a 4145 // class or structure definition. For example: 4146 // __declspec(property(get=GetX, put=PutX)) int x[]; 4147 // The above statement indicates that x[] can be used with one or more array 4148 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4149 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4150 if (IsMSPropertySubscript) { 4151 // Build MS property subscript expression if base is MS property reference 4152 // or MS property subscript. 4153 return new (Context) MSPropertySubscriptExpr( 4154 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4155 } 4156 4157 // Use C++ overloaded-operator rules if either operand has record 4158 // type. The spec says to do this if either type is *overloadable*, 4159 // but enum types can't declare subscript operators or conversion 4160 // operators, so there's nothing interesting for overload resolution 4161 // to do if there aren't any record types involved. 4162 // 4163 // ObjC pointers have their own subscripting logic that is not tied 4164 // to overload resolution and so should not take this path. 4165 if (getLangOpts().CPlusPlus && 4166 (base->getType()->isRecordType() || 4167 (!base->getType()->isObjCObjectPointerType() && 4168 idx->getType()->isRecordType()))) { 4169 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4170 } 4171 4172 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4173 } 4174 4175 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4176 Expr *LowerBound, 4177 SourceLocation ColonLoc, Expr *Length, 4178 SourceLocation RBLoc) { 4179 if (Base->getType()->isPlaceholderType() && 4180 !Base->getType()->isSpecificPlaceholderType( 4181 BuiltinType::OMPArraySection)) { 4182 ExprResult Result = CheckPlaceholderExpr(Base); 4183 if (Result.isInvalid()) 4184 return ExprError(); 4185 Base = Result.get(); 4186 } 4187 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4188 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4189 if (Result.isInvalid()) 4190 return ExprError(); 4191 Result = DefaultLvalueConversion(Result.get()); 4192 if (Result.isInvalid()) 4193 return ExprError(); 4194 LowerBound = Result.get(); 4195 } 4196 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4197 ExprResult Result = CheckPlaceholderExpr(Length); 4198 if (Result.isInvalid()) 4199 return ExprError(); 4200 Result = DefaultLvalueConversion(Result.get()); 4201 if (Result.isInvalid()) 4202 return ExprError(); 4203 Length = Result.get(); 4204 } 4205 4206 // Build an unanalyzed expression if either operand is type-dependent. 4207 if (Base->isTypeDependent() || 4208 (LowerBound && 4209 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4210 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4211 return new (Context) 4212 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4213 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4214 } 4215 4216 // Perform default conversions. 4217 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4218 QualType ResultTy; 4219 if (OriginalTy->isAnyPointerType()) { 4220 ResultTy = OriginalTy->getPointeeType(); 4221 } else if (OriginalTy->isArrayType()) { 4222 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4223 } else { 4224 return ExprError( 4225 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4226 << Base->getSourceRange()); 4227 } 4228 // C99 6.5.2.1p1 4229 if (LowerBound) { 4230 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4231 LowerBound); 4232 if (Res.isInvalid()) 4233 return ExprError(Diag(LowerBound->getExprLoc(), 4234 diag::err_omp_typecheck_section_not_integer) 4235 << 0 << LowerBound->getSourceRange()); 4236 LowerBound = Res.get(); 4237 4238 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4239 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4240 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4241 << 0 << LowerBound->getSourceRange(); 4242 } 4243 if (Length) { 4244 auto Res = 4245 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4246 if (Res.isInvalid()) 4247 return ExprError(Diag(Length->getExprLoc(), 4248 diag::err_omp_typecheck_section_not_integer) 4249 << 1 << Length->getSourceRange()); 4250 Length = Res.get(); 4251 4252 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4253 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4254 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4255 << 1 << Length->getSourceRange(); 4256 } 4257 4258 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4259 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4260 // type. Note that functions are not objects, and that (in C99 parlance) 4261 // incomplete types are not object types. 4262 if (ResultTy->isFunctionType()) { 4263 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4264 << ResultTy << Base->getSourceRange(); 4265 return ExprError(); 4266 } 4267 4268 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4269 diag::err_omp_section_incomplete_type, Base)) 4270 return ExprError(); 4271 4272 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4273 llvm::APSInt LowerBoundValue; 4274 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) { 4275 // OpenMP 4.5, [2.4 Array Sections] 4276 // The array section must be a subset of the original array. 4277 if (LowerBoundValue.isNegative()) { 4278 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4279 << LowerBound->getSourceRange(); 4280 return ExprError(); 4281 } 4282 } 4283 } 4284 4285 if (Length) { 4286 llvm::APSInt LengthValue; 4287 if (Length->EvaluateAsInt(LengthValue, Context)) { 4288 // OpenMP 4.5, [2.4 Array Sections] 4289 // The length must evaluate to non-negative integers. 4290 if (LengthValue.isNegative()) { 4291 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4292 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4293 << Length->getSourceRange(); 4294 return ExprError(); 4295 } 4296 } 4297 } else if (ColonLoc.isValid() && 4298 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4299 !OriginalTy->isVariableArrayType()))) { 4300 // OpenMP 4.5, [2.4 Array Sections] 4301 // When the size of the array dimension is not known, the length must be 4302 // specified explicitly. 4303 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4304 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4305 return ExprError(); 4306 } 4307 4308 if (!Base->getType()->isSpecificPlaceholderType( 4309 BuiltinType::OMPArraySection)) { 4310 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4311 if (Result.isInvalid()) 4312 return ExprError(); 4313 Base = Result.get(); 4314 } 4315 return new (Context) 4316 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4317 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4318 } 4319 4320 ExprResult 4321 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4322 Expr *Idx, SourceLocation RLoc) { 4323 Expr *LHSExp = Base; 4324 Expr *RHSExp = Idx; 4325 4326 ExprValueKind VK = VK_LValue; 4327 ExprObjectKind OK = OK_Ordinary; 4328 4329 // Per C++ core issue 1213, the result is an xvalue if either operand is 4330 // a non-lvalue array, and an lvalue otherwise. 4331 if (getLangOpts().CPlusPlus11 && 4332 ((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) || 4333 (RHSExp->getType()->isArrayType() && !RHSExp->isLValue()))) 4334 VK = VK_XValue; 4335 4336 // Perform default conversions. 4337 if (!LHSExp->getType()->getAs<VectorType>()) { 4338 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4339 if (Result.isInvalid()) 4340 return ExprError(); 4341 LHSExp = Result.get(); 4342 } 4343 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4344 if (Result.isInvalid()) 4345 return ExprError(); 4346 RHSExp = Result.get(); 4347 4348 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4349 4350 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4351 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4352 // in the subscript position. As a result, we need to derive the array base 4353 // and index from the expression types. 4354 Expr *BaseExpr, *IndexExpr; 4355 QualType ResultType; 4356 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4357 BaseExpr = LHSExp; 4358 IndexExpr = RHSExp; 4359 ResultType = Context.DependentTy; 4360 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4361 BaseExpr = LHSExp; 4362 IndexExpr = RHSExp; 4363 ResultType = PTy->getPointeeType(); 4364 } else if (const ObjCObjectPointerType *PTy = 4365 LHSTy->getAs<ObjCObjectPointerType>()) { 4366 BaseExpr = LHSExp; 4367 IndexExpr = RHSExp; 4368 4369 // Use custom logic if this should be the pseudo-object subscript 4370 // expression. 4371 if (!LangOpts.isSubscriptPointerArithmetic()) 4372 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4373 nullptr); 4374 4375 ResultType = PTy->getPointeeType(); 4376 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4377 // Handle the uncommon case of "123[Ptr]". 4378 BaseExpr = RHSExp; 4379 IndexExpr = LHSExp; 4380 ResultType = PTy->getPointeeType(); 4381 } else if (const ObjCObjectPointerType *PTy = 4382 RHSTy->getAs<ObjCObjectPointerType>()) { 4383 // Handle the uncommon case of "123[Ptr]". 4384 BaseExpr = RHSExp; 4385 IndexExpr = LHSExp; 4386 ResultType = PTy->getPointeeType(); 4387 if (!LangOpts.isSubscriptPointerArithmetic()) { 4388 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4389 << ResultType << BaseExpr->getSourceRange(); 4390 return ExprError(); 4391 } 4392 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4393 BaseExpr = LHSExp; // vectors: V[123] 4394 IndexExpr = RHSExp; 4395 VK = LHSExp->getValueKind(); 4396 if (VK != VK_RValue) 4397 OK = OK_VectorComponent; 4398 4399 // FIXME: need to deal with const... 4400 ResultType = VTy->getElementType(); 4401 } else if (LHSTy->isArrayType()) { 4402 // If we see an array that wasn't promoted by 4403 // DefaultFunctionArrayLvalueConversion, it must be an array that 4404 // wasn't promoted because of the C90 rule that doesn't 4405 // allow promoting non-lvalue arrays. Warn, then 4406 // force the promotion here. 4407 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4408 LHSExp->getSourceRange(); 4409 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4410 CK_ArrayToPointerDecay).get(); 4411 LHSTy = LHSExp->getType(); 4412 4413 BaseExpr = LHSExp; 4414 IndexExpr = RHSExp; 4415 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4416 } else if (RHSTy->isArrayType()) { 4417 // Same as previous, except for 123[f().a] case 4418 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4419 RHSExp->getSourceRange(); 4420 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4421 CK_ArrayToPointerDecay).get(); 4422 RHSTy = RHSExp->getType(); 4423 4424 BaseExpr = RHSExp; 4425 IndexExpr = LHSExp; 4426 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4427 } else { 4428 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4429 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4430 } 4431 // C99 6.5.2.1p1 4432 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4433 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4434 << IndexExpr->getSourceRange()); 4435 4436 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4437 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4438 && !IndexExpr->isTypeDependent()) 4439 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4440 4441 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4442 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4443 // type. Note that Functions are not objects, and that (in C99 parlance) 4444 // incomplete types are not object types. 4445 if (ResultType->isFunctionType()) { 4446 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 4447 << ResultType << BaseExpr->getSourceRange(); 4448 return ExprError(); 4449 } 4450 4451 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4452 // GNU extension: subscripting on pointer to void 4453 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4454 << BaseExpr->getSourceRange(); 4455 4456 // C forbids expressions of unqualified void type from being l-values. 4457 // See IsCForbiddenLValueType. 4458 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4459 } else if (!ResultType->isDependentType() && 4460 RequireCompleteType(LLoc, ResultType, 4461 diag::err_subscript_incomplete_type, BaseExpr)) 4462 return ExprError(); 4463 4464 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4465 !ResultType.isCForbiddenLValueType()); 4466 4467 return new (Context) 4468 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4469 } 4470 4471 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 4472 ParmVarDecl *Param) { 4473 if (Param->hasUnparsedDefaultArg()) { 4474 Diag(CallLoc, 4475 diag::err_use_of_default_argument_to_function_declared_later) << 4476 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4477 Diag(UnparsedDefaultArgLocs[Param], 4478 diag::note_default_argument_declared_here); 4479 return true; 4480 } 4481 4482 if (Param->hasUninstantiatedDefaultArg()) { 4483 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4484 4485 EnterExpressionEvaluationContext EvalContext( 4486 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 4487 4488 // Instantiate the expression. 4489 // 4490 // FIXME: Pass in a correct Pattern argument, otherwise 4491 // getTemplateInstantiationArgs uses the lexical context of FD, e.g. 4492 // 4493 // template<typename T> 4494 // struct A { 4495 // static int FooImpl(); 4496 // 4497 // template<typename Tp> 4498 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level 4499 // // template argument list [[T], [Tp]], should be [[Tp]]. 4500 // friend A<Tp> Foo(int a); 4501 // }; 4502 // 4503 // template<typename T> 4504 // A<T> Foo(int a = A<T>::FooImpl()); 4505 MultiLevelTemplateArgumentList MutiLevelArgList 4506 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4507 4508 InstantiatingTemplate Inst(*this, CallLoc, Param, 4509 MutiLevelArgList.getInnermost()); 4510 if (Inst.isInvalid()) 4511 return true; 4512 if (Inst.isAlreadyInstantiating()) { 4513 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4514 Param->setInvalidDecl(); 4515 return true; 4516 } 4517 4518 ExprResult Result; 4519 { 4520 // C++ [dcl.fct.default]p5: 4521 // The names in the [default argument] expression are bound, and 4522 // the semantic constraints are checked, at the point where the 4523 // default argument expression appears. 4524 ContextRAII SavedContext(*this, FD); 4525 LocalInstantiationScope Local(*this); 4526 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 4527 /*DirectInit*/false); 4528 } 4529 if (Result.isInvalid()) 4530 return true; 4531 4532 // Check the expression as an initializer for the parameter. 4533 InitializedEntity Entity 4534 = InitializedEntity::InitializeParameter(Context, Param); 4535 InitializationKind Kind 4536 = InitializationKind::CreateCopy(Param->getLocation(), 4537 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 4538 Expr *ResultE = Result.getAs<Expr>(); 4539 4540 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4541 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4542 if (Result.isInvalid()) 4543 return true; 4544 4545 Result = ActOnFinishFullExpr(Result.getAs<Expr>(), 4546 Param->getOuterLocStart()); 4547 if (Result.isInvalid()) 4548 return true; 4549 4550 // Remember the instantiated default argument. 4551 Param->setDefaultArg(Result.getAs<Expr>()); 4552 if (ASTMutationListener *L = getASTMutationListener()) { 4553 L->DefaultArgumentInstantiated(Param); 4554 } 4555 } 4556 4557 // If the default argument expression is not set yet, we are building it now. 4558 if (!Param->hasInit()) { 4559 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4560 Param->setInvalidDecl(); 4561 return true; 4562 } 4563 4564 // If the default expression creates temporaries, we need to 4565 // push them to the current stack of expression temporaries so they'll 4566 // be properly destroyed. 4567 // FIXME: We should really be rebuilding the default argument with new 4568 // bound temporaries; see the comment in PR5810. 4569 // We don't need to do that with block decls, though, because 4570 // blocks in default argument expression can never capture anything. 4571 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 4572 // Set the "needs cleanups" bit regardless of whether there are 4573 // any explicit objects. 4574 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 4575 4576 // Append all the objects to the cleanup list. Right now, this 4577 // should always be a no-op, because blocks in default argument 4578 // expressions should never be able to capture anything. 4579 assert(!Init->getNumObjects() && 4580 "default argument expression has capturing blocks?"); 4581 } 4582 4583 // We already type-checked the argument, so we know it works. 4584 // Just mark all of the declarations in this potentially-evaluated expression 4585 // as being "referenced". 4586 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4587 /*SkipLocalVariables=*/true); 4588 return false; 4589 } 4590 4591 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4592 FunctionDecl *FD, ParmVarDecl *Param) { 4593 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 4594 return ExprError(); 4595 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4596 } 4597 4598 Sema::VariadicCallType 4599 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4600 Expr *Fn) { 4601 if (Proto && Proto->isVariadic()) { 4602 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4603 return VariadicConstructor; 4604 else if (Fn && Fn->getType()->isBlockPointerType()) 4605 return VariadicBlock; 4606 else if (FDecl) { 4607 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4608 if (Method->isInstance()) 4609 return VariadicMethod; 4610 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4611 return VariadicMethod; 4612 return VariadicFunction; 4613 } 4614 return VariadicDoesNotApply; 4615 } 4616 4617 namespace { 4618 class FunctionCallCCC : public FunctionCallFilterCCC { 4619 public: 4620 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4621 unsigned NumArgs, MemberExpr *ME) 4622 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4623 FunctionName(FuncName) {} 4624 4625 bool ValidateCandidate(const TypoCorrection &candidate) override { 4626 if (!candidate.getCorrectionSpecifier() || 4627 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4628 return false; 4629 } 4630 4631 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4632 } 4633 4634 private: 4635 const IdentifierInfo *const FunctionName; 4636 }; 4637 } 4638 4639 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4640 FunctionDecl *FDecl, 4641 ArrayRef<Expr *> Args) { 4642 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4643 DeclarationName FuncName = FDecl->getDeclName(); 4644 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart(); 4645 4646 if (TypoCorrection Corrected = S.CorrectTypo( 4647 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4648 S.getScopeForContext(S.CurContext), nullptr, 4649 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4650 Args.size(), ME), 4651 Sema::CTK_ErrorRecovery)) { 4652 if (NamedDecl *ND = Corrected.getFoundDecl()) { 4653 if (Corrected.isOverloaded()) { 4654 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4655 OverloadCandidateSet::iterator Best; 4656 for (NamedDecl *CD : Corrected) { 4657 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 4658 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4659 OCS); 4660 } 4661 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4662 case OR_Success: 4663 ND = Best->FoundDecl; 4664 Corrected.setCorrectionDecl(ND); 4665 break; 4666 default: 4667 break; 4668 } 4669 } 4670 ND = ND->getUnderlyingDecl(); 4671 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 4672 return Corrected; 4673 } 4674 } 4675 return TypoCorrection(); 4676 } 4677 4678 /// ConvertArgumentsForCall - Converts the arguments specified in 4679 /// Args/NumArgs to the parameter types of the function FDecl with 4680 /// function prototype Proto. Call is the call expression itself, and 4681 /// Fn is the function expression. For a C++ member function, this 4682 /// routine does not attempt to convert the object argument. Returns 4683 /// true if the call is ill-formed. 4684 bool 4685 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4686 FunctionDecl *FDecl, 4687 const FunctionProtoType *Proto, 4688 ArrayRef<Expr *> Args, 4689 SourceLocation RParenLoc, 4690 bool IsExecConfig) { 4691 // Bail out early if calling a builtin with custom typechecking. 4692 if (FDecl) 4693 if (unsigned ID = FDecl->getBuiltinID()) 4694 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4695 return false; 4696 4697 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4698 // assignment, to the types of the corresponding parameter, ... 4699 unsigned NumParams = Proto->getNumParams(); 4700 bool Invalid = false; 4701 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4702 unsigned FnKind = Fn->getType()->isBlockPointerType() 4703 ? 1 /* block */ 4704 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4705 : 0 /* function */); 4706 4707 // If too few arguments are available (and we don't have default 4708 // arguments for the remaining parameters), don't make the call. 4709 if (Args.size() < NumParams) { 4710 if (Args.size() < MinArgs) { 4711 TypoCorrection TC; 4712 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4713 unsigned diag_id = 4714 MinArgs == NumParams && !Proto->isVariadic() 4715 ? diag::err_typecheck_call_too_few_args_suggest 4716 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4717 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4718 << static_cast<unsigned>(Args.size()) 4719 << TC.getCorrectionRange()); 4720 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4721 Diag(RParenLoc, 4722 MinArgs == NumParams && !Proto->isVariadic() 4723 ? diag::err_typecheck_call_too_few_args_one 4724 : diag::err_typecheck_call_too_few_args_at_least_one) 4725 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4726 else 4727 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4728 ? diag::err_typecheck_call_too_few_args 4729 : diag::err_typecheck_call_too_few_args_at_least) 4730 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4731 << Fn->getSourceRange(); 4732 4733 // Emit the location of the prototype. 4734 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4735 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4736 << FDecl; 4737 4738 return true; 4739 } 4740 Call->setNumArgs(Context, NumParams); 4741 } 4742 4743 // If too many are passed and not variadic, error on the extras and drop 4744 // them. 4745 if (Args.size() > NumParams) { 4746 if (!Proto->isVariadic()) { 4747 TypoCorrection TC; 4748 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4749 unsigned diag_id = 4750 MinArgs == NumParams && !Proto->isVariadic() 4751 ? diag::err_typecheck_call_too_many_args_suggest 4752 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4753 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4754 << static_cast<unsigned>(Args.size()) 4755 << TC.getCorrectionRange()); 4756 } else if (NumParams == 1 && FDecl && 4757 FDecl->getParamDecl(0)->getDeclName()) 4758 Diag(Args[NumParams]->getLocStart(), 4759 MinArgs == NumParams 4760 ? diag::err_typecheck_call_too_many_args_one 4761 : diag::err_typecheck_call_too_many_args_at_most_one) 4762 << FnKind << FDecl->getParamDecl(0) 4763 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4764 << SourceRange(Args[NumParams]->getLocStart(), 4765 Args.back()->getLocEnd()); 4766 else 4767 Diag(Args[NumParams]->getLocStart(), 4768 MinArgs == NumParams 4769 ? diag::err_typecheck_call_too_many_args 4770 : diag::err_typecheck_call_too_many_args_at_most) 4771 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4772 << Fn->getSourceRange() 4773 << SourceRange(Args[NumParams]->getLocStart(), 4774 Args.back()->getLocEnd()); 4775 4776 // Emit the location of the prototype. 4777 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4778 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4779 << FDecl; 4780 4781 // This deletes the extra arguments. 4782 Call->setNumArgs(Context, NumParams); 4783 return true; 4784 } 4785 } 4786 SmallVector<Expr *, 8> AllArgs; 4787 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4788 4789 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4790 Proto, 0, Args, AllArgs, CallType); 4791 if (Invalid) 4792 return true; 4793 unsigned TotalNumArgs = AllArgs.size(); 4794 for (unsigned i = 0; i < TotalNumArgs; ++i) 4795 Call->setArg(i, AllArgs[i]); 4796 4797 return false; 4798 } 4799 4800 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4801 const FunctionProtoType *Proto, 4802 unsigned FirstParam, ArrayRef<Expr *> Args, 4803 SmallVectorImpl<Expr *> &AllArgs, 4804 VariadicCallType CallType, bool AllowExplicit, 4805 bool IsListInitialization) { 4806 unsigned NumParams = Proto->getNumParams(); 4807 bool Invalid = false; 4808 size_t ArgIx = 0; 4809 // Continue to check argument types (even if we have too few/many args). 4810 for (unsigned i = FirstParam; i < NumParams; i++) { 4811 QualType ProtoArgType = Proto->getParamType(i); 4812 4813 Expr *Arg; 4814 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4815 if (ArgIx < Args.size()) { 4816 Arg = Args[ArgIx++]; 4817 4818 if (RequireCompleteType(Arg->getLocStart(), 4819 ProtoArgType, 4820 diag::err_call_incomplete_argument, Arg)) 4821 return true; 4822 4823 // Strip the unbridged-cast placeholder expression off, if applicable. 4824 bool CFAudited = false; 4825 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4826 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4827 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4828 Arg = stripARCUnbridgedCast(Arg); 4829 else if (getLangOpts().ObjCAutoRefCount && 4830 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4831 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4832 CFAudited = true; 4833 4834 InitializedEntity Entity = 4835 Param ? InitializedEntity::InitializeParameter(Context, Param, 4836 ProtoArgType) 4837 : InitializedEntity::InitializeParameter( 4838 Context, ProtoArgType, Proto->isParamConsumed(i)); 4839 4840 // Remember that parameter belongs to a CF audited API. 4841 if (CFAudited) 4842 Entity.setParameterCFAudited(); 4843 4844 ExprResult ArgE = PerformCopyInitialization( 4845 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 4846 if (ArgE.isInvalid()) 4847 return true; 4848 4849 Arg = ArgE.getAs<Expr>(); 4850 } else { 4851 assert(Param && "can't use default arguments without a known callee"); 4852 4853 ExprResult ArgExpr = 4854 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4855 if (ArgExpr.isInvalid()) 4856 return true; 4857 4858 Arg = ArgExpr.getAs<Expr>(); 4859 } 4860 4861 // Check for array bounds violations for each argument to the call. This 4862 // check only triggers warnings when the argument isn't a more complex Expr 4863 // with its own checking, such as a BinaryOperator. 4864 CheckArrayAccess(Arg); 4865 4866 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4867 CheckStaticArrayArgument(CallLoc, Param, Arg); 4868 4869 AllArgs.push_back(Arg); 4870 } 4871 4872 // If this is a variadic call, handle args passed through "...". 4873 if (CallType != VariadicDoesNotApply) { 4874 // Assume that extern "C" functions with variadic arguments that 4875 // return __unknown_anytype aren't *really* variadic. 4876 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4877 FDecl->isExternC()) { 4878 for (Expr *A : Args.slice(ArgIx)) { 4879 QualType paramType; // ignored 4880 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 4881 Invalid |= arg.isInvalid(); 4882 AllArgs.push_back(arg.get()); 4883 } 4884 4885 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4886 } else { 4887 for (Expr *A : Args.slice(ArgIx)) { 4888 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 4889 Invalid |= Arg.isInvalid(); 4890 AllArgs.push_back(Arg.get()); 4891 } 4892 } 4893 4894 // Check for array bounds violations. 4895 for (Expr *A : Args.slice(ArgIx)) 4896 CheckArrayAccess(A); 4897 } 4898 return Invalid; 4899 } 4900 4901 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4902 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4903 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4904 TL = DTL.getOriginalLoc(); 4905 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4906 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4907 << ATL.getLocalSourceRange(); 4908 } 4909 4910 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4911 /// array parameter, check that it is non-null, and that if it is formed by 4912 /// array-to-pointer decay, the underlying array is sufficiently large. 4913 /// 4914 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4915 /// array type derivation, then for each call to the function, the value of the 4916 /// corresponding actual argument shall provide access to the first element of 4917 /// an array with at least as many elements as specified by the size expression. 4918 void 4919 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4920 ParmVarDecl *Param, 4921 const Expr *ArgExpr) { 4922 // Static array parameters are not supported in C++. 4923 if (!Param || getLangOpts().CPlusPlus) 4924 return; 4925 4926 QualType OrigTy = Param->getOriginalType(); 4927 4928 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4929 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4930 return; 4931 4932 if (ArgExpr->isNullPointerConstant(Context, 4933 Expr::NPC_NeverValueDependent)) { 4934 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4935 DiagnoseCalleeStaticArrayParam(*this, Param); 4936 return; 4937 } 4938 4939 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 4940 if (!CAT) 4941 return; 4942 4943 const ConstantArrayType *ArgCAT = 4944 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 4945 if (!ArgCAT) 4946 return; 4947 4948 if (ArgCAT->getSize().ult(CAT->getSize())) { 4949 Diag(CallLoc, diag::warn_static_array_too_small) 4950 << ArgExpr->getSourceRange() 4951 << (unsigned) ArgCAT->getSize().getZExtValue() 4952 << (unsigned) CAT->getSize().getZExtValue(); 4953 DiagnoseCalleeStaticArrayParam(*this, Param); 4954 } 4955 } 4956 4957 /// Given a function expression of unknown-any type, try to rebuild it 4958 /// to have a function type. 4959 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 4960 4961 /// Is the given type a placeholder that we need to lower out 4962 /// immediately during argument processing? 4963 static bool isPlaceholderToRemoveAsArg(QualType type) { 4964 // Placeholders are never sugared. 4965 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 4966 if (!placeholder) return false; 4967 4968 switch (placeholder->getKind()) { 4969 // Ignore all the non-placeholder types. 4970 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 4971 case BuiltinType::Id: 4972 #include "clang/Basic/OpenCLImageTypes.def" 4973 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 4974 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 4975 #include "clang/AST/BuiltinTypes.def" 4976 return false; 4977 4978 // We cannot lower out overload sets; they might validly be resolved 4979 // by the call machinery. 4980 case BuiltinType::Overload: 4981 return false; 4982 4983 // Unbridged casts in ARC can be handled in some call positions and 4984 // should be left in place. 4985 case BuiltinType::ARCUnbridgedCast: 4986 return false; 4987 4988 // Pseudo-objects should be converted as soon as possible. 4989 case BuiltinType::PseudoObject: 4990 return true; 4991 4992 // The debugger mode could theoretically but currently does not try 4993 // to resolve unknown-typed arguments based on known parameter types. 4994 case BuiltinType::UnknownAny: 4995 return true; 4996 4997 // These are always invalid as call arguments and should be reported. 4998 case BuiltinType::BoundMember: 4999 case BuiltinType::BuiltinFn: 5000 case BuiltinType::OMPArraySection: 5001 return true; 5002 5003 } 5004 llvm_unreachable("bad builtin type kind"); 5005 } 5006 5007 /// Check an argument list for placeholders that we won't try to 5008 /// handle later. 5009 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5010 // Apply this processing to all the arguments at once instead of 5011 // dying at the first failure. 5012 bool hasInvalid = false; 5013 for (size_t i = 0, e = args.size(); i != e; i++) { 5014 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5015 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5016 if (result.isInvalid()) hasInvalid = true; 5017 else args[i] = result.get(); 5018 } else if (hasInvalid) { 5019 (void)S.CorrectDelayedTyposInExpr(args[i]); 5020 } 5021 } 5022 return hasInvalid; 5023 } 5024 5025 /// If a builtin function has a pointer argument with no explicit address 5026 /// space, then it should be able to accept a pointer to any address 5027 /// space as input. In order to do this, we need to replace the 5028 /// standard builtin declaration with one that uses the same address space 5029 /// as the call. 5030 /// 5031 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5032 /// it does not contain any pointer arguments without 5033 /// an address space qualifer. Otherwise the rewritten 5034 /// FunctionDecl is returned. 5035 /// TODO: Handle pointer return types. 5036 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5037 const FunctionDecl *FDecl, 5038 MultiExprArg ArgExprs) { 5039 5040 QualType DeclType = FDecl->getType(); 5041 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5042 5043 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 5044 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 5045 return nullptr; 5046 5047 bool NeedsNewDecl = false; 5048 unsigned i = 0; 5049 SmallVector<QualType, 8> OverloadParams; 5050 5051 for (QualType ParamType : FT->param_types()) { 5052 5053 // Convert array arguments to pointer to simplify type lookup. 5054 ExprResult ArgRes = 5055 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5056 if (ArgRes.isInvalid()) 5057 return nullptr; 5058 Expr *Arg = ArgRes.get(); 5059 QualType ArgType = Arg->getType(); 5060 if (!ParamType->isPointerType() || 5061 ParamType.getQualifiers().hasAddressSpace() || 5062 !ArgType->isPointerType() || 5063 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 5064 OverloadParams.push_back(ParamType); 5065 continue; 5066 } 5067 5068 NeedsNewDecl = true; 5069 unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace(); 5070 5071 QualType PointeeType = ParamType->getPointeeType(); 5072 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5073 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5074 } 5075 5076 if (!NeedsNewDecl) 5077 return nullptr; 5078 5079 FunctionProtoType::ExtProtoInfo EPI; 5080 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5081 OverloadParams, EPI); 5082 DeclContext *Parent = Context.getTranslationUnitDecl(); 5083 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5084 FDecl->getLocation(), 5085 FDecl->getLocation(), 5086 FDecl->getIdentifier(), 5087 OverloadTy, 5088 /*TInfo=*/nullptr, 5089 SC_Extern, false, 5090 /*hasPrototype=*/true); 5091 SmallVector<ParmVarDecl*, 16> Params; 5092 FT = cast<FunctionProtoType>(OverloadTy); 5093 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5094 QualType ParamType = FT->getParamType(i); 5095 ParmVarDecl *Parm = 5096 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5097 SourceLocation(), nullptr, ParamType, 5098 /*TInfo=*/nullptr, SC_None, nullptr); 5099 Parm->setScopeInfo(0, i); 5100 Params.push_back(Parm); 5101 } 5102 OverloadDecl->setParams(Params); 5103 return OverloadDecl; 5104 } 5105 5106 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 5107 FunctionDecl *Callee, 5108 MultiExprArg ArgExprs) { 5109 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 5110 // similar attributes) really don't like it when functions are called with an 5111 // invalid number of args. 5112 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 5113 /*PartialOverloading=*/false) && 5114 !Callee->isVariadic()) 5115 return; 5116 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 5117 return; 5118 5119 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) { 5120 S.Diag(Fn->getLocStart(), 5121 isa<CXXMethodDecl>(Callee) 5122 ? diag::err_ovl_no_viable_member_function_in_call 5123 : diag::err_ovl_no_viable_function_in_call) 5124 << Callee << Callee->getSourceRange(); 5125 S.Diag(Callee->getLocation(), 5126 diag::note_ovl_candidate_disabled_by_function_cond_attr) 5127 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5128 return; 5129 } 5130 } 5131 5132 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 5133 /// This provides the location of the left/right parens and a list of comma 5134 /// locations. 5135 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5136 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5137 Expr *ExecConfig, bool IsExecConfig) { 5138 // Since this might be a postfix expression, get rid of ParenListExprs. 5139 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 5140 if (Result.isInvalid()) return ExprError(); 5141 Fn = Result.get(); 5142 5143 if (checkArgsForPlaceholders(*this, ArgExprs)) 5144 return ExprError(); 5145 5146 if (getLangOpts().CPlusPlus) { 5147 // If this is a pseudo-destructor expression, build the call immediately. 5148 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5149 if (!ArgExprs.empty()) { 5150 // Pseudo-destructor calls should not have any arguments. 5151 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 5152 << FixItHint::CreateRemoval( 5153 SourceRange(ArgExprs.front()->getLocStart(), 5154 ArgExprs.back()->getLocEnd())); 5155 } 5156 5157 return new (Context) 5158 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc); 5159 } 5160 if (Fn->getType() == Context.PseudoObjectTy) { 5161 ExprResult result = CheckPlaceholderExpr(Fn); 5162 if (result.isInvalid()) return ExprError(); 5163 Fn = result.get(); 5164 } 5165 5166 // Determine whether this is a dependent call inside a C++ template, 5167 // in which case we won't do any semantic analysis now. 5168 bool Dependent = false; 5169 if (Fn->isTypeDependent()) 5170 Dependent = true; 5171 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5172 Dependent = true; 5173 5174 if (Dependent) { 5175 if (ExecConfig) { 5176 return new (Context) CUDAKernelCallExpr( 5177 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5178 Context.DependentTy, VK_RValue, RParenLoc); 5179 } else { 5180 return new (Context) CallExpr( 5181 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5182 } 5183 } 5184 5185 // Determine whether this is a call to an object (C++ [over.call.object]). 5186 if (Fn->getType()->isRecordType()) 5187 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 5188 RParenLoc); 5189 5190 if (Fn->getType() == Context.UnknownAnyTy) { 5191 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5192 if (result.isInvalid()) return ExprError(); 5193 Fn = result.get(); 5194 } 5195 5196 if (Fn->getType() == Context.BoundMemberTy) { 5197 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5198 RParenLoc); 5199 } 5200 } 5201 5202 // Check for overloaded calls. This can happen even in C due to extensions. 5203 if (Fn->getType() == Context.OverloadTy) { 5204 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5205 5206 // We aren't supposed to apply this logic if there's an '&' involved. 5207 if (!find.HasFormOfMemberPointer) { 5208 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5209 return new (Context) CallExpr( 5210 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5211 OverloadExpr *ovl = find.Expression; 5212 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5213 return BuildOverloadedCallExpr( 5214 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 5215 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 5216 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5217 RParenLoc); 5218 } 5219 } 5220 5221 // If we're directly calling a function, get the appropriate declaration. 5222 if (Fn->getType() == Context.UnknownAnyTy) { 5223 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5224 if (result.isInvalid()) return ExprError(); 5225 Fn = result.get(); 5226 } 5227 5228 Expr *NakedFn = Fn->IgnoreParens(); 5229 5230 bool CallingNDeclIndirectly = false; 5231 NamedDecl *NDecl = nullptr; 5232 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5233 if (UnOp->getOpcode() == UO_AddrOf) { 5234 CallingNDeclIndirectly = true; 5235 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5236 } 5237 } 5238 5239 if (isa<DeclRefExpr>(NakedFn)) { 5240 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 5241 5242 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5243 if (FDecl && FDecl->getBuiltinID()) { 5244 // Rewrite the function decl for this builtin by replacing parameters 5245 // with no explicit address space with the address space of the arguments 5246 // in ArgExprs. 5247 if ((FDecl = 5248 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5249 NDecl = FDecl; 5250 Fn = DeclRefExpr::Create( 5251 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 5252 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl); 5253 } 5254 } 5255 } else if (isa<MemberExpr>(NakedFn)) 5256 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5257 5258 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5259 if (CallingNDeclIndirectly && 5260 !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 5261 Fn->getLocStart())) 5262 return ExprError(); 5263 5264 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 5265 return ExprError(); 5266 5267 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 5268 } 5269 5270 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5271 ExecConfig, IsExecConfig); 5272 } 5273 5274 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5275 /// 5276 /// __builtin_astype( value, dst type ) 5277 /// 5278 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5279 SourceLocation BuiltinLoc, 5280 SourceLocation RParenLoc) { 5281 ExprValueKind VK = VK_RValue; 5282 ExprObjectKind OK = OK_Ordinary; 5283 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5284 QualType SrcTy = E->getType(); 5285 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5286 return ExprError(Diag(BuiltinLoc, 5287 diag::err_invalid_astype_of_different_size) 5288 << DstTy 5289 << SrcTy 5290 << E->getSourceRange()); 5291 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5292 } 5293 5294 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5295 /// provided arguments. 5296 /// 5297 /// __builtin_convertvector( value, dst type ) 5298 /// 5299 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5300 SourceLocation BuiltinLoc, 5301 SourceLocation RParenLoc) { 5302 TypeSourceInfo *TInfo; 5303 GetTypeFromParser(ParsedDestTy, &TInfo); 5304 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5305 } 5306 5307 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5308 /// i.e. an expression not of \p OverloadTy. The expression should 5309 /// unary-convert to an expression of function-pointer or 5310 /// block-pointer type. 5311 /// 5312 /// \param NDecl the declaration being called, if available 5313 ExprResult 5314 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5315 SourceLocation LParenLoc, 5316 ArrayRef<Expr *> Args, 5317 SourceLocation RParenLoc, 5318 Expr *Config, bool IsExecConfig) { 5319 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5320 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5321 5322 // Functions with 'interrupt' attribute cannot be called directly. 5323 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5324 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5325 return ExprError(); 5326 } 5327 5328 // Interrupt handlers don't save off the VFP regs automatically on ARM, 5329 // so there's some risk when calling out to non-interrupt handler functions 5330 // that the callee might not preserve them. This is easy to diagnose here, 5331 // but can be very challenging to debug. 5332 if (auto *Caller = getCurFunctionDecl()) 5333 if (Caller->hasAttr<ARMInterruptAttr>()) { 5334 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 5335 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) 5336 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 5337 } 5338 5339 // Promote the function operand. 5340 // We special-case function promotion here because we only allow promoting 5341 // builtin functions to function pointers in the callee of a call. 5342 ExprResult Result; 5343 if (BuiltinID && 5344 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5345 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 5346 CK_BuiltinFnToFnPtr).get(); 5347 } else { 5348 Result = CallExprUnaryConversions(Fn); 5349 } 5350 if (Result.isInvalid()) 5351 return ExprError(); 5352 Fn = Result.get(); 5353 5354 // Make the call expr early, before semantic checks. This guarantees cleanup 5355 // of arguments and function on error. 5356 CallExpr *TheCall; 5357 if (Config) 5358 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 5359 cast<CallExpr>(Config), Args, 5360 Context.BoolTy, VK_RValue, 5361 RParenLoc); 5362 else 5363 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 5364 VK_RValue, RParenLoc); 5365 5366 if (!getLangOpts().CPlusPlus) { 5367 // C cannot always handle TypoExpr nodes in builtin calls and direct 5368 // function calls as their argument checking don't necessarily handle 5369 // dependent types properly, so make sure any TypoExprs have been 5370 // dealt with. 5371 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5372 if (!Result.isUsable()) return ExprError(); 5373 TheCall = dyn_cast<CallExpr>(Result.get()); 5374 if (!TheCall) return Result; 5375 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5376 } 5377 5378 // Bail out early if calling a builtin with custom typechecking. 5379 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5380 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5381 5382 retry: 5383 const FunctionType *FuncT; 5384 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5385 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5386 // have type pointer to function". 5387 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5388 if (!FuncT) 5389 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5390 << Fn->getType() << Fn->getSourceRange()); 5391 } else if (const BlockPointerType *BPT = 5392 Fn->getType()->getAs<BlockPointerType>()) { 5393 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5394 } else { 5395 // Handle calls to expressions of unknown-any type. 5396 if (Fn->getType() == Context.UnknownAnyTy) { 5397 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5398 if (rewrite.isInvalid()) return ExprError(); 5399 Fn = rewrite.get(); 5400 TheCall->setCallee(Fn); 5401 goto retry; 5402 } 5403 5404 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5405 << Fn->getType() << Fn->getSourceRange()); 5406 } 5407 5408 if (getLangOpts().CUDA) { 5409 if (Config) { 5410 // CUDA: Kernel calls must be to global functions 5411 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5412 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5413 << FDecl->getName() << Fn->getSourceRange()); 5414 5415 // CUDA: Kernel function must have 'void' return type 5416 if (!FuncT->getReturnType()->isVoidType()) 5417 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5418 << Fn->getType() << Fn->getSourceRange()); 5419 } else { 5420 // CUDA: Calls to global functions must be configured 5421 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5422 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5423 << FDecl->getName() << Fn->getSourceRange()); 5424 } 5425 } 5426 5427 // Check for a valid return type 5428 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall, 5429 FDecl)) 5430 return ExprError(); 5431 5432 // We know the result type of the call, set it. 5433 TheCall->setType(FuncT->getCallResultType(Context)); 5434 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5435 5436 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 5437 if (Proto) { 5438 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5439 IsExecConfig)) 5440 return ExprError(); 5441 } else { 5442 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5443 5444 if (FDecl) { 5445 // Check if we have too few/too many template arguments, based 5446 // on our knowledge of the function definition. 5447 const FunctionDecl *Def = nullptr; 5448 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5449 Proto = Def->getType()->getAs<FunctionProtoType>(); 5450 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5451 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5452 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5453 } 5454 5455 // If the function we're calling isn't a function prototype, but we have 5456 // a function prototype from a prior declaratiom, use that prototype. 5457 if (!FDecl->hasPrototype()) 5458 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5459 } 5460 5461 // Promote the arguments (C99 6.5.2.2p6). 5462 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5463 Expr *Arg = Args[i]; 5464 5465 if (Proto && i < Proto->getNumParams()) { 5466 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5467 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5468 ExprResult ArgE = 5469 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5470 if (ArgE.isInvalid()) 5471 return true; 5472 5473 Arg = ArgE.getAs<Expr>(); 5474 5475 } else { 5476 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5477 5478 if (ArgE.isInvalid()) 5479 return true; 5480 5481 Arg = ArgE.getAs<Expr>(); 5482 } 5483 5484 if (RequireCompleteType(Arg->getLocStart(), 5485 Arg->getType(), 5486 diag::err_call_incomplete_argument, Arg)) 5487 return ExprError(); 5488 5489 TheCall->setArg(i, Arg); 5490 } 5491 } 5492 5493 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5494 if (!Method->isStatic()) 5495 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5496 << Fn->getSourceRange()); 5497 5498 // Check for sentinels 5499 if (NDecl) 5500 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5501 5502 // Do special checking on direct calls to functions. 5503 if (FDecl) { 5504 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5505 return ExprError(); 5506 5507 if (BuiltinID) 5508 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5509 } else if (NDecl) { 5510 if (CheckPointerCall(NDecl, TheCall, Proto)) 5511 return ExprError(); 5512 } else { 5513 if (CheckOtherCall(TheCall, Proto)) 5514 return ExprError(); 5515 } 5516 5517 return MaybeBindToTemporary(TheCall); 5518 } 5519 5520 ExprResult 5521 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5522 SourceLocation RParenLoc, Expr *InitExpr) { 5523 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5524 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 5525 5526 TypeSourceInfo *TInfo; 5527 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5528 if (!TInfo) 5529 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5530 5531 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5532 } 5533 5534 ExprResult 5535 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5536 SourceLocation RParenLoc, Expr *LiteralExpr) { 5537 QualType literalType = TInfo->getType(); 5538 5539 if (literalType->isArrayType()) { 5540 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5541 diag::err_illegal_decl_array_incomplete_type, 5542 SourceRange(LParenLoc, 5543 LiteralExpr->getSourceRange().getEnd()))) 5544 return ExprError(); 5545 if (literalType->isVariableArrayType()) 5546 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5547 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5548 } else if (!literalType->isDependentType() && 5549 RequireCompleteType(LParenLoc, literalType, 5550 diag::err_typecheck_decl_incomplete_type, 5551 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5552 return ExprError(); 5553 5554 InitializedEntity Entity 5555 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5556 InitializationKind Kind 5557 = InitializationKind::CreateCStyleCast(LParenLoc, 5558 SourceRange(LParenLoc, RParenLoc), 5559 /*InitList=*/true); 5560 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5561 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5562 &literalType); 5563 if (Result.isInvalid()) 5564 return ExprError(); 5565 LiteralExpr = Result.get(); 5566 5567 bool isFileScope = !CurContext->isFunctionOrMethod(); 5568 if (isFileScope && 5569 !LiteralExpr->isTypeDependent() && 5570 !LiteralExpr->isValueDependent() && 5571 !literalType->isDependentType()) { // 6.5.2.5p3 5572 if (CheckForConstantInitializer(LiteralExpr, literalType)) 5573 return ExprError(); 5574 } 5575 5576 // In C, compound literals are l-values for some reason. 5577 // For GCC compatibility, in C++, file-scope array compound literals with 5578 // constant initializers are also l-values, and compound literals are 5579 // otherwise prvalues. 5580 // 5581 // (GCC also treats C++ list-initialized file-scope array prvalues with 5582 // constant initializers as l-values, but that's non-conforming, so we don't 5583 // follow it there.) 5584 // 5585 // FIXME: It would be better to handle the lvalue cases as materializing and 5586 // lifetime-extending a temporary object, but our materialized temporaries 5587 // representation only supports lifetime extension from a variable, not "out 5588 // of thin air". 5589 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 5590 // is bound to the result of applying array-to-pointer decay to the compound 5591 // literal. 5592 // FIXME: GCC supports compound literals of reference type, which should 5593 // obviously have a value kind derived from the kind of reference involved. 5594 ExprValueKind VK = 5595 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 5596 ? VK_RValue 5597 : VK_LValue; 5598 5599 return MaybeBindToTemporary( 5600 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 5601 VK, LiteralExpr, isFileScope)); 5602 } 5603 5604 ExprResult 5605 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 5606 SourceLocation RBraceLoc) { 5607 // Immediately handle non-overload placeholders. Overloads can be 5608 // resolved contextually, but everything else here can't. 5609 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 5610 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 5611 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 5612 5613 // Ignore failures; dropping the entire initializer list because 5614 // of one failure would be terrible for indexing/etc. 5615 if (result.isInvalid()) continue; 5616 5617 InitArgList[I] = result.get(); 5618 } 5619 } 5620 5621 // Semantic analysis for initializers is done by ActOnDeclarator() and 5622 // CheckInitializer() - it requires knowledge of the object being intialized. 5623 5624 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 5625 RBraceLoc); 5626 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 5627 return E; 5628 } 5629 5630 /// Do an explicit extend of the given block pointer if we're in ARC. 5631 void Sema::maybeExtendBlockObject(ExprResult &E) { 5632 assert(E.get()->getType()->isBlockPointerType()); 5633 assert(E.get()->isRValue()); 5634 5635 // Only do this in an r-value context. 5636 if (!getLangOpts().ObjCAutoRefCount) return; 5637 5638 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 5639 CK_ARCExtendBlockObject, E.get(), 5640 /*base path*/ nullptr, VK_RValue); 5641 Cleanup.setExprNeedsCleanups(true); 5642 } 5643 5644 /// Prepare a conversion of the given expression to an ObjC object 5645 /// pointer type. 5646 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 5647 QualType type = E.get()->getType(); 5648 if (type->isObjCObjectPointerType()) { 5649 return CK_BitCast; 5650 } else if (type->isBlockPointerType()) { 5651 maybeExtendBlockObject(E); 5652 return CK_BlockPointerToObjCPointerCast; 5653 } else { 5654 assert(type->isPointerType()); 5655 return CK_CPointerToObjCPointerCast; 5656 } 5657 } 5658 5659 /// Prepares for a scalar cast, performing all the necessary stages 5660 /// except the final cast and returning the kind required. 5661 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 5662 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 5663 // Also, callers should have filtered out the invalid cases with 5664 // pointers. Everything else should be possible. 5665 5666 QualType SrcTy = Src.get()->getType(); 5667 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 5668 return CK_NoOp; 5669 5670 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 5671 case Type::STK_MemberPointer: 5672 llvm_unreachable("member pointer type in C"); 5673 5674 case Type::STK_CPointer: 5675 case Type::STK_BlockPointer: 5676 case Type::STK_ObjCObjectPointer: 5677 switch (DestTy->getScalarTypeKind()) { 5678 case Type::STK_CPointer: { 5679 unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace(); 5680 unsigned DestAS = DestTy->getPointeeType().getAddressSpace(); 5681 if (SrcAS != DestAS) 5682 return CK_AddressSpaceConversion; 5683 return CK_BitCast; 5684 } 5685 case Type::STK_BlockPointer: 5686 return (SrcKind == Type::STK_BlockPointer 5687 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 5688 case Type::STK_ObjCObjectPointer: 5689 if (SrcKind == Type::STK_ObjCObjectPointer) 5690 return CK_BitCast; 5691 if (SrcKind == Type::STK_CPointer) 5692 return CK_CPointerToObjCPointerCast; 5693 maybeExtendBlockObject(Src); 5694 return CK_BlockPointerToObjCPointerCast; 5695 case Type::STK_Bool: 5696 return CK_PointerToBoolean; 5697 case Type::STK_Integral: 5698 return CK_PointerToIntegral; 5699 case Type::STK_Floating: 5700 case Type::STK_FloatingComplex: 5701 case Type::STK_IntegralComplex: 5702 case Type::STK_MemberPointer: 5703 llvm_unreachable("illegal cast from pointer"); 5704 } 5705 llvm_unreachable("Should have returned before this"); 5706 5707 case Type::STK_Bool: // casting from bool is like casting from an integer 5708 case Type::STK_Integral: 5709 switch (DestTy->getScalarTypeKind()) { 5710 case Type::STK_CPointer: 5711 case Type::STK_ObjCObjectPointer: 5712 case Type::STK_BlockPointer: 5713 if (Src.get()->isNullPointerConstant(Context, 5714 Expr::NPC_ValueDependentIsNull)) 5715 return CK_NullToPointer; 5716 return CK_IntegralToPointer; 5717 case Type::STK_Bool: 5718 return CK_IntegralToBoolean; 5719 case Type::STK_Integral: 5720 return CK_IntegralCast; 5721 case Type::STK_Floating: 5722 return CK_IntegralToFloating; 5723 case Type::STK_IntegralComplex: 5724 Src = ImpCastExprToType(Src.get(), 5725 DestTy->castAs<ComplexType>()->getElementType(), 5726 CK_IntegralCast); 5727 return CK_IntegralRealToComplex; 5728 case Type::STK_FloatingComplex: 5729 Src = ImpCastExprToType(Src.get(), 5730 DestTy->castAs<ComplexType>()->getElementType(), 5731 CK_IntegralToFloating); 5732 return CK_FloatingRealToComplex; 5733 case Type::STK_MemberPointer: 5734 llvm_unreachable("member pointer type in C"); 5735 } 5736 llvm_unreachable("Should have returned before this"); 5737 5738 case Type::STK_Floating: 5739 switch (DestTy->getScalarTypeKind()) { 5740 case Type::STK_Floating: 5741 return CK_FloatingCast; 5742 case Type::STK_Bool: 5743 return CK_FloatingToBoolean; 5744 case Type::STK_Integral: 5745 return CK_FloatingToIntegral; 5746 case Type::STK_FloatingComplex: 5747 Src = ImpCastExprToType(Src.get(), 5748 DestTy->castAs<ComplexType>()->getElementType(), 5749 CK_FloatingCast); 5750 return CK_FloatingRealToComplex; 5751 case Type::STK_IntegralComplex: 5752 Src = ImpCastExprToType(Src.get(), 5753 DestTy->castAs<ComplexType>()->getElementType(), 5754 CK_FloatingToIntegral); 5755 return CK_IntegralRealToComplex; 5756 case Type::STK_CPointer: 5757 case Type::STK_ObjCObjectPointer: 5758 case Type::STK_BlockPointer: 5759 llvm_unreachable("valid float->pointer cast?"); 5760 case Type::STK_MemberPointer: 5761 llvm_unreachable("member pointer type in C"); 5762 } 5763 llvm_unreachable("Should have returned before this"); 5764 5765 case Type::STK_FloatingComplex: 5766 switch (DestTy->getScalarTypeKind()) { 5767 case Type::STK_FloatingComplex: 5768 return CK_FloatingComplexCast; 5769 case Type::STK_IntegralComplex: 5770 return CK_FloatingComplexToIntegralComplex; 5771 case Type::STK_Floating: { 5772 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5773 if (Context.hasSameType(ET, DestTy)) 5774 return CK_FloatingComplexToReal; 5775 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 5776 return CK_FloatingCast; 5777 } 5778 case Type::STK_Bool: 5779 return CK_FloatingComplexToBoolean; 5780 case Type::STK_Integral: 5781 Src = ImpCastExprToType(Src.get(), 5782 SrcTy->castAs<ComplexType>()->getElementType(), 5783 CK_FloatingComplexToReal); 5784 return CK_FloatingToIntegral; 5785 case Type::STK_CPointer: 5786 case Type::STK_ObjCObjectPointer: 5787 case Type::STK_BlockPointer: 5788 llvm_unreachable("valid complex float->pointer cast?"); 5789 case Type::STK_MemberPointer: 5790 llvm_unreachable("member pointer type in C"); 5791 } 5792 llvm_unreachable("Should have returned before this"); 5793 5794 case Type::STK_IntegralComplex: 5795 switch (DestTy->getScalarTypeKind()) { 5796 case Type::STK_FloatingComplex: 5797 return CK_IntegralComplexToFloatingComplex; 5798 case Type::STK_IntegralComplex: 5799 return CK_IntegralComplexCast; 5800 case Type::STK_Integral: { 5801 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5802 if (Context.hasSameType(ET, DestTy)) 5803 return CK_IntegralComplexToReal; 5804 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 5805 return CK_IntegralCast; 5806 } 5807 case Type::STK_Bool: 5808 return CK_IntegralComplexToBoolean; 5809 case Type::STK_Floating: 5810 Src = ImpCastExprToType(Src.get(), 5811 SrcTy->castAs<ComplexType>()->getElementType(), 5812 CK_IntegralComplexToReal); 5813 return CK_IntegralToFloating; 5814 case Type::STK_CPointer: 5815 case Type::STK_ObjCObjectPointer: 5816 case Type::STK_BlockPointer: 5817 llvm_unreachable("valid complex int->pointer cast?"); 5818 case Type::STK_MemberPointer: 5819 llvm_unreachable("member pointer type in C"); 5820 } 5821 llvm_unreachable("Should have returned before this"); 5822 } 5823 5824 llvm_unreachable("Unhandled scalar cast"); 5825 } 5826 5827 static bool breakDownVectorType(QualType type, uint64_t &len, 5828 QualType &eltType) { 5829 // Vectors are simple. 5830 if (const VectorType *vecType = type->getAs<VectorType>()) { 5831 len = vecType->getNumElements(); 5832 eltType = vecType->getElementType(); 5833 assert(eltType->isScalarType()); 5834 return true; 5835 } 5836 5837 // We allow lax conversion to and from non-vector types, but only if 5838 // they're real types (i.e. non-complex, non-pointer scalar types). 5839 if (!type->isRealType()) return false; 5840 5841 len = 1; 5842 eltType = type; 5843 return true; 5844 } 5845 5846 /// Are the two types lax-compatible vector types? That is, given 5847 /// that one of them is a vector, do they have equal storage sizes, 5848 /// where the storage size is the number of elements times the element 5849 /// size? 5850 /// 5851 /// This will also return false if either of the types is neither a 5852 /// vector nor a real type. 5853 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 5854 assert(destTy->isVectorType() || srcTy->isVectorType()); 5855 5856 // Disallow lax conversions between scalars and ExtVectors (these 5857 // conversions are allowed for other vector types because common headers 5858 // depend on them). Most scalar OP ExtVector cases are handled by the 5859 // splat path anyway, which does what we want (convert, not bitcast). 5860 // What this rules out for ExtVectors is crazy things like char4*float. 5861 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 5862 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 5863 5864 uint64_t srcLen, destLen; 5865 QualType srcEltTy, destEltTy; 5866 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 5867 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 5868 5869 // ASTContext::getTypeSize will return the size rounded up to a 5870 // power of 2, so instead of using that, we need to use the raw 5871 // element size multiplied by the element count. 5872 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 5873 uint64_t destEltSize = Context.getTypeSize(destEltTy); 5874 5875 return (srcLen * srcEltSize == destLen * destEltSize); 5876 } 5877 5878 /// Is this a legal conversion between two types, one of which is 5879 /// known to be a vector type? 5880 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 5881 assert(destTy->isVectorType() || srcTy->isVectorType()); 5882 5883 if (!Context.getLangOpts().LaxVectorConversions) 5884 return false; 5885 return areLaxCompatibleVectorTypes(srcTy, destTy); 5886 } 5887 5888 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5889 CastKind &Kind) { 5890 assert(VectorTy->isVectorType() && "Not a vector type!"); 5891 5892 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 5893 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 5894 return Diag(R.getBegin(), 5895 Ty->isVectorType() ? 5896 diag::err_invalid_conversion_between_vectors : 5897 diag::err_invalid_conversion_between_vector_and_integer) 5898 << VectorTy << Ty << R; 5899 } else 5900 return Diag(R.getBegin(), 5901 diag::err_invalid_conversion_between_vector_and_scalar) 5902 << VectorTy << Ty << R; 5903 5904 Kind = CK_BitCast; 5905 return false; 5906 } 5907 5908 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 5909 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 5910 5911 if (DestElemTy == SplattedExpr->getType()) 5912 return SplattedExpr; 5913 5914 assert(DestElemTy->isFloatingType() || 5915 DestElemTy->isIntegralOrEnumerationType()); 5916 5917 CastKind CK; 5918 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 5919 // OpenCL requires that we convert `true` boolean expressions to -1, but 5920 // only when splatting vectors. 5921 if (DestElemTy->isFloatingType()) { 5922 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 5923 // in two steps: boolean to signed integral, then to floating. 5924 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 5925 CK_BooleanToSignedIntegral); 5926 SplattedExpr = CastExprRes.get(); 5927 CK = CK_IntegralToFloating; 5928 } else { 5929 CK = CK_BooleanToSignedIntegral; 5930 } 5931 } else { 5932 ExprResult CastExprRes = SplattedExpr; 5933 CK = PrepareScalarCast(CastExprRes, DestElemTy); 5934 if (CastExprRes.isInvalid()) 5935 return ExprError(); 5936 SplattedExpr = CastExprRes.get(); 5937 } 5938 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 5939 } 5940 5941 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 5942 Expr *CastExpr, CastKind &Kind) { 5943 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 5944 5945 QualType SrcTy = CastExpr->getType(); 5946 5947 // If SrcTy is a VectorType, the total size must match to explicitly cast to 5948 // an ExtVectorType. 5949 // In OpenCL, casts between vectors of different types are not allowed. 5950 // (See OpenCL 6.2). 5951 if (SrcTy->isVectorType()) { 5952 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) 5953 || (getLangOpts().OpenCL && 5954 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 5955 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 5956 << DestTy << SrcTy << R; 5957 return ExprError(); 5958 } 5959 Kind = CK_BitCast; 5960 return CastExpr; 5961 } 5962 5963 // All non-pointer scalars can be cast to ExtVector type. The appropriate 5964 // conversion will take place first from scalar to elt type, and then 5965 // splat from elt type to vector. 5966 if (SrcTy->isPointerType()) 5967 return Diag(R.getBegin(), 5968 diag::err_invalid_conversion_between_vector_and_scalar) 5969 << DestTy << SrcTy << R; 5970 5971 Kind = CK_VectorSplat; 5972 return prepareVectorSplat(DestTy, CastExpr); 5973 } 5974 5975 ExprResult 5976 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 5977 Declarator &D, ParsedType &Ty, 5978 SourceLocation RParenLoc, Expr *CastExpr) { 5979 assert(!D.isInvalidType() && (CastExpr != nullptr) && 5980 "ActOnCastExpr(): missing type or expr"); 5981 5982 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 5983 if (D.isInvalidType()) 5984 return ExprError(); 5985 5986 if (getLangOpts().CPlusPlus) { 5987 // Check that there are no default arguments (C++ only). 5988 CheckExtraCXXDefaultArguments(D); 5989 } else { 5990 // Make sure any TypoExprs have been dealt with. 5991 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 5992 if (!Res.isUsable()) 5993 return ExprError(); 5994 CastExpr = Res.get(); 5995 } 5996 5997 checkUnusedDeclAttributes(D); 5998 5999 QualType castType = castTInfo->getType(); 6000 Ty = CreateParsedType(castType, castTInfo); 6001 6002 bool isVectorLiteral = false; 6003 6004 // Check for an altivec or OpenCL literal, 6005 // i.e. all the elements are integer constants. 6006 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 6007 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 6008 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 6009 && castType->isVectorType() && (PE || PLE)) { 6010 if (PLE && PLE->getNumExprs() == 0) { 6011 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 6012 return ExprError(); 6013 } 6014 if (PE || PLE->getNumExprs() == 1) { 6015 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 6016 if (!E->getType()->isVectorType()) 6017 isVectorLiteral = true; 6018 } 6019 else 6020 isVectorLiteral = true; 6021 } 6022 6023 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 6024 // then handle it as such. 6025 if (isVectorLiteral) 6026 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 6027 6028 // If the Expr being casted is a ParenListExpr, handle it specially. 6029 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 6030 // sequence of BinOp comma operators. 6031 if (isa<ParenListExpr>(CastExpr)) { 6032 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 6033 if (Result.isInvalid()) return ExprError(); 6034 CastExpr = Result.get(); 6035 } 6036 6037 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6038 !getSourceManager().isInSystemMacro(LParenLoc)) 6039 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6040 6041 CheckTollFreeBridgeCast(castType, CastExpr); 6042 6043 CheckObjCBridgeRelatedCast(castType, CastExpr); 6044 6045 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 6046 6047 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6048 } 6049 6050 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6051 SourceLocation RParenLoc, Expr *E, 6052 TypeSourceInfo *TInfo) { 6053 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6054 "Expected paren or paren list expression"); 6055 6056 Expr **exprs; 6057 unsigned numExprs; 6058 Expr *subExpr; 6059 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6060 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6061 LiteralLParenLoc = PE->getLParenLoc(); 6062 LiteralRParenLoc = PE->getRParenLoc(); 6063 exprs = PE->getExprs(); 6064 numExprs = PE->getNumExprs(); 6065 } else { // isa<ParenExpr> by assertion at function entrance 6066 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6067 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6068 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6069 exprs = &subExpr; 6070 numExprs = 1; 6071 } 6072 6073 QualType Ty = TInfo->getType(); 6074 assert(Ty->isVectorType() && "Expected vector type"); 6075 6076 SmallVector<Expr *, 8> initExprs; 6077 const VectorType *VTy = Ty->getAs<VectorType>(); 6078 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 6079 6080 // '(...)' form of vector initialization in AltiVec: the number of 6081 // initializers must be one or must match the size of the vector. 6082 // If a single value is specified in the initializer then it will be 6083 // replicated to all the components of the vector 6084 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6085 // The number of initializers must be one or must match the size of the 6086 // vector. If a single value is specified in the initializer then it will 6087 // be replicated to all the components of the vector 6088 if (numExprs == 1) { 6089 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6090 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6091 if (Literal.isInvalid()) 6092 return ExprError(); 6093 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6094 PrepareScalarCast(Literal, ElemTy)); 6095 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6096 } 6097 else if (numExprs < numElems) { 6098 Diag(E->getExprLoc(), 6099 diag::err_incorrect_number_of_vector_initializers); 6100 return ExprError(); 6101 } 6102 else 6103 initExprs.append(exprs, exprs + numExprs); 6104 } 6105 else { 6106 // For OpenCL, when the number of initializers is a single value, 6107 // it will be replicated to all components of the vector. 6108 if (getLangOpts().OpenCL && 6109 VTy->getVectorKind() == VectorType::GenericVector && 6110 numExprs == 1) { 6111 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6112 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6113 if (Literal.isInvalid()) 6114 return ExprError(); 6115 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6116 PrepareScalarCast(Literal, ElemTy)); 6117 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6118 } 6119 6120 initExprs.append(exprs, exprs + numExprs); 6121 } 6122 // FIXME: This means that pretty-printing the final AST will produce curly 6123 // braces instead of the original commas. 6124 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6125 initExprs, LiteralRParenLoc); 6126 initE->setType(Ty); 6127 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6128 } 6129 6130 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6131 /// the ParenListExpr into a sequence of comma binary operators. 6132 ExprResult 6133 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6134 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6135 if (!E) 6136 return OrigExpr; 6137 6138 ExprResult Result(E->getExpr(0)); 6139 6140 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6141 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6142 E->getExpr(i)); 6143 6144 if (Result.isInvalid()) return ExprError(); 6145 6146 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6147 } 6148 6149 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6150 SourceLocation R, 6151 MultiExprArg Val) { 6152 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 6153 return expr; 6154 } 6155 6156 /// \brief Emit a specialized diagnostic when one expression is a null pointer 6157 /// constant and the other is not a pointer. Returns true if a diagnostic is 6158 /// emitted. 6159 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6160 SourceLocation QuestionLoc) { 6161 Expr *NullExpr = LHSExpr; 6162 Expr *NonPointerExpr = RHSExpr; 6163 Expr::NullPointerConstantKind NullKind = 6164 NullExpr->isNullPointerConstant(Context, 6165 Expr::NPC_ValueDependentIsNotNull); 6166 6167 if (NullKind == Expr::NPCK_NotNull) { 6168 NullExpr = RHSExpr; 6169 NonPointerExpr = LHSExpr; 6170 NullKind = 6171 NullExpr->isNullPointerConstant(Context, 6172 Expr::NPC_ValueDependentIsNotNull); 6173 } 6174 6175 if (NullKind == Expr::NPCK_NotNull) 6176 return false; 6177 6178 if (NullKind == Expr::NPCK_ZeroExpression) 6179 return false; 6180 6181 if (NullKind == Expr::NPCK_ZeroLiteral) { 6182 // In this case, check to make sure that we got here from a "NULL" 6183 // string in the source code. 6184 NullExpr = NullExpr->IgnoreParenImpCasts(); 6185 SourceLocation loc = NullExpr->getExprLoc(); 6186 if (!findMacroSpelling(loc, "NULL")) 6187 return false; 6188 } 6189 6190 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6191 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6192 << NonPointerExpr->getType() << DiagType 6193 << NonPointerExpr->getSourceRange(); 6194 return true; 6195 } 6196 6197 /// \brief Return false if the condition expression is valid, true otherwise. 6198 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6199 QualType CondTy = Cond->getType(); 6200 6201 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6202 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6203 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6204 << CondTy << Cond->getSourceRange(); 6205 return true; 6206 } 6207 6208 // C99 6.5.15p2 6209 if (CondTy->isScalarType()) return false; 6210 6211 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6212 << CondTy << Cond->getSourceRange(); 6213 return true; 6214 } 6215 6216 /// \brief Handle when one or both operands are void type. 6217 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6218 ExprResult &RHS) { 6219 Expr *LHSExpr = LHS.get(); 6220 Expr *RHSExpr = RHS.get(); 6221 6222 if (!LHSExpr->getType()->isVoidType()) 6223 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6224 << RHSExpr->getSourceRange(); 6225 if (!RHSExpr->getType()->isVoidType()) 6226 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6227 << LHSExpr->getSourceRange(); 6228 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6229 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6230 return S.Context.VoidTy; 6231 } 6232 6233 /// \brief Return false if the NullExpr can be promoted to PointerTy, 6234 /// true otherwise. 6235 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6236 QualType PointerTy) { 6237 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6238 !NullExpr.get()->isNullPointerConstant(S.Context, 6239 Expr::NPC_ValueDependentIsNull)) 6240 return true; 6241 6242 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6243 return false; 6244 } 6245 6246 /// \brief Checks compatibility between two pointers and return the resulting 6247 /// type. 6248 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6249 ExprResult &RHS, 6250 SourceLocation Loc) { 6251 QualType LHSTy = LHS.get()->getType(); 6252 QualType RHSTy = RHS.get()->getType(); 6253 6254 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6255 // Two identical pointers types are always compatible. 6256 return LHSTy; 6257 } 6258 6259 QualType lhptee, rhptee; 6260 6261 // Get the pointee types. 6262 bool IsBlockPointer = false; 6263 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6264 lhptee = LHSBTy->getPointeeType(); 6265 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6266 IsBlockPointer = true; 6267 } else { 6268 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6269 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6270 } 6271 6272 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6273 // differently qualified versions of compatible types, the result type is 6274 // a pointer to an appropriately qualified version of the composite 6275 // type. 6276 6277 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6278 // clause doesn't make sense for our extensions. E.g. address space 2 should 6279 // be incompatible with address space 3: they may live on different devices or 6280 // anything. 6281 Qualifiers lhQual = lhptee.getQualifiers(); 6282 Qualifiers rhQual = rhptee.getQualifiers(); 6283 6284 unsigned ResultAddrSpace = 0; 6285 unsigned LAddrSpace = lhQual.getAddressSpace(); 6286 unsigned RAddrSpace = rhQual.getAddressSpace(); 6287 if (S.getLangOpts().OpenCL) { 6288 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 6289 // spaces is disallowed. 6290 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 6291 ResultAddrSpace = LAddrSpace; 6292 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 6293 ResultAddrSpace = RAddrSpace; 6294 else { 6295 S.Diag(Loc, 6296 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 6297 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 6298 << RHS.get()->getSourceRange(); 6299 return QualType(); 6300 } 6301 } 6302 6303 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6304 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 6305 lhQual.removeCVRQualifiers(); 6306 rhQual.removeCVRQualifiers(); 6307 6308 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 6309 // (C99 6.7.3) for address spaces. We assume that the check should behave in 6310 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 6311 // qual types are compatible iff 6312 // * corresponded types are compatible 6313 // * CVR qualifiers are equal 6314 // * address spaces are equal 6315 // Thus for conditional operator we merge CVR and address space unqualified 6316 // pointees and if there is a composite type we return a pointer to it with 6317 // merged qualifiers. 6318 if (S.getLangOpts().OpenCL) { 6319 LHSCastKind = LAddrSpace == ResultAddrSpace 6320 ? CK_BitCast 6321 : CK_AddressSpaceConversion; 6322 RHSCastKind = RAddrSpace == ResultAddrSpace 6323 ? CK_BitCast 6324 : CK_AddressSpaceConversion; 6325 lhQual.removeAddressSpace(); 6326 rhQual.removeAddressSpace(); 6327 } 6328 6329 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 6330 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 6331 6332 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 6333 6334 if (CompositeTy.isNull()) { 6335 // In this situation, we assume void* type. No especially good 6336 // reason, but this is what gcc does, and we do have to pick 6337 // to get a consistent AST. 6338 QualType incompatTy; 6339 incompatTy = S.Context.getPointerType( 6340 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 6341 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 6342 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 6343 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 6344 // for casts between types with incompatible address space qualifiers. 6345 // For the following code the compiler produces casts between global and 6346 // local address spaces of the corresponded innermost pointees: 6347 // local int *global *a; 6348 // global int *global *b; 6349 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 6350 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 6351 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6352 << RHS.get()->getSourceRange(); 6353 return incompatTy; 6354 } 6355 6356 // The pointer types are compatible. 6357 // In case of OpenCL ResultTy should have the address space qualifier 6358 // which is a superset of address spaces of both the 2nd and the 3rd 6359 // operands of the conditional operator. 6360 QualType ResultTy = [&, ResultAddrSpace]() { 6361 if (S.getLangOpts().OpenCL) { 6362 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 6363 CompositeQuals.setAddressSpace(ResultAddrSpace); 6364 return S.Context 6365 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 6366 .withCVRQualifiers(MergedCVRQual); 6367 } 6368 return CompositeTy.withCVRQualifiers(MergedCVRQual); 6369 }(); 6370 if (IsBlockPointer) 6371 ResultTy = S.Context.getBlockPointerType(ResultTy); 6372 else 6373 ResultTy = S.Context.getPointerType(ResultTy); 6374 6375 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 6376 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 6377 return ResultTy; 6378 } 6379 6380 /// \brief Return the resulting type when the operands are both block pointers. 6381 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 6382 ExprResult &LHS, 6383 ExprResult &RHS, 6384 SourceLocation Loc) { 6385 QualType LHSTy = LHS.get()->getType(); 6386 QualType RHSTy = RHS.get()->getType(); 6387 6388 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 6389 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 6390 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 6391 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6392 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6393 return destType; 6394 } 6395 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 6396 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6397 << RHS.get()->getSourceRange(); 6398 return QualType(); 6399 } 6400 6401 // We have 2 block pointer types. 6402 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6403 } 6404 6405 /// \brief Return the resulting type when the operands are both pointers. 6406 static QualType 6407 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 6408 ExprResult &RHS, 6409 SourceLocation Loc) { 6410 // get the pointer types 6411 QualType LHSTy = LHS.get()->getType(); 6412 QualType RHSTy = RHS.get()->getType(); 6413 6414 // get the "pointed to" types 6415 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6416 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6417 6418 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 6419 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 6420 // Figure out necessary qualifiers (C99 6.5.15p6) 6421 QualType destPointee 6422 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6423 QualType destType = S.Context.getPointerType(destPointee); 6424 // Add qualifiers if necessary. 6425 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6426 // Promote to void*. 6427 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6428 return destType; 6429 } 6430 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 6431 QualType destPointee 6432 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6433 QualType destType = S.Context.getPointerType(destPointee); 6434 // Add qualifiers if necessary. 6435 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6436 // Promote to void*. 6437 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6438 return destType; 6439 } 6440 6441 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6442 } 6443 6444 /// \brief Return false if the first expression is not an integer and the second 6445 /// expression is not a pointer, true otherwise. 6446 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 6447 Expr* PointerExpr, SourceLocation Loc, 6448 bool IsIntFirstExpr) { 6449 if (!PointerExpr->getType()->isPointerType() || 6450 !Int.get()->getType()->isIntegerType()) 6451 return false; 6452 6453 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 6454 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 6455 6456 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 6457 << Expr1->getType() << Expr2->getType() 6458 << Expr1->getSourceRange() << Expr2->getSourceRange(); 6459 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 6460 CK_IntegralToPointer); 6461 return true; 6462 } 6463 6464 /// \brief Simple conversion between integer and floating point types. 6465 /// 6466 /// Used when handling the OpenCL conditional operator where the 6467 /// condition is a vector while the other operands are scalar. 6468 /// 6469 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 6470 /// types are either integer or floating type. Between the two 6471 /// operands, the type with the higher rank is defined as the "result 6472 /// type". The other operand needs to be promoted to the same type. No 6473 /// other type promotion is allowed. We cannot use 6474 /// UsualArithmeticConversions() for this purpose, since it always 6475 /// promotes promotable types. 6476 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 6477 ExprResult &RHS, 6478 SourceLocation QuestionLoc) { 6479 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 6480 if (LHS.isInvalid()) 6481 return QualType(); 6482 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 6483 if (RHS.isInvalid()) 6484 return QualType(); 6485 6486 // For conversion purposes, we ignore any qualifiers. 6487 // For example, "const float" and "float" are equivalent. 6488 QualType LHSType = 6489 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6490 QualType RHSType = 6491 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6492 6493 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 6494 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6495 << LHSType << LHS.get()->getSourceRange(); 6496 return QualType(); 6497 } 6498 6499 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 6500 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6501 << RHSType << RHS.get()->getSourceRange(); 6502 return QualType(); 6503 } 6504 6505 // If both types are identical, no conversion is needed. 6506 if (LHSType == RHSType) 6507 return LHSType; 6508 6509 // Now handle "real" floating types (i.e. float, double, long double). 6510 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 6511 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 6512 /*IsCompAssign = */ false); 6513 6514 // Finally, we have two differing integer types. 6515 return handleIntegerConversion<doIntegralCast, doIntegralCast> 6516 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 6517 } 6518 6519 /// \brief Convert scalar operands to a vector that matches the 6520 /// condition in length. 6521 /// 6522 /// Used when handling the OpenCL conditional operator where the 6523 /// condition is a vector while the other operands are scalar. 6524 /// 6525 /// We first compute the "result type" for the scalar operands 6526 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 6527 /// into a vector of that type where the length matches the condition 6528 /// vector type. s6.11.6 requires that the element types of the result 6529 /// and the condition must have the same number of bits. 6530 static QualType 6531 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 6532 QualType CondTy, SourceLocation QuestionLoc) { 6533 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 6534 if (ResTy.isNull()) return QualType(); 6535 6536 const VectorType *CV = CondTy->getAs<VectorType>(); 6537 assert(CV); 6538 6539 // Determine the vector result type 6540 unsigned NumElements = CV->getNumElements(); 6541 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 6542 6543 // Ensure that all types have the same number of bits 6544 if (S.Context.getTypeSize(CV->getElementType()) 6545 != S.Context.getTypeSize(ResTy)) { 6546 // Since VectorTy is created internally, it does not pretty print 6547 // with an OpenCL name. Instead, we just print a description. 6548 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 6549 SmallString<64> Str; 6550 llvm::raw_svector_ostream OS(Str); 6551 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 6552 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6553 << CondTy << OS.str(); 6554 return QualType(); 6555 } 6556 6557 // Convert operands to the vector result type 6558 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 6559 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 6560 6561 return VectorTy; 6562 } 6563 6564 /// \brief Return false if this is a valid OpenCL condition vector 6565 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 6566 SourceLocation QuestionLoc) { 6567 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 6568 // integral type. 6569 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 6570 assert(CondTy); 6571 QualType EleTy = CondTy->getElementType(); 6572 if (EleTy->isIntegerType()) return false; 6573 6574 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6575 << Cond->getType() << Cond->getSourceRange(); 6576 return true; 6577 } 6578 6579 /// \brief Return false if the vector condition type and the vector 6580 /// result type are compatible. 6581 /// 6582 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 6583 /// number of elements, and their element types have the same number 6584 /// of bits. 6585 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 6586 SourceLocation QuestionLoc) { 6587 const VectorType *CV = CondTy->getAs<VectorType>(); 6588 const VectorType *RV = VecResTy->getAs<VectorType>(); 6589 assert(CV && RV); 6590 6591 if (CV->getNumElements() != RV->getNumElements()) { 6592 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 6593 << CondTy << VecResTy; 6594 return true; 6595 } 6596 6597 QualType CVE = CV->getElementType(); 6598 QualType RVE = RV->getElementType(); 6599 6600 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 6601 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6602 << CondTy << VecResTy; 6603 return true; 6604 } 6605 6606 return false; 6607 } 6608 6609 /// \brief Return the resulting type for the conditional operator in 6610 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 6611 /// s6.3.i) when the condition is a vector type. 6612 static QualType 6613 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 6614 ExprResult &LHS, ExprResult &RHS, 6615 SourceLocation QuestionLoc) { 6616 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 6617 if (Cond.isInvalid()) 6618 return QualType(); 6619 QualType CondTy = Cond.get()->getType(); 6620 6621 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 6622 return QualType(); 6623 6624 // If either operand is a vector then find the vector type of the 6625 // result as specified in OpenCL v1.1 s6.3.i. 6626 if (LHS.get()->getType()->isVectorType() || 6627 RHS.get()->getType()->isVectorType()) { 6628 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 6629 /*isCompAssign*/false, 6630 /*AllowBothBool*/true, 6631 /*AllowBoolConversions*/false); 6632 if (VecResTy.isNull()) return QualType(); 6633 // The result type must match the condition type as specified in 6634 // OpenCL v1.1 s6.11.6. 6635 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 6636 return QualType(); 6637 return VecResTy; 6638 } 6639 6640 // Both operands are scalar. 6641 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 6642 } 6643 6644 /// \brief Return true if the Expr is block type 6645 static bool checkBlockType(Sema &S, const Expr *E) { 6646 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 6647 QualType Ty = CE->getCallee()->getType(); 6648 if (Ty->isBlockPointerType()) { 6649 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 6650 return true; 6651 } 6652 } 6653 return false; 6654 } 6655 6656 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 6657 /// In that case, LHS = cond. 6658 /// C99 6.5.15 6659 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 6660 ExprResult &RHS, ExprValueKind &VK, 6661 ExprObjectKind &OK, 6662 SourceLocation QuestionLoc) { 6663 6664 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 6665 if (!LHSResult.isUsable()) return QualType(); 6666 LHS = LHSResult; 6667 6668 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 6669 if (!RHSResult.isUsable()) return QualType(); 6670 RHS = RHSResult; 6671 6672 // C++ is sufficiently different to merit its own checker. 6673 if (getLangOpts().CPlusPlus) 6674 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 6675 6676 VK = VK_RValue; 6677 OK = OK_Ordinary; 6678 6679 // The OpenCL operator with a vector condition is sufficiently 6680 // different to merit its own checker. 6681 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 6682 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 6683 6684 // First, check the condition. 6685 Cond = UsualUnaryConversions(Cond.get()); 6686 if (Cond.isInvalid()) 6687 return QualType(); 6688 if (checkCondition(*this, Cond.get(), QuestionLoc)) 6689 return QualType(); 6690 6691 // Now check the two expressions. 6692 if (LHS.get()->getType()->isVectorType() || 6693 RHS.get()->getType()->isVectorType()) 6694 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 6695 /*AllowBothBool*/true, 6696 /*AllowBoolConversions*/false); 6697 6698 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 6699 if (LHS.isInvalid() || RHS.isInvalid()) 6700 return QualType(); 6701 6702 QualType LHSTy = LHS.get()->getType(); 6703 QualType RHSTy = RHS.get()->getType(); 6704 6705 // Diagnose attempts to convert between __float128 and long double where 6706 // such conversions currently can't be handled. 6707 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 6708 Diag(QuestionLoc, 6709 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 6710 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6711 return QualType(); 6712 } 6713 6714 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 6715 // selection operator (?:). 6716 if (getLangOpts().OpenCL && 6717 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 6718 return QualType(); 6719 } 6720 6721 // If both operands have arithmetic type, do the usual arithmetic conversions 6722 // to find a common type: C99 6.5.15p3,5. 6723 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 6724 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 6725 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 6726 6727 return ResTy; 6728 } 6729 6730 // If both operands are the same structure or union type, the result is that 6731 // type. 6732 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 6733 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 6734 if (LHSRT->getDecl() == RHSRT->getDecl()) 6735 // "If both the operands have structure or union type, the result has 6736 // that type." This implies that CV qualifiers are dropped. 6737 return LHSTy.getUnqualifiedType(); 6738 // FIXME: Type of conditional expression must be complete in C mode. 6739 } 6740 6741 // C99 6.5.15p5: "If both operands have void type, the result has void type." 6742 // The following || allows only one side to be void (a GCC-ism). 6743 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 6744 return checkConditionalVoidType(*this, LHS, RHS); 6745 } 6746 6747 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 6748 // the type of the other operand." 6749 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 6750 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 6751 6752 // All objective-c pointer type analysis is done here. 6753 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 6754 QuestionLoc); 6755 if (LHS.isInvalid() || RHS.isInvalid()) 6756 return QualType(); 6757 if (!compositeType.isNull()) 6758 return compositeType; 6759 6760 6761 // Handle block pointer types. 6762 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 6763 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 6764 QuestionLoc); 6765 6766 // Check constraints for C object pointers types (C99 6.5.15p3,6). 6767 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 6768 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 6769 QuestionLoc); 6770 6771 // GCC compatibility: soften pointer/integer mismatch. Note that 6772 // null pointers have been filtered out by this point. 6773 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 6774 /*isIntFirstExpr=*/true)) 6775 return RHSTy; 6776 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 6777 /*isIntFirstExpr=*/false)) 6778 return LHSTy; 6779 6780 // Emit a better diagnostic if one of the expressions is a null pointer 6781 // constant and the other is not a pointer type. In this case, the user most 6782 // likely forgot to take the address of the other expression. 6783 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 6784 return QualType(); 6785 6786 // Otherwise, the operands are not compatible. 6787 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 6788 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6789 << RHS.get()->getSourceRange(); 6790 return QualType(); 6791 } 6792 6793 /// FindCompositeObjCPointerType - Helper method to find composite type of 6794 /// two objective-c pointer types of the two input expressions. 6795 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 6796 SourceLocation QuestionLoc) { 6797 QualType LHSTy = LHS.get()->getType(); 6798 QualType RHSTy = RHS.get()->getType(); 6799 6800 // Handle things like Class and struct objc_class*. Here we case the result 6801 // to the pseudo-builtin, because that will be implicitly cast back to the 6802 // redefinition type if an attempt is made to access its fields. 6803 if (LHSTy->isObjCClassType() && 6804 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 6805 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6806 return LHSTy; 6807 } 6808 if (RHSTy->isObjCClassType() && 6809 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 6810 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6811 return RHSTy; 6812 } 6813 // And the same for struct objc_object* / id 6814 if (LHSTy->isObjCIdType() && 6815 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 6816 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6817 return LHSTy; 6818 } 6819 if (RHSTy->isObjCIdType() && 6820 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 6821 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6822 return RHSTy; 6823 } 6824 // And the same for struct objc_selector* / SEL 6825 if (Context.isObjCSelType(LHSTy) && 6826 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 6827 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 6828 return LHSTy; 6829 } 6830 if (Context.isObjCSelType(RHSTy) && 6831 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 6832 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 6833 return RHSTy; 6834 } 6835 // Check constraints for Objective-C object pointers types. 6836 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 6837 6838 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 6839 // Two identical object pointer types are always compatible. 6840 return LHSTy; 6841 } 6842 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 6843 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 6844 QualType compositeType = LHSTy; 6845 6846 // If both operands are interfaces and either operand can be 6847 // assigned to the other, use that type as the composite 6848 // type. This allows 6849 // xxx ? (A*) a : (B*) b 6850 // where B is a subclass of A. 6851 // 6852 // Additionally, as for assignment, if either type is 'id' 6853 // allow silent coercion. Finally, if the types are 6854 // incompatible then make sure to use 'id' as the composite 6855 // type so the result is acceptable for sending messages to. 6856 6857 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 6858 // It could return the composite type. 6859 if (!(compositeType = 6860 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 6861 // Nothing more to do. 6862 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 6863 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 6864 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 6865 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 6866 } else if ((LHSTy->isObjCQualifiedIdType() || 6867 RHSTy->isObjCQualifiedIdType()) && 6868 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 6869 // Need to handle "id<xx>" explicitly. 6870 // GCC allows qualified id and any Objective-C type to devolve to 6871 // id. Currently localizing to here until clear this should be 6872 // part of ObjCQualifiedIdTypesAreCompatible. 6873 compositeType = Context.getObjCIdType(); 6874 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 6875 compositeType = Context.getObjCIdType(); 6876 } else { 6877 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 6878 << LHSTy << RHSTy 6879 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6880 QualType incompatTy = Context.getObjCIdType(); 6881 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6882 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6883 return incompatTy; 6884 } 6885 // The object pointer types are compatible. 6886 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 6887 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 6888 return compositeType; 6889 } 6890 // Check Objective-C object pointer types and 'void *' 6891 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 6892 if (getLangOpts().ObjCAutoRefCount) { 6893 // ARC forbids the implicit conversion of object pointers to 'void *', 6894 // so these types are not compatible. 6895 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6896 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6897 LHS = RHS = true; 6898 return QualType(); 6899 } 6900 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6901 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6902 QualType destPointee 6903 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6904 QualType destType = Context.getPointerType(destPointee); 6905 // Add qualifiers if necessary. 6906 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6907 // Promote to void*. 6908 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6909 return destType; 6910 } 6911 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 6912 if (getLangOpts().ObjCAutoRefCount) { 6913 // ARC forbids the implicit conversion of object pointers to 'void *', 6914 // so these types are not compatible. 6915 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6916 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6917 LHS = RHS = true; 6918 return QualType(); 6919 } 6920 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6921 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6922 QualType destPointee 6923 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6924 QualType destType = Context.getPointerType(destPointee); 6925 // Add qualifiers if necessary. 6926 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6927 // Promote to void*. 6928 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6929 return destType; 6930 } 6931 return QualType(); 6932 } 6933 6934 /// SuggestParentheses - Emit a note with a fixit hint that wraps 6935 /// ParenRange in parentheses. 6936 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 6937 const PartialDiagnostic &Note, 6938 SourceRange ParenRange) { 6939 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 6940 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 6941 EndLoc.isValid()) { 6942 Self.Diag(Loc, Note) 6943 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 6944 << FixItHint::CreateInsertion(EndLoc, ")"); 6945 } else { 6946 // We can't display the parentheses, so just show the bare note. 6947 Self.Diag(Loc, Note) << ParenRange; 6948 } 6949 } 6950 6951 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 6952 return BinaryOperator::isAdditiveOp(Opc) || 6953 BinaryOperator::isMultiplicativeOp(Opc) || 6954 BinaryOperator::isShiftOp(Opc); 6955 } 6956 6957 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 6958 /// expression, either using a built-in or overloaded operator, 6959 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 6960 /// expression. 6961 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 6962 Expr **RHSExprs) { 6963 // Don't strip parenthesis: we should not warn if E is in parenthesis. 6964 E = E->IgnoreImpCasts(); 6965 E = E->IgnoreConversionOperator(); 6966 E = E->IgnoreImpCasts(); 6967 6968 // Built-in binary operator. 6969 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 6970 if (IsArithmeticOp(OP->getOpcode())) { 6971 *Opcode = OP->getOpcode(); 6972 *RHSExprs = OP->getRHS(); 6973 return true; 6974 } 6975 } 6976 6977 // Overloaded operator. 6978 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 6979 if (Call->getNumArgs() != 2) 6980 return false; 6981 6982 // Make sure this is really a binary operator that is safe to pass into 6983 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 6984 OverloadedOperatorKind OO = Call->getOperator(); 6985 if (OO < OO_Plus || OO > OO_Arrow || 6986 OO == OO_PlusPlus || OO == OO_MinusMinus) 6987 return false; 6988 6989 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 6990 if (IsArithmeticOp(OpKind)) { 6991 *Opcode = OpKind; 6992 *RHSExprs = Call->getArg(1); 6993 return true; 6994 } 6995 } 6996 6997 return false; 6998 } 6999 7000 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 7001 /// or is a logical expression such as (x==y) which has int type, but is 7002 /// commonly interpreted as boolean. 7003 static bool ExprLooksBoolean(Expr *E) { 7004 E = E->IgnoreParenImpCasts(); 7005 7006 if (E->getType()->isBooleanType()) 7007 return true; 7008 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 7009 return OP->isComparisonOp() || OP->isLogicalOp(); 7010 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 7011 return OP->getOpcode() == UO_LNot; 7012 if (E->getType()->isPointerType()) 7013 return true; 7014 7015 return false; 7016 } 7017 7018 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 7019 /// and binary operator are mixed in a way that suggests the programmer assumed 7020 /// the conditional operator has higher precedence, for example: 7021 /// "int x = a + someBinaryCondition ? 1 : 2". 7022 static void DiagnoseConditionalPrecedence(Sema &Self, 7023 SourceLocation OpLoc, 7024 Expr *Condition, 7025 Expr *LHSExpr, 7026 Expr *RHSExpr) { 7027 BinaryOperatorKind CondOpcode; 7028 Expr *CondRHS; 7029 7030 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 7031 return; 7032 if (!ExprLooksBoolean(CondRHS)) 7033 return; 7034 7035 // The condition is an arithmetic binary expression, with a right- 7036 // hand side that looks boolean, so warn. 7037 7038 Self.Diag(OpLoc, diag::warn_precedence_conditional) 7039 << Condition->getSourceRange() 7040 << BinaryOperator::getOpcodeStr(CondOpcode); 7041 7042 SuggestParentheses(Self, OpLoc, 7043 Self.PDiag(diag::note_precedence_silence) 7044 << BinaryOperator::getOpcodeStr(CondOpcode), 7045 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 7046 7047 SuggestParentheses(Self, OpLoc, 7048 Self.PDiag(diag::note_precedence_conditional_first), 7049 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 7050 } 7051 7052 /// Compute the nullability of a conditional expression. 7053 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 7054 QualType LHSTy, QualType RHSTy, 7055 ASTContext &Ctx) { 7056 if (!ResTy->isAnyPointerType()) 7057 return ResTy; 7058 7059 auto GetNullability = [&Ctx](QualType Ty) { 7060 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 7061 if (Kind) 7062 return *Kind; 7063 return NullabilityKind::Unspecified; 7064 }; 7065 7066 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 7067 NullabilityKind MergedKind; 7068 7069 // Compute nullability of a binary conditional expression. 7070 if (IsBin) { 7071 if (LHSKind == NullabilityKind::NonNull) 7072 MergedKind = NullabilityKind::NonNull; 7073 else 7074 MergedKind = RHSKind; 7075 // Compute nullability of a normal conditional expression. 7076 } else { 7077 if (LHSKind == NullabilityKind::Nullable || 7078 RHSKind == NullabilityKind::Nullable) 7079 MergedKind = NullabilityKind::Nullable; 7080 else if (LHSKind == NullabilityKind::NonNull) 7081 MergedKind = RHSKind; 7082 else if (RHSKind == NullabilityKind::NonNull) 7083 MergedKind = LHSKind; 7084 else 7085 MergedKind = NullabilityKind::Unspecified; 7086 } 7087 7088 // Return if ResTy already has the correct nullability. 7089 if (GetNullability(ResTy) == MergedKind) 7090 return ResTy; 7091 7092 // Strip all nullability from ResTy. 7093 while (ResTy->getNullability(Ctx)) 7094 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 7095 7096 // Create a new AttributedType with the new nullability kind. 7097 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 7098 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 7099 } 7100 7101 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7102 /// in the case of a the GNU conditional expr extension. 7103 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7104 SourceLocation ColonLoc, 7105 Expr *CondExpr, Expr *LHSExpr, 7106 Expr *RHSExpr) { 7107 if (!getLangOpts().CPlusPlus) { 7108 // C cannot handle TypoExpr nodes in the condition because it 7109 // doesn't handle dependent types properly, so make sure any TypoExprs have 7110 // been dealt with before checking the operands. 7111 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7112 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7113 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7114 7115 if (!CondResult.isUsable()) 7116 return ExprError(); 7117 7118 if (LHSExpr) { 7119 if (!LHSResult.isUsable()) 7120 return ExprError(); 7121 } 7122 7123 if (!RHSResult.isUsable()) 7124 return ExprError(); 7125 7126 CondExpr = CondResult.get(); 7127 LHSExpr = LHSResult.get(); 7128 RHSExpr = RHSResult.get(); 7129 } 7130 7131 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7132 // was the condition. 7133 OpaqueValueExpr *opaqueValue = nullptr; 7134 Expr *commonExpr = nullptr; 7135 if (!LHSExpr) { 7136 commonExpr = CondExpr; 7137 // Lower out placeholder types first. This is important so that we don't 7138 // try to capture a placeholder. This happens in few cases in C++; such 7139 // as Objective-C++'s dictionary subscripting syntax. 7140 if (commonExpr->hasPlaceholderType()) { 7141 ExprResult result = CheckPlaceholderExpr(commonExpr); 7142 if (!result.isUsable()) return ExprError(); 7143 commonExpr = result.get(); 7144 } 7145 // We usually want to apply unary conversions *before* saving, except 7146 // in the special case of a C++ l-value conditional. 7147 if (!(getLangOpts().CPlusPlus 7148 && !commonExpr->isTypeDependent() 7149 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7150 && commonExpr->isGLValue() 7151 && commonExpr->isOrdinaryOrBitFieldObject() 7152 && RHSExpr->isOrdinaryOrBitFieldObject() 7153 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7154 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7155 if (commonRes.isInvalid()) 7156 return ExprError(); 7157 commonExpr = commonRes.get(); 7158 } 7159 7160 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7161 commonExpr->getType(), 7162 commonExpr->getValueKind(), 7163 commonExpr->getObjectKind(), 7164 commonExpr); 7165 LHSExpr = CondExpr = opaqueValue; 7166 } 7167 7168 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 7169 ExprValueKind VK = VK_RValue; 7170 ExprObjectKind OK = OK_Ordinary; 7171 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7172 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7173 VK, OK, QuestionLoc); 7174 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7175 RHS.isInvalid()) 7176 return ExprError(); 7177 7178 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7179 RHS.get()); 7180 7181 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 7182 7183 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 7184 Context); 7185 7186 if (!commonExpr) 7187 return new (Context) 7188 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 7189 RHS.get(), result, VK, OK); 7190 7191 return new (Context) BinaryConditionalOperator( 7192 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 7193 ColonLoc, result, VK, OK); 7194 } 7195 7196 // checkPointerTypesForAssignment - This is a very tricky routine (despite 7197 // being closely modeled after the C99 spec:-). The odd characteristic of this 7198 // routine is it effectively iqnores the qualifiers on the top level pointee. 7199 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 7200 // FIXME: add a couple examples in this comment. 7201 static Sema::AssignConvertType 7202 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 7203 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7204 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7205 7206 // get the "pointed to" type (ignoring qualifiers at the top level) 7207 const Type *lhptee, *rhptee; 7208 Qualifiers lhq, rhq; 7209 std::tie(lhptee, lhq) = 7210 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 7211 std::tie(rhptee, rhq) = 7212 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 7213 7214 Sema::AssignConvertType ConvTy = Sema::Compatible; 7215 7216 // C99 6.5.16.1p1: This following citation is common to constraints 7217 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 7218 // qualifiers of the type *pointed to* by the right; 7219 7220 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 7221 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 7222 lhq.compatiblyIncludesObjCLifetime(rhq)) { 7223 // Ignore lifetime for further calculation. 7224 lhq.removeObjCLifetime(); 7225 rhq.removeObjCLifetime(); 7226 } 7227 7228 if (!lhq.compatiblyIncludes(rhq)) { 7229 // Treat address-space mismatches as fatal. TODO: address subspaces 7230 if (!lhq.isAddressSpaceSupersetOf(rhq)) 7231 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7232 7233 // It's okay to add or remove GC or lifetime qualifiers when converting to 7234 // and from void*. 7235 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 7236 .compatiblyIncludes( 7237 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 7238 && (lhptee->isVoidType() || rhptee->isVoidType())) 7239 ; // keep old 7240 7241 // Treat lifetime mismatches as fatal. 7242 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 7243 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7244 7245 // For GCC/MS compatibility, other qualifier mismatches are treated 7246 // as still compatible in C. 7247 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7248 } 7249 7250 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 7251 // incomplete type and the other is a pointer to a qualified or unqualified 7252 // version of void... 7253 if (lhptee->isVoidType()) { 7254 if (rhptee->isIncompleteOrObjectType()) 7255 return ConvTy; 7256 7257 // As an extension, we allow cast to/from void* to function pointer. 7258 assert(rhptee->isFunctionType()); 7259 return Sema::FunctionVoidPointer; 7260 } 7261 7262 if (rhptee->isVoidType()) { 7263 if (lhptee->isIncompleteOrObjectType()) 7264 return ConvTy; 7265 7266 // As an extension, we allow cast to/from void* to function pointer. 7267 assert(lhptee->isFunctionType()); 7268 return Sema::FunctionVoidPointer; 7269 } 7270 7271 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7272 // unqualified versions of compatible types, ... 7273 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7274 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7275 // Check if the pointee types are compatible ignoring the sign. 7276 // We explicitly check for char so that we catch "char" vs 7277 // "unsigned char" on systems where "char" is unsigned. 7278 if (lhptee->isCharType()) 7279 ltrans = S.Context.UnsignedCharTy; 7280 else if (lhptee->hasSignedIntegerRepresentation()) 7281 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7282 7283 if (rhptee->isCharType()) 7284 rtrans = S.Context.UnsignedCharTy; 7285 else if (rhptee->hasSignedIntegerRepresentation()) 7286 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 7287 7288 if (ltrans == rtrans) { 7289 // Types are compatible ignoring the sign. Qualifier incompatibility 7290 // takes priority over sign incompatibility because the sign 7291 // warning can be disabled. 7292 if (ConvTy != Sema::Compatible) 7293 return ConvTy; 7294 7295 return Sema::IncompatiblePointerSign; 7296 } 7297 7298 // If we are a multi-level pointer, it's possible that our issue is simply 7299 // one of qualification - e.g. char ** -> const char ** is not allowed. If 7300 // the eventual target type is the same and the pointers have the same 7301 // level of indirection, this must be the issue. 7302 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 7303 do { 7304 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 7305 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 7306 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 7307 7308 if (lhptee == rhptee) 7309 return Sema::IncompatibleNestedPointerQualifiers; 7310 } 7311 7312 // General pointer incompatibility takes priority over qualifiers. 7313 return Sema::IncompatiblePointer; 7314 } 7315 if (!S.getLangOpts().CPlusPlus && 7316 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 7317 return Sema::IncompatiblePointer; 7318 return ConvTy; 7319 } 7320 7321 /// checkBlockPointerTypesForAssignment - This routine determines whether two 7322 /// block pointer types are compatible or whether a block and normal pointer 7323 /// are compatible. It is more restrict than comparing two function pointer 7324 // types. 7325 static Sema::AssignConvertType 7326 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 7327 QualType RHSType) { 7328 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7329 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7330 7331 QualType lhptee, rhptee; 7332 7333 // get the "pointed to" type (ignoring qualifiers at the top level) 7334 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 7335 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 7336 7337 // In C++, the types have to match exactly. 7338 if (S.getLangOpts().CPlusPlus) 7339 return Sema::IncompatibleBlockPointer; 7340 7341 Sema::AssignConvertType ConvTy = Sema::Compatible; 7342 7343 // For blocks we enforce that qualifiers are identical. 7344 Qualifiers LQuals = lhptee.getLocalQualifiers(); 7345 Qualifiers RQuals = rhptee.getLocalQualifiers(); 7346 if (S.getLangOpts().OpenCL) { 7347 LQuals.removeAddressSpace(); 7348 RQuals.removeAddressSpace(); 7349 } 7350 if (LQuals != RQuals) 7351 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7352 7353 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 7354 // assignment. 7355 // The current behavior is similar to C++ lambdas. A block might be 7356 // assigned to a variable iff its return type and parameters are compatible 7357 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 7358 // an assignment. Presumably it should behave in way that a function pointer 7359 // assignment does in C, so for each parameter and return type: 7360 // * CVR and address space of LHS should be a superset of CVR and address 7361 // space of RHS. 7362 // * unqualified types should be compatible. 7363 if (S.getLangOpts().OpenCL) { 7364 if (!S.Context.typesAreBlockPointerCompatible( 7365 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 7366 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 7367 return Sema::IncompatibleBlockPointer; 7368 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 7369 return Sema::IncompatibleBlockPointer; 7370 7371 return ConvTy; 7372 } 7373 7374 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 7375 /// for assignment compatibility. 7376 static Sema::AssignConvertType 7377 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 7378 QualType RHSType) { 7379 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 7380 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 7381 7382 if (LHSType->isObjCBuiltinType()) { 7383 // Class is not compatible with ObjC object pointers. 7384 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 7385 !RHSType->isObjCQualifiedClassType()) 7386 return Sema::IncompatiblePointer; 7387 return Sema::Compatible; 7388 } 7389 if (RHSType->isObjCBuiltinType()) { 7390 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 7391 !LHSType->isObjCQualifiedClassType()) 7392 return Sema::IncompatiblePointer; 7393 return Sema::Compatible; 7394 } 7395 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7396 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7397 7398 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 7399 // make an exception for id<P> 7400 !LHSType->isObjCQualifiedIdType()) 7401 return Sema::CompatiblePointerDiscardsQualifiers; 7402 7403 if (S.Context.typesAreCompatible(LHSType, RHSType)) 7404 return Sema::Compatible; 7405 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 7406 return Sema::IncompatibleObjCQualifiedId; 7407 return Sema::IncompatiblePointer; 7408 } 7409 7410 Sema::AssignConvertType 7411 Sema::CheckAssignmentConstraints(SourceLocation Loc, 7412 QualType LHSType, QualType RHSType) { 7413 // Fake up an opaque expression. We don't actually care about what 7414 // cast operations are required, so if CheckAssignmentConstraints 7415 // adds casts to this they'll be wasted, but fortunately that doesn't 7416 // usually happen on valid code. 7417 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 7418 ExprResult RHSPtr = &RHSExpr; 7419 CastKind K = CK_Invalid; 7420 7421 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 7422 } 7423 7424 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 7425 /// has code to accommodate several GCC extensions when type checking 7426 /// pointers. Here are some objectionable examples that GCC considers warnings: 7427 /// 7428 /// int a, *pint; 7429 /// short *pshort; 7430 /// struct foo *pfoo; 7431 /// 7432 /// pint = pshort; // warning: assignment from incompatible pointer type 7433 /// a = pint; // warning: assignment makes integer from pointer without a cast 7434 /// pint = a; // warning: assignment makes pointer from integer without a cast 7435 /// pint = pfoo; // warning: assignment from incompatible pointer type 7436 /// 7437 /// As a result, the code for dealing with pointers is more complex than the 7438 /// C99 spec dictates. 7439 /// 7440 /// Sets 'Kind' for any result kind except Incompatible. 7441 Sema::AssignConvertType 7442 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 7443 CastKind &Kind, bool ConvertRHS) { 7444 QualType RHSType = RHS.get()->getType(); 7445 QualType OrigLHSType = LHSType; 7446 7447 // Get canonical types. We're not formatting these types, just comparing 7448 // them. 7449 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 7450 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 7451 7452 // Common case: no conversion required. 7453 if (LHSType == RHSType) { 7454 Kind = CK_NoOp; 7455 return Compatible; 7456 } 7457 7458 // If we have an atomic type, try a non-atomic assignment, then just add an 7459 // atomic qualification step. 7460 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 7461 Sema::AssignConvertType result = 7462 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 7463 if (result != Compatible) 7464 return result; 7465 if (Kind != CK_NoOp && ConvertRHS) 7466 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 7467 Kind = CK_NonAtomicToAtomic; 7468 return Compatible; 7469 } 7470 7471 // If the left-hand side is a reference type, then we are in a 7472 // (rare!) case where we've allowed the use of references in C, 7473 // e.g., as a parameter type in a built-in function. In this case, 7474 // just make sure that the type referenced is compatible with the 7475 // right-hand side type. The caller is responsible for adjusting 7476 // LHSType so that the resulting expression does not have reference 7477 // type. 7478 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 7479 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 7480 Kind = CK_LValueBitCast; 7481 return Compatible; 7482 } 7483 return Incompatible; 7484 } 7485 7486 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 7487 // to the same ExtVector type. 7488 if (LHSType->isExtVectorType()) { 7489 if (RHSType->isExtVectorType()) 7490 return Incompatible; 7491 if (RHSType->isArithmeticType()) { 7492 // CK_VectorSplat does T -> vector T, so first cast to the element type. 7493 if (ConvertRHS) 7494 RHS = prepareVectorSplat(LHSType, RHS.get()); 7495 Kind = CK_VectorSplat; 7496 return Compatible; 7497 } 7498 } 7499 7500 // Conversions to or from vector type. 7501 if (LHSType->isVectorType() || RHSType->isVectorType()) { 7502 if (LHSType->isVectorType() && RHSType->isVectorType()) { 7503 // Allow assignments of an AltiVec vector type to an equivalent GCC 7504 // vector type and vice versa 7505 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7506 Kind = CK_BitCast; 7507 return Compatible; 7508 } 7509 7510 // If we are allowing lax vector conversions, and LHS and RHS are both 7511 // vectors, the total size only needs to be the same. This is a bitcast; 7512 // no bits are changed but the result type is different. 7513 if (isLaxVectorConversion(RHSType, LHSType)) { 7514 Kind = CK_BitCast; 7515 return IncompatibleVectors; 7516 } 7517 } 7518 7519 // When the RHS comes from another lax conversion (e.g. binops between 7520 // scalars and vectors) the result is canonicalized as a vector. When the 7521 // LHS is also a vector, the lax is allowed by the condition above. Handle 7522 // the case where LHS is a scalar. 7523 if (LHSType->isScalarType()) { 7524 const VectorType *VecType = RHSType->getAs<VectorType>(); 7525 if (VecType && VecType->getNumElements() == 1 && 7526 isLaxVectorConversion(RHSType, LHSType)) { 7527 ExprResult *VecExpr = &RHS; 7528 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 7529 Kind = CK_BitCast; 7530 return Compatible; 7531 } 7532 } 7533 7534 return Incompatible; 7535 } 7536 7537 // Diagnose attempts to convert between __float128 and long double where 7538 // such conversions currently can't be handled. 7539 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 7540 return Incompatible; 7541 7542 // Disallow assigning a _Complex to a real type in C++ mode since it simply 7543 // discards the imaginary part. 7544 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 7545 !LHSType->getAs<ComplexType>()) 7546 return Incompatible; 7547 7548 // Arithmetic conversions. 7549 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 7550 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 7551 if (ConvertRHS) 7552 Kind = PrepareScalarCast(RHS, LHSType); 7553 return Compatible; 7554 } 7555 7556 // Conversions to normal pointers. 7557 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 7558 // U* -> T* 7559 if (isa<PointerType>(RHSType)) { 7560 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7561 unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 7562 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7563 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 7564 } 7565 7566 // int -> T* 7567 if (RHSType->isIntegerType()) { 7568 Kind = CK_IntegralToPointer; // FIXME: null? 7569 return IntToPointer; 7570 } 7571 7572 // C pointers are not compatible with ObjC object pointers, 7573 // with two exceptions: 7574 if (isa<ObjCObjectPointerType>(RHSType)) { 7575 // - conversions to void* 7576 if (LHSPointer->getPointeeType()->isVoidType()) { 7577 Kind = CK_BitCast; 7578 return Compatible; 7579 } 7580 7581 // - conversions from 'Class' to the redefinition type 7582 if (RHSType->isObjCClassType() && 7583 Context.hasSameType(LHSType, 7584 Context.getObjCClassRedefinitionType())) { 7585 Kind = CK_BitCast; 7586 return Compatible; 7587 } 7588 7589 Kind = CK_BitCast; 7590 return IncompatiblePointer; 7591 } 7592 7593 // U^ -> void* 7594 if (RHSType->getAs<BlockPointerType>()) { 7595 if (LHSPointer->getPointeeType()->isVoidType()) { 7596 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7597 unsigned AddrSpaceR = RHSType->getAs<BlockPointerType>() 7598 ->getPointeeType() 7599 .getAddressSpace(); 7600 Kind = 7601 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7602 return Compatible; 7603 } 7604 } 7605 7606 return Incompatible; 7607 } 7608 7609 // Conversions to block pointers. 7610 if (isa<BlockPointerType>(LHSType)) { 7611 // U^ -> T^ 7612 if (RHSType->isBlockPointerType()) { 7613 unsigned AddrSpaceL = LHSType->getAs<BlockPointerType>() 7614 ->getPointeeType() 7615 .getAddressSpace(); 7616 unsigned AddrSpaceR = RHSType->getAs<BlockPointerType>() 7617 ->getPointeeType() 7618 .getAddressSpace(); 7619 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7620 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 7621 } 7622 7623 // int or null -> T^ 7624 if (RHSType->isIntegerType()) { 7625 Kind = CK_IntegralToPointer; // FIXME: null 7626 return IntToBlockPointer; 7627 } 7628 7629 // id -> T^ 7630 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 7631 Kind = CK_AnyPointerToBlockPointerCast; 7632 return Compatible; 7633 } 7634 7635 // void* -> T^ 7636 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 7637 if (RHSPT->getPointeeType()->isVoidType()) { 7638 Kind = CK_AnyPointerToBlockPointerCast; 7639 return Compatible; 7640 } 7641 7642 return Incompatible; 7643 } 7644 7645 // Conversions to Objective-C pointers. 7646 if (isa<ObjCObjectPointerType>(LHSType)) { 7647 // A* -> B* 7648 if (RHSType->isObjCObjectPointerType()) { 7649 Kind = CK_BitCast; 7650 Sema::AssignConvertType result = 7651 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 7652 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 7653 result == Compatible && 7654 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 7655 result = IncompatibleObjCWeakRef; 7656 return result; 7657 } 7658 7659 // int or null -> A* 7660 if (RHSType->isIntegerType()) { 7661 Kind = CK_IntegralToPointer; // FIXME: null 7662 return IntToPointer; 7663 } 7664 7665 // In general, C pointers are not compatible with ObjC object pointers, 7666 // with two exceptions: 7667 if (isa<PointerType>(RHSType)) { 7668 Kind = CK_CPointerToObjCPointerCast; 7669 7670 // - conversions from 'void*' 7671 if (RHSType->isVoidPointerType()) { 7672 return Compatible; 7673 } 7674 7675 // - conversions to 'Class' from its redefinition type 7676 if (LHSType->isObjCClassType() && 7677 Context.hasSameType(RHSType, 7678 Context.getObjCClassRedefinitionType())) { 7679 return Compatible; 7680 } 7681 7682 return IncompatiblePointer; 7683 } 7684 7685 // Only under strict condition T^ is compatible with an Objective-C pointer. 7686 if (RHSType->isBlockPointerType() && 7687 LHSType->isBlockCompatibleObjCPointerType(Context)) { 7688 if (ConvertRHS) 7689 maybeExtendBlockObject(RHS); 7690 Kind = CK_BlockPointerToObjCPointerCast; 7691 return Compatible; 7692 } 7693 7694 return Incompatible; 7695 } 7696 7697 // Conversions from pointers that are not covered by the above. 7698 if (isa<PointerType>(RHSType)) { 7699 // T* -> _Bool 7700 if (LHSType == Context.BoolTy) { 7701 Kind = CK_PointerToBoolean; 7702 return Compatible; 7703 } 7704 7705 // T* -> int 7706 if (LHSType->isIntegerType()) { 7707 Kind = CK_PointerToIntegral; 7708 return PointerToInt; 7709 } 7710 7711 return Incompatible; 7712 } 7713 7714 // Conversions from Objective-C pointers that are not covered by the above. 7715 if (isa<ObjCObjectPointerType>(RHSType)) { 7716 // T* -> _Bool 7717 if (LHSType == Context.BoolTy) { 7718 Kind = CK_PointerToBoolean; 7719 return Compatible; 7720 } 7721 7722 // T* -> int 7723 if (LHSType->isIntegerType()) { 7724 Kind = CK_PointerToIntegral; 7725 return PointerToInt; 7726 } 7727 7728 return Incompatible; 7729 } 7730 7731 // struct A -> struct B 7732 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 7733 if (Context.typesAreCompatible(LHSType, RHSType)) { 7734 Kind = CK_NoOp; 7735 return Compatible; 7736 } 7737 } 7738 7739 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 7740 Kind = CK_IntToOCLSampler; 7741 return Compatible; 7742 } 7743 7744 return Incompatible; 7745 } 7746 7747 /// \brief Constructs a transparent union from an expression that is 7748 /// used to initialize the transparent union. 7749 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 7750 ExprResult &EResult, QualType UnionType, 7751 FieldDecl *Field) { 7752 // Build an initializer list that designates the appropriate member 7753 // of the transparent union. 7754 Expr *E = EResult.get(); 7755 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 7756 E, SourceLocation()); 7757 Initializer->setType(UnionType); 7758 Initializer->setInitializedFieldInUnion(Field); 7759 7760 // Build a compound literal constructing a value of the transparent 7761 // union type from this initializer list. 7762 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 7763 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 7764 VK_RValue, Initializer, false); 7765 } 7766 7767 Sema::AssignConvertType 7768 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 7769 ExprResult &RHS) { 7770 QualType RHSType = RHS.get()->getType(); 7771 7772 // If the ArgType is a Union type, we want to handle a potential 7773 // transparent_union GCC extension. 7774 const RecordType *UT = ArgType->getAsUnionType(); 7775 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 7776 return Incompatible; 7777 7778 // The field to initialize within the transparent union. 7779 RecordDecl *UD = UT->getDecl(); 7780 FieldDecl *InitField = nullptr; 7781 // It's compatible if the expression matches any of the fields. 7782 for (auto *it : UD->fields()) { 7783 if (it->getType()->isPointerType()) { 7784 // If the transparent union contains a pointer type, we allow: 7785 // 1) void pointer 7786 // 2) null pointer constant 7787 if (RHSType->isPointerType()) 7788 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 7789 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 7790 InitField = it; 7791 break; 7792 } 7793 7794 if (RHS.get()->isNullPointerConstant(Context, 7795 Expr::NPC_ValueDependentIsNull)) { 7796 RHS = ImpCastExprToType(RHS.get(), it->getType(), 7797 CK_NullToPointer); 7798 InitField = it; 7799 break; 7800 } 7801 } 7802 7803 CastKind Kind = CK_Invalid; 7804 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 7805 == Compatible) { 7806 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 7807 InitField = it; 7808 break; 7809 } 7810 } 7811 7812 if (!InitField) 7813 return Incompatible; 7814 7815 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 7816 return Compatible; 7817 } 7818 7819 Sema::AssignConvertType 7820 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 7821 bool Diagnose, 7822 bool DiagnoseCFAudited, 7823 bool ConvertRHS) { 7824 // We need to be able to tell the caller whether we diagnosed a problem, if 7825 // they ask us to issue diagnostics. 7826 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 7827 7828 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 7829 // we can't avoid *all* modifications at the moment, so we need some somewhere 7830 // to put the updated value. 7831 ExprResult LocalRHS = CallerRHS; 7832 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 7833 7834 if (getLangOpts().CPlusPlus) { 7835 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 7836 // C++ 5.17p3: If the left operand is not of class type, the 7837 // expression is implicitly converted (C++ 4) to the 7838 // cv-unqualified type of the left operand. 7839 QualType RHSType = RHS.get()->getType(); 7840 if (Diagnose) { 7841 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7842 AA_Assigning); 7843 } else { 7844 ImplicitConversionSequence ICS = 7845 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7846 /*SuppressUserConversions=*/false, 7847 /*AllowExplicit=*/false, 7848 /*InOverloadResolution=*/false, 7849 /*CStyle=*/false, 7850 /*AllowObjCWritebackConversion=*/false); 7851 if (ICS.isFailure()) 7852 return Incompatible; 7853 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7854 ICS, AA_Assigning); 7855 } 7856 if (RHS.isInvalid()) 7857 return Incompatible; 7858 Sema::AssignConvertType result = Compatible; 7859 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 7860 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 7861 result = IncompatibleObjCWeakRef; 7862 return result; 7863 } 7864 7865 // FIXME: Currently, we fall through and treat C++ classes like C 7866 // structures. 7867 // FIXME: We also fall through for atomics; not sure what should 7868 // happen there, though. 7869 } else if (RHS.get()->getType() == Context.OverloadTy) { 7870 // As a set of extensions to C, we support overloading on functions. These 7871 // functions need to be resolved here. 7872 DeclAccessPair DAP; 7873 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 7874 RHS.get(), LHSType, /*Complain=*/false, DAP)) 7875 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 7876 else 7877 return Incompatible; 7878 } 7879 7880 // C99 6.5.16.1p1: the left operand is a pointer and the right is 7881 // a null pointer constant. 7882 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 7883 LHSType->isBlockPointerType()) && 7884 RHS.get()->isNullPointerConstant(Context, 7885 Expr::NPC_ValueDependentIsNull)) { 7886 if (Diagnose || ConvertRHS) { 7887 CastKind Kind; 7888 CXXCastPath Path; 7889 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 7890 /*IgnoreBaseAccess=*/false, Diagnose); 7891 if (ConvertRHS) 7892 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 7893 } 7894 return Compatible; 7895 } 7896 7897 // This check seems unnatural, however it is necessary to ensure the proper 7898 // conversion of functions/arrays. If the conversion were done for all 7899 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 7900 // expressions that suppress this implicit conversion (&, sizeof). 7901 // 7902 // Suppress this for references: C++ 8.5.3p5. 7903 if (!LHSType->isReferenceType()) { 7904 // FIXME: We potentially allocate here even if ConvertRHS is false. 7905 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 7906 if (RHS.isInvalid()) 7907 return Incompatible; 7908 } 7909 7910 Expr *PRE = RHS.get()->IgnoreParenCasts(); 7911 if (Diagnose && isa<ObjCProtocolExpr>(PRE)) { 7912 ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol(); 7913 if (PDecl && !PDecl->hasDefinition()) { 7914 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName(); 7915 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl; 7916 } 7917 } 7918 7919 CastKind Kind = CK_Invalid; 7920 Sema::AssignConvertType result = 7921 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 7922 7923 // C99 6.5.16.1p2: The value of the right operand is converted to the 7924 // type of the assignment expression. 7925 // CheckAssignmentConstraints allows the left-hand side to be a reference, 7926 // so that we can use references in built-in functions even in C. 7927 // The getNonReferenceType() call makes sure that the resulting expression 7928 // does not have reference type. 7929 if (result != Incompatible && RHS.get()->getType() != LHSType) { 7930 QualType Ty = LHSType.getNonLValueExprType(Context); 7931 Expr *E = RHS.get(); 7932 7933 // Check for various Objective-C errors. If we are not reporting 7934 // diagnostics and just checking for errors, e.g., during overload 7935 // resolution, return Incompatible to indicate the failure. 7936 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 7937 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 7938 Diagnose, DiagnoseCFAudited) != ACR_okay) { 7939 if (!Diagnose) 7940 return Incompatible; 7941 } 7942 if (getLangOpts().ObjC1 && 7943 (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType, 7944 E->getType(), E, Diagnose) || 7945 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 7946 if (!Diagnose) 7947 return Incompatible; 7948 // Replace the expression with a corrected version and continue so we 7949 // can find further errors. 7950 RHS = E; 7951 return Compatible; 7952 } 7953 7954 if (ConvertRHS) 7955 RHS = ImpCastExprToType(E, Ty, Kind); 7956 } 7957 return result; 7958 } 7959 7960 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 7961 ExprResult &RHS) { 7962 Diag(Loc, diag::err_typecheck_invalid_operands) 7963 << LHS.get()->getType() << RHS.get()->getType() 7964 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7965 return QualType(); 7966 } 7967 7968 // Diagnose cases where a scalar was implicitly converted to a vector and 7969 // diagnose the underlying types. Otherwise, diagnose the error 7970 // as invalid vector logical operands for non-C++ cases. 7971 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 7972 ExprResult &RHS) { 7973 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 7974 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 7975 7976 bool LHSNatVec = LHSType->isVectorType(); 7977 bool RHSNatVec = RHSType->isVectorType(); 7978 7979 if (!(LHSNatVec && RHSNatVec)) { 7980 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 7981 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 7982 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 7983 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 7984 << Vector->getSourceRange(); 7985 return QualType(); 7986 } 7987 7988 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 7989 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 7990 << RHS.get()->getSourceRange(); 7991 7992 return QualType(); 7993 } 7994 7995 /// Try to convert a value of non-vector type to a vector type by converting 7996 /// the type to the element type of the vector and then performing a splat. 7997 /// If the language is OpenCL, we only use conversions that promote scalar 7998 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 7999 /// for float->int. 8000 /// 8001 /// OpenCL V2.0 6.2.6.p2: 8002 /// An error shall occur if any scalar operand type has greater rank 8003 /// than the type of the vector element. 8004 /// 8005 /// \param scalar - if non-null, actually perform the conversions 8006 /// \return true if the operation fails (but without diagnosing the failure) 8007 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 8008 QualType scalarTy, 8009 QualType vectorEltTy, 8010 QualType vectorTy, 8011 unsigned &DiagID) { 8012 // The conversion to apply to the scalar before splatting it, 8013 // if necessary. 8014 CastKind scalarCast = CK_Invalid; 8015 8016 if (vectorEltTy->isIntegralType(S.Context)) { 8017 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 8018 (scalarTy->isIntegerType() && 8019 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 8020 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8021 return true; 8022 } 8023 if (!scalarTy->isIntegralType(S.Context)) 8024 return true; 8025 scalarCast = CK_IntegralCast; 8026 } else if (vectorEltTy->isRealFloatingType()) { 8027 if (scalarTy->isRealFloatingType()) { 8028 if (S.getLangOpts().OpenCL && 8029 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 8030 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8031 return true; 8032 } 8033 scalarCast = CK_FloatingCast; 8034 } 8035 else if (scalarTy->isIntegralType(S.Context)) 8036 scalarCast = CK_IntegralToFloating; 8037 else 8038 return true; 8039 } else { 8040 return true; 8041 } 8042 8043 // Adjust scalar if desired. 8044 if (scalar) { 8045 if (scalarCast != CK_Invalid) 8046 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 8047 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 8048 } 8049 return false; 8050 } 8051 8052 /// Test if a (constant) integer Int can be casted to another integer type 8053 /// IntTy without losing precision. 8054 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 8055 QualType OtherIntTy) { 8056 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8057 8058 // Reject cases where the value of the Int is unknown as that would 8059 // possibly cause truncation, but accept cases where the scalar can be 8060 // demoted without loss of precision. 8061 llvm::APSInt Result; 8062 bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context); 8063 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 8064 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 8065 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 8066 8067 if (CstInt) { 8068 // If the scalar is constant and is of a higher order and has more active 8069 // bits that the vector element type, reject it. 8070 unsigned NumBits = IntSigned 8071 ? (Result.isNegative() ? Result.getMinSignedBits() 8072 : Result.getActiveBits()) 8073 : Result.getActiveBits(); 8074 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 8075 return true; 8076 8077 // If the signedness of the scalar type and the vector element type 8078 // differs and the number of bits is greater than that of the vector 8079 // element reject it. 8080 return (IntSigned != OtherIntSigned && 8081 NumBits > S.Context.getIntWidth(OtherIntTy)); 8082 } 8083 8084 // Reject cases where the value of the scalar is not constant and it's 8085 // order is greater than that of the vector element type. 8086 return (Order < 0); 8087 } 8088 8089 /// Test if a (constant) integer Int can be casted to floating point type 8090 /// FloatTy without losing precision. 8091 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 8092 QualType FloatTy) { 8093 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8094 8095 // Determine if the integer constant can be expressed as a floating point 8096 // number of the appropiate type. 8097 llvm::APSInt Result; 8098 bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context); 8099 uint64_t Bits = 0; 8100 if (CstInt) { 8101 // Reject constants that would be truncated if they were converted to 8102 // the floating point type. Test by simple to/from conversion. 8103 // FIXME: Ideally the conversion to an APFloat and from an APFloat 8104 // could be avoided if there was a convertFromAPInt method 8105 // which could signal back if implicit truncation occurred. 8106 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 8107 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 8108 llvm::APFloat::rmTowardZero); 8109 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 8110 !IntTy->hasSignedIntegerRepresentation()); 8111 bool Ignored = false; 8112 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 8113 &Ignored); 8114 if (Result != ConvertBack) 8115 return true; 8116 } else { 8117 // Reject types that cannot be fully encoded into the mantissa of 8118 // the float. 8119 Bits = S.Context.getTypeSize(IntTy); 8120 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 8121 S.Context.getFloatTypeSemantics(FloatTy)); 8122 if (Bits > FloatPrec) 8123 return true; 8124 } 8125 8126 return false; 8127 } 8128 8129 /// Attempt to convert and splat Scalar into a vector whose types matches 8130 /// Vector following GCC conversion rules. The rule is that implicit 8131 /// conversion can occur when Scalar can be casted to match Vector's element 8132 /// type without causing truncation of Scalar. 8133 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 8134 ExprResult *Vector) { 8135 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 8136 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 8137 const VectorType *VT = VectorTy->getAs<VectorType>(); 8138 8139 assert(!isa<ExtVectorType>(VT) && 8140 "ExtVectorTypes should not be handled here!"); 8141 8142 QualType VectorEltTy = VT->getElementType(); 8143 8144 // Reject cases where the vector element type or the scalar element type are 8145 // not integral or floating point types. 8146 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 8147 return true; 8148 8149 // The conversion to apply to the scalar before splatting it, 8150 // if necessary. 8151 CastKind ScalarCast = CK_NoOp; 8152 8153 // Accept cases where the vector elements are integers and the scalar is 8154 // an integer. 8155 // FIXME: Notionally if the scalar was a floating point value with a precise 8156 // integral representation, we could cast it to an appropriate integer 8157 // type and then perform the rest of the checks here. GCC will perform 8158 // this conversion in some cases as determined by the input language. 8159 // We should accept it on a language independent basis. 8160 if (VectorEltTy->isIntegralType(S.Context) && 8161 ScalarTy->isIntegralType(S.Context) && 8162 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 8163 8164 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 8165 return true; 8166 8167 ScalarCast = CK_IntegralCast; 8168 } else if (VectorEltTy->isRealFloatingType()) { 8169 if (ScalarTy->isRealFloatingType()) { 8170 8171 // Reject cases where the scalar type is not a constant and has a higher 8172 // Order than the vector element type. 8173 llvm::APFloat Result(0.0); 8174 bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context); 8175 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 8176 if (!CstScalar && Order < 0) 8177 return true; 8178 8179 // If the scalar cannot be safely casted to the vector element type, 8180 // reject it. 8181 if (CstScalar) { 8182 bool Truncated = false; 8183 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 8184 llvm::APFloat::rmNearestTiesToEven, &Truncated); 8185 if (Truncated) 8186 return true; 8187 } 8188 8189 ScalarCast = CK_FloatingCast; 8190 } else if (ScalarTy->isIntegralType(S.Context)) { 8191 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 8192 return true; 8193 8194 ScalarCast = CK_IntegralToFloating; 8195 } else 8196 return true; 8197 } 8198 8199 // Adjust scalar if desired. 8200 if (Scalar) { 8201 if (ScalarCast != CK_NoOp) 8202 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 8203 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 8204 } 8205 return false; 8206 } 8207 8208 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 8209 SourceLocation Loc, bool IsCompAssign, 8210 bool AllowBothBool, 8211 bool AllowBoolConversions) { 8212 if (!IsCompAssign) { 8213 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 8214 if (LHS.isInvalid()) 8215 return QualType(); 8216 } 8217 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 8218 if (RHS.isInvalid()) 8219 return QualType(); 8220 8221 // For conversion purposes, we ignore any qualifiers. 8222 // For example, "const float" and "float" are equivalent. 8223 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 8224 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 8225 8226 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 8227 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 8228 assert(LHSVecType || RHSVecType); 8229 8230 // AltiVec-style "vector bool op vector bool" combinations are allowed 8231 // for some operators but not others. 8232 if (!AllowBothBool && 8233 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8234 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8235 return InvalidOperands(Loc, LHS, RHS); 8236 8237 // If the vector types are identical, return. 8238 if (Context.hasSameType(LHSType, RHSType)) 8239 return LHSType; 8240 8241 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 8242 if (LHSVecType && RHSVecType && 8243 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8244 if (isa<ExtVectorType>(LHSVecType)) { 8245 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8246 return LHSType; 8247 } 8248 8249 if (!IsCompAssign) 8250 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8251 return RHSType; 8252 } 8253 8254 // AllowBoolConversions says that bool and non-bool AltiVec vectors 8255 // can be mixed, with the result being the non-bool type. The non-bool 8256 // operand must have integer element type. 8257 if (AllowBoolConversions && LHSVecType && RHSVecType && 8258 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 8259 (Context.getTypeSize(LHSVecType->getElementType()) == 8260 Context.getTypeSize(RHSVecType->getElementType()))) { 8261 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 8262 LHSVecType->getElementType()->isIntegerType() && 8263 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 8264 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8265 return LHSType; 8266 } 8267 if (!IsCompAssign && 8268 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8269 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 8270 RHSVecType->getElementType()->isIntegerType()) { 8271 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8272 return RHSType; 8273 } 8274 } 8275 8276 // If there's a vector type and a scalar, try to convert the scalar to 8277 // the vector element type and splat. 8278 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 8279 if (!RHSVecType) { 8280 if (isa<ExtVectorType>(LHSVecType)) { 8281 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 8282 LHSVecType->getElementType(), LHSType, 8283 DiagID)) 8284 return LHSType; 8285 } else { 8286 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 8287 return LHSType; 8288 } 8289 } 8290 if (!LHSVecType) { 8291 if (isa<ExtVectorType>(RHSVecType)) { 8292 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 8293 LHSType, RHSVecType->getElementType(), 8294 RHSType, DiagID)) 8295 return RHSType; 8296 } else { 8297 if (LHS.get()->getValueKind() == VK_LValue || 8298 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 8299 return RHSType; 8300 } 8301 } 8302 8303 // FIXME: The code below also handles conversion between vectors and 8304 // non-scalars, we should break this down into fine grained specific checks 8305 // and emit proper diagnostics. 8306 QualType VecType = LHSVecType ? LHSType : RHSType; 8307 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 8308 QualType OtherType = LHSVecType ? RHSType : LHSType; 8309 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 8310 if (isLaxVectorConversion(OtherType, VecType)) { 8311 // If we're allowing lax vector conversions, only the total (data) size 8312 // needs to be the same. For non compound assignment, if one of the types is 8313 // scalar, the result is always the vector type. 8314 if (!IsCompAssign) { 8315 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 8316 return VecType; 8317 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 8318 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 8319 // type. Note that this is already done by non-compound assignments in 8320 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 8321 // <1 x T> -> T. The result is also a vector type. 8322 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 8323 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 8324 ExprResult *RHSExpr = &RHS; 8325 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 8326 return VecType; 8327 } 8328 } 8329 8330 // Okay, the expression is invalid. 8331 8332 // If there's a non-vector, non-real operand, diagnose that. 8333 if ((!RHSVecType && !RHSType->isRealType()) || 8334 (!LHSVecType && !LHSType->isRealType())) { 8335 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 8336 << LHSType << RHSType 8337 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8338 return QualType(); 8339 } 8340 8341 // OpenCL V1.1 6.2.6.p1: 8342 // If the operands are of more than one vector type, then an error shall 8343 // occur. Implicit conversions between vector types are not permitted, per 8344 // section 6.2.1. 8345 if (getLangOpts().OpenCL && 8346 RHSVecType && isa<ExtVectorType>(RHSVecType) && 8347 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 8348 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 8349 << RHSType; 8350 return QualType(); 8351 } 8352 8353 8354 // If there is a vector type that is not a ExtVector and a scalar, we reach 8355 // this point if scalar could not be converted to the vector's element type 8356 // without truncation. 8357 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 8358 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 8359 QualType Scalar = LHSVecType ? RHSType : LHSType; 8360 QualType Vector = LHSVecType ? LHSType : RHSType; 8361 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 8362 Diag(Loc, 8363 diag::err_typecheck_vector_not_convertable_implict_truncation) 8364 << ScalarOrVector << Scalar << Vector; 8365 8366 return QualType(); 8367 } 8368 8369 // Otherwise, use the generic diagnostic. 8370 Diag(Loc, DiagID) 8371 << LHSType << RHSType 8372 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8373 return QualType(); 8374 } 8375 8376 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 8377 // expression. These are mainly cases where the null pointer is used as an 8378 // integer instead of a pointer. 8379 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 8380 SourceLocation Loc, bool IsCompare) { 8381 // The canonical way to check for a GNU null is with isNullPointerConstant, 8382 // but we use a bit of a hack here for speed; this is a relatively 8383 // hot path, and isNullPointerConstant is slow. 8384 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 8385 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 8386 8387 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 8388 8389 // Avoid analyzing cases where the result will either be invalid (and 8390 // diagnosed as such) or entirely valid and not something to warn about. 8391 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 8392 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 8393 return; 8394 8395 // Comparison operations would not make sense with a null pointer no matter 8396 // what the other expression is. 8397 if (!IsCompare) { 8398 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 8399 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 8400 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 8401 return; 8402 } 8403 8404 // The rest of the operations only make sense with a null pointer 8405 // if the other expression is a pointer. 8406 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 8407 NonNullType->canDecayToPointerType()) 8408 return; 8409 8410 S.Diag(Loc, diag::warn_null_in_comparison_operation) 8411 << LHSNull /* LHS is NULL */ << NonNullType 8412 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8413 } 8414 8415 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 8416 ExprResult &RHS, 8417 SourceLocation Loc, bool IsDiv) { 8418 // Check for division/remainder by zero. 8419 llvm::APSInt RHSValue; 8420 if (!RHS.get()->isValueDependent() && 8421 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0) 8422 S.DiagRuntimeBehavior(Loc, RHS.get(), 8423 S.PDiag(diag::warn_remainder_division_by_zero) 8424 << IsDiv << RHS.get()->getSourceRange()); 8425 } 8426 8427 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 8428 SourceLocation Loc, 8429 bool IsCompAssign, bool IsDiv) { 8430 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8431 8432 if (LHS.get()->getType()->isVectorType() || 8433 RHS.get()->getType()->isVectorType()) 8434 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8435 /*AllowBothBool*/getLangOpts().AltiVec, 8436 /*AllowBoolConversions*/false); 8437 8438 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8439 if (LHS.isInvalid() || RHS.isInvalid()) 8440 return QualType(); 8441 8442 8443 if (compType.isNull() || !compType->isArithmeticType()) 8444 return InvalidOperands(Loc, LHS, RHS); 8445 if (IsDiv) 8446 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 8447 return compType; 8448 } 8449 8450 QualType Sema::CheckRemainderOperands( 8451 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 8452 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8453 8454 if (LHS.get()->getType()->isVectorType() || 8455 RHS.get()->getType()->isVectorType()) { 8456 if (LHS.get()->getType()->hasIntegerRepresentation() && 8457 RHS.get()->getType()->hasIntegerRepresentation()) 8458 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8459 /*AllowBothBool*/getLangOpts().AltiVec, 8460 /*AllowBoolConversions*/false); 8461 return InvalidOperands(Loc, LHS, RHS); 8462 } 8463 8464 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8465 if (LHS.isInvalid() || RHS.isInvalid()) 8466 return QualType(); 8467 8468 if (compType.isNull() || !compType->isIntegerType()) 8469 return InvalidOperands(Loc, LHS, RHS); 8470 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 8471 return compType; 8472 } 8473 8474 /// \brief Diagnose invalid arithmetic on two void pointers. 8475 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 8476 Expr *LHSExpr, Expr *RHSExpr) { 8477 S.Diag(Loc, S.getLangOpts().CPlusPlus 8478 ? diag::err_typecheck_pointer_arith_void_type 8479 : diag::ext_gnu_void_ptr) 8480 << 1 /* two pointers */ << LHSExpr->getSourceRange() 8481 << RHSExpr->getSourceRange(); 8482 } 8483 8484 /// \brief Diagnose invalid arithmetic on a void pointer. 8485 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 8486 Expr *Pointer) { 8487 S.Diag(Loc, S.getLangOpts().CPlusPlus 8488 ? diag::err_typecheck_pointer_arith_void_type 8489 : diag::ext_gnu_void_ptr) 8490 << 0 /* one pointer */ << Pointer->getSourceRange(); 8491 } 8492 8493 /// \brief Diagnose invalid arithmetic on two function pointers. 8494 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 8495 Expr *LHS, Expr *RHS) { 8496 assert(LHS->getType()->isAnyPointerType()); 8497 assert(RHS->getType()->isAnyPointerType()); 8498 S.Diag(Loc, S.getLangOpts().CPlusPlus 8499 ? diag::err_typecheck_pointer_arith_function_type 8500 : diag::ext_gnu_ptr_func_arith) 8501 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 8502 // We only show the second type if it differs from the first. 8503 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 8504 RHS->getType()) 8505 << RHS->getType()->getPointeeType() 8506 << LHS->getSourceRange() << RHS->getSourceRange(); 8507 } 8508 8509 /// \brief Diagnose invalid arithmetic on a function pointer. 8510 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 8511 Expr *Pointer) { 8512 assert(Pointer->getType()->isAnyPointerType()); 8513 S.Diag(Loc, S.getLangOpts().CPlusPlus 8514 ? diag::err_typecheck_pointer_arith_function_type 8515 : diag::ext_gnu_ptr_func_arith) 8516 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 8517 << 0 /* one pointer, so only one type */ 8518 << Pointer->getSourceRange(); 8519 } 8520 8521 /// \brief Emit error if Operand is incomplete pointer type 8522 /// 8523 /// \returns True if pointer has incomplete type 8524 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 8525 Expr *Operand) { 8526 QualType ResType = Operand->getType(); 8527 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8528 ResType = ResAtomicType->getValueType(); 8529 8530 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 8531 QualType PointeeTy = ResType->getPointeeType(); 8532 return S.RequireCompleteType(Loc, PointeeTy, 8533 diag::err_typecheck_arithmetic_incomplete_type, 8534 PointeeTy, Operand->getSourceRange()); 8535 } 8536 8537 /// \brief Check the validity of an arithmetic pointer operand. 8538 /// 8539 /// If the operand has pointer type, this code will check for pointer types 8540 /// which are invalid in arithmetic operations. These will be diagnosed 8541 /// appropriately, including whether or not the use is supported as an 8542 /// extension. 8543 /// 8544 /// \returns True when the operand is valid to use (even if as an extension). 8545 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 8546 Expr *Operand) { 8547 QualType ResType = Operand->getType(); 8548 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8549 ResType = ResAtomicType->getValueType(); 8550 8551 if (!ResType->isAnyPointerType()) return true; 8552 8553 QualType PointeeTy = ResType->getPointeeType(); 8554 if (PointeeTy->isVoidType()) { 8555 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 8556 return !S.getLangOpts().CPlusPlus; 8557 } 8558 if (PointeeTy->isFunctionType()) { 8559 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 8560 return !S.getLangOpts().CPlusPlus; 8561 } 8562 8563 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 8564 8565 return true; 8566 } 8567 8568 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 8569 /// operands. 8570 /// 8571 /// This routine will diagnose any invalid arithmetic on pointer operands much 8572 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 8573 /// for emitting a single diagnostic even for operations where both LHS and RHS 8574 /// are (potentially problematic) pointers. 8575 /// 8576 /// \returns True when the operand is valid to use (even if as an extension). 8577 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 8578 Expr *LHSExpr, Expr *RHSExpr) { 8579 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 8580 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 8581 if (!isLHSPointer && !isRHSPointer) return true; 8582 8583 QualType LHSPointeeTy, RHSPointeeTy; 8584 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 8585 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 8586 8587 // if both are pointers check if operation is valid wrt address spaces 8588 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 8589 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 8590 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 8591 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 8592 S.Diag(Loc, 8593 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8594 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 8595 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 8596 return false; 8597 } 8598 } 8599 8600 // Check for arithmetic on pointers to incomplete types. 8601 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 8602 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 8603 if (isLHSVoidPtr || isRHSVoidPtr) { 8604 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 8605 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 8606 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 8607 8608 return !S.getLangOpts().CPlusPlus; 8609 } 8610 8611 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 8612 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 8613 if (isLHSFuncPtr || isRHSFuncPtr) { 8614 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 8615 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 8616 RHSExpr); 8617 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 8618 8619 return !S.getLangOpts().CPlusPlus; 8620 } 8621 8622 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 8623 return false; 8624 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 8625 return false; 8626 8627 return true; 8628 } 8629 8630 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 8631 /// literal. 8632 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 8633 Expr *LHSExpr, Expr *RHSExpr) { 8634 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 8635 Expr* IndexExpr = RHSExpr; 8636 if (!StrExpr) { 8637 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 8638 IndexExpr = LHSExpr; 8639 } 8640 8641 bool IsStringPlusInt = StrExpr && 8642 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 8643 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 8644 return; 8645 8646 llvm::APSInt index; 8647 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 8648 unsigned StrLenWithNull = StrExpr->getLength() + 1; 8649 if (index.isNonNegative() && 8650 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 8651 index.isUnsigned())) 8652 return; 8653 } 8654 8655 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8656 Self.Diag(OpLoc, diag::warn_string_plus_int) 8657 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 8658 8659 // Only print a fixit for "str" + int, not for int + "str". 8660 if (IndexExpr == RHSExpr) { 8661 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8662 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8663 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8664 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8665 << FixItHint::CreateInsertion(EndLoc, "]"); 8666 } else 8667 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8668 } 8669 8670 /// \brief Emit a warning when adding a char literal to a string. 8671 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 8672 Expr *LHSExpr, Expr *RHSExpr) { 8673 const Expr *StringRefExpr = LHSExpr; 8674 const CharacterLiteral *CharExpr = 8675 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 8676 8677 if (!CharExpr) { 8678 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 8679 StringRefExpr = RHSExpr; 8680 } 8681 8682 if (!CharExpr || !StringRefExpr) 8683 return; 8684 8685 const QualType StringType = StringRefExpr->getType(); 8686 8687 // Return if not a PointerType. 8688 if (!StringType->isAnyPointerType()) 8689 return; 8690 8691 // Return if not a CharacterType. 8692 if (!StringType->getPointeeType()->isAnyCharacterType()) 8693 return; 8694 8695 ASTContext &Ctx = Self.getASTContext(); 8696 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8697 8698 const QualType CharType = CharExpr->getType(); 8699 if (!CharType->isAnyCharacterType() && 8700 CharType->isIntegerType() && 8701 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 8702 Self.Diag(OpLoc, diag::warn_string_plus_char) 8703 << DiagRange << Ctx.CharTy; 8704 } else { 8705 Self.Diag(OpLoc, diag::warn_string_plus_char) 8706 << DiagRange << CharExpr->getType(); 8707 } 8708 8709 // Only print a fixit for str + char, not for char + str. 8710 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 8711 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8712 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8713 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8714 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8715 << FixItHint::CreateInsertion(EndLoc, "]"); 8716 } else { 8717 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8718 } 8719 } 8720 8721 /// \brief Emit error when two pointers are incompatible. 8722 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 8723 Expr *LHSExpr, Expr *RHSExpr) { 8724 assert(LHSExpr->getType()->isAnyPointerType()); 8725 assert(RHSExpr->getType()->isAnyPointerType()); 8726 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 8727 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 8728 << RHSExpr->getSourceRange(); 8729 } 8730 8731 // C99 6.5.6 8732 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 8733 SourceLocation Loc, BinaryOperatorKind Opc, 8734 QualType* CompLHSTy) { 8735 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8736 8737 if (LHS.get()->getType()->isVectorType() || 8738 RHS.get()->getType()->isVectorType()) { 8739 QualType compType = CheckVectorOperands( 8740 LHS, RHS, Loc, CompLHSTy, 8741 /*AllowBothBool*/getLangOpts().AltiVec, 8742 /*AllowBoolConversions*/getLangOpts().ZVector); 8743 if (CompLHSTy) *CompLHSTy = compType; 8744 return compType; 8745 } 8746 8747 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8748 if (LHS.isInvalid() || RHS.isInvalid()) 8749 return QualType(); 8750 8751 // Diagnose "string literal" '+' int and string '+' "char literal". 8752 if (Opc == BO_Add) { 8753 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 8754 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 8755 } 8756 8757 // handle the common case first (both operands are arithmetic). 8758 if (!compType.isNull() && compType->isArithmeticType()) { 8759 if (CompLHSTy) *CompLHSTy = compType; 8760 return compType; 8761 } 8762 8763 // Type-checking. Ultimately the pointer's going to be in PExp; 8764 // note that we bias towards the LHS being the pointer. 8765 Expr *PExp = LHS.get(), *IExp = RHS.get(); 8766 8767 bool isObjCPointer; 8768 if (PExp->getType()->isPointerType()) { 8769 isObjCPointer = false; 8770 } else if (PExp->getType()->isObjCObjectPointerType()) { 8771 isObjCPointer = true; 8772 } else { 8773 std::swap(PExp, IExp); 8774 if (PExp->getType()->isPointerType()) { 8775 isObjCPointer = false; 8776 } else if (PExp->getType()->isObjCObjectPointerType()) { 8777 isObjCPointer = true; 8778 } else { 8779 return InvalidOperands(Loc, LHS, RHS); 8780 } 8781 } 8782 assert(PExp->getType()->isAnyPointerType()); 8783 8784 if (!IExp->getType()->isIntegerType()) 8785 return InvalidOperands(Loc, LHS, RHS); 8786 8787 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 8788 return QualType(); 8789 8790 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 8791 return QualType(); 8792 8793 // Check array bounds for pointer arithemtic 8794 CheckArrayAccess(PExp, IExp); 8795 8796 if (CompLHSTy) { 8797 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 8798 if (LHSTy.isNull()) { 8799 LHSTy = LHS.get()->getType(); 8800 if (LHSTy->isPromotableIntegerType()) 8801 LHSTy = Context.getPromotedIntegerType(LHSTy); 8802 } 8803 *CompLHSTy = LHSTy; 8804 } 8805 8806 return PExp->getType(); 8807 } 8808 8809 // C99 6.5.6 8810 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 8811 SourceLocation Loc, 8812 QualType* CompLHSTy) { 8813 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8814 8815 if (LHS.get()->getType()->isVectorType() || 8816 RHS.get()->getType()->isVectorType()) { 8817 QualType compType = CheckVectorOperands( 8818 LHS, RHS, Loc, CompLHSTy, 8819 /*AllowBothBool*/getLangOpts().AltiVec, 8820 /*AllowBoolConversions*/getLangOpts().ZVector); 8821 if (CompLHSTy) *CompLHSTy = compType; 8822 return compType; 8823 } 8824 8825 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8826 if (LHS.isInvalid() || RHS.isInvalid()) 8827 return QualType(); 8828 8829 // Enforce type constraints: C99 6.5.6p3. 8830 8831 // Handle the common case first (both operands are arithmetic). 8832 if (!compType.isNull() && compType->isArithmeticType()) { 8833 if (CompLHSTy) *CompLHSTy = compType; 8834 return compType; 8835 } 8836 8837 // Either ptr - int or ptr - ptr. 8838 if (LHS.get()->getType()->isAnyPointerType()) { 8839 QualType lpointee = LHS.get()->getType()->getPointeeType(); 8840 8841 // Diagnose bad cases where we step over interface counts. 8842 if (LHS.get()->getType()->isObjCObjectPointerType() && 8843 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 8844 return QualType(); 8845 8846 // The result type of a pointer-int computation is the pointer type. 8847 if (RHS.get()->getType()->isIntegerType()) { 8848 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 8849 return QualType(); 8850 8851 // Check array bounds for pointer arithemtic 8852 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 8853 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 8854 8855 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8856 return LHS.get()->getType(); 8857 } 8858 8859 // Handle pointer-pointer subtractions. 8860 if (const PointerType *RHSPTy 8861 = RHS.get()->getType()->getAs<PointerType>()) { 8862 QualType rpointee = RHSPTy->getPointeeType(); 8863 8864 if (getLangOpts().CPlusPlus) { 8865 // Pointee types must be the same: C++ [expr.add] 8866 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 8867 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8868 } 8869 } else { 8870 // Pointee types must be compatible C99 6.5.6p3 8871 if (!Context.typesAreCompatible( 8872 Context.getCanonicalType(lpointee).getUnqualifiedType(), 8873 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 8874 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8875 return QualType(); 8876 } 8877 } 8878 8879 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 8880 LHS.get(), RHS.get())) 8881 return QualType(); 8882 8883 // The pointee type may have zero size. As an extension, a structure or 8884 // union may have zero size or an array may have zero length. In this 8885 // case subtraction does not make sense. 8886 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 8887 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 8888 if (ElementSize.isZero()) { 8889 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 8890 << rpointee.getUnqualifiedType() 8891 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8892 } 8893 } 8894 8895 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8896 return Context.getPointerDiffType(); 8897 } 8898 } 8899 8900 return InvalidOperands(Loc, LHS, RHS); 8901 } 8902 8903 static bool isScopedEnumerationType(QualType T) { 8904 if (const EnumType *ET = T->getAs<EnumType>()) 8905 return ET->getDecl()->isScoped(); 8906 return false; 8907 } 8908 8909 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 8910 SourceLocation Loc, BinaryOperatorKind Opc, 8911 QualType LHSType) { 8912 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 8913 // so skip remaining warnings as we don't want to modify values within Sema. 8914 if (S.getLangOpts().OpenCL) 8915 return; 8916 8917 llvm::APSInt Right; 8918 // Check right/shifter operand 8919 if (RHS.get()->isValueDependent() || 8920 !RHS.get()->EvaluateAsInt(Right, S.Context)) 8921 return; 8922 8923 if (Right.isNegative()) { 8924 S.DiagRuntimeBehavior(Loc, RHS.get(), 8925 S.PDiag(diag::warn_shift_negative) 8926 << RHS.get()->getSourceRange()); 8927 return; 8928 } 8929 llvm::APInt LeftBits(Right.getBitWidth(), 8930 S.Context.getTypeSize(LHS.get()->getType())); 8931 if (Right.uge(LeftBits)) { 8932 S.DiagRuntimeBehavior(Loc, RHS.get(), 8933 S.PDiag(diag::warn_shift_gt_typewidth) 8934 << RHS.get()->getSourceRange()); 8935 return; 8936 } 8937 if (Opc != BO_Shl) 8938 return; 8939 8940 // When left shifting an ICE which is signed, we can check for overflow which 8941 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 8942 // integers have defined behavior modulo one more than the maximum value 8943 // representable in the result type, so never warn for those. 8944 llvm::APSInt Left; 8945 if (LHS.get()->isValueDependent() || 8946 LHSType->hasUnsignedIntegerRepresentation() || 8947 !LHS.get()->EvaluateAsInt(Left, S.Context)) 8948 return; 8949 8950 // If LHS does not have a signed type and non-negative value 8951 // then, the behavior is undefined. Warn about it. 8952 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) { 8953 S.DiagRuntimeBehavior(Loc, LHS.get(), 8954 S.PDiag(diag::warn_shift_lhs_negative) 8955 << LHS.get()->getSourceRange()); 8956 return; 8957 } 8958 8959 llvm::APInt ResultBits = 8960 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 8961 if (LeftBits.uge(ResultBits)) 8962 return; 8963 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 8964 Result = Result.shl(Right); 8965 8966 // Print the bit representation of the signed integer as an unsigned 8967 // hexadecimal number. 8968 SmallString<40> HexResult; 8969 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 8970 8971 // If we are only missing a sign bit, this is less likely to result in actual 8972 // bugs -- if the result is cast back to an unsigned type, it will have the 8973 // expected value. Thus we place this behind a different warning that can be 8974 // turned off separately if needed. 8975 if (LeftBits == ResultBits - 1) { 8976 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 8977 << HexResult << LHSType 8978 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8979 return; 8980 } 8981 8982 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 8983 << HexResult.str() << Result.getMinSignedBits() << LHSType 8984 << Left.getBitWidth() << LHS.get()->getSourceRange() 8985 << RHS.get()->getSourceRange(); 8986 } 8987 8988 /// \brief Return the resulting type when a vector is shifted 8989 /// by a scalar or vector shift amount. 8990 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 8991 SourceLocation Loc, bool IsCompAssign) { 8992 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 8993 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 8994 !LHS.get()->getType()->isVectorType()) { 8995 S.Diag(Loc, diag::err_shift_rhs_only_vector) 8996 << RHS.get()->getType() << LHS.get()->getType() 8997 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8998 return QualType(); 8999 } 9000 9001 if (!IsCompAssign) { 9002 LHS = S.UsualUnaryConversions(LHS.get()); 9003 if (LHS.isInvalid()) return QualType(); 9004 } 9005 9006 RHS = S.UsualUnaryConversions(RHS.get()); 9007 if (RHS.isInvalid()) return QualType(); 9008 9009 QualType LHSType = LHS.get()->getType(); 9010 // Note that LHS might be a scalar because the routine calls not only in 9011 // OpenCL case. 9012 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 9013 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 9014 9015 // Note that RHS might not be a vector. 9016 QualType RHSType = RHS.get()->getType(); 9017 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 9018 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 9019 9020 // The operands need to be integers. 9021 if (!LHSEleType->isIntegerType()) { 9022 S.Diag(Loc, diag::err_typecheck_expect_int) 9023 << LHS.get()->getType() << LHS.get()->getSourceRange(); 9024 return QualType(); 9025 } 9026 9027 if (!RHSEleType->isIntegerType()) { 9028 S.Diag(Loc, diag::err_typecheck_expect_int) 9029 << RHS.get()->getType() << RHS.get()->getSourceRange(); 9030 return QualType(); 9031 } 9032 9033 if (!LHSVecTy) { 9034 assert(RHSVecTy); 9035 if (IsCompAssign) 9036 return RHSType; 9037 if (LHSEleType != RHSEleType) { 9038 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 9039 LHSEleType = RHSEleType; 9040 } 9041 QualType VecTy = 9042 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 9043 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 9044 LHSType = VecTy; 9045 } else if (RHSVecTy) { 9046 // OpenCL v1.1 s6.3.j says that for vector types, the operators 9047 // are applied component-wise. So if RHS is a vector, then ensure 9048 // that the number of elements is the same as LHS... 9049 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 9050 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 9051 << LHS.get()->getType() << RHS.get()->getType() 9052 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9053 return QualType(); 9054 } 9055 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 9056 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 9057 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 9058 if (LHSBT != RHSBT && 9059 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 9060 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 9061 << LHS.get()->getType() << RHS.get()->getType() 9062 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9063 } 9064 } 9065 } else { 9066 // ...else expand RHS to match the number of elements in LHS. 9067 QualType VecTy = 9068 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 9069 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 9070 } 9071 9072 return LHSType; 9073 } 9074 9075 // C99 6.5.7 9076 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 9077 SourceLocation Loc, BinaryOperatorKind Opc, 9078 bool IsCompAssign) { 9079 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9080 9081 // Vector shifts promote their scalar inputs to vector type. 9082 if (LHS.get()->getType()->isVectorType() || 9083 RHS.get()->getType()->isVectorType()) { 9084 if (LangOpts.ZVector) { 9085 // The shift operators for the z vector extensions work basically 9086 // like general shifts, except that neither the LHS nor the RHS is 9087 // allowed to be a "vector bool". 9088 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 9089 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 9090 return InvalidOperands(Loc, LHS, RHS); 9091 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 9092 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9093 return InvalidOperands(Loc, LHS, RHS); 9094 } 9095 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 9096 } 9097 9098 // Shifts don't perform usual arithmetic conversions, they just do integer 9099 // promotions on each operand. C99 6.5.7p3 9100 9101 // For the LHS, do usual unary conversions, but then reset them away 9102 // if this is a compound assignment. 9103 ExprResult OldLHS = LHS; 9104 LHS = UsualUnaryConversions(LHS.get()); 9105 if (LHS.isInvalid()) 9106 return QualType(); 9107 QualType LHSType = LHS.get()->getType(); 9108 if (IsCompAssign) LHS = OldLHS; 9109 9110 // The RHS is simpler. 9111 RHS = UsualUnaryConversions(RHS.get()); 9112 if (RHS.isInvalid()) 9113 return QualType(); 9114 QualType RHSType = RHS.get()->getType(); 9115 9116 // C99 6.5.7p2: Each of the operands shall have integer type. 9117 if (!LHSType->hasIntegerRepresentation() || 9118 !RHSType->hasIntegerRepresentation()) 9119 return InvalidOperands(Loc, LHS, RHS); 9120 9121 // C++0x: Don't allow scoped enums. FIXME: Use something better than 9122 // hasIntegerRepresentation() above instead of this. 9123 if (isScopedEnumerationType(LHSType) || 9124 isScopedEnumerationType(RHSType)) { 9125 return InvalidOperands(Loc, LHS, RHS); 9126 } 9127 // Sanity-check shift operands 9128 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 9129 9130 // "The type of the result is that of the promoted left operand." 9131 return LHSType; 9132 } 9133 9134 static bool IsWithinTemplateSpecialization(Decl *D) { 9135 if (DeclContext *DC = D->getDeclContext()) { 9136 if (isa<ClassTemplateSpecializationDecl>(DC)) 9137 return true; 9138 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 9139 return FD->isFunctionTemplateSpecialization(); 9140 } 9141 return false; 9142 } 9143 9144 /// If two different enums are compared, raise a warning. 9145 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 9146 Expr *RHS) { 9147 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 9148 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 9149 9150 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 9151 if (!LHSEnumType) 9152 return; 9153 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 9154 if (!RHSEnumType) 9155 return; 9156 9157 // Ignore anonymous enums. 9158 if (!LHSEnumType->getDecl()->getIdentifier()) 9159 return; 9160 if (!RHSEnumType->getDecl()->getIdentifier()) 9161 return; 9162 9163 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 9164 return; 9165 9166 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 9167 << LHSStrippedType << RHSStrippedType 9168 << LHS->getSourceRange() << RHS->getSourceRange(); 9169 } 9170 9171 /// \brief Diagnose bad pointer comparisons. 9172 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 9173 ExprResult &LHS, ExprResult &RHS, 9174 bool IsError) { 9175 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 9176 : diag::ext_typecheck_comparison_of_distinct_pointers) 9177 << LHS.get()->getType() << RHS.get()->getType() 9178 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9179 } 9180 9181 /// \brief Returns false if the pointers are converted to a composite type, 9182 /// true otherwise. 9183 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 9184 ExprResult &LHS, ExprResult &RHS) { 9185 // C++ [expr.rel]p2: 9186 // [...] Pointer conversions (4.10) and qualification 9187 // conversions (4.4) are performed on pointer operands (or on 9188 // a pointer operand and a null pointer constant) to bring 9189 // them to their composite pointer type. [...] 9190 // 9191 // C++ [expr.eq]p1 uses the same notion for (in)equality 9192 // comparisons of pointers. 9193 9194 QualType LHSType = LHS.get()->getType(); 9195 QualType RHSType = RHS.get()->getType(); 9196 assert(LHSType->isPointerType() || RHSType->isPointerType() || 9197 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 9198 9199 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 9200 if (T.isNull()) { 9201 if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) && 9202 (RHSType->isPointerType() || RHSType->isMemberPointerType())) 9203 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 9204 else 9205 S.InvalidOperands(Loc, LHS, RHS); 9206 return true; 9207 } 9208 9209 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 9210 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 9211 return false; 9212 } 9213 9214 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 9215 ExprResult &LHS, 9216 ExprResult &RHS, 9217 bool IsError) { 9218 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 9219 : diag::ext_typecheck_comparison_of_fptr_to_void) 9220 << LHS.get()->getType() << RHS.get()->getType() 9221 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9222 } 9223 9224 static bool isObjCObjectLiteral(ExprResult &E) { 9225 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 9226 case Stmt::ObjCArrayLiteralClass: 9227 case Stmt::ObjCDictionaryLiteralClass: 9228 case Stmt::ObjCStringLiteralClass: 9229 case Stmt::ObjCBoxedExprClass: 9230 return true; 9231 default: 9232 // Note that ObjCBoolLiteral is NOT an object literal! 9233 return false; 9234 } 9235 } 9236 9237 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 9238 const ObjCObjectPointerType *Type = 9239 LHS->getType()->getAs<ObjCObjectPointerType>(); 9240 9241 // If this is not actually an Objective-C object, bail out. 9242 if (!Type) 9243 return false; 9244 9245 // Get the LHS object's interface type. 9246 QualType InterfaceType = Type->getPointeeType(); 9247 9248 // If the RHS isn't an Objective-C object, bail out. 9249 if (!RHS->getType()->isObjCObjectPointerType()) 9250 return false; 9251 9252 // Try to find the -isEqual: method. 9253 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 9254 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 9255 InterfaceType, 9256 /*instance=*/true); 9257 if (!Method) { 9258 if (Type->isObjCIdType()) { 9259 // For 'id', just check the global pool. 9260 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 9261 /*receiverId=*/true); 9262 } else { 9263 // Check protocols. 9264 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 9265 /*instance=*/true); 9266 } 9267 } 9268 9269 if (!Method) 9270 return false; 9271 9272 QualType T = Method->parameters()[0]->getType(); 9273 if (!T->isObjCObjectPointerType()) 9274 return false; 9275 9276 QualType R = Method->getReturnType(); 9277 if (!R->isScalarType()) 9278 return false; 9279 9280 return true; 9281 } 9282 9283 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 9284 FromE = FromE->IgnoreParenImpCasts(); 9285 switch (FromE->getStmtClass()) { 9286 default: 9287 break; 9288 case Stmt::ObjCStringLiteralClass: 9289 // "string literal" 9290 return LK_String; 9291 case Stmt::ObjCArrayLiteralClass: 9292 // "array literal" 9293 return LK_Array; 9294 case Stmt::ObjCDictionaryLiteralClass: 9295 // "dictionary literal" 9296 return LK_Dictionary; 9297 case Stmt::BlockExprClass: 9298 return LK_Block; 9299 case Stmt::ObjCBoxedExprClass: { 9300 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 9301 switch (Inner->getStmtClass()) { 9302 case Stmt::IntegerLiteralClass: 9303 case Stmt::FloatingLiteralClass: 9304 case Stmt::CharacterLiteralClass: 9305 case Stmt::ObjCBoolLiteralExprClass: 9306 case Stmt::CXXBoolLiteralExprClass: 9307 // "numeric literal" 9308 return LK_Numeric; 9309 case Stmt::ImplicitCastExprClass: { 9310 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 9311 // Boolean literals can be represented by implicit casts. 9312 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 9313 return LK_Numeric; 9314 break; 9315 } 9316 default: 9317 break; 9318 } 9319 return LK_Boxed; 9320 } 9321 } 9322 return LK_None; 9323 } 9324 9325 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 9326 ExprResult &LHS, ExprResult &RHS, 9327 BinaryOperator::Opcode Opc){ 9328 Expr *Literal; 9329 Expr *Other; 9330 if (isObjCObjectLiteral(LHS)) { 9331 Literal = LHS.get(); 9332 Other = RHS.get(); 9333 } else { 9334 Literal = RHS.get(); 9335 Other = LHS.get(); 9336 } 9337 9338 // Don't warn on comparisons against nil. 9339 Other = Other->IgnoreParenCasts(); 9340 if (Other->isNullPointerConstant(S.getASTContext(), 9341 Expr::NPC_ValueDependentIsNotNull)) 9342 return; 9343 9344 // This should be kept in sync with warn_objc_literal_comparison. 9345 // LK_String should always be after the other literals, since it has its own 9346 // warning flag. 9347 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 9348 assert(LiteralKind != Sema::LK_Block); 9349 if (LiteralKind == Sema::LK_None) { 9350 llvm_unreachable("Unknown Objective-C object literal kind"); 9351 } 9352 9353 if (LiteralKind == Sema::LK_String) 9354 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 9355 << Literal->getSourceRange(); 9356 else 9357 S.Diag(Loc, diag::warn_objc_literal_comparison) 9358 << LiteralKind << Literal->getSourceRange(); 9359 9360 if (BinaryOperator::isEqualityOp(Opc) && 9361 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 9362 SourceLocation Start = LHS.get()->getLocStart(); 9363 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd()); 9364 CharSourceRange OpRange = 9365 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 9366 9367 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 9368 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 9369 << FixItHint::CreateReplacement(OpRange, " isEqual:") 9370 << FixItHint::CreateInsertion(End, "]"); 9371 } 9372 } 9373 9374 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 9375 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 9376 ExprResult &RHS, SourceLocation Loc, 9377 BinaryOperatorKind Opc) { 9378 // Check that left hand side is !something. 9379 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 9380 if (!UO || UO->getOpcode() != UO_LNot) return; 9381 9382 // Only check if the right hand side is non-bool arithmetic type. 9383 if (RHS.get()->isKnownToHaveBooleanValue()) return; 9384 9385 // Make sure that the something in !something is not bool. 9386 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 9387 if (SubExpr->isKnownToHaveBooleanValue()) return; 9388 9389 // Emit warning. 9390 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 9391 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 9392 << Loc << IsBitwiseOp; 9393 9394 // First note suggest !(x < y) 9395 SourceLocation FirstOpen = SubExpr->getLocStart(); 9396 SourceLocation FirstClose = RHS.get()->getLocEnd(); 9397 FirstClose = S.getLocForEndOfToken(FirstClose); 9398 if (FirstClose.isInvalid()) 9399 FirstOpen = SourceLocation(); 9400 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 9401 << IsBitwiseOp 9402 << FixItHint::CreateInsertion(FirstOpen, "(") 9403 << FixItHint::CreateInsertion(FirstClose, ")"); 9404 9405 // Second note suggests (!x) < y 9406 SourceLocation SecondOpen = LHS.get()->getLocStart(); 9407 SourceLocation SecondClose = LHS.get()->getLocEnd(); 9408 SecondClose = S.getLocForEndOfToken(SecondClose); 9409 if (SecondClose.isInvalid()) 9410 SecondOpen = SourceLocation(); 9411 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 9412 << FixItHint::CreateInsertion(SecondOpen, "(") 9413 << FixItHint::CreateInsertion(SecondClose, ")"); 9414 } 9415 9416 // Get the decl for a simple expression: a reference to a variable, 9417 // an implicit C++ field reference, or an implicit ObjC ivar reference. 9418 static ValueDecl *getCompareDecl(Expr *E) { 9419 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E)) 9420 return DR->getDecl(); 9421 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 9422 if (Ivar->isFreeIvar()) 9423 return Ivar->getDecl(); 9424 } 9425 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) { 9426 if (Mem->isImplicitAccess()) 9427 return Mem->getMemberDecl(); 9428 } 9429 return nullptr; 9430 } 9431 9432 // C99 6.5.8, C++ [expr.rel] 9433 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 9434 SourceLocation Loc, BinaryOperatorKind Opc, 9435 bool IsRelational) { 9436 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 9437 9438 // Handle vector comparisons separately. 9439 if (LHS.get()->getType()->isVectorType() || 9440 RHS.get()->getType()->isVectorType()) 9441 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 9442 9443 QualType LHSType = LHS.get()->getType(); 9444 QualType RHSType = RHS.get()->getType(); 9445 9446 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 9447 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 9448 9449 checkEnumComparison(*this, Loc, LHS.get(), RHS.get()); 9450 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 9451 9452 if (!LHSType->hasFloatingRepresentation() && 9453 !(LHSType->isBlockPointerType() && IsRelational) && 9454 !LHS.get()->getLocStart().isMacroID() && 9455 !RHS.get()->getLocStart().isMacroID() && 9456 !inTemplateInstantiation()) { 9457 // For non-floating point types, check for self-comparisons of the form 9458 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9459 // often indicate logic errors in the program. 9460 // 9461 // NOTE: Don't warn about comparison expressions resulting from macro 9462 // expansion. Also don't warn about comparisons which are only self 9463 // comparisons within a template specialization. The warnings should catch 9464 // obvious cases in the definition of the template anyways. The idea is to 9465 // warn when the typed comparison operator will always evaluate to the same 9466 // result. 9467 ValueDecl *DL = getCompareDecl(LHSStripped); 9468 ValueDecl *DR = getCompareDecl(RHSStripped); 9469 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) { 9470 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 9471 << 0 // self- 9472 << (Opc == BO_EQ 9473 || Opc == BO_LE 9474 || Opc == BO_GE)); 9475 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() && 9476 !DL->getType()->isReferenceType() && 9477 !DR->getType()->isReferenceType()) { 9478 // what is it always going to eval to? 9479 char always_evals_to; 9480 switch(Opc) { 9481 case BO_EQ: // e.g. array1 == array2 9482 always_evals_to = 0; // false 9483 break; 9484 case BO_NE: // e.g. array1 != array2 9485 always_evals_to = 1; // true 9486 break; 9487 default: 9488 // best we can say is 'a constant' 9489 always_evals_to = 2; // e.g. array1 <= array2 9490 break; 9491 } 9492 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 9493 << 1 // array 9494 << always_evals_to); 9495 } 9496 9497 if (isa<CastExpr>(LHSStripped)) 9498 LHSStripped = LHSStripped->IgnoreParenCasts(); 9499 if (isa<CastExpr>(RHSStripped)) 9500 RHSStripped = RHSStripped->IgnoreParenCasts(); 9501 9502 // Warn about comparisons against a string constant (unless the other 9503 // operand is null), the user probably wants strcmp. 9504 Expr *literalString = nullptr; 9505 Expr *literalStringStripped = nullptr; 9506 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 9507 !RHSStripped->isNullPointerConstant(Context, 9508 Expr::NPC_ValueDependentIsNull)) { 9509 literalString = LHS.get(); 9510 literalStringStripped = LHSStripped; 9511 } else if ((isa<StringLiteral>(RHSStripped) || 9512 isa<ObjCEncodeExpr>(RHSStripped)) && 9513 !LHSStripped->isNullPointerConstant(Context, 9514 Expr::NPC_ValueDependentIsNull)) { 9515 literalString = RHS.get(); 9516 literalStringStripped = RHSStripped; 9517 } 9518 9519 if (literalString) { 9520 DiagRuntimeBehavior(Loc, nullptr, 9521 PDiag(diag::warn_stringcompare) 9522 << isa<ObjCEncodeExpr>(literalStringStripped) 9523 << literalString->getSourceRange()); 9524 } 9525 } 9526 9527 // C99 6.5.8p3 / C99 6.5.9p4 9528 UsualArithmeticConversions(LHS, RHS); 9529 if (LHS.isInvalid() || RHS.isInvalid()) 9530 return QualType(); 9531 9532 LHSType = LHS.get()->getType(); 9533 RHSType = RHS.get()->getType(); 9534 9535 // The result of comparisons is 'bool' in C++, 'int' in C. 9536 QualType ResultTy = Context.getLogicalOperationType(); 9537 9538 if (IsRelational) { 9539 if (LHSType->isRealType() && RHSType->isRealType()) 9540 return ResultTy; 9541 } else { 9542 // Check for comparisons of floating point operands using != and ==. 9543 if (LHSType->hasFloatingRepresentation()) 9544 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9545 9546 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 9547 return ResultTy; 9548 } 9549 9550 const Expr::NullPointerConstantKind LHSNullKind = 9551 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9552 const Expr::NullPointerConstantKind RHSNullKind = 9553 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9554 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 9555 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 9556 9557 if (!IsRelational && LHSIsNull != RHSIsNull) { 9558 bool IsEquality = Opc == BO_EQ; 9559 if (RHSIsNull) 9560 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 9561 RHS.get()->getSourceRange()); 9562 else 9563 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 9564 LHS.get()->getSourceRange()); 9565 } 9566 9567 if ((LHSType->isIntegerType() && !LHSIsNull) || 9568 (RHSType->isIntegerType() && !RHSIsNull)) { 9569 // Skip normal pointer conversion checks in this case; we have better 9570 // diagnostics for this below. 9571 } else if (getLangOpts().CPlusPlus) { 9572 // Equality comparison of a function pointer to a void pointer is invalid, 9573 // but we allow it as an extension. 9574 // FIXME: If we really want to allow this, should it be part of composite 9575 // pointer type computation so it works in conditionals too? 9576 if (!IsRelational && 9577 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 9578 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 9579 // This is a gcc extension compatibility comparison. 9580 // In a SFINAE context, we treat this as a hard error to maintain 9581 // conformance with the C++ standard. 9582 diagnoseFunctionPointerToVoidComparison( 9583 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 9584 9585 if (isSFINAEContext()) 9586 return QualType(); 9587 9588 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9589 return ResultTy; 9590 } 9591 9592 // C++ [expr.eq]p2: 9593 // If at least one operand is a pointer [...] bring them to their 9594 // composite pointer type. 9595 // C++ [expr.rel]p2: 9596 // If both operands are pointers, [...] bring them to their composite 9597 // pointer type. 9598 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 9599 (IsRelational ? 2 : 1) && 9600 (!LangOpts.ObjCAutoRefCount || 9601 !(LHSType->isObjCObjectPointerType() || 9602 RHSType->isObjCObjectPointerType()))) { 9603 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9604 return QualType(); 9605 else 9606 return ResultTy; 9607 } 9608 } else if (LHSType->isPointerType() && 9609 RHSType->isPointerType()) { // C99 6.5.8p2 9610 // All of the following pointer-related warnings are GCC extensions, except 9611 // when handling null pointer constants. 9612 QualType LCanPointeeTy = 9613 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9614 QualType RCanPointeeTy = 9615 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9616 9617 // C99 6.5.9p2 and C99 6.5.8p2 9618 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 9619 RCanPointeeTy.getUnqualifiedType())) { 9620 // Valid unless a relational comparison of function pointers 9621 if (IsRelational && LCanPointeeTy->isFunctionType()) { 9622 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 9623 << LHSType << RHSType << LHS.get()->getSourceRange() 9624 << RHS.get()->getSourceRange(); 9625 } 9626 } else if (!IsRelational && 9627 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 9628 // Valid unless comparison between non-null pointer and function pointer 9629 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 9630 && !LHSIsNull && !RHSIsNull) 9631 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 9632 /*isError*/false); 9633 } else { 9634 // Invalid 9635 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 9636 } 9637 if (LCanPointeeTy != RCanPointeeTy) { 9638 // Treat NULL constant as a special case in OpenCL. 9639 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 9640 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 9641 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 9642 Diag(Loc, 9643 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 9644 << LHSType << RHSType << 0 /* comparison */ 9645 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9646 } 9647 } 9648 unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace(); 9649 unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace(); 9650 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 9651 : CK_BitCast; 9652 if (LHSIsNull && !RHSIsNull) 9653 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 9654 else 9655 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 9656 } 9657 return ResultTy; 9658 } 9659 9660 if (getLangOpts().CPlusPlus) { 9661 // C++ [expr.eq]p4: 9662 // Two operands of type std::nullptr_t or one operand of type 9663 // std::nullptr_t and the other a null pointer constant compare equal. 9664 if (!IsRelational && LHSIsNull && RHSIsNull) { 9665 if (LHSType->isNullPtrType()) { 9666 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9667 return ResultTy; 9668 } 9669 if (RHSType->isNullPtrType()) { 9670 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9671 return ResultTy; 9672 } 9673 } 9674 9675 // Comparison of Objective-C pointers and block pointers against nullptr_t. 9676 // These aren't covered by the composite pointer type rules. 9677 if (!IsRelational && RHSType->isNullPtrType() && 9678 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 9679 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9680 return ResultTy; 9681 } 9682 if (!IsRelational && LHSType->isNullPtrType() && 9683 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 9684 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9685 return ResultTy; 9686 } 9687 9688 if (IsRelational && 9689 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 9690 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 9691 // HACK: Relational comparison of nullptr_t against a pointer type is 9692 // invalid per DR583, but we allow it within std::less<> and friends, 9693 // since otherwise common uses of it break. 9694 // FIXME: Consider removing this hack once LWG fixes std::less<> and 9695 // friends to have std::nullptr_t overload candidates. 9696 DeclContext *DC = CurContext; 9697 if (isa<FunctionDecl>(DC)) 9698 DC = DC->getParent(); 9699 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 9700 if (CTSD->isInStdNamespace() && 9701 llvm::StringSwitch<bool>(CTSD->getName()) 9702 .Cases("less", "less_equal", "greater", "greater_equal", true) 9703 .Default(false)) { 9704 if (RHSType->isNullPtrType()) 9705 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9706 else 9707 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9708 return ResultTy; 9709 } 9710 } 9711 } 9712 9713 // C++ [expr.eq]p2: 9714 // If at least one operand is a pointer to member, [...] bring them to 9715 // their composite pointer type. 9716 if (!IsRelational && 9717 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 9718 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9719 return QualType(); 9720 else 9721 return ResultTy; 9722 } 9723 9724 // Handle scoped enumeration types specifically, since they don't promote 9725 // to integers. 9726 if (LHS.get()->getType()->isEnumeralType() && 9727 Context.hasSameUnqualifiedType(LHS.get()->getType(), 9728 RHS.get()->getType())) 9729 return ResultTy; 9730 } 9731 9732 // Handle block pointer types. 9733 if (!IsRelational && LHSType->isBlockPointerType() && 9734 RHSType->isBlockPointerType()) { 9735 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 9736 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 9737 9738 if (!LHSIsNull && !RHSIsNull && 9739 !Context.typesAreCompatible(lpointee, rpointee)) { 9740 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9741 << LHSType << RHSType << LHS.get()->getSourceRange() 9742 << RHS.get()->getSourceRange(); 9743 } 9744 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9745 return ResultTy; 9746 } 9747 9748 // Allow block pointers to be compared with null pointer constants. 9749 if (!IsRelational 9750 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 9751 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 9752 if (!LHSIsNull && !RHSIsNull) { 9753 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 9754 ->getPointeeType()->isVoidType()) 9755 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 9756 ->getPointeeType()->isVoidType()))) 9757 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9758 << LHSType << RHSType << LHS.get()->getSourceRange() 9759 << RHS.get()->getSourceRange(); 9760 } 9761 if (LHSIsNull && !RHSIsNull) 9762 LHS = ImpCastExprToType(LHS.get(), RHSType, 9763 RHSType->isPointerType() ? CK_BitCast 9764 : CK_AnyPointerToBlockPointerCast); 9765 else 9766 RHS = ImpCastExprToType(RHS.get(), LHSType, 9767 LHSType->isPointerType() ? CK_BitCast 9768 : CK_AnyPointerToBlockPointerCast); 9769 return ResultTy; 9770 } 9771 9772 if (LHSType->isObjCObjectPointerType() || 9773 RHSType->isObjCObjectPointerType()) { 9774 const PointerType *LPT = LHSType->getAs<PointerType>(); 9775 const PointerType *RPT = RHSType->getAs<PointerType>(); 9776 if (LPT || RPT) { 9777 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 9778 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 9779 9780 if (!LPtrToVoid && !RPtrToVoid && 9781 !Context.typesAreCompatible(LHSType, RHSType)) { 9782 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9783 /*isError*/false); 9784 } 9785 if (LHSIsNull && !RHSIsNull) { 9786 Expr *E = LHS.get(); 9787 if (getLangOpts().ObjCAutoRefCount) 9788 CheckObjCConversion(SourceRange(), RHSType, E, 9789 CCK_ImplicitConversion); 9790 LHS = ImpCastExprToType(E, RHSType, 9791 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9792 } 9793 else { 9794 Expr *E = RHS.get(); 9795 if (getLangOpts().ObjCAutoRefCount) 9796 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 9797 /*Diagnose=*/true, 9798 /*DiagnoseCFAudited=*/false, Opc); 9799 RHS = ImpCastExprToType(E, LHSType, 9800 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9801 } 9802 return ResultTy; 9803 } 9804 if (LHSType->isObjCObjectPointerType() && 9805 RHSType->isObjCObjectPointerType()) { 9806 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 9807 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9808 /*isError*/false); 9809 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 9810 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 9811 9812 if (LHSIsNull && !RHSIsNull) 9813 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9814 else 9815 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9816 return ResultTy; 9817 } 9818 } 9819 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 9820 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 9821 unsigned DiagID = 0; 9822 bool isError = false; 9823 if (LangOpts.DebuggerSupport) { 9824 // Under a debugger, allow the comparison of pointers to integers, 9825 // since users tend to want to compare addresses. 9826 } else if ((LHSIsNull && LHSType->isIntegerType()) || 9827 (RHSIsNull && RHSType->isIntegerType())) { 9828 if (IsRelational) { 9829 isError = getLangOpts().CPlusPlus; 9830 DiagID = 9831 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 9832 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 9833 } 9834 } else if (getLangOpts().CPlusPlus) { 9835 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 9836 isError = true; 9837 } else if (IsRelational) 9838 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 9839 else 9840 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 9841 9842 if (DiagID) { 9843 Diag(Loc, DiagID) 9844 << LHSType << RHSType << LHS.get()->getSourceRange() 9845 << RHS.get()->getSourceRange(); 9846 if (isError) 9847 return QualType(); 9848 } 9849 9850 if (LHSType->isIntegerType()) 9851 LHS = ImpCastExprToType(LHS.get(), RHSType, 9852 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 9853 else 9854 RHS = ImpCastExprToType(RHS.get(), LHSType, 9855 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 9856 return ResultTy; 9857 } 9858 9859 // Handle block pointers. 9860 if (!IsRelational && RHSIsNull 9861 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 9862 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9863 return ResultTy; 9864 } 9865 if (!IsRelational && LHSIsNull 9866 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 9867 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9868 return ResultTy; 9869 } 9870 9871 if (getLangOpts().OpenCLVersion >= 200) { 9872 if (LHSIsNull && RHSType->isQueueT()) { 9873 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9874 return ResultTy; 9875 } 9876 9877 if (LHSType->isQueueT() && RHSIsNull) { 9878 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9879 return ResultTy; 9880 } 9881 } 9882 9883 return InvalidOperands(Loc, LHS, RHS); 9884 } 9885 9886 // Return a signed ext_vector_type that is of identical size and number of 9887 // elements. For floating point vectors, return an integer type of identical 9888 // size and number of elements. In the non ext_vector_type case, search from 9889 // the largest type to the smallest type to avoid cases where long long == long, 9890 // where long gets picked over long long. 9891 QualType Sema::GetSignedVectorType(QualType V) { 9892 const VectorType *VTy = V->getAs<VectorType>(); 9893 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 9894 9895 if (isa<ExtVectorType>(VTy)) { 9896 if (TypeSize == Context.getTypeSize(Context.CharTy)) 9897 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 9898 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 9899 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 9900 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 9901 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 9902 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 9903 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 9904 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 9905 "Unhandled vector element size in vector compare"); 9906 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 9907 } 9908 9909 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 9910 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 9911 VectorType::GenericVector); 9912 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 9913 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 9914 VectorType::GenericVector); 9915 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 9916 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 9917 VectorType::GenericVector); 9918 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 9919 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 9920 VectorType::GenericVector); 9921 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 9922 "Unhandled vector element size in vector compare"); 9923 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 9924 VectorType::GenericVector); 9925 } 9926 9927 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 9928 /// operates on extended vector types. Instead of producing an IntTy result, 9929 /// like a scalar comparison, a vector comparison produces a vector of integer 9930 /// types. 9931 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 9932 SourceLocation Loc, 9933 bool IsRelational) { 9934 // Check to make sure we're operating on vectors of the same type and width, 9935 // Allowing one side to be a scalar of element type. 9936 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 9937 /*AllowBothBool*/true, 9938 /*AllowBoolConversions*/getLangOpts().ZVector); 9939 if (vType.isNull()) 9940 return vType; 9941 9942 QualType LHSType = LHS.get()->getType(); 9943 9944 // If AltiVec, the comparison results in a numeric type, i.e. 9945 // bool for C++, int for C 9946 if (getLangOpts().AltiVec && 9947 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 9948 return Context.getLogicalOperationType(); 9949 9950 // For non-floating point types, check for self-comparisons of the form 9951 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9952 // often indicate logic errors in the program. 9953 if (!LHSType->hasFloatingRepresentation() && !inTemplateInstantiation()) { 9954 if (DeclRefExpr* DRL 9955 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 9956 if (DeclRefExpr* DRR 9957 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 9958 if (DRL->getDecl() == DRR->getDecl()) 9959 DiagRuntimeBehavior(Loc, nullptr, 9960 PDiag(diag::warn_comparison_always) 9961 << 0 // self- 9962 << 2 // "a constant" 9963 ); 9964 } 9965 9966 // Check for comparisons of floating point operands using != and ==. 9967 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 9968 assert (RHS.get()->getType()->hasFloatingRepresentation()); 9969 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9970 } 9971 9972 // Return a signed type for the vector. 9973 return GetSignedVectorType(vType); 9974 } 9975 9976 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 9977 SourceLocation Loc) { 9978 // Ensure that either both operands are of the same vector type, or 9979 // one operand is of a vector type and the other is of its element type. 9980 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 9981 /*AllowBothBool*/true, 9982 /*AllowBoolConversions*/false); 9983 if (vType.isNull()) 9984 return InvalidOperands(Loc, LHS, RHS); 9985 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 9986 vType->hasFloatingRepresentation()) 9987 return InvalidOperands(Loc, LHS, RHS); 9988 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 9989 // usage of the logical operators && and || with vectors in C. This 9990 // check could be notionally dropped. 9991 if (!getLangOpts().CPlusPlus && 9992 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 9993 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 9994 9995 return GetSignedVectorType(LHS.get()->getType()); 9996 } 9997 9998 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 9999 SourceLocation Loc, 10000 BinaryOperatorKind Opc) { 10001 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 10002 10003 bool IsCompAssign = 10004 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 10005 10006 if (LHS.get()->getType()->isVectorType() || 10007 RHS.get()->getType()->isVectorType()) { 10008 if (LHS.get()->getType()->hasIntegerRepresentation() && 10009 RHS.get()->getType()->hasIntegerRepresentation()) 10010 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10011 /*AllowBothBool*/true, 10012 /*AllowBoolConversions*/getLangOpts().ZVector); 10013 return InvalidOperands(Loc, LHS, RHS); 10014 } 10015 10016 if (Opc == BO_And) 10017 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 10018 10019 ExprResult LHSResult = LHS, RHSResult = RHS; 10020 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 10021 IsCompAssign); 10022 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 10023 return QualType(); 10024 LHS = LHSResult.get(); 10025 RHS = RHSResult.get(); 10026 10027 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 10028 return compType; 10029 return InvalidOperands(Loc, LHS, RHS); 10030 } 10031 10032 // C99 6.5.[13,14] 10033 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 10034 SourceLocation Loc, 10035 BinaryOperatorKind Opc) { 10036 // Check vector operands differently. 10037 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 10038 return CheckVectorLogicalOperands(LHS, RHS, Loc); 10039 10040 // Diagnose cases where the user write a logical and/or but probably meant a 10041 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 10042 // is a constant. 10043 if (LHS.get()->getType()->isIntegerType() && 10044 !LHS.get()->getType()->isBooleanType() && 10045 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 10046 // Don't warn in macros or template instantiations. 10047 !Loc.isMacroID() && !inTemplateInstantiation()) { 10048 // If the RHS can be constant folded, and if it constant folds to something 10049 // that isn't 0 or 1 (which indicate a potential logical operation that 10050 // happened to fold to true/false) then warn. 10051 // Parens on the RHS are ignored. 10052 llvm::APSInt Result; 10053 if (RHS.get()->EvaluateAsInt(Result, Context)) 10054 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 10055 !RHS.get()->getExprLoc().isMacroID()) || 10056 (Result != 0 && Result != 1)) { 10057 Diag(Loc, diag::warn_logical_instead_of_bitwise) 10058 << RHS.get()->getSourceRange() 10059 << (Opc == BO_LAnd ? "&&" : "||"); 10060 // Suggest replacing the logical operator with the bitwise version 10061 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 10062 << (Opc == BO_LAnd ? "&" : "|") 10063 << FixItHint::CreateReplacement(SourceRange( 10064 Loc, getLocForEndOfToken(Loc)), 10065 Opc == BO_LAnd ? "&" : "|"); 10066 if (Opc == BO_LAnd) 10067 // Suggest replacing "Foo() && kNonZero" with "Foo()" 10068 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 10069 << FixItHint::CreateRemoval( 10070 SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()), 10071 RHS.get()->getLocEnd())); 10072 } 10073 } 10074 10075 if (!Context.getLangOpts().CPlusPlus) { 10076 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 10077 // not operate on the built-in scalar and vector float types. 10078 if (Context.getLangOpts().OpenCL && 10079 Context.getLangOpts().OpenCLVersion < 120) { 10080 if (LHS.get()->getType()->isFloatingType() || 10081 RHS.get()->getType()->isFloatingType()) 10082 return InvalidOperands(Loc, LHS, RHS); 10083 } 10084 10085 LHS = UsualUnaryConversions(LHS.get()); 10086 if (LHS.isInvalid()) 10087 return QualType(); 10088 10089 RHS = UsualUnaryConversions(RHS.get()); 10090 if (RHS.isInvalid()) 10091 return QualType(); 10092 10093 if (!LHS.get()->getType()->isScalarType() || 10094 !RHS.get()->getType()->isScalarType()) 10095 return InvalidOperands(Loc, LHS, RHS); 10096 10097 return Context.IntTy; 10098 } 10099 10100 // The following is safe because we only use this method for 10101 // non-overloadable operands. 10102 10103 // C++ [expr.log.and]p1 10104 // C++ [expr.log.or]p1 10105 // The operands are both contextually converted to type bool. 10106 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 10107 if (LHSRes.isInvalid()) 10108 return InvalidOperands(Loc, LHS, RHS); 10109 LHS = LHSRes; 10110 10111 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 10112 if (RHSRes.isInvalid()) 10113 return InvalidOperands(Loc, LHS, RHS); 10114 RHS = RHSRes; 10115 10116 // C++ [expr.log.and]p2 10117 // C++ [expr.log.or]p2 10118 // The result is a bool. 10119 return Context.BoolTy; 10120 } 10121 10122 static bool IsReadonlyMessage(Expr *E, Sema &S) { 10123 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 10124 if (!ME) return false; 10125 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 10126 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 10127 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 10128 if (!Base) return false; 10129 return Base->getMethodDecl() != nullptr; 10130 } 10131 10132 /// Is the given expression (which must be 'const') a reference to a 10133 /// variable which was originally non-const, but which has become 10134 /// 'const' due to being captured within a block? 10135 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 10136 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 10137 assert(E->isLValue() && E->getType().isConstQualified()); 10138 E = E->IgnoreParens(); 10139 10140 // Must be a reference to a declaration from an enclosing scope. 10141 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 10142 if (!DRE) return NCCK_None; 10143 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 10144 10145 // The declaration must be a variable which is not declared 'const'. 10146 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 10147 if (!var) return NCCK_None; 10148 if (var->getType().isConstQualified()) return NCCK_None; 10149 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 10150 10151 // Decide whether the first capture was for a block or a lambda. 10152 DeclContext *DC = S.CurContext, *Prev = nullptr; 10153 // Decide whether the first capture was for a block or a lambda. 10154 while (DC) { 10155 // For init-capture, it is possible that the variable belongs to the 10156 // template pattern of the current context. 10157 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 10158 if (var->isInitCapture() && 10159 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 10160 break; 10161 if (DC == var->getDeclContext()) 10162 break; 10163 Prev = DC; 10164 DC = DC->getParent(); 10165 } 10166 // Unless we have an init-capture, we've gone one step too far. 10167 if (!var->isInitCapture()) 10168 DC = Prev; 10169 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 10170 } 10171 10172 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 10173 Ty = Ty.getNonReferenceType(); 10174 if (IsDereference && Ty->isPointerType()) 10175 Ty = Ty->getPointeeType(); 10176 return !Ty.isConstQualified(); 10177 } 10178 10179 /// Emit the "read-only variable not assignable" error and print notes to give 10180 /// more information about why the variable is not assignable, such as pointing 10181 /// to the declaration of a const variable, showing that a method is const, or 10182 /// that the function is returning a const reference. 10183 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 10184 SourceLocation Loc) { 10185 // Update err_typecheck_assign_const and note_typecheck_assign_const 10186 // when this enum is changed. 10187 enum { 10188 ConstFunction, 10189 ConstVariable, 10190 ConstMember, 10191 ConstMethod, 10192 ConstUnknown, // Keep as last element 10193 }; 10194 10195 SourceRange ExprRange = E->getSourceRange(); 10196 10197 // Only emit one error on the first const found. All other consts will emit 10198 // a note to the error. 10199 bool DiagnosticEmitted = false; 10200 10201 // Track if the current expression is the result of a dereference, and if the 10202 // next checked expression is the result of a dereference. 10203 bool IsDereference = false; 10204 bool NextIsDereference = false; 10205 10206 // Loop to process MemberExpr chains. 10207 while (true) { 10208 IsDereference = NextIsDereference; 10209 10210 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 10211 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 10212 NextIsDereference = ME->isArrow(); 10213 const ValueDecl *VD = ME->getMemberDecl(); 10214 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 10215 // Mutable fields can be modified even if the class is const. 10216 if (Field->isMutable()) { 10217 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 10218 break; 10219 } 10220 10221 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 10222 if (!DiagnosticEmitted) { 10223 S.Diag(Loc, diag::err_typecheck_assign_const) 10224 << ExprRange << ConstMember << false /*static*/ << Field 10225 << Field->getType(); 10226 DiagnosticEmitted = true; 10227 } 10228 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10229 << ConstMember << false /*static*/ << Field << Field->getType() 10230 << Field->getSourceRange(); 10231 } 10232 E = ME->getBase(); 10233 continue; 10234 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 10235 if (VDecl->getType().isConstQualified()) { 10236 if (!DiagnosticEmitted) { 10237 S.Diag(Loc, diag::err_typecheck_assign_const) 10238 << ExprRange << ConstMember << true /*static*/ << VDecl 10239 << VDecl->getType(); 10240 DiagnosticEmitted = true; 10241 } 10242 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10243 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 10244 << VDecl->getSourceRange(); 10245 } 10246 // Static fields do not inherit constness from parents. 10247 break; 10248 } 10249 break; 10250 } // End MemberExpr 10251 break; 10252 } 10253 10254 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 10255 // Function calls 10256 const FunctionDecl *FD = CE->getDirectCallee(); 10257 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 10258 if (!DiagnosticEmitted) { 10259 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 10260 << ConstFunction << FD; 10261 DiagnosticEmitted = true; 10262 } 10263 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 10264 diag::note_typecheck_assign_const) 10265 << ConstFunction << FD << FD->getReturnType() 10266 << FD->getReturnTypeSourceRange(); 10267 } 10268 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 10269 // Point to variable declaration. 10270 if (const ValueDecl *VD = DRE->getDecl()) { 10271 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 10272 if (!DiagnosticEmitted) { 10273 S.Diag(Loc, diag::err_typecheck_assign_const) 10274 << ExprRange << ConstVariable << VD << VD->getType(); 10275 DiagnosticEmitted = true; 10276 } 10277 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10278 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 10279 } 10280 } 10281 } else if (isa<CXXThisExpr>(E)) { 10282 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 10283 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 10284 if (MD->isConst()) { 10285 if (!DiagnosticEmitted) { 10286 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 10287 << ConstMethod << MD; 10288 DiagnosticEmitted = true; 10289 } 10290 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 10291 << ConstMethod << MD << MD->getSourceRange(); 10292 } 10293 } 10294 } 10295 } 10296 10297 if (DiagnosticEmitted) 10298 return; 10299 10300 // Can't determine a more specific message, so display the generic error. 10301 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 10302 } 10303 10304 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 10305 /// emit an error and return true. If so, return false. 10306 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 10307 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 10308 10309 S.CheckShadowingDeclModification(E, Loc); 10310 10311 SourceLocation OrigLoc = Loc; 10312 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 10313 &Loc); 10314 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 10315 IsLV = Expr::MLV_InvalidMessageExpression; 10316 if (IsLV == Expr::MLV_Valid) 10317 return false; 10318 10319 unsigned DiagID = 0; 10320 bool NeedType = false; 10321 switch (IsLV) { // C99 6.5.16p2 10322 case Expr::MLV_ConstQualified: 10323 // Use a specialized diagnostic when we're assigning to an object 10324 // from an enclosing function or block. 10325 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 10326 if (NCCK == NCCK_Block) 10327 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 10328 else 10329 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 10330 break; 10331 } 10332 10333 // In ARC, use some specialized diagnostics for occasions where we 10334 // infer 'const'. These are always pseudo-strong variables. 10335 if (S.getLangOpts().ObjCAutoRefCount) { 10336 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 10337 if (declRef && isa<VarDecl>(declRef->getDecl())) { 10338 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 10339 10340 // Use the normal diagnostic if it's pseudo-__strong but the 10341 // user actually wrote 'const'. 10342 if (var->isARCPseudoStrong() && 10343 (!var->getTypeSourceInfo() || 10344 !var->getTypeSourceInfo()->getType().isConstQualified())) { 10345 // There are two pseudo-strong cases: 10346 // - self 10347 ObjCMethodDecl *method = S.getCurMethodDecl(); 10348 if (method && var == method->getSelfDecl()) 10349 DiagID = method->isClassMethod() 10350 ? diag::err_typecheck_arc_assign_self_class_method 10351 : diag::err_typecheck_arc_assign_self; 10352 10353 // - fast enumeration variables 10354 else 10355 DiagID = diag::err_typecheck_arr_assign_enumeration; 10356 10357 SourceRange Assign; 10358 if (Loc != OrigLoc) 10359 Assign = SourceRange(OrigLoc, OrigLoc); 10360 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10361 // We need to preserve the AST regardless, so migration tool 10362 // can do its job. 10363 return false; 10364 } 10365 } 10366 } 10367 10368 // If none of the special cases above are triggered, then this is a 10369 // simple const assignment. 10370 if (DiagID == 0) { 10371 DiagnoseConstAssignment(S, E, Loc); 10372 return true; 10373 } 10374 10375 break; 10376 case Expr::MLV_ConstAddrSpace: 10377 DiagnoseConstAssignment(S, E, Loc); 10378 return true; 10379 case Expr::MLV_ArrayType: 10380 case Expr::MLV_ArrayTemporary: 10381 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 10382 NeedType = true; 10383 break; 10384 case Expr::MLV_NotObjectType: 10385 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 10386 NeedType = true; 10387 break; 10388 case Expr::MLV_LValueCast: 10389 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 10390 break; 10391 case Expr::MLV_Valid: 10392 llvm_unreachable("did not take early return for MLV_Valid"); 10393 case Expr::MLV_InvalidExpression: 10394 case Expr::MLV_MemberFunction: 10395 case Expr::MLV_ClassTemporary: 10396 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 10397 break; 10398 case Expr::MLV_IncompleteType: 10399 case Expr::MLV_IncompleteVoidType: 10400 return S.RequireCompleteType(Loc, E->getType(), 10401 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 10402 case Expr::MLV_DuplicateVectorComponents: 10403 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 10404 break; 10405 case Expr::MLV_NoSetterProperty: 10406 llvm_unreachable("readonly properties should be processed differently"); 10407 case Expr::MLV_InvalidMessageExpression: 10408 DiagID = diag::err_readonly_message_assignment; 10409 break; 10410 case Expr::MLV_SubObjCPropertySetting: 10411 DiagID = diag::err_no_subobject_property_setting; 10412 break; 10413 } 10414 10415 SourceRange Assign; 10416 if (Loc != OrigLoc) 10417 Assign = SourceRange(OrigLoc, OrigLoc); 10418 if (NeedType) 10419 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 10420 else 10421 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10422 return true; 10423 } 10424 10425 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 10426 SourceLocation Loc, 10427 Sema &Sema) { 10428 // C / C++ fields 10429 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 10430 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 10431 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 10432 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 10433 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 10434 } 10435 10436 // Objective-C instance variables 10437 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 10438 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 10439 if (OL && OR && OL->getDecl() == OR->getDecl()) { 10440 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 10441 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 10442 if (RL && RR && RL->getDecl() == RR->getDecl()) 10443 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 10444 } 10445 } 10446 10447 // C99 6.5.16.1 10448 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 10449 SourceLocation Loc, 10450 QualType CompoundType) { 10451 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 10452 10453 // Verify that LHS is a modifiable lvalue, and emit error if not. 10454 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 10455 return QualType(); 10456 10457 QualType LHSType = LHSExpr->getType(); 10458 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 10459 CompoundType; 10460 // OpenCL v1.2 s6.1.1.1 p2: 10461 // The half data type can only be used to declare a pointer to a buffer that 10462 // contains half values 10463 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 10464 LHSType->isHalfType()) { 10465 Diag(Loc, diag::err_opencl_half_load_store) << 1 10466 << LHSType.getUnqualifiedType(); 10467 return QualType(); 10468 } 10469 10470 AssignConvertType ConvTy; 10471 if (CompoundType.isNull()) { 10472 Expr *RHSCheck = RHS.get(); 10473 10474 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 10475 10476 QualType LHSTy(LHSType); 10477 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 10478 if (RHS.isInvalid()) 10479 return QualType(); 10480 // Special case of NSObject attributes on c-style pointer types. 10481 if (ConvTy == IncompatiblePointer && 10482 ((Context.isObjCNSObjectType(LHSType) && 10483 RHSType->isObjCObjectPointerType()) || 10484 (Context.isObjCNSObjectType(RHSType) && 10485 LHSType->isObjCObjectPointerType()))) 10486 ConvTy = Compatible; 10487 10488 if (ConvTy == Compatible && 10489 LHSType->isObjCObjectType()) 10490 Diag(Loc, diag::err_objc_object_assignment) 10491 << LHSType; 10492 10493 // If the RHS is a unary plus or minus, check to see if they = and + are 10494 // right next to each other. If so, the user may have typo'd "x =+ 4" 10495 // instead of "x += 4". 10496 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 10497 RHSCheck = ICE->getSubExpr(); 10498 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 10499 if ((UO->getOpcode() == UO_Plus || 10500 UO->getOpcode() == UO_Minus) && 10501 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 10502 // Only if the two operators are exactly adjacent. 10503 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 10504 // And there is a space or other character before the subexpr of the 10505 // unary +/-. We don't want to warn on "x=-1". 10506 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 10507 UO->getSubExpr()->getLocStart().isFileID()) { 10508 Diag(Loc, diag::warn_not_compound_assign) 10509 << (UO->getOpcode() == UO_Plus ? "+" : "-") 10510 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 10511 } 10512 } 10513 10514 if (ConvTy == Compatible) { 10515 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 10516 // Warn about retain cycles where a block captures the LHS, but 10517 // not if the LHS is a simple variable into which the block is 10518 // being stored...unless that variable can be captured by reference! 10519 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 10520 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 10521 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 10522 checkRetainCycles(LHSExpr, RHS.get()); 10523 } 10524 10525 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 10526 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 10527 // It is safe to assign a weak reference into a strong variable. 10528 // Although this code can still have problems: 10529 // id x = self.weakProp; 10530 // id y = self.weakProp; 10531 // we do not warn to warn spuriously when 'x' and 'y' are on separate 10532 // paths through the function. This should be revisited if 10533 // -Wrepeated-use-of-weak is made flow-sensitive. 10534 // For ObjCWeak only, we do not warn if the assign is to a non-weak 10535 // variable, which will be valid for the current autorelease scope. 10536 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 10537 RHS.get()->getLocStart())) 10538 getCurFunction()->markSafeWeakUse(RHS.get()); 10539 10540 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 10541 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 10542 } 10543 } 10544 } else { 10545 // Compound assignment "x += y" 10546 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 10547 } 10548 10549 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 10550 RHS.get(), AA_Assigning)) 10551 return QualType(); 10552 10553 CheckForNullPointerDereference(*this, LHSExpr); 10554 10555 // C99 6.5.16p3: The type of an assignment expression is the type of the 10556 // left operand unless the left operand has qualified type, in which case 10557 // it is the unqualified version of the type of the left operand. 10558 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 10559 // is converted to the type of the assignment expression (above). 10560 // C++ 5.17p1: the type of the assignment expression is that of its left 10561 // operand. 10562 return (getLangOpts().CPlusPlus 10563 ? LHSType : LHSType.getUnqualifiedType()); 10564 } 10565 10566 // Only ignore explicit casts to void. 10567 static bool IgnoreCommaOperand(const Expr *E) { 10568 E = E->IgnoreParens(); 10569 10570 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 10571 if (CE->getCastKind() == CK_ToVoid) { 10572 return true; 10573 } 10574 } 10575 10576 return false; 10577 } 10578 10579 // Look for instances where it is likely the comma operator is confused with 10580 // another operator. There is a whitelist of acceptable expressions for the 10581 // left hand side of the comma operator, otherwise emit a warning. 10582 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 10583 // No warnings in macros 10584 if (Loc.isMacroID()) 10585 return; 10586 10587 // Don't warn in template instantiations. 10588 if (inTemplateInstantiation()) 10589 return; 10590 10591 // Scope isn't fine-grained enough to whitelist the specific cases, so 10592 // instead, skip more than needed, then call back into here with the 10593 // CommaVisitor in SemaStmt.cpp. 10594 // The whitelisted locations are the initialization and increment portions 10595 // of a for loop. The additional checks are on the condition of 10596 // if statements, do/while loops, and for loops. 10597 const unsigned ForIncrementFlags = 10598 Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope; 10599 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 10600 const unsigned ScopeFlags = getCurScope()->getFlags(); 10601 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 10602 (ScopeFlags & ForInitFlags) == ForInitFlags) 10603 return; 10604 10605 // If there are multiple comma operators used together, get the RHS of the 10606 // of the comma operator as the LHS. 10607 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 10608 if (BO->getOpcode() != BO_Comma) 10609 break; 10610 LHS = BO->getRHS(); 10611 } 10612 10613 // Only allow some expressions on LHS to not warn. 10614 if (IgnoreCommaOperand(LHS)) 10615 return; 10616 10617 Diag(Loc, diag::warn_comma_operator); 10618 Diag(LHS->getLocStart(), diag::note_cast_to_void) 10619 << LHS->getSourceRange() 10620 << FixItHint::CreateInsertion(LHS->getLocStart(), 10621 LangOpts.CPlusPlus ? "static_cast<void>(" 10622 : "(void)(") 10623 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()), 10624 ")"); 10625 } 10626 10627 // C99 6.5.17 10628 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 10629 SourceLocation Loc) { 10630 LHS = S.CheckPlaceholderExpr(LHS.get()); 10631 RHS = S.CheckPlaceholderExpr(RHS.get()); 10632 if (LHS.isInvalid() || RHS.isInvalid()) 10633 return QualType(); 10634 10635 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 10636 // operands, but not unary promotions. 10637 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 10638 10639 // So we treat the LHS as a ignored value, and in C++ we allow the 10640 // containing site to determine what should be done with the RHS. 10641 LHS = S.IgnoredValueConversions(LHS.get()); 10642 if (LHS.isInvalid()) 10643 return QualType(); 10644 10645 S.DiagnoseUnusedExprResult(LHS.get()); 10646 10647 if (!S.getLangOpts().CPlusPlus) { 10648 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 10649 if (RHS.isInvalid()) 10650 return QualType(); 10651 if (!RHS.get()->getType()->isVoidType()) 10652 S.RequireCompleteType(Loc, RHS.get()->getType(), 10653 diag::err_incomplete_type); 10654 } 10655 10656 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 10657 S.DiagnoseCommaOperator(LHS.get(), Loc); 10658 10659 return RHS.get()->getType(); 10660 } 10661 10662 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 10663 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 10664 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 10665 ExprValueKind &VK, 10666 ExprObjectKind &OK, 10667 SourceLocation OpLoc, 10668 bool IsInc, bool IsPrefix) { 10669 if (Op->isTypeDependent()) 10670 return S.Context.DependentTy; 10671 10672 QualType ResType = Op->getType(); 10673 // Atomic types can be used for increment / decrement where the non-atomic 10674 // versions can, so ignore the _Atomic() specifier for the purpose of 10675 // checking. 10676 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10677 ResType = ResAtomicType->getValueType(); 10678 10679 assert(!ResType.isNull() && "no type for increment/decrement expression"); 10680 10681 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 10682 // Decrement of bool is not allowed. 10683 if (!IsInc) { 10684 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 10685 return QualType(); 10686 } 10687 // Increment of bool sets it to true, but is deprecated. 10688 S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool 10689 : diag::warn_increment_bool) 10690 << Op->getSourceRange(); 10691 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 10692 // Error on enum increments and decrements in C++ mode 10693 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 10694 return QualType(); 10695 } else if (ResType->isRealType()) { 10696 // OK! 10697 } else if (ResType->isPointerType()) { 10698 // C99 6.5.2.4p2, 6.5.6p2 10699 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 10700 return QualType(); 10701 } else if (ResType->isObjCObjectPointerType()) { 10702 // On modern runtimes, ObjC pointer arithmetic is forbidden. 10703 // Otherwise, we just need a complete type. 10704 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 10705 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 10706 return QualType(); 10707 } else if (ResType->isAnyComplexType()) { 10708 // C99 does not support ++/-- on complex types, we allow as an extension. 10709 S.Diag(OpLoc, diag::ext_integer_increment_complex) 10710 << ResType << Op->getSourceRange(); 10711 } else if (ResType->isPlaceholderType()) { 10712 ExprResult PR = S.CheckPlaceholderExpr(Op); 10713 if (PR.isInvalid()) return QualType(); 10714 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 10715 IsInc, IsPrefix); 10716 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 10717 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 10718 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 10719 (ResType->getAs<VectorType>()->getVectorKind() != 10720 VectorType::AltiVecBool)) { 10721 // The z vector extensions allow ++ and -- for non-bool vectors. 10722 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 10723 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 10724 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 10725 } else { 10726 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 10727 << ResType << int(IsInc) << Op->getSourceRange(); 10728 return QualType(); 10729 } 10730 // At this point, we know we have a real, complex or pointer type. 10731 // Now make sure the operand is a modifiable lvalue. 10732 if (CheckForModifiableLvalue(Op, OpLoc, S)) 10733 return QualType(); 10734 // In C++, a prefix increment is the same type as the operand. Otherwise 10735 // (in C or with postfix), the increment is the unqualified type of the 10736 // operand. 10737 if (IsPrefix && S.getLangOpts().CPlusPlus) { 10738 VK = VK_LValue; 10739 OK = Op->getObjectKind(); 10740 return ResType; 10741 } else { 10742 VK = VK_RValue; 10743 return ResType.getUnqualifiedType(); 10744 } 10745 } 10746 10747 10748 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 10749 /// This routine allows us to typecheck complex/recursive expressions 10750 /// where the declaration is needed for type checking. We only need to 10751 /// handle cases when the expression references a function designator 10752 /// or is an lvalue. Here are some examples: 10753 /// - &(x) => x 10754 /// - &*****f => f for f a function designator. 10755 /// - &s.xx => s 10756 /// - &s.zz[1].yy -> s, if zz is an array 10757 /// - *(x + 1) -> x, if x is an array 10758 /// - &"123"[2] -> 0 10759 /// - & __real__ x -> x 10760 static ValueDecl *getPrimaryDecl(Expr *E) { 10761 switch (E->getStmtClass()) { 10762 case Stmt::DeclRefExprClass: 10763 return cast<DeclRefExpr>(E)->getDecl(); 10764 case Stmt::MemberExprClass: 10765 // If this is an arrow operator, the address is an offset from 10766 // the base's value, so the object the base refers to is 10767 // irrelevant. 10768 if (cast<MemberExpr>(E)->isArrow()) 10769 return nullptr; 10770 // Otherwise, the expression refers to a part of the base 10771 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 10772 case Stmt::ArraySubscriptExprClass: { 10773 // FIXME: This code shouldn't be necessary! We should catch the implicit 10774 // promotion of register arrays earlier. 10775 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 10776 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 10777 if (ICE->getSubExpr()->getType()->isArrayType()) 10778 return getPrimaryDecl(ICE->getSubExpr()); 10779 } 10780 return nullptr; 10781 } 10782 case Stmt::UnaryOperatorClass: { 10783 UnaryOperator *UO = cast<UnaryOperator>(E); 10784 10785 switch(UO->getOpcode()) { 10786 case UO_Real: 10787 case UO_Imag: 10788 case UO_Extension: 10789 return getPrimaryDecl(UO->getSubExpr()); 10790 default: 10791 return nullptr; 10792 } 10793 } 10794 case Stmt::ParenExprClass: 10795 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 10796 case Stmt::ImplicitCastExprClass: 10797 // If the result of an implicit cast is an l-value, we care about 10798 // the sub-expression; otherwise, the result here doesn't matter. 10799 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 10800 default: 10801 return nullptr; 10802 } 10803 } 10804 10805 namespace { 10806 enum { 10807 AO_Bit_Field = 0, 10808 AO_Vector_Element = 1, 10809 AO_Property_Expansion = 2, 10810 AO_Register_Variable = 3, 10811 AO_No_Error = 4 10812 }; 10813 } 10814 /// \brief Diagnose invalid operand for address of operations. 10815 /// 10816 /// \param Type The type of operand which cannot have its address taken. 10817 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 10818 Expr *E, unsigned Type) { 10819 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 10820 } 10821 10822 /// CheckAddressOfOperand - The operand of & must be either a function 10823 /// designator or an lvalue designating an object. If it is an lvalue, the 10824 /// object cannot be declared with storage class register or be a bit field. 10825 /// Note: The usual conversions are *not* applied to the operand of the & 10826 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 10827 /// In C++, the operand might be an overloaded function name, in which case 10828 /// we allow the '&' but retain the overloaded-function type. 10829 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 10830 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 10831 if (PTy->getKind() == BuiltinType::Overload) { 10832 Expr *E = OrigOp.get()->IgnoreParens(); 10833 if (!isa<OverloadExpr>(E)) { 10834 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 10835 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 10836 << OrigOp.get()->getSourceRange(); 10837 return QualType(); 10838 } 10839 10840 OverloadExpr *Ovl = cast<OverloadExpr>(E); 10841 if (isa<UnresolvedMemberExpr>(Ovl)) 10842 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 10843 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10844 << OrigOp.get()->getSourceRange(); 10845 return QualType(); 10846 } 10847 10848 return Context.OverloadTy; 10849 } 10850 10851 if (PTy->getKind() == BuiltinType::UnknownAny) 10852 return Context.UnknownAnyTy; 10853 10854 if (PTy->getKind() == BuiltinType::BoundMember) { 10855 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10856 << OrigOp.get()->getSourceRange(); 10857 return QualType(); 10858 } 10859 10860 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 10861 if (OrigOp.isInvalid()) return QualType(); 10862 } 10863 10864 if (OrigOp.get()->isTypeDependent()) 10865 return Context.DependentTy; 10866 10867 assert(!OrigOp.get()->getType()->isPlaceholderType()); 10868 10869 // Make sure to ignore parentheses in subsequent checks 10870 Expr *op = OrigOp.get()->IgnoreParens(); 10871 10872 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 10873 if (LangOpts.OpenCL && op->getType()->isFunctionType()) { 10874 Diag(op->getExprLoc(), diag::err_opencl_taking_function_address); 10875 return QualType(); 10876 } 10877 10878 if (getLangOpts().C99) { 10879 // Implement C99-only parts of addressof rules. 10880 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 10881 if (uOp->getOpcode() == UO_Deref) 10882 // Per C99 6.5.3.2, the address of a deref always returns a valid result 10883 // (assuming the deref expression is valid). 10884 return uOp->getSubExpr()->getType(); 10885 } 10886 // Technically, there should be a check for array subscript 10887 // expressions here, but the result of one is always an lvalue anyway. 10888 } 10889 ValueDecl *dcl = getPrimaryDecl(op); 10890 10891 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 10892 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 10893 op->getLocStart())) 10894 return QualType(); 10895 10896 Expr::LValueClassification lval = op->ClassifyLValue(Context); 10897 unsigned AddressOfError = AO_No_Error; 10898 10899 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 10900 bool sfinae = (bool)isSFINAEContext(); 10901 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 10902 : diag::ext_typecheck_addrof_temporary) 10903 << op->getType() << op->getSourceRange(); 10904 if (sfinae) 10905 return QualType(); 10906 // Materialize the temporary as an lvalue so that we can take its address. 10907 OrigOp = op = 10908 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 10909 } else if (isa<ObjCSelectorExpr>(op)) { 10910 return Context.getPointerType(op->getType()); 10911 } else if (lval == Expr::LV_MemberFunction) { 10912 // If it's an instance method, make a member pointer. 10913 // The expression must have exactly the form &A::foo. 10914 10915 // If the underlying expression isn't a decl ref, give up. 10916 if (!isa<DeclRefExpr>(op)) { 10917 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10918 << OrigOp.get()->getSourceRange(); 10919 return QualType(); 10920 } 10921 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 10922 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 10923 10924 // The id-expression was parenthesized. 10925 if (OrigOp.get() != DRE) { 10926 Diag(OpLoc, diag::err_parens_pointer_member_function) 10927 << OrigOp.get()->getSourceRange(); 10928 10929 // The method was named without a qualifier. 10930 } else if (!DRE->getQualifier()) { 10931 if (MD->getParent()->getName().empty()) 10932 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 10933 << op->getSourceRange(); 10934 else { 10935 SmallString<32> Str; 10936 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 10937 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 10938 << op->getSourceRange() 10939 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 10940 } 10941 } 10942 10943 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 10944 if (isa<CXXDestructorDecl>(MD)) 10945 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 10946 10947 QualType MPTy = Context.getMemberPointerType( 10948 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 10949 // Under the MS ABI, lock down the inheritance model now. 10950 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 10951 (void)isCompleteType(OpLoc, MPTy); 10952 return MPTy; 10953 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 10954 // C99 6.5.3.2p1 10955 // The operand must be either an l-value or a function designator 10956 if (!op->getType()->isFunctionType()) { 10957 // Use a special diagnostic for loads from property references. 10958 if (isa<PseudoObjectExpr>(op)) { 10959 AddressOfError = AO_Property_Expansion; 10960 } else { 10961 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 10962 << op->getType() << op->getSourceRange(); 10963 return QualType(); 10964 } 10965 } 10966 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 10967 // The operand cannot be a bit-field 10968 AddressOfError = AO_Bit_Field; 10969 } else if (op->getObjectKind() == OK_VectorComponent) { 10970 // The operand cannot be an element of a vector 10971 AddressOfError = AO_Vector_Element; 10972 } else if (dcl) { // C99 6.5.3.2p1 10973 // We have an lvalue with a decl. Make sure the decl is not declared 10974 // with the register storage-class specifier. 10975 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 10976 // in C++ it is not error to take address of a register 10977 // variable (c++03 7.1.1P3) 10978 if (vd->getStorageClass() == SC_Register && 10979 !getLangOpts().CPlusPlus) { 10980 AddressOfError = AO_Register_Variable; 10981 } 10982 } else if (isa<MSPropertyDecl>(dcl)) { 10983 AddressOfError = AO_Property_Expansion; 10984 } else if (isa<FunctionTemplateDecl>(dcl)) { 10985 return Context.OverloadTy; 10986 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 10987 // Okay: we can take the address of a field. 10988 // Could be a pointer to member, though, if there is an explicit 10989 // scope qualifier for the class. 10990 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 10991 DeclContext *Ctx = dcl->getDeclContext(); 10992 if (Ctx && Ctx->isRecord()) { 10993 if (dcl->getType()->isReferenceType()) { 10994 Diag(OpLoc, 10995 diag::err_cannot_form_pointer_to_member_of_reference_type) 10996 << dcl->getDeclName() << dcl->getType(); 10997 return QualType(); 10998 } 10999 11000 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 11001 Ctx = Ctx->getParent(); 11002 11003 QualType MPTy = Context.getMemberPointerType( 11004 op->getType(), 11005 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 11006 // Under the MS ABI, lock down the inheritance model now. 11007 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11008 (void)isCompleteType(OpLoc, MPTy); 11009 return MPTy; 11010 } 11011 } 11012 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 11013 !isa<BindingDecl>(dcl)) 11014 llvm_unreachable("Unknown/unexpected decl type"); 11015 } 11016 11017 if (AddressOfError != AO_No_Error) { 11018 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 11019 return QualType(); 11020 } 11021 11022 if (lval == Expr::LV_IncompleteVoidType) { 11023 // Taking the address of a void variable is technically illegal, but we 11024 // allow it in cases which are otherwise valid. 11025 // Example: "extern void x; void* y = &x;". 11026 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 11027 } 11028 11029 // If the operand has type "type", the result has type "pointer to type". 11030 if (op->getType()->isObjCObjectType()) 11031 return Context.getObjCObjectPointerType(op->getType()); 11032 11033 CheckAddressOfPackedMember(op); 11034 11035 return Context.getPointerType(op->getType()); 11036 } 11037 11038 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 11039 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 11040 if (!DRE) 11041 return; 11042 const Decl *D = DRE->getDecl(); 11043 if (!D) 11044 return; 11045 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 11046 if (!Param) 11047 return; 11048 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 11049 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 11050 return; 11051 if (FunctionScopeInfo *FD = S.getCurFunction()) 11052 if (!FD->ModifiedNonNullParams.count(Param)) 11053 FD->ModifiedNonNullParams.insert(Param); 11054 } 11055 11056 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 11057 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 11058 SourceLocation OpLoc) { 11059 if (Op->isTypeDependent()) 11060 return S.Context.DependentTy; 11061 11062 ExprResult ConvResult = S.UsualUnaryConversions(Op); 11063 if (ConvResult.isInvalid()) 11064 return QualType(); 11065 Op = ConvResult.get(); 11066 QualType OpTy = Op->getType(); 11067 QualType Result; 11068 11069 if (isa<CXXReinterpretCastExpr>(Op)) { 11070 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 11071 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 11072 Op->getSourceRange()); 11073 } 11074 11075 if (const PointerType *PT = OpTy->getAs<PointerType>()) 11076 { 11077 Result = PT->getPointeeType(); 11078 } 11079 else if (const ObjCObjectPointerType *OPT = 11080 OpTy->getAs<ObjCObjectPointerType>()) 11081 Result = OPT->getPointeeType(); 11082 else { 11083 ExprResult PR = S.CheckPlaceholderExpr(Op); 11084 if (PR.isInvalid()) return QualType(); 11085 if (PR.get() != Op) 11086 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 11087 } 11088 11089 if (Result.isNull()) { 11090 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 11091 << OpTy << Op->getSourceRange(); 11092 return QualType(); 11093 } 11094 11095 // Note that per both C89 and C99, indirection is always legal, even if Result 11096 // is an incomplete type or void. It would be possible to warn about 11097 // dereferencing a void pointer, but it's completely well-defined, and such a 11098 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 11099 // for pointers to 'void' but is fine for any other pointer type: 11100 // 11101 // C++ [expr.unary.op]p1: 11102 // [...] the expression to which [the unary * operator] is applied shall 11103 // be a pointer to an object type, or a pointer to a function type 11104 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 11105 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 11106 << OpTy << Op->getSourceRange(); 11107 11108 // Dereferences are usually l-values... 11109 VK = VK_LValue; 11110 11111 // ...except that certain expressions are never l-values in C. 11112 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 11113 VK = VK_RValue; 11114 11115 return Result; 11116 } 11117 11118 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 11119 BinaryOperatorKind Opc; 11120 switch (Kind) { 11121 default: llvm_unreachable("Unknown binop!"); 11122 case tok::periodstar: Opc = BO_PtrMemD; break; 11123 case tok::arrowstar: Opc = BO_PtrMemI; break; 11124 case tok::star: Opc = BO_Mul; break; 11125 case tok::slash: Opc = BO_Div; break; 11126 case tok::percent: Opc = BO_Rem; break; 11127 case tok::plus: Opc = BO_Add; break; 11128 case tok::minus: Opc = BO_Sub; break; 11129 case tok::lessless: Opc = BO_Shl; break; 11130 case tok::greatergreater: Opc = BO_Shr; break; 11131 case tok::lessequal: Opc = BO_LE; break; 11132 case tok::less: Opc = BO_LT; break; 11133 case tok::greaterequal: Opc = BO_GE; break; 11134 case tok::greater: Opc = BO_GT; break; 11135 case tok::exclaimequal: Opc = BO_NE; break; 11136 case tok::equalequal: Opc = BO_EQ; break; 11137 case tok::amp: Opc = BO_And; break; 11138 case tok::caret: Opc = BO_Xor; break; 11139 case tok::pipe: Opc = BO_Or; break; 11140 case tok::ampamp: Opc = BO_LAnd; break; 11141 case tok::pipepipe: Opc = BO_LOr; break; 11142 case tok::equal: Opc = BO_Assign; break; 11143 case tok::starequal: Opc = BO_MulAssign; break; 11144 case tok::slashequal: Opc = BO_DivAssign; break; 11145 case tok::percentequal: Opc = BO_RemAssign; break; 11146 case tok::plusequal: Opc = BO_AddAssign; break; 11147 case tok::minusequal: Opc = BO_SubAssign; break; 11148 case tok::lesslessequal: Opc = BO_ShlAssign; break; 11149 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 11150 case tok::ampequal: Opc = BO_AndAssign; break; 11151 case tok::caretequal: Opc = BO_XorAssign; break; 11152 case tok::pipeequal: Opc = BO_OrAssign; break; 11153 case tok::comma: Opc = BO_Comma; break; 11154 } 11155 return Opc; 11156 } 11157 11158 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 11159 tok::TokenKind Kind) { 11160 UnaryOperatorKind Opc; 11161 switch (Kind) { 11162 default: llvm_unreachable("Unknown unary op!"); 11163 case tok::plusplus: Opc = UO_PreInc; break; 11164 case tok::minusminus: Opc = UO_PreDec; break; 11165 case tok::amp: Opc = UO_AddrOf; break; 11166 case tok::star: Opc = UO_Deref; break; 11167 case tok::plus: Opc = UO_Plus; break; 11168 case tok::minus: Opc = UO_Minus; break; 11169 case tok::tilde: Opc = UO_Not; break; 11170 case tok::exclaim: Opc = UO_LNot; break; 11171 case tok::kw___real: Opc = UO_Real; break; 11172 case tok::kw___imag: Opc = UO_Imag; break; 11173 case tok::kw___extension__: Opc = UO_Extension; break; 11174 } 11175 return Opc; 11176 } 11177 11178 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 11179 /// This warning is only emitted for builtin assignment operations. It is also 11180 /// suppressed in the event of macro expansions. 11181 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 11182 SourceLocation OpLoc) { 11183 if (S.inTemplateInstantiation()) 11184 return; 11185 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 11186 return; 11187 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 11188 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 11189 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 11190 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 11191 if (!LHSDeclRef || !RHSDeclRef || 11192 LHSDeclRef->getLocation().isMacroID() || 11193 RHSDeclRef->getLocation().isMacroID()) 11194 return; 11195 const ValueDecl *LHSDecl = 11196 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 11197 const ValueDecl *RHSDecl = 11198 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 11199 if (LHSDecl != RHSDecl) 11200 return; 11201 if (LHSDecl->getType().isVolatileQualified()) 11202 return; 11203 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 11204 if (RefTy->getPointeeType().isVolatileQualified()) 11205 return; 11206 11207 S.Diag(OpLoc, diag::warn_self_assignment) 11208 << LHSDeclRef->getType() 11209 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 11210 } 11211 11212 /// Check if a bitwise-& is performed on an Objective-C pointer. This 11213 /// is usually indicative of introspection within the Objective-C pointer. 11214 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 11215 SourceLocation OpLoc) { 11216 if (!S.getLangOpts().ObjC1) 11217 return; 11218 11219 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 11220 const Expr *LHS = L.get(); 11221 const Expr *RHS = R.get(); 11222 11223 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 11224 ObjCPointerExpr = LHS; 11225 OtherExpr = RHS; 11226 } 11227 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 11228 ObjCPointerExpr = RHS; 11229 OtherExpr = LHS; 11230 } 11231 11232 // This warning is deliberately made very specific to reduce false 11233 // positives with logic that uses '&' for hashing. This logic mainly 11234 // looks for code trying to introspect into tagged pointers, which 11235 // code should generally never do. 11236 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 11237 unsigned Diag = diag::warn_objc_pointer_masking; 11238 // Determine if we are introspecting the result of performSelectorXXX. 11239 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 11240 // Special case messages to -performSelector and friends, which 11241 // can return non-pointer values boxed in a pointer value. 11242 // Some clients may wish to silence warnings in this subcase. 11243 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 11244 Selector S = ME->getSelector(); 11245 StringRef SelArg0 = S.getNameForSlot(0); 11246 if (SelArg0.startswith("performSelector")) 11247 Diag = diag::warn_objc_pointer_masking_performSelector; 11248 } 11249 11250 S.Diag(OpLoc, Diag) 11251 << ObjCPointerExpr->getSourceRange(); 11252 } 11253 } 11254 11255 static NamedDecl *getDeclFromExpr(Expr *E) { 11256 if (!E) 11257 return nullptr; 11258 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 11259 return DRE->getDecl(); 11260 if (auto *ME = dyn_cast<MemberExpr>(E)) 11261 return ME->getMemberDecl(); 11262 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 11263 return IRE->getDecl(); 11264 return nullptr; 11265 } 11266 11267 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 11268 /// operator @p Opc at location @c TokLoc. This routine only supports 11269 /// built-in operations; ActOnBinOp handles overloaded operators. 11270 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 11271 BinaryOperatorKind Opc, 11272 Expr *LHSExpr, Expr *RHSExpr) { 11273 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 11274 // The syntax only allows initializer lists on the RHS of assignment, 11275 // so we don't need to worry about accepting invalid code for 11276 // non-assignment operators. 11277 // C++11 5.17p9: 11278 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 11279 // of x = {} is x = T(). 11280 InitializationKind Kind = 11281 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 11282 InitializedEntity Entity = 11283 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 11284 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 11285 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 11286 if (Init.isInvalid()) 11287 return Init; 11288 RHSExpr = Init.get(); 11289 } 11290 11291 ExprResult LHS = LHSExpr, RHS = RHSExpr; 11292 QualType ResultTy; // Result type of the binary operator. 11293 // The following two variables are used for compound assignment operators 11294 QualType CompLHSTy; // Type of LHS after promotions for computation 11295 QualType CompResultTy; // Type of computation result 11296 ExprValueKind VK = VK_RValue; 11297 ExprObjectKind OK = OK_Ordinary; 11298 11299 if (!getLangOpts().CPlusPlus) { 11300 // C cannot handle TypoExpr nodes on either side of a binop because it 11301 // doesn't handle dependent types properly, so make sure any TypoExprs have 11302 // been dealt with before checking the operands. 11303 LHS = CorrectDelayedTyposInExpr(LHSExpr); 11304 RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) { 11305 if (Opc != BO_Assign) 11306 return ExprResult(E); 11307 // Avoid correcting the RHS to the same Expr as the LHS. 11308 Decl *D = getDeclFromExpr(E); 11309 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 11310 }); 11311 if (!LHS.isUsable() || !RHS.isUsable()) 11312 return ExprError(); 11313 } 11314 11315 if (getLangOpts().OpenCL) { 11316 QualType LHSTy = LHSExpr->getType(); 11317 QualType RHSTy = RHSExpr->getType(); 11318 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 11319 // the ATOMIC_VAR_INIT macro. 11320 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 11321 SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 11322 if (BO_Assign == Opc) 11323 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 11324 else 11325 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 11326 return ExprError(); 11327 } 11328 11329 // OpenCL special types - image, sampler, pipe, and blocks are to be used 11330 // only with a builtin functions and therefore should be disallowed here. 11331 if (LHSTy->isImageType() || RHSTy->isImageType() || 11332 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 11333 LHSTy->isPipeType() || RHSTy->isPipeType() || 11334 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 11335 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 11336 return ExprError(); 11337 } 11338 } 11339 11340 switch (Opc) { 11341 case BO_Assign: 11342 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 11343 if (getLangOpts().CPlusPlus && 11344 LHS.get()->getObjectKind() != OK_ObjCProperty) { 11345 VK = LHS.get()->getValueKind(); 11346 OK = LHS.get()->getObjectKind(); 11347 } 11348 if (!ResultTy.isNull()) { 11349 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 11350 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 11351 } 11352 RecordModifiableNonNullParam(*this, LHS.get()); 11353 break; 11354 case BO_PtrMemD: 11355 case BO_PtrMemI: 11356 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 11357 Opc == BO_PtrMemI); 11358 break; 11359 case BO_Mul: 11360 case BO_Div: 11361 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 11362 Opc == BO_Div); 11363 break; 11364 case BO_Rem: 11365 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 11366 break; 11367 case BO_Add: 11368 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 11369 break; 11370 case BO_Sub: 11371 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 11372 break; 11373 case BO_Shl: 11374 case BO_Shr: 11375 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 11376 break; 11377 case BO_LE: 11378 case BO_LT: 11379 case BO_GE: 11380 case BO_GT: 11381 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 11382 break; 11383 case BO_EQ: 11384 case BO_NE: 11385 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 11386 break; 11387 case BO_And: 11388 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 11389 LLVM_FALLTHROUGH; 11390 case BO_Xor: 11391 case BO_Or: 11392 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 11393 break; 11394 case BO_LAnd: 11395 case BO_LOr: 11396 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 11397 break; 11398 case BO_MulAssign: 11399 case BO_DivAssign: 11400 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 11401 Opc == BO_DivAssign); 11402 CompLHSTy = CompResultTy; 11403 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11404 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11405 break; 11406 case BO_RemAssign: 11407 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 11408 CompLHSTy = CompResultTy; 11409 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11410 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11411 break; 11412 case BO_AddAssign: 11413 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 11414 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11415 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11416 break; 11417 case BO_SubAssign: 11418 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 11419 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11420 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11421 break; 11422 case BO_ShlAssign: 11423 case BO_ShrAssign: 11424 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 11425 CompLHSTy = CompResultTy; 11426 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11427 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11428 break; 11429 case BO_AndAssign: 11430 case BO_OrAssign: // fallthrough 11431 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 11432 LLVM_FALLTHROUGH; 11433 case BO_XorAssign: 11434 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 11435 CompLHSTy = CompResultTy; 11436 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11437 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11438 break; 11439 case BO_Comma: 11440 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 11441 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 11442 VK = RHS.get()->getValueKind(); 11443 OK = RHS.get()->getObjectKind(); 11444 } 11445 break; 11446 } 11447 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 11448 return ExprError(); 11449 11450 // Check for array bounds violations for both sides of the BinaryOperator 11451 CheckArrayAccess(LHS.get()); 11452 CheckArrayAccess(RHS.get()); 11453 11454 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 11455 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 11456 &Context.Idents.get("object_setClass"), 11457 SourceLocation(), LookupOrdinaryName); 11458 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 11459 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd()); 11460 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 11461 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 11462 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 11463 FixItHint::CreateInsertion(RHSLocEnd, ")"); 11464 } 11465 else 11466 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 11467 } 11468 else if (const ObjCIvarRefExpr *OIRE = 11469 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 11470 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 11471 11472 if (CompResultTy.isNull()) 11473 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 11474 OK, OpLoc, FPFeatures); 11475 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 11476 OK_ObjCProperty) { 11477 VK = VK_LValue; 11478 OK = LHS.get()->getObjectKind(); 11479 } 11480 return new (Context) CompoundAssignOperator( 11481 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 11482 OpLoc, FPFeatures); 11483 } 11484 11485 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 11486 /// operators are mixed in a way that suggests that the programmer forgot that 11487 /// comparison operators have higher precedence. The most typical example of 11488 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 11489 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 11490 SourceLocation OpLoc, Expr *LHSExpr, 11491 Expr *RHSExpr) { 11492 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 11493 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 11494 11495 // Check that one of the sides is a comparison operator and the other isn't. 11496 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 11497 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 11498 if (isLeftComp == isRightComp) 11499 return; 11500 11501 // Bitwise operations are sometimes used as eager logical ops. 11502 // Don't diagnose this. 11503 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 11504 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 11505 if (isLeftBitwise || isRightBitwise) 11506 return; 11507 11508 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 11509 OpLoc) 11510 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 11511 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 11512 SourceRange ParensRange = isLeftComp ? 11513 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 11514 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd()); 11515 11516 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 11517 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 11518 SuggestParentheses(Self, OpLoc, 11519 Self.PDiag(diag::note_precedence_silence) << OpStr, 11520 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 11521 SuggestParentheses(Self, OpLoc, 11522 Self.PDiag(diag::note_precedence_bitwise_first) 11523 << BinaryOperator::getOpcodeStr(Opc), 11524 ParensRange); 11525 } 11526 11527 /// \brief It accepts a '&&' expr that is inside a '||' one. 11528 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 11529 /// in parentheses. 11530 static void 11531 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 11532 BinaryOperator *Bop) { 11533 assert(Bop->getOpcode() == BO_LAnd); 11534 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 11535 << Bop->getSourceRange() << OpLoc; 11536 SuggestParentheses(Self, Bop->getOperatorLoc(), 11537 Self.PDiag(diag::note_precedence_silence) 11538 << Bop->getOpcodeStr(), 11539 Bop->getSourceRange()); 11540 } 11541 11542 /// \brief Returns true if the given expression can be evaluated as a constant 11543 /// 'true'. 11544 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 11545 bool Res; 11546 return !E->isValueDependent() && 11547 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 11548 } 11549 11550 /// \brief Returns true if the given expression can be evaluated as a constant 11551 /// 'false'. 11552 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 11553 bool Res; 11554 return !E->isValueDependent() && 11555 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 11556 } 11557 11558 /// \brief Look for '&&' in the left hand of a '||' expr. 11559 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 11560 Expr *LHSExpr, Expr *RHSExpr) { 11561 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 11562 if (Bop->getOpcode() == BO_LAnd) { 11563 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 11564 if (EvaluatesAsFalse(S, RHSExpr)) 11565 return; 11566 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 11567 if (!EvaluatesAsTrue(S, Bop->getLHS())) 11568 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11569 } else if (Bop->getOpcode() == BO_LOr) { 11570 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 11571 // If it's "a || b && 1 || c" we didn't warn earlier for 11572 // "a || b && 1", but warn now. 11573 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 11574 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 11575 } 11576 } 11577 } 11578 } 11579 11580 /// \brief Look for '&&' in the right hand of a '||' expr. 11581 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 11582 Expr *LHSExpr, Expr *RHSExpr) { 11583 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 11584 if (Bop->getOpcode() == BO_LAnd) { 11585 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 11586 if (EvaluatesAsFalse(S, LHSExpr)) 11587 return; 11588 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 11589 if (!EvaluatesAsTrue(S, Bop->getRHS())) 11590 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11591 } 11592 } 11593 } 11594 11595 /// \brief Look for bitwise op in the left or right hand of a bitwise op with 11596 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 11597 /// the '&' expression in parentheses. 11598 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 11599 SourceLocation OpLoc, Expr *SubExpr) { 11600 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11601 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 11602 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 11603 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 11604 << Bop->getSourceRange() << OpLoc; 11605 SuggestParentheses(S, Bop->getOperatorLoc(), 11606 S.PDiag(diag::note_precedence_silence) 11607 << Bop->getOpcodeStr(), 11608 Bop->getSourceRange()); 11609 } 11610 } 11611 } 11612 11613 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 11614 Expr *SubExpr, StringRef Shift) { 11615 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11616 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 11617 StringRef Op = Bop->getOpcodeStr(); 11618 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 11619 << Bop->getSourceRange() << OpLoc << Shift << Op; 11620 SuggestParentheses(S, Bop->getOperatorLoc(), 11621 S.PDiag(diag::note_precedence_silence) << Op, 11622 Bop->getSourceRange()); 11623 } 11624 } 11625 } 11626 11627 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 11628 Expr *LHSExpr, Expr *RHSExpr) { 11629 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 11630 if (!OCE) 11631 return; 11632 11633 FunctionDecl *FD = OCE->getDirectCallee(); 11634 if (!FD || !FD->isOverloadedOperator()) 11635 return; 11636 11637 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 11638 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 11639 return; 11640 11641 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 11642 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 11643 << (Kind == OO_LessLess); 11644 SuggestParentheses(S, OCE->getOperatorLoc(), 11645 S.PDiag(diag::note_precedence_silence) 11646 << (Kind == OO_LessLess ? "<<" : ">>"), 11647 OCE->getSourceRange()); 11648 SuggestParentheses(S, OpLoc, 11649 S.PDiag(diag::note_evaluate_comparison_first), 11650 SourceRange(OCE->getArg(1)->getLocStart(), 11651 RHSExpr->getLocEnd())); 11652 } 11653 11654 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 11655 /// precedence. 11656 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 11657 SourceLocation OpLoc, Expr *LHSExpr, 11658 Expr *RHSExpr){ 11659 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 11660 if (BinaryOperator::isBitwiseOp(Opc)) 11661 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 11662 11663 // Diagnose "arg1 & arg2 | arg3" 11664 if ((Opc == BO_Or || Opc == BO_Xor) && 11665 !OpLoc.isMacroID()/* Don't warn in macros. */) { 11666 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 11667 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 11668 } 11669 11670 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 11671 // We don't warn for 'assert(a || b && "bad")' since this is safe. 11672 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 11673 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 11674 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 11675 } 11676 11677 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 11678 || Opc == BO_Shr) { 11679 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 11680 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 11681 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 11682 } 11683 11684 // Warn on overloaded shift operators and comparisons, such as: 11685 // cout << 5 == 4; 11686 if (BinaryOperator::isComparisonOp(Opc)) 11687 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 11688 } 11689 11690 // Binary Operators. 'Tok' is the token for the operator. 11691 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 11692 tok::TokenKind Kind, 11693 Expr *LHSExpr, Expr *RHSExpr) { 11694 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 11695 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 11696 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 11697 11698 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 11699 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 11700 11701 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 11702 } 11703 11704 /// Build an overloaded binary operator expression in the given scope. 11705 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 11706 BinaryOperatorKind Opc, 11707 Expr *LHS, Expr *RHS) { 11708 // Find all of the overloaded operators visible from this 11709 // point. We perform both an operator-name lookup from the local 11710 // scope and an argument-dependent lookup based on the types of 11711 // the arguments. 11712 UnresolvedSet<16> Functions; 11713 OverloadedOperatorKind OverOp 11714 = BinaryOperator::getOverloadedOperator(Opc); 11715 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 11716 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 11717 RHS->getType(), Functions); 11718 11719 // Build the (potentially-overloaded, potentially-dependent) 11720 // binary operation. 11721 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 11722 } 11723 11724 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 11725 BinaryOperatorKind Opc, 11726 Expr *LHSExpr, Expr *RHSExpr) { 11727 // We want to end up calling one of checkPseudoObjectAssignment 11728 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 11729 // both expressions are overloadable or either is type-dependent), 11730 // or CreateBuiltinBinOp (in any other case). We also want to get 11731 // any placeholder types out of the way. 11732 11733 // Handle pseudo-objects in the LHS. 11734 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 11735 // Assignments with a pseudo-object l-value need special analysis. 11736 if (pty->getKind() == BuiltinType::PseudoObject && 11737 BinaryOperator::isAssignmentOp(Opc)) 11738 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 11739 11740 // Don't resolve overloads if the other type is overloadable. 11741 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 11742 // We can't actually test that if we still have a placeholder, 11743 // though. Fortunately, none of the exceptions we see in that 11744 // code below are valid when the LHS is an overload set. Note 11745 // that an overload set can be dependently-typed, but it never 11746 // instantiates to having an overloadable type. 11747 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 11748 if (resolvedRHS.isInvalid()) return ExprError(); 11749 RHSExpr = resolvedRHS.get(); 11750 11751 if (RHSExpr->isTypeDependent() || 11752 RHSExpr->getType()->isOverloadableType()) 11753 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11754 } 11755 11756 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 11757 // template, diagnose the missing 'template' keyword instead of diagnosing 11758 // an invalid use of a bound member function. 11759 // 11760 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 11761 // to C++1z [over.over]/1.4, but we already checked for that case above. 11762 if (Opc == BO_LT && inTemplateInstantiation() && 11763 (pty->getKind() == BuiltinType::BoundMember || 11764 pty->getKind() == BuiltinType::Overload)) { 11765 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 11766 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 11767 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 11768 return isa<FunctionTemplateDecl>(ND); 11769 })) { 11770 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 11771 : OE->getNameLoc(), 11772 diag::err_template_kw_missing) 11773 << OE->getName().getAsString() << ""; 11774 return ExprError(); 11775 } 11776 } 11777 11778 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 11779 if (LHS.isInvalid()) return ExprError(); 11780 LHSExpr = LHS.get(); 11781 } 11782 11783 // Handle pseudo-objects in the RHS. 11784 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 11785 // An overload in the RHS can potentially be resolved by the type 11786 // being assigned to. 11787 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 11788 if (getLangOpts().CPlusPlus && 11789 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 11790 LHSExpr->getType()->isOverloadableType())) 11791 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11792 11793 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 11794 } 11795 11796 // Don't resolve overloads if the other type is overloadable. 11797 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 11798 LHSExpr->getType()->isOverloadableType()) 11799 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11800 11801 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 11802 if (!resolvedRHS.isUsable()) return ExprError(); 11803 RHSExpr = resolvedRHS.get(); 11804 } 11805 11806 if (getLangOpts().CPlusPlus) { 11807 // If either expression is type-dependent, always build an 11808 // overloaded op. 11809 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 11810 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11811 11812 // Otherwise, build an overloaded op if either expression has an 11813 // overloadable type. 11814 if (LHSExpr->getType()->isOverloadableType() || 11815 RHSExpr->getType()->isOverloadableType()) 11816 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11817 } 11818 11819 // Build a built-in binary operation. 11820 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 11821 } 11822 11823 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 11824 UnaryOperatorKind Opc, 11825 Expr *InputExpr) { 11826 ExprResult Input = InputExpr; 11827 ExprValueKind VK = VK_RValue; 11828 ExprObjectKind OK = OK_Ordinary; 11829 QualType resultType; 11830 if (getLangOpts().OpenCL) { 11831 QualType Ty = InputExpr->getType(); 11832 // The only legal unary operation for atomics is '&'. 11833 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 11834 // OpenCL special types - image, sampler, pipe, and blocks are to be used 11835 // only with a builtin functions and therefore should be disallowed here. 11836 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 11837 || Ty->isBlockPointerType())) { 11838 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11839 << InputExpr->getType() 11840 << Input.get()->getSourceRange()); 11841 } 11842 } 11843 switch (Opc) { 11844 case UO_PreInc: 11845 case UO_PreDec: 11846 case UO_PostInc: 11847 case UO_PostDec: 11848 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 11849 OpLoc, 11850 Opc == UO_PreInc || 11851 Opc == UO_PostInc, 11852 Opc == UO_PreInc || 11853 Opc == UO_PreDec); 11854 break; 11855 case UO_AddrOf: 11856 resultType = CheckAddressOfOperand(Input, OpLoc); 11857 RecordModifiableNonNullParam(*this, InputExpr); 11858 break; 11859 case UO_Deref: { 11860 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 11861 if (Input.isInvalid()) return ExprError(); 11862 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 11863 break; 11864 } 11865 case UO_Plus: 11866 case UO_Minus: 11867 Input = UsualUnaryConversions(Input.get()); 11868 if (Input.isInvalid()) return ExprError(); 11869 resultType = Input.get()->getType(); 11870 if (resultType->isDependentType()) 11871 break; 11872 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 11873 break; 11874 else if (resultType->isVectorType() && 11875 // The z vector extensions don't allow + or - with bool vectors. 11876 (!Context.getLangOpts().ZVector || 11877 resultType->getAs<VectorType>()->getVectorKind() != 11878 VectorType::AltiVecBool)) 11879 break; 11880 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 11881 Opc == UO_Plus && 11882 resultType->isPointerType()) 11883 break; 11884 11885 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11886 << resultType << Input.get()->getSourceRange()); 11887 11888 case UO_Not: // bitwise complement 11889 Input = UsualUnaryConversions(Input.get()); 11890 if (Input.isInvalid()) 11891 return ExprError(); 11892 resultType = Input.get()->getType(); 11893 if (resultType->isDependentType()) 11894 break; 11895 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 11896 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 11897 // C99 does not support '~' for complex conjugation. 11898 Diag(OpLoc, diag::ext_integer_complement_complex) 11899 << resultType << Input.get()->getSourceRange(); 11900 else if (resultType->hasIntegerRepresentation()) 11901 break; 11902 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 11903 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 11904 // on vector float types. 11905 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 11906 if (!T->isIntegerType()) 11907 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11908 << resultType << Input.get()->getSourceRange()); 11909 } else { 11910 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11911 << resultType << Input.get()->getSourceRange()); 11912 } 11913 break; 11914 11915 case UO_LNot: // logical negation 11916 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 11917 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 11918 if (Input.isInvalid()) return ExprError(); 11919 resultType = Input.get()->getType(); 11920 11921 // Though we still have to promote half FP to float... 11922 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 11923 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 11924 resultType = Context.FloatTy; 11925 } 11926 11927 if (resultType->isDependentType()) 11928 break; 11929 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 11930 // C99 6.5.3.3p1: ok, fallthrough; 11931 if (Context.getLangOpts().CPlusPlus) { 11932 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 11933 // operand contextually converted to bool. 11934 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 11935 ScalarTypeToBooleanCastKind(resultType)); 11936 } else if (Context.getLangOpts().OpenCL && 11937 Context.getLangOpts().OpenCLVersion < 120) { 11938 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 11939 // operate on scalar float types. 11940 if (!resultType->isIntegerType() && !resultType->isPointerType()) 11941 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11942 << resultType << Input.get()->getSourceRange()); 11943 } 11944 } else if (resultType->isExtVectorType()) { 11945 if (Context.getLangOpts().OpenCL && 11946 Context.getLangOpts().OpenCLVersion < 120) { 11947 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 11948 // operate on vector float types. 11949 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 11950 if (!T->isIntegerType()) 11951 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11952 << resultType << Input.get()->getSourceRange()); 11953 } 11954 // Vector logical not returns the signed variant of the operand type. 11955 resultType = GetSignedVectorType(resultType); 11956 break; 11957 } else { 11958 // FIXME: GCC's vector extension permits the usage of '!' with a vector 11959 // type in C++. We should allow that here too. 11960 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11961 << resultType << Input.get()->getSourceRange()); 11962 } 11963 11964 // LNot always has type int. C99 6.5.3.3p5. 11965 // In C++, it's bool. C++ 5.3.1p8 11966 resultType = Context.getLogicalOperationType(); 11967 break; 11968 case UO_Real: 11969 case UO_Imag: 11970 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 11971 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 11972 // complex l-values to ordinary l-values and all other values to r-values. 11973 if (Input.isInvalid()) return ExprError(); 11974 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 11975 if (Input.get()->getValueKind() != VK_RValue && 11976 Input.get()->getObjectKind() == OK_Ordinary) 11977 VK = Input.get()->getValueKind(); 11978 } else if (!getLangOpts().CPlusPlus) { 11979 // In C, a volatile scalar is read by __imag. In C++, it is not. 11980 Input = DefaultLvalueConversion(Input.get()); 11981 } 11982 break; 11983 case UO_Extension: 11984 resultType = Input.get()->getType(); 11985 VK = Input.get()->getValueKind(); 11986 OK = Input.get()->getObjectKind(); 11987 break; 11988 case UO_Coawait: 11989 // It's unnessesary to represent the pass-through operator co_await in the 11990 // AST; just return the input expression instead. 11991 assert(!Input.get()->getType()->isDependentType() && 11992 "the co_await expression must be non-dependant before " 11993 "building operator co_await"); 11994 return Input; 11995 } 11996 if (resultType.isNull() || Input.isInvalid()) 11997 return ExprError(); 11998 11999 // Check for array bounds violations in the operand of the UnaryOperator, 12000 // except for the '*' and '&' operators that have to be handled specially 12001 // by CheckArrayAccess (as there are special cases like &array[arraysize] 12002 // that are explicitly defined as valid by the standard). 12003 if (Opc != UO_AddrOf && Opc != UO_Deref) 12004 CheckArrayAccess(Input.get()); 12005 12006 return new (Context) 12007 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc); 12008 } 12009 12010 /// \brief Determine whether the given expression is a qualified member 12011 /// access expression, of a form that could be turned into a pointer to member 12012 /// with the address-of operator. 12013 static bool isQualifiedMemberAccess(Expr *E) { 12014 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12015 if (!DRE->getQualifier()) 12016 return false; 12017 12018 ValueDecl *VD = DRE->getDecl(); 12019 if (!VD->isCXXClassMember()) 12020 return false; 12021 12022 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 12023 return true; 12024 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 12025 return Method->isInstance(); 12026 12027 return false; 12028 } 12029 12030 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 12031 if (!ULE->getQualifier()) 12032 return false; 12033 12034 for (NamedDecl *D : ULE->decls()) { 12035 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 12036 if (Method->isInstance()) 12037 return true; 12038 } else { 12039 // Overload set does not contain methods. 12040 break; 12041 } 12042 } 12043 12044 return false; 12045 } 12046 12047 return false; 12048 } 12049 12050 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 12051 UnaryOperatorKind Opc, Expr *Input) { 12052 // First things first: handle placeholders so that the 12053 // overloaded-operator check considers the right type. 12054 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 12055 // Increment and decrement of pseudo-object references. 12056 if (pty->getKind() == BuiltinType::PseudoObject && 12057 UnaryOperator::isIncrementDecrementOp(Opc)) 12058 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 12059 12060 // extension is always a builtin operator. 12061 if (Opc == UO_Extension) 12062 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12063 12064 // & gets special logic for several kinds of placeholder. 12065 // The builtin code knows what to do. 12066 if (Opc == UO_AddrOf && 12067 (pty->getKind() == BuiltinType::Overload || 12068 pty->getKind() == BuiltinType::UnknownAny || 12069 pty->getKind() == BuiltinType::BoundMember)) 12070 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12071 12072 // Anything else needs to be handled now. 12073 ExprResult Result = CheckPlaceholderExpr(Input); 12074 if (Result.isInvalid()) return ExprError(); 12075 Input = Result.get(); 12076 } 12077 12078 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 12079 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 12080 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 12081 // Find all of the overloaded operators visible from this 12082 // point. We perform both an operator-name lookup from the local 12083 // scope and an argument-dependent lookup based on the types of 12084 // the arguments. 12085 UnresolvedSet<16> Functions; 12086 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 12087 if (S && OverOp != OO_None) 12088 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 12089 Functions); 12090 12091 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 12092 } 12093 12094 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12095 } 12096 12097 // Unary Operators. 'Tok' is the token for the operator. 12098 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 12099 tok::TokenKind Op, Expr *Input) { 12100 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 12101 } 12102 12103 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 12104 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 12105 LabelDecl *TheDecl) { 12106 TheDecl->markUsed(Context); 12107 // Create the AST node. The address of a label always has type 'void*'. 12108 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 12109 Context.getPointerType(Context.VoidTy)); 12110 } 12111 12112 /// Given the last statement in a statement-expression, check whether 12113 /// the result is a producing expression (like a call to an 12114 /// ns_returns_retained function) and, if so, rebuild it to hoist the 12115 /// release out of the full-expression. Otherwise, return null. 12116 /// Cannot fail. 12117 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 12118 // Should always be wrapped with one of these. 12119 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 12120 if (!cleanups) return nullptr; 12121 12122 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 12123 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 12124 return nullptr; 12125 12126 // Splice out the cast. This shouldn't modify any interesting 12127 // features of the statement. 12128 Expr *producer = cast->getSubExpr(); 12129 assert(producer->getType() == cast->getType()); 12130 assert(producer->getValueKind() == cast->getValueKind()); 12131 cleanups->setSubExpr(producer); 12132 return cleanups; 12133 } 12134 12135 void Sema::ActOnStartStmtExpr() { 12136 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 12137 } 12138 12139 void Sema::ActOnStmtExprError() { 12140 // Note that function is also called by TreeTransform when leaving a 12141 // StmtExpr scope without rebuilding anything. 12142 12143 DiscardCleanupsInEvaluationContext(); 12144 PopExpressionEvaluationContext(); 12145 } 12146 12147 ExprResult 12148 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 12149 SourceLocation RPLoc) { // "({..})" 12150 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 12151 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 12152 12153 if (hasAnyUnrecoverableErrorsInThisFunction()) 12154 DiscardCleanupsInEvaluationContext(); 12155 assert(!Cleanup.exprNeedsCleanups() && 12156 "cleanups within StmtExpr not correctly bound!"); 12157 PopExpressionEvaluationContext(); 12158 12159 // FIXME: there are a variety of strange constraints to enforce here, for 12160 // example, it is not possible to goto into a stmt expression apparently. 12161 // More semantic analysis is needed. 12162 12163 // If there are sub-stmts in the compound stmt, take the type of the last one 12164 // as the type of the stmtexpr. 12165 QualType Ty = Context.VoidTy; 12166 bool StmtExprMayBindToTemp = false; 12167 if (!Compound->body_empty()) { 12168 Stmt *LastStmt = Compound->body_back(); 12169 LabelStmt *LastLabelStmt = nullptr; 12170 // If LastStmt is a label, skip down through into the body. 12171 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 12172 LastLabelStmt = Label; 12173 LastStmt = Label->getSubStmt(); 12174 } 12175 12176 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 12177 // Do function/array conversion on the last expression, but not 12178 // lvalue-to-rvalue. However, initialize an unqualified type. 12179 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 12180 if (LastExpr.isInvalid()) 12181 return ExprError(); 12182 Ty = LastExpr.get()->getType().getUnqualifiedType(); 12183 12184 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 12185 // In ARC, if the final expression ends in a consume, splice 12186 // the consume out and bind it later. In the alternate case 12187 // (when dealing with a retainable type), the result 12188 // initialization will create a produce. In both cases the 12189 // result will be +1, and we'll need to balance that out with 12190 // a bind. 12191 if (Expr *rebuiltLastStmt 12192 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 12193 LastExpr = rebuiltLastStmt; 12194 } else { 12195 LastExpr = PerformCopyInitialization( 12196 InitializedEntity::InitializeResult(LPLoc, 12197 Ty, 12198 false), 12199 SourceLocation(), 12200 LastExpr); 12201 } 12202 12203 if (LastExpr.isInvalid()) 12204 return ExprError(); 12205 if (LastExpr.get() != nullptr) { 12206 if (!LastLabelStmt) 12207 Compound->setLastStmt(LastExpr.get()); 12208 else 12209 LastLabelStmt->setSubStmt(LastExpr.get()); 12210 StmtExprMayBindToTemp = true; 12211 } 12212 } 12213 } 12214 } 12215 12216 // FIXME: Check that expression type is complete/non-abstract; statement 12217 // expressions are not lvalues. 12218 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 12219 if (StmtExprMayBindToTemp) 12220 return MaybeBindToTemporary(ResStmtExpr); 12221 return ResStmtExpr; 12222 } 12223 12224 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 12225 TypeSourceInfo *TInfo, 12226 ArrayRef<OffsetOfComponent> Components, 12227 SourceLocation RParenLoc) { 12228 QualType ArgTy = TInfo->getType(); 12229 bool Dependent = ArgTy->isDependentType(); 12230 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 12231 12232 // We must have at least one component that refers to the type, and the first 12233 // one is known to be a field designator. Verify that the ArgTy represents 12234 // a struct/union/class. 12235 if (!Dependent && !ArgTy->isRecordType()) 12236 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 12237 << ArgTy << TypeRange); 12238 12239 // Type must be complete per C99 7.17p3 because a declaring a variable 12240 // with an incomplete type would be ill-formed. 12241 if (!Dependent 12242 && RequireCompleteType(BuiltinLoc, ArgTy, 12243 diag::err_offsetof_incomplete_type, TypeRange)) 12244 return ExprError(); 12245 12246 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 12247 // GCC extension, diagnose them. 12248 // FIXME: This diagnostic isn't actually visible because the location is in 12249 // a system header! 12250 if (Components.size() != 1) 12251 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 12252 << SourceRange(Components[1].LocStart, Components.back().LocEnd); 12253 12254 bool DidWarnAboutNonPOD = false; 12255 QualType CurrentType = ArgTy; 12256 SmallVector<OffsetOfNode, 4> Comps; 12257 SmallVector<Expr*, 4> Exprs; 12258 for (const OffsetOfComponent &OC : Components) { 12259 if (OC.isBrackets) { 12260 // Offset of an array sub-field. TODO: Should we allow vector elements? 12261 if (!CurrentType->isDependentType()) { 12262 const ArrayType *AT = Context.getAsArrayType(CurrentType); 12263 if(!AT) 12264 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 12265 << CurrentType); 12266 CurrentType = AT->getElementType(); 12267 } else 12268 CurrentType = Context.DependentTy; 12269 12270 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 12271 if (IdxRval.isInvalid()) 12272 return ExprError(); 12273 Expr *Idx = IdxRval.get(); 12274 12275 // The expression must be an integral expression. 12276 // FIXME: An integral constant expression? 12277 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 12278 !Idx->getType()->isIntegerType()) 12279 return ExprError(Diag(Idx->getLocStart(), 12280 diag::err_typecheck_subscript_not_integer) 12281 << Idx->getSourceRange()); 12282 12283 // Record this array index. 12284 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 12285 Exprs.push_back(Idx); 12286 continue; 12287 } 12288 12289 // Offset of a field. 12290 if (CurrentType->isDependentType()) { 12291 // We have the offset of a field, but we can't look into the dependent 12292 // type. Just record the identifier of the field. 12293 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 12294 CurrentType = Context.DependentTy; 12295 continue; 12296 } 12297 12298 // We need to have a complete type to look into. 12299 if (RequireCompleteType(OC.LocStart, CurrentType, 12300 diag::err_offsetof_incomplete_type)) 12301 return ExprError(); 12302 12303 // Look for the designated field. 12304 const RecordType *RC = CurrentType->getAs<RecordType>(); 12305 if (!RC) 12306 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 12307 << CurrentType); 12308 RecordDecl *RD = RC->getDecl(); 12309 12310 // C++ [lib.support.types]p5: 12311 // The macro offsetof accepts a restricted set of type arguments in this 12312 // International Standard. type shall be a POD structure or a POD union 12313 // (clause 9). 12314 // C++11 [support.types]p4: 12315 // If type is not a standard-layout class (Clause 9), the results are 12316 // undefined. 12317 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 12318 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 12319 unsigned DiagID = 12320 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 12321 : diag::ext_offsetof_non_pod_type; 12322 12323 if (!IsSafe && !DidWarnAboutNonPOD && 12324 DiagRuntimeBehavior(BuiltinLoc, nullptr, 12325 PDiag(DiagID) 12326 << SourceRange(Components[0].LocStart, OC.LocEnd) 12327 << CurrentType)) 12328 DidWarnAboutNonPOD = true; 12329 } 12330 12331 // Look for the field. 12332 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 12333 LookupQualifiedName(R, RD); 12334 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 12335 IndirectFieldDecl *IndirectMemberDecl = nullptr; 12336 if (!MemberDecl) { 12337 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 12338 MemberDecl = IndirectMemberDecl->getAnonField(); 12339 } 12340 12341 if (!MemberDecl) 12342 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 12343 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 12344 OC.LocEnd)); 12345 12346 // C99 7.17p3: 12347 // (If the specified member is a bit-field, the behavior is undefined.) 12348 // 12349 // We diagnose this as an error. 12350 if (MemberDecl->isBitField()) { 12351 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 12352 << MemberDecl->getDeclName() 12353 << SourceRange(BuiltinLoc, RParenLoc); 12354 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 12355 return ExprError(); 12356 } 12357 12358 RecordDecl *Parent = MemberDecl->getParent(); 12359 if (IndirectMemberDecl) 12360 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 12361 12362 // If the member was found in a base class, introduce OffsetOfNodes for 12363 // the base class indirections. 12364 CXXBasePaths Paths; 12365 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 12366 Paths)) { 12367 if (Paths.getDetectedVirtual()) { 12368 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 12369 << MemberDecl->getDeclName() 12370 << SourceRange(BuiltinLoc, RParenLoc); 12371 return ExprError(); 12372 } 12373 12374 CXXBasePath &Path = Paths.front(); 12375 for (const CXXBasePathElement &B : Path) 12376 Comps.push_back(OffsetOfNode(B.Base)); 12377 } 12378 12379 if (IndirectMemberDecl) { 12380 for (auto *FI : IndirectMemberDecl->chain()) { 12381 assert(isa<FieldDecl>(FI)); 12382 Comps.push_back(OffsetOfNode(OC.LocStart, 12383 cast<FieldDecl>(FI), OC.LocEnd)); 12384 } 12385 } else 12386 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 12387 12388 CurrentType = MemberDecl->getType().getNonReferenceType(); 12389 } 12390 12391 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 12392 Comps, Exprs, RParenLoc); 12393 } 12394 12395 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 12396 SourceLocation BuiltinLoc, 12397 SourceLocation TypeLoc, 12398 ParsedType ParsedArgTy, 12399 ArrayRef<OffsetOfComponent> Components, 12400 SourceLocation RParenLoc) { 12401 12402 TypeSourceInfo *ArgTInfo; 12403 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 12404 if (ArgTy.isNull()) 12405 return ExprError(); 12406 12407 if (!ArgTInfo) 12408 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 12409 12410 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 12411 } 12412 12413 12414 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 12415 Expr *CondExpr, 12416 Expr *LHSExpr, Expr *RHSExpr, 12417 SourceLocation RPLoc) { 12418 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 12419 12420 ExprValueKind VK = VK_RValue; 12421 ExprObjectKind OK = OK_Ordinary; 12422 QualType resType; 12423 bool ValueDependent = false; 12424 bool CondIsTrue = false; 12425 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 12426 resType = Context.DependentTy; 12427 ValueDependent = true; 12428 } else { 12429 // The conditional expression is required to be a constant expression. 12430 llvm::APSInt condEval(32); 12431 ExprResult CondICE 12432 = VerifyIntegerConstantExpression(CondExpr, &condEval, 12433 diag::err_typecheck_choose_expr_requires_constant, false); 12434 if (CondICE.isInvalid()) 12435 return ExprError(); 12436 CondExpr = CondICE.get(); 12437 CondIsTrue = condEval.getZExtValue(); 12438 12439 // If the condition is > zero, then the AST type is the same as the LSHExpr. 12440 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 12441 12442 resType = ActiveExpr->getType(); 12443 ValueDependent = ActiveExpr->isValueDependent(); 12444 VK = ActiveExpr->getValueKind(); 12445 OK = ActiveExpr->getObjectKind(); 12446 } 12447 12448 return new (Context) 12449 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 12450 CondIsTrue, resType->isDependentType(), ValueDependent); 12451 } 12452 12453 //===----------------------------------------------------------------------===// 12454 // Clang Extensions. 12455 //===----------------------------------------------------------------------===// 12456 12457 /// ActOnBlockStart - This callback is invoked when a block literal is started. 12458 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 12459 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 12460 12461 if (LangOpts.CPlusPlus) { 12462 Decl *ManglingContextDecl; 12463 if (MangleNumberingContext *MCtx = 12464 getCurrentMangleNumberContext(Block->getDeclContext(), 12465 ManglingContextDecl)) { 12466 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 12467 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 12468 } 12469 } 12470 12471 PushBlockScope(CurScope, Block); 12472 CurContext->addDecl(Block); 12473 if (CurScope) 12474 PushDeclContext(CurScope, Block); 12475 else 12476 CurContext = Block; 12477 12478 getCurBlock()->HasImplicitReturnType = true; 12479 12480 // Enter a new evaluation context to insulate the block from any 12481 // cleanups from the enclosing full-expression. 12482 PushExpressionEvaluationContext( 12483 ExpressionEvaluationContext::PotentiallyEvaluated); 12484 } 12485 12486 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 12487 Scope *CurScope) { 12488 assert(ParamInfo.getIdentifier() == nullptr && 12489 "block-id should have no identifier!"); 12490 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 12491 BlockScopeInfo *CurBlock = getCurBlock(); 12492 12493 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 12494 QualType T = Sig->getType(); 12495 12496 // FIXME: We should allow unexpanded parameter packs here, but that would, 12497 // in turn, make the block expression contain unexpanded parameter packs. 12498 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 12499 // Drop the parameters. 12500 FunctionProtoType::ExtProtoInfo EPI; 12501 EPI.HasTrailingReturn = false; 12502 EPI.TypeQuals |= DeclSpec::TQ_const; 12503 T = Context.getFunctionType(Context.DependentTy, None, EPI); 12504 Sig = Context.getTrivialTypeSourceInfo(T); 12505 } 12506 12507 // GetTypeForDeclarator always produces a function type for a block 12508 // literal signature. Furthermore, it is always a FunctionProtoType 12509 // unless the function was written with a typedef. 12510 assert(T->isFunctionType() && 12511 "GetTypeForDeclarator made a non-function block signature"); 12512 12513 // Look for an explicit signature in that function type. 12514 FunctionProtoTypeLoc ExplicitSignature; 12515 12516 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 12517 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) { 12518 12519 // Check whether that explicit signature was synthesized by 12520 // GetTypeForDeclarator. If so, don't save that as part of the 12521 // written signature. 12522 if (ExplicitSignature.getLocalRangeBegin() == 12523 ExplicitSignature.getLocalRangeEnd()) { 12524 // This would be much cheaper if we stored TypeLocs instead of 12525 // TypeSourceInfos. 12526 TypeLoc Result = ExplicitSignature.getReturnLoc(); 12527 unsigned Size = Result.getFullDataSize(); 12528 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 12529 Sig->getTypeLoc().initializeFullCopy(Result, Size); 12530 12531 ExplicitSignature = FunctionProtoTypeLoc(); 12532 } 12533 } 12534 12535 CurBlock->TheDecl->setSignatureAsWritten(Sig); 12536 CurBlock->FunctionType = T; 12537 12538 const FunctionType *Fn = T->getAs<FunctionType>(); 12539 QualType RetTy = Fn->getReturnType(); 12540 bool isVariadic = 12541 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 12542 12543 CurBlock->TheDecl->setIsVariadic(isVariadic); 12544 12545 // Context.DependentTy is used as a placeholder for a missing block 12546 // return type. TODO: what should we do with declarators like: 12547 // ^ * { ... } 12548 // If the answer is "apply template argument deduction".... 12549 if (RetTy != Context.DependentTy) { 12550 CurBlock->ReturnType = RetTy; 12551 CurBlock->TheDecl->setBlockMissingReturnType(false); 12552 CurBlock->HasImplicitReturnType = false; 12553 } 12554 12555 // Push block parameters from the declarator if we had them. 12556 SmallVector<ParmVarDecl*, 8> Params; 12557 if (ExplicitSignature) { 12558 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 12559 ParmVarDecl *Param = ExplicitSignature.getParam(I); 12560 if (Param->getIdentifier() == nullptr && 12561 !Param->isImplicit() && 12562 !Param->isInvalidDecl() && 12563 !getLangOpts().CPlusPlus) 12564 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 12565 Params.push_back(Param); 12566 } 12567 12568 // Fake up parameter variables if we have a typedef, like 12569 // ^ fntype { ... } 12570 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 12571 for (const auto &I : Fn->param_types()) { 12572 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 12573 CurBlock->TheDecl, ParamInfo.getLocStart(), I); 12574 Params.push_back(Param); 12575 } 12576 } 12577 12578 // Set the parameters on the block decl. 12579 if (!Params.empty()) { 12580 CurBlock->TheDecl->setParams(Params); 12581 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 12582 /*CheckParameterNames=*/false); 12583 } 12584 12585 // Finally we can process decl attributes. 12586 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 12587 12588 // Put the parameter variables in scope. 12589 for (auto AI : CurBlock->TheDecl->parameters()) { 12590 AI->setOwningFunction(CurBlock->TheDecl); 12591 12592 // If this has an identifier, add it to the scope stack. 12593 if (AI->getIdentifier()) { 12594 CheckShadow(CurBlock->TheScope, AI); 12595 12596 PushOnScopeChains(AI, CurBlock->TheScope); 12597 } 12598 } 12599 } 12600 12601 /// ActOnBlockError - If there is an error parsing a block, this callback 12602 /// is invoked to pop the information about the block from the action impl. 12603 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 12604 // Leave the expression-evaluation context. 12605 DiscardCleanupsInEvaluationContext(); 12606 PopExpressionEvaluationContext(); 12607 12608 // Pop off CurBlock, handle nested blocks. 12609 PopDeclContext(); 12610 PopFunctionScopeInfo(); 12611 } 12612 12613 /// ActOnBlockStmtExpr - This is called when the body of a block statement 12614 /// literal was successfully completed. ^(int x){...} 12615 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 12616 Stmt *Body, Scope *CurScope) { 12617 // If blocks are disabled, emit an error. 12618 if (!LangOpts.Blocks) 12619 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 12620 12621 // Leave the expression-evaluation context. 12622 if (hasAnyUnrecoverableErrorsInThisFunction()) 12623 DiscardCleanupsInEvaluationContext(); 12624 assert(!Cleanup.exprNeedsCleanups() && 12625 "cleanups within block not correctly bound!"); 12626 PopExpressionEvaluationContext(); 12627 12628 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 12629 12630 if (BSI->HasImplicitReturnType) 12631 deduceClosureReturnType(*BSI); 12632 12633 PopDeclContext(); 12634 12635 QualType RetTy = Context.VoidTy; 12636 if (!BSI->ReturnType.isNull()) 12637 RetTy = BSI->ReturnType; 12638 12639 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 12640 QualType BlockTy; 12641 12642 // Set the captured variables on the block. 12643 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 12644 SmallVector<BlockDecl::Capture, 4> Captures; 12645 for (CapturingScopeInfo::Capture &Cap : BSI->Captures) { 12646 if (Cap.isThisCapture()) 12647 continue; 12648 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 12649 Cap.isNested(), Cap.getInitExpr()); 12650 Captures.push_back(NewCap); 12651 } 12652 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 12653 12654 // If the user wrote a function type in some form, try to use that. 12655 if (!BSI->FunctionType.isNull()) { 12656 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 12657 12658 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 12659 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 12660 12661 // Turn protoless block types into nullary block types. 12662 if (isa<FunctionNoProtoType>(FTy)) { 12663 FunctionProtoType::ExtProtoInfo EPI; 12664 EPI.ExtInfo = Ext; 12665 BlockTy = Context.getFunctionType(RetTy, None, EPI); 12666 12667 // Otherwise, if we don't need to change anything about the function type, 12668 // preserve its sugar structure. 12669 } else if (FTy->getReturnType() == RetTy && 12670 (!NoReturn || FTy->getNoReturnAttr())) { 12671 BlockTy = BSI->FunctionType; 12672 12673 // Otherwise, make the minimal modifications to the function type. 12674 } else { 12675 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 12676 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 12677 EPI.TypeQuals = 0; // FIXME: silently? 12678 EPI.ExtInfo = Ext; 12679 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 12680 } 12681 12682 // If we don't have a function type, just build one from nothing. 12683 } else { 12684 FunctionProtoType::ExtProtoInfo EPI; 12685 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 12686 BlockTy = Context.getFunctionType(RetTy, None, EPI); 12687 } 12688 12689 DiagnoseUnusedParameters(BSI->TheDecl->parameters()); 12690 BlockTy = Context.getBlockPointerType(BlockTy); 12691 12692 // If needed, diagnose invalid gotos and switches in the block. 12693 if (getCurFunction()->NeedsScopeChecking() && 12694 !PP.isCodeCompletionEnabled()) 12695 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 12696 12697 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 12698 12699 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 12700 DiagnoseUnguardedAvailabilityViolations(BSI->TheDecl); 12701 12702 // Try to apply the named return value optimization. We have to check again 12703 // if we can do this, though, because blocks keep return statements around 12704 // to deduce an implicit return type. 12705 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 12706 !BSI->TheDecl->isDependentContext()) 12707 computeNRVO(Body, BSI); 12708 12709 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 12710 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 12711 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 12712 12713 // If the block isn't obviously global, i.e. it captures anything at 12714 // all, then we need to do a few things in the surrounding context: 12715 if (Result->getBlockDecl()->hasCaptures()) { 12716 // First, this expression has a new cleanup object. 12717 ExprCleanupObjects.push_back(Result->getBlockDecl()); 12718 Cleanup.setExprNeedsCleanups(true); 12719 12720 // It also gets a branch-protected scope if any of the captured 12721 // variables needs destruction. 12722 for (const auto &CI : Result->getBlockDecl()->captures()) { 12723 const VarDecl *var = CI.getVariable(); 12724 if (var->getType().isDestructedType() != QualType::DK_none) { 12725 getCurFunction()->setHasBranchProtectedScope(); 12726 break; 12727 } 12728 } 12729 } 12730 12731 return Result; 12732 } 12733 12734 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 12735 SourceLocation RPLoc) { 12736 TypeSourceInfo *TInfo; 12737 GetTypeFromParser(Ty, &TInfo); 12738 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 12739 } 12740 12741 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 12742 Expr *E, TypeSourceInfo *TInfo, 12743 SourceLocation RPLoc) { 12744 Expr *OrigExpr = E; 12745 bool IsMS = false; 12746 12747 // CUDA device code does not support varargs. 12748 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 12749 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 12750 CUDAFunctionTarget T = IdentifyCUDATarget(F); 12751 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 12752 return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device)); 12753 } 12754 } 12755 12756 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 12757 // as Microsoft ABI on an actual Microsoft platform, where 12758 // __builtin_ms_va_list and __builtin_va_list are the same.) 12759 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 12760 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 12761 QualType MSVaListType = Context.getBuiltinMSVaListType(); 12762 if (Context.hasSameType(MSVaListType, E->getType())) { 12763 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 12764 return ExprError(); 12765 IsMS = true; 12766 } 12767 } 12768 12769 // Get the va_list type 12770 QualType VaListType = Context.getBuiltinVaListType(); 12771 if (!IsMS) { 12772 if (VaListType->isArrayType()) { 12773 // Deal with implicit array decay; for example, on x86-64, 12774 // va_list is an array, but it's supposed to decay to 12775 // a pointer for va_arg. 12776 VaListType = Context.getArrayDecayedType(VaListType); 12777 // Make sure the input expression also decays appropriately. 12778 ExprResult Result = UsualUnaryConversions(E); 12779 if (Result.isInvalid()) 12780 return ExprError(); 12781 E = Result.get(); 12782 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 12783 // If va_list is a record type and we are compiling in C++ mode, 12784 // check the argument using reference binding. 12785 InitializedEntity Entity = InitializedEntity::InitializeParameter( 12786 Context, Context.getLValueReferenceType(VaListType), false); 12787 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 12788 if (Init.isInvalid()) 12789 return ExprError(); 12790 E = Init.getAs<Expr>(); 12791 } else { 12792 // Otherwise, the va_list argument must be an l-value because 12793 // it is modified by va_arg. 12794 if (!E->isTypeDependent() && 12795 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 12796 return ExprError(); 12797 } 12798 } 12799 12800 if (!IsMS && !E->isTypeDependent() && 12801 !Context.hasSameType(VaListType, E->getType())) 12802 return ExprError(Diag(E->getLocStart(), 12803 diag::err_first_argument_to_va_arg_not_of_type_va_list) 12804 << OrigExpr->getType() << E->getSourceRange()); 12805 12806 if (!TInfo->getType()->isDependentType()) { 12807 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 12808 diag::err_second_parameter_to_va_arg_incomplete, 12809 TInfo->getTypeLoc())) 12810 return ExprError(); 12811 12812 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 12813 TInfo->getType(), 12814 diag::err_second_parameter_to_va_arg_abstract, 12815 TInfo->getTypeLoc())) 12816 return ExprError(); 12817 12818 if (!TInfo->getType().isPODType(Context)) { 12819 Diag(TInfo->getTypeLoc().getBeginLoc(), 12820 TInfo->getType()->isObjCLifetimeType() 12821 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 12822 : diag::warn_second_parameter_to_va_arg_not_pod) 12823 << TInfo->getType() 12824 << TInfo->getTypeLoc().getSourceRange(); 12825 } 12826 12827 // Check for va_arg where arguments of the given type will be promoted 12828 // (i.e. this va_arg is guaranteed to have undefined behavior). 12829 QualType PromoteType; 12830 if (TInfo->getType()->isPromotableIntegerType()) { 12831 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 12832 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 12833 PromoteType = QualType(); 12834 } 12835 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 12836 PromoteType = Context.DoubleTy; 12837 if (!PromoteType.isNull()) 12838 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 12839 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 12840 << TInfo->getType() 12841 << PromoteType 12842 << TInfo->getTypeLoc().getSourceRange()); 12843 } 12844 12845 QualType T = TInfo->getType().getNonLValueExprType(Context); 12846 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 12847 } 12848 12849 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 12850 // The type of __null will be int or long, depending on the size of 12851 // pointers on the target. 12852 QualType Ty; 12853 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 12854 if (pw == Context.getTargetInfo().getIntWidth()) 12855 Ty = Context.IntTy; 12856 else if (pw == Context.getTargetInfo().getLongWidth()) 12857 Ty = Context.LongTy; 12858 else if (pw == Context.getTargetInfo().getLongLongWidth()) 12859 Ty = Context.LongLongTy; 12860 else { 12861 llvm_unreachable("I don't know size of pointer!"); 12862 } 12863 12864 return new (Context) GNUNullExpr(Ty, TokenLoc); 12865 } 12866 12867 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 12868 bool Diagnose) { 12869 if (!getLangOpts().ObjC1) 12870 return false; 12871 12872 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 12873 if (!PT) 12874 return false; 12875 12876 if (!PT->isObjCIdType()) { 12877 // Check if the destination is the 'NSString' interface. 12878 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 12879 if (!ID || !ID->getIdentifier()->isStr("NSString")) 12880 return false; 12881 } 12882 12883 // Ignore any parens, implicit casts (should only be 12884 // array-to-pointer decays), and not-so-opaque values. The last is 12885 // important for making this trigger for property assignments. 12886 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 12887 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 12888 if (OV->getSourceExpr()) 12889 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 12890 12891 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 12892 if (!SL || !SL->isAscii()) 12893 return false; 12894 if (Diagnose) { 12895 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix) 12896 << FixItHint::CreateInsertion(SL->getLocStart(), "@"); 12897 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get(); 12898 } 12899 return true; 12900 } 12901 12902 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 12903 const Expr *SrcExpr) { 12904 if (!DstType->isFunctionPointerType() || 12905 !SrcExpr->getType()->isFunctionType()) 12906 return false; 12907 12908 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 12909 if (!DRE) 12910 return false; 12911 12912 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 12913 if (!FD) 12914 return false; 12915 12916 return !S.checkAddressOfFunctionIsAvailable(FD, 12917 /*Complain=*/true, 12918 SrcExpr->getLocStart()); 12919 } 12920 12921 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 12922 SourceLocation Loc, 12923 QualType DstType, QualType SrcType, 12924 Expr *SrcExpr, AssignmentAction Action, 12925 bool *Complained) { 12926 if (Complained) 12927 *Complained = false; 12928 12929 // Decode the result (notice that AST's are still created for extensions). 12930 bool CheckInferredResultType = false; 12931 bool isInvalid = false; 12932 unsigned DiagKind = 0; 12933 FixItHint Hint; 12934 ConversionFixItGenerator ConvHints; 12935 bool MayHaveConvFixit = false; 12936 bool MayHaveFunctionDiff = false; 12937 const ObjCInterfaceDecl *IFace = nullptr; 12938 const ObjCProtocolDecl *PDecl = nullptr; 12939 12940 switch (ConvTy) { 12941 case Compatible: 12942 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 12943 return false; 12944 12945 case PointerToInt: 12946 DiagKind = diag::ext_typecheck_convert_pointer_int; 12947 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12948 MayHaveConvFixit = true; 12949 break; 12950 case IntToPointer: 12951 DiagKind = diag::ext_typecheck_convert_int_pointer; 12952 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12953 MayHaveConvFixit = true; 12954 break; 12955 case IncompatiblePointer: 12956 if (Action == AA_Passing_CFAudited) 12957 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 12958 else if (SrcType->isFunctionPointerType() && 12959 DstType->isFunctionPointerType()) 12960 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 12961 else 12962 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 12963 12964 CheckInferredResultType = DstType->isObjCObjectPointerType() && 12965 SrcType->isObjCObjectPointerType(); 12966 if (Hint.isNull() && !CheckInferredResultType) { 12967 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12968 } 12969 else if (CheckInferredResultType) { 12970 SrcType = SrcType.getUnqualifiedType(); 12971 DstType = DstType.getUnqualifiedType(); 12972 } 12973 MayHaveConvFixit = true; 12974 break; 12975 case IncompatiblePointerSign: 12976 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 12977 break; 12978 case FunctionVoidPointer: 12979 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 12980 break; 12981 case IncompatiblePointerDiscardsQualifiers: { 12982 // Perform array-to-pointer decay if necessary. 12983 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 12984 12985 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 12986 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 12987 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 12988 DiagKind = diag::err_typecheck_incompatible_address_space; 12989 break; 12990 12991 12992 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 12993 DiagKind = diag::err_typecheck_incompatible_ownership; 12994 break; 12995 } 12996 12997 llvm_unreachable("unknown error case for discarding qualifiers!"); 12998 // fallthrough 12999 } 13000 case CompatiblePointerDiscardsQualifiers: 13001 // If the qualifiers lost were because we were applying the 13002 // (deprecated) C++ conversion from a string literal to a char* 13003 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 13004 // Ideally, this check would be performed in 13005 // checkPointerTypesForAssignment. However, that would require a 13006 // bit of refactoring (so that the second argument is an 13007 // expression, rather than a type), which should be done as part 13008 // of a larger effort to fix checkPointerTypesForAssignment for 13009 // C++ semantics. 13010 if (getLangOpts().CPlusPlus && 13011 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 13012 return false; 13013 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 13014 break; 13015 case IncompatibleNestedPointerQualifiers: 13016 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 13017 break; 13018 case IntToBlockPointer: 13019 DiagKind = diag::err_int_to_block_pointer; 13020 break; 13021 case IncompatibleBlockPointer: 13022 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 13023 break; 13024 case IncompatibleObjCQualifiedId: { 13025 if (SrcType->isObjCQualifiedIdType()) { 13026 const ObjCObjectPointerType *srcOPT = 13027 SrcType->getAs<ObjCObjectPointerType>(); 13028 for (auto *srcProto : srcOPT->quals()) { 13029 PDecl = srcProto; 13030 break; 13031 } 13032 if (const ObjCInterfaceType *IFaceT = 13033 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 13034 IFace = IFaceT->getDecl(); 13035 } 13036 else if (DstType->isObjCQualifiedIdType()) { 13037 const ObjCObjectPointerType *dstOPT = 13038 DstType->getAs<ObjCObjectPointerType>(); 13039 for (auto *dstProto : dstOPT->quals()) { 13040 PDecl = dstProto; 13041 break; 13042 } 13043 if (const ObjCInterfaceType *IFaceT = 13044 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 13045 IFace = IFaceT->getDecl(); 13046 } 13047 DiagKind = diag::warn_incompatible_qualified_id; 13048 break; 13049 } 13050 case IncompatibleVectors: 13051 DiagKind = diag::warn_incompatible_vectors; 13052 break; 13053 case IncompatibleObjCWeakRef: 13054 DiagKind = diag::err_arc_weak_unavailable_assign; 13055 break; 13056 case Incompatible: 13057 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 13058 if (Complained) 13059 *Complained = true; 13060 return true; 13061 } 13062 13063 DiagKind = diag::err_typecheck_convert_incompatible; 13064 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13065 MayHaveConvFixit = true; 13066 isInvalid = true; 13067 MayHaveFunctionDiff = true; 13068 break; 13069 } 13070 13071 QualType FirstType, SecondType; 13072 switch (Action) { 13073 case AA_Assigning: 13074 case AA_Initializing: 13075 // The destination type comes first. 13076 FirstType = DstType; 13077 SecondType = SrcType; 13078 break; 13079 13080 case AA_Returning: 13081 case AA_Passing: 13082 case AA_Passing_CFAudited: 13083 case AA_Converting: 13084 case AA_Sending: 13085 case AA_Casting: 13086 // The source type comes first. 13087 FirstType = SrcType; 13088 SecondType = DstType; 13089 break; 13090 } 13091 13092 PartialDiagnostic FDiag = PDiag(DiagKind); 13093 if (Action == AA_Passing_CFAudited) 13094 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 13095 else 13096 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 13097 13098 // If we can fix the conversion, suggest the FixIts. 13099 assert(ConvHints.isNull() || Hint.isNull()); 13100 if (!ConvHints.isNull()) { 13101 for (FixItHint &H : ConvHints.Hints) 13102 FDiag << H; 13103 } else { 13104 FDiag << Hint; 13105 } 13106 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 13107 13108 if (MayHaveFunctionDiff) 13109 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 13110 13111 Diag(Loc, FDiag); 13112 if (DiagKind == diag::warn_incompatible_qualified_id && 13113 PDecl && IFace && !IFace->hasDefinition()) 13114 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 13115 << IFace->getName() << PDecl->getName(); 13116 13117 if (SecondType == Context.OverloadTy) 13118 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 13119 FirstType, /*TakingAddress=*/true); 13120 13121 if (CheckInferredResultType) 13122 EmitRelatedResultTypeNote(SrcExpr); 13123 13124 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 13125 EmitRelatedResultTypeNoteForReturn(DstType); 13126 13127 if (Complained) 13128 *Complained = true; 13129 return isInvalid; 13130 } 13131 13132 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 13133 llvm::APSInt *Result) { 13134 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 13135 public: 13136 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 13137 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 13138 } 13139 } Diagnoser; 13140 13141 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 13142 } 13143 13144 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 13145 llvm::APSInt *Result, 13146 unsigned DiagID, 13147 bool AllowFold) { 13148 class IDDiagnoser : public VerifyICEDiagnoser { 13149 unsigned DiagID; 13150 13151 public: 13152 IDDiagnoser(unsigned DiagID) 13153 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 13154 13155 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 13156 S.Diag(Loc, DiagID) << SR; 13157 } 13158 } Diagnoser(DiagID); 13159 13160 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 13161 } 13162 13163 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 13164 SourceRange SR) { 13165 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 13166 } 13167 13168 ExprResult 13169 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 13170 VerifyICEDiagnoser &Diagnoser, 13171 bool AllowFold) { 13172 SourceLocation DiagLoc = E->getLocStart(); 13173 13174 if (getLangOpts().CPlusPlus11) { 13175 // C++11 [expr.const]p5: 13176 // If an expression of literal class type is used in a context where an 13177 // integral constant expression is required, then that class type shall 13178 // have a single non-explicit conversion function to an integral or 13179 // unscoped enumeration type 13180 ExprResult Converted; 13181 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 13182 public: 13183 CXX11ConvertDiagnoser(bool Silent) 13184 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 13185 Silent, true) {} 13186 13187 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 13188 QualType T) override { 13189 return S.Diag(Loc, diag::err_ice_not_integral) << T; 13190 } 13191 13192 SemaDiagnosticBuilder diagnoseIncomplete( 13193 Sema &S, SourceLocation Loc, QualType T) override { 13194 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 13195 } 13196 13197 SemaDiagnosticBuilder diagnoseExplicitConv( 13198 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 13199 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 13200 } 13201 13202 SemaDiagnosticBuilder noteExplicitConv( 13203 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 13204 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 13205 << ConvTy->isEnumeralType() << ConvTy; 13206 } 13207 13208 SemaDiagnosticBuilder diagnoseAmbiguous( 13209 Sema &S, SourceLocation Loc, QualType T) override { 13210 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 13211 } 13212 13213 SemaDiagnosticBuilder noteAmbiguous( 13214 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 13215 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 13216 << ConvTy->isEnumeralType() << ConvTy; 13217 } 13218 13219 SemaDiagnosticBuilder diagnoseConversion( 13220 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 13221 llvm_unreachable("conversion functions are permitted"); 13222 } 13223 } ConvertDiagnoser(Diagnoser.Suppress); 13224 13225 Converted = PerformContextualImplicitConversion(DiagLoc, E, 13226 ConvertDiagnoser); 13227 if (Converted.isInvalid()) 13228 return Converted; 13229 E = Converted.get(); 13230 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 13231 return ExprError(); 13232 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 13233 // An ICE must be of integral or unscoped enumeration type. 13234 if (!Diagnoser.Suppress) 13235 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 13236 return ExprError(); 13237 } 13238 13239 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 13240 // in the non-ICE case. 13241 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 13242 if (Result) 13243 *Result = E->EvaluateKnownConstInt(Context); 13244 return E; 13245 } 13246 13247 Expr::EvalResult EvalResult; 13248 SmallVector<PartialDiagnosticAt, 8> Notes; 13249 EvalResult.Diag = &Notes; 13250 13251 // Try to evaluate the expression, and produce diagnostics explaining why it's 13252 // not a constant expression as a side-effect. 13253 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 13254 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 13255 13256 // In C++11, we can rely on diagnostics being produced for any expression 13257 // which is not a constant expression. If no diagnostics were produced, then 13258 // this is a constant expression. 13259 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 13260 if (Result) 13261 *Result = EvalResult.Val.getInt(); 13262 return E; 13263 } 13264 13265 // If our only note is the usual "invalid subexpression" note, just point 13266 // the caret at its location rather than producing an essentially 13267 // redundant note. 13268 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 13269 diag::note_invalid_subexpr_in_const_expr) { 13270 DiagLoc = Notes[0].first; 13271 Notes.clear(); 13272 } 13273 13274 if (!Folded || !AllowFold) { 13275 if (!Diagnoser.Suppress) { 13276 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 13277 for (const PartialDiagnosticAt &Note : Notes) 13278 Diag(Note.first, Note.second); 13279 } 13280 13281 return ExprError(); 13282 } 13283 13284 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 13285 for (const PartialDiagnosticAt &Note : Notes) 13286 Diag(Note.first, Note.second); 13287 13288 if (Result) 13289 *Result = EvalResult.Val.getInt(); 13290 return E; 13291 } 13292 13293 namespace { 13294 // Handle the case where we conclude a expression which we speculatively 13295 // considered to be unevaluated is actually evaluated. 13296 class TransformToPE : public TreeTransform<TransformToPE> { 13297 typedef TreeTransform<TransformToPE> BaseTransform; 13298 13299 public: 13300 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 13301 13302 // Make sure we redo semantic analysis 13303 bool AlwaysRebuild() { return true; } 13304 13305 // Make sure we handle LabelStmts correctly. 13306 // FIXME: This does the right thing, but maybe we need a more general 13307 // fix to TreeTransform? 13308 StmtResult TransformLabelStmt(LabelStmt *S) { 13309 S->getDecl()->setStmt(nullptr); 13310 return BaseTransform::TransformLabelStmt(S); 13311 } 13312 13313 // We need to special-case DeclRefExprs referring to FieldDecls which 13314 // are not part of a member pointer formation; normal TreeTransforming 13315 // doesn't catch this case because of the way we represent them in the AST. 13316 // FIXME: This is a bit ugly; is it really the best way to handle this 13317 // case? 13318 // 13319 // Error on DeclRefExprs referring to FieldDecls. 13320 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 13321 if (isa<FieldDecl>(E->getDecl()) && 13322 !SemaRef.isUnevaluatedContext()) 13323 return SemaRef.Diag(E->getLocation(), 13324 diag::err_invalid_non_static_member_use) 13325 << E->getDecl() << E->getSourceRange(); 13326 13327 return BaseTransform::TransformDeclRefExpr(E); 13328 } 13329 13330 // Exception: filter out member pointer formation 13331 ExprResult TransformUnaryOperator(UnaryOperator *E) { 13332 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 13333 return E; 13334 13335 return BaseTransform::TransformUnaryOperator(E); 13336 } 13337 13338 ExprResult TransformLambdaExpr(LambdaExpr *E) { 13339 // Lambdas never need to be transformed. 13340 return E; 13341 } 13342 }; 13343 } 13344 13345 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 13346 assert(isUnevaluatedContext() && 13347 "Should only transform unevaluated expressions"); 13348 ExprEvalContexts.back().Context = 13349 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 13350 if (isUnevaluatedContext()) 13351 return E; 13352 return TransformToPE(*this).TransformExpr(E); 13353 } 13354 13355 void 13356 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 13357 Decl *LambdaContextDecl, 13358 bool IsDecltype) { 13359 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 13360 LambdaContextDecl, IsDecltype); 13361 Cleanup.reset(); 13362 if (!MaybeODRUseExprs.empty()) 13363 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 13364 } 13365 13366 void 13367 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 13368 ReuseLambdaContextDecl_t, 13369 bool IsDecltype) { 13370 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 13371 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 13372 } 13373 13374 void Sema::PopExpressionEvaluationContext() { 13375 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 13376 unsigned NumTypos = Rec.NumTypos; 13377 13378 if (!Rec.Lambdas.empty()) { 13379 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 13380 unsigned D; 13381 if (Rec.isUnevaluated()) { 13382 // C++11 [expr.prim.lambda]p2: 13383 // A lambda-expression shall not appear in an unevaluated operand 13384 // (Clause 5). 13385 D = diag::err_lambda_unevaluated_operand; 13386 } else { 13387 // C++1y [expr.const]p2: 13388 // A conditional-expression e is a core constant expression unless the 13389 // evaluation of e, following the rules of the abstract machine, would 13390 // evaluate [...] a lambda-expression. 13391 D = diag::err_lambda_in_constant_expression; 13392 } 13393 13394 // C++1z allows lambda expressions as core constant expressions. 13395 // FIXME: In C++1z, reinstate the restrictions on lambda expressions (CWG 13396 // 1607) from appearing within template-arguments and array-bounds that 13397 // are part of function-signatures. Be mindful that P0315 (Lambdas in 13398 // unevaluated contexts) might lift some of these restrictions in a 13399 // future version. 13400 if (!Rec.isConstantEvaluated() || !getLangOpts().CPlusPlus1z) 13401 for (const auto *L : Rec.Lambdas) 13402 Diag(L->getLocStart(), D); 13403 } else { 13404 // Mark the capture expressions odr-used. This was deferred 13405 // during lambda expression creation. 13406 for (auto *Lambda : Rec.Lambdas) { 13407 for (auto *C : Lambda->capture_inits()) 13408 MarkDeclarationsReferencedInExpr(C); 13409 } 13410 } 13411 } 13412 13413 // When are coming out of an unevaluated context, clear out any 13414 // temporaries that we may have created as part of the evaluation of 13415 // the expression in that context: they aren't relevant because they 13416 // will never be constructed. 13417 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 13418 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 13419 ExprCleanupObjects.end()); 13420 Cleanup = Rec.ParentCleanup; 13421 CleanupVarDeclMarking(); 13422 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 13423 // Otherwise, merge the contexts together. 13424 } else { 13425 Cleanup.mergeFrom(Rec.ParentCleanup); 13426 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 13427 Rec.SavedMaybeODRUseExprs.end()); 13428 } 13429 13430 // Pop the current expression evaluation context off the stack. 13431 ExprEvalContexts.pop_back(); 13432 13433 if (!ExprEvalContexts.empty()) 13434 ExprEvalContexts.back().NumTypos += NumTypos; 13435 else 13436 assert(NumTypos == 0 && "There are outstanding typos after popping the " 13437 "last ExpressionEvaluationContextRecord"); 13438 } 13439 13440 void Sema::DiscardCleanupsInEvaluationContext() { 13441 ExprCleanupObjects.erase( 13442 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 13443 ExprCleanupObjects.end()); 13444 Cleanup.reset(); 13445 MaybeODRUseExprs.clear(); 13446 } 13447 13448 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 13449 if (!E->getType()->isVariablyModifiedType()) 13450 return E; 13451 return TransformToPotentiallyEvaluated(E); 13452 } 13453 13454 /// Are we within a context in which some evaluation could be performed (be it 13455 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite 13456 /// captured by C++'s idea of an "unevaluated context". 13457 static bool isEvaluatableContext(Sema &SemaRef) { 13458 switch (SemaRef.ExprEvalContexts.back().Context) { 13459 case Sema::ExpressionEvaluationContext::Unevaluated: 13460 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 13461 case Sema::ExpressionEvaluationContext::DiscardedStatement: 13462 // Expressions in this context are never evaluated. 13463 return false; 13464 13465 case Sema::ExpressionEvaluationContext::UnevaluatedList: 13466 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 13467 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 13468 // Expressions in this context could be evaluated. 13469 return true; 13470 13471 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 13472 // Referenced declarations will only be used if the construct in the 13473 // containing expression is used, at which point we'll be given another 13474 // turn to mark them. 13475 return false; 13476 } 13477 llvm_unreachable("Invalid context"); 13478 } 13479 13480 /// Are we within a context in which references to resolved functions or to 13481 /// variables result in odr-use? 13482 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) { 13483 // An expression in a template is not really an expression until it's been 13484 // instantiated, so it doesn't trigger odr-use. 13485 if (SkipDependentUses && SemaRef.CurContext->isDependentContext()) 13486 return false; 13487 13488 switch (SemaRef.ExprEvalContexts.back().Context) { 13489 case Sema::ExpressionEvaluationContext::Unevaluated: 13490 case Sema::ExpressionEvaluationContext::UnevaluatedList: 13491 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 13492 case Sema::ExpressionEvaluationContext::DiscardedStatement: 13493 return false; 13494 13495 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 13496 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 13497 return true; 13498 13499 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 13500 return false; 13501 } 13502 llvm_unreachable("Invalid context"); 13503 } 13504 13505 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 13506 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 13507 return Func->isConstexpr() && 13508 (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided())); 13509 } 13510 13511 /// \brief Mark a function referenced, and check whether it is odr-used 13512 /// (C++ [basic.def.odr]p2, C99 6.9p3) 13513 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 13514 bool MightBeOdrUse) { 13515 assert(Func && "No function?"); 13516 13517 Func->setReferenced(); 13518 13519 // C++11 [basic.def.odr]p3: 13520 // A function whose name appears as a potentially-evaluated expression is 13521 // odr-used if it is the unique lookup result or the selected member of a 13522 // set of overloaded functions [...]. 13523 // 13524 // We (incorrectly) mark overload resolution as an unevaluated context, so we 13525 // can just check that here. 13526 bool OdrUse = MightBeOdrUse && isOdrUseContext(*this); 13527 13528 // Determine whether we require a function definition to exist, per 13529 // C++11 [temp.inst]p3: 13530 // Unless a function template specialization has been explicitly 13531 // instantiated or explicitly specialized, the function template 13532 // specialization is implicitly instantiated when the specialization is 13533 // referenced in a context that requires a function definition to exist. 13534 // 13535 // That is either when this is an odr-use, or when a usage of a constexpr 13536 // function occurs within an evaluatable context. 13537 bool NeedDefinition = 13538 OdrUse || (isEvaluatableContext(*this) && 13539 isImplicitlyDefinableConstexprFunction(Func)); 13540 13541 // C++14 [temp.expl.spec]p6: 13542 // If a template [...] is explicitly specialized then that specialization 13543 // shall be declared before the first use of that specialization that would 13544 // cause an implicit instantiation to take place, in every translation unit 13545 // in which such a use occurs 13546 if (NeedDefinition && 13547 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 13548 Func->getMemberSpecializationInfo())) 13549 checkSpecializationVisibility(Loc, Func); 13550 13551 // C++14 [except.spec]p17: 13552 // An exception-specification is considered to be needed when: 13553 // - the function is odr-used or, if it appears in an unevaluated operand, 13554 // would be odr-used if the expression were potentially-evaluated; 13555 // 13556 // Note, we do this even if MightBeOdrUse is false. That indicates that the 13557 // function is a pure virtual function we're calling, and in that case the 13558 // function was selected by overload resolution and we need to resolve its 13559 // exception specification for a different reason. 13560 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 13561 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 13562 ResolveExceptionSpec(Loc, FPT); 13563 13564 // If we don't need to mark the function as used, and we don't need to 13565 // try to provide a definition, there's nothing more to do. 13566 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) && 13567 (!NeedDefinition || Func->getBody())) 13568 return; 13569 13570 // Note that this declaration has been used. 13571 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 13572 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 13573 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 13574 if (Constructor->isDefaultConstructor()) { 13575 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 13576 return; 13577 DefineImplicitDefaultConstructor(Loc, Constructor); 13578 } else if (Constructor->isCopyConstructor()) { 13579 DefineImplicitCopyConstructor(Loc, Constructor); 13580 } else if (Constructor->isMoveConstructor()) { 13581 DefineImplicitMoveConstructor(Loc, Constructor); 13582 } 13583 } else if (Constructor->getInheritedConstructor()) { 13584 DefineInheritingConstructor(Loc, Constructor); 13585 } 13586 } else if (CXXDestructorDecl *Destructor = 13587 dyn_cast<CXXDestructorDecl>(Func)) { 13588 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 13589 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 13590 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 13591 return; 13592 DefineImplicitDestructor(Loc, Destructor); 13593 } 13594 if (Destructor->isVirtual() && getLangOpts().AppleKext) 13595 MarkVTableUsed(Loc, Destructor->getParent()); 13596 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 13597 if (MethodDecl->isOverloadedOperator() && 13598 MethodDecl->getOverloadedOperator() == OO_Equal) { 13599 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 13600 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 13601 if (MethodDecl->isCopyAssignmentOperator()) 13602 DefineImplicitCopyAssignment(Loc, MethodDecl); 13603 else if (MethodDecl->isMoveAssignmentOperator()) 13604 DefineImplicitMoveAssignment(Loc, MethodDecl); 13605 } 13606 } else if (isa<CXXConversionDecl>(MethodDecl) && 13607 MethodDecl->getParent()->isLambda()) { 13608 CXXConversionDecl *Conversion = 13609 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 13610 if (Conversion->isLambdaToBlockPointerConversion()) 13611 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 13612 else 13613 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 13614 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 13615 MarkVTableUsed(Loc, MethodDecl->getParent()); 13616 } 13617 13618 // Recursive functions should be marked when used from another function. 13619 // FIXME: Is this really right? 13620 if (CurContext == Func) return; 13621 13622 // Implicit instantiation of function templates and member functions of 13623 // class templates. 13624 if (Func->isImplicitlyInstantiable()) { 13625 bool AlreadyInstantiated = false; 13626 SourceLocation PointOfInstantiation = Loc; 13627 if (FunctionTemplateSpecializationInfo *SpecInfo 13628 = Func->getTemplateSpecializationInfo()) { 13629 if (SpecInfo->getPointOfInstantiation().isInvalid()) 13630 SpecInfo->setPointOfInstantiation(Loc); 13631 else if (SpecInfo->getTemplateSpecializationKind() 13632 == TSK_ImplicitInstantiation) { 13633 AlreadyInstantiated = true; 13634 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 13635 } 13636 } else if (MemberSpecializationInfo *MSInfo 13637 = Func->getMemberSpecializationInfo()) { 13638 if (MSInfo->getPointOfInstantiation().isInvalid()) 13639 MSInfo->setPointOfInstantiation(Loc); 13640 else if (MSInfo->getTemplateSpecializationKind() 13641 == TSK_ImplicitInstantiation) { 13642 AlreadyInstantiated = true; 13643 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 13644 } 13645 } 13646 13647 if (!AlreadyInstantiated || Func->isConstexpr()) { 13648 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 13649 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 13650 CodeSynthesisContexts.size()) 13651 PendingLocalImplicitInstantiations.push_back( 13652 std::make_pair(Func, PointOfInstantiation)); 13653 else if (Func->isConstexpr()) 13654 // Do not defer instantiations of constexpr functions, to avoid the 13655 // expression evaluator needing to call back into Sema if it sees a 13656 // call to such a function. 13657 InstantiateFunctionDefinition(PointOfInstantiation, Func); 13658 else { 13659 Func->setInstantiationIsPending(true); 13660 PendingInstantiations.push_back(std::make_pair(Func, 13661 PointOfInstantiation)); 13662 // Notify the consumer that a function was implicitly instantiated. 13663 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 13664 } 13665 } 13666 } else { 13667 // Walk redefinitions, as some of them may be instantiable. 13668 for (auto i : Func->redecls()) { 13669 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 13670 MarkFunctionReferenced(Loc, i, OdrUse); 13671 } 13672 } 13673 13674 if (!OdrUse) return; 13675 13676 // Keep track of used but undefined functions. 13677 if (!Func->isDefined()) { 13678 if (mightHaveNonExternalLinkage(Func)) 13679 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 13680 else if (Func->getMostRecentDecl()->isInlined() && 13681 !LangOpts.GNUInline && 13682 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 13683 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 13684 } 13685 13686 Func->markUsed(Context); 13687 } 13688 13689 static void 13690 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 13691 ValueDecl *var, DeclContext *DC) { 13692 DeclContext *VarDC = var->getDeclContext(); 13693 13694 // If the parameter still belongs to the translation unit, then 13695 // we're actually just using one parameter in the declaration of 13696 // the next. 13697 if (isa<ParmVarDecl>(var) && 13698 isa<TranslationUnitDecl>(VarDC)) 13699 return; 13700 13701 // For C code, don't diagnose about capture if we're not actually in code 13702 // right now; it's impossible to write a non-constant expression outside of 13703 // function context, so we'll get other (more useful) diagnostics later. 13704 // 13705 // For C++, things get a bit more nasty... it would be nice to suppress this 13706 // diagnostic for certain cases like using a local variable in an array bound 13707 // for a member of a local class, but the correct predicate is not obvious. 13708 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 13709 return; 13710 13711 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 13712 unsigned ContextKind = 3; // unknown 13713 if (isa<CXXMethodDecl>(VarDC) && 13714 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 13715 ContextKind = 2; 13716 } else if (isa<FunctionDecl>(VarDC)) { 13717 ContextKind = 0; 13718 } else if (isa<BlockDecl>(VarDC)) { 13719 ContextKind = 1; 13720 } 13721 13722 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 13723 << var << ValueKind << ContextKind << VarDC; 13724 S.Diag(var->getLocation(), diag::note_entity_declared_at) 13725 << var; 13726 13727 // FIXME: Add additional diagnostic info about class etc. which prevents 13728 // capture. 13729 } 13730 13731 13732 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 13733 bool &SubCapturesAreNested, 13734 QualType &CaptureType, 13735 QualType &DeclRefType) { 13736 // Check whether we've already captured it. 13737 if (CSI->CaptureMap.count(Var)) { 13738 // If we found a capture, any subcaptures are nested. 13739 SubCapturesAreNested = true; 13740 13741 // Retrieve the capture type for this variable. 13742 CaptureType = CSI->getCapture(Var).getCaptureType(); 13743 13744 // Compute the type of an expression that refers to this variable. 13745 DeclRefType = CaptureType.getNonReferenceType(); 13746 13747 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 13748 // are mutable in the sense that user can change their value - they are 13749 // private instances of the captured declarations. 13750 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 13751 if (Cap.isCopyCapture() && 13752 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 13753 !(isa<CapturedRegionScopeInfo>(CSI) && 13754 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 13755 DeclRefType.addConst(); 13756 return true; 13757 } 13758 return false; 13759 } 13760 13761 // Only block literals, captured statements, and lambda expressions can 13762 // capture; other scopes don't work. 13763 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 13764 SourceLocation Loc, 13765 const bool Diagnose, Sema &S) { 13766 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 13767 return getLambdaAwareParentOfDeclContext(DC); 13768 else if (Var->hasLocalStorage()) { 13769 if (Diagnose) 13770 diagnoseUncapturableValueReference(S, Loc, Var, DC); 13771 } 13772 return nullptr; 13773 } 13774 13775 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 13776 // certain types of variables (unnamed, variably modified types etc.) 13777 // so check for eligibility. 13778 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 13779 SourceLocation Loc, 13780 const bool Diagnose, Sema &S) { 13781 13782 bool IsBlock = isa<BlockScopeInfo>(CSI); 13783 bool IsLambda = isa<LambdaScopeInfo>(CSI); 13784 13785 // Lambdas are not allowed to capture unnamed variables 13786 // (e.g. anonymous unions). 13787 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 13788 // assuming that's the intent. 13789 if (IsLambda && !Var->getDeclName()) { 13790 if (Diagnose) { 13791 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 13792 S.Diag(Var->getLocation(), diag::note_declared_at); 13793 } 13794 return false; 13795 } 13796 13797 // Prohibit variably-modified types in blocks; they're difficult to deal with. 13798 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 13799 if (Diagnose) { 13800 S.Diag(Loc, diag::err_ref_vm_type); 13801 S.Diag(Var->getLocation(), diag::note_previous_decl) 13802 << Var->getDeclName(); 13803 } 13804 return false; 13805 } 13806 // Prohibit structs with flexible array members too. 13807 // We cannot capture what is in the tail end of the struct. 13808 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 13809 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 13810 if (Diagnose) { 13811 if (IsBlock) 13812 S.Diag(Loc, diag::err_ref_flexarray_type); 13813 else 13814 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 13815 << Var->getDeclName(); 13816 S.Diag(Var->getLocation(), diag::note_previous_decl) 13817 << Var->getDeclName(); 13818 } 13819 return false; 13820 } 13821 } 13822 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 13823 // Lambdas and captured statements are not allowed to capture __block 13824 // variables; they don't support the expected semantics. 13825 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 13826 if (Diagnose) { 13827 S.Diag(Loc, diag::err_capture_block_variable) 13828 << Var->getDeclName() << !IsLambda; 13829 S.Diag(Var->getLocation(), diag::note_previous_decl) 13830 << Var->getDeclName(); 13831 } 13832 return false; 13833 } 13834 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 13835 if (S.getLangOpts().OpenCL && IsBlock && 13836 Var->getType()->isBlockPointerType()) { 13837 if (Diagnose) 13838 S.Diag(Loc, diag::err_opencl_block_ref_block); 13839 return false; 13840 } 13841 13842 return true; 13843 } 13844 13845 // Returns true if the capture by block was successful. 13846 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 13847 SourceLocation Loc, 13848 const bool BuildAndDiagnose, 13849 QualType &CaptureType, 13850 QualType &DeclRefType, 13851 const bool Nested, 13852 Sema &S) { 13853 Expr *CopyExpr = nullptr; 13854 bool ByRef = false; 13855 13856 // Blocks are not allowed to capture arrays. 13857 if (CaptureType->isArrayType()) { 13858 if (BuildAndDiagnose) { 13859 S.Diag(Loc, diag::err_ref_array_type); 13860 S.Diag(Var->getLocation(), diag::note_previous_decl) 13861 << Var->getDeclName(); 13862 } 13863 return false; 13864 } 13865 13866 // Forbid the block-capture of autoreleasing variables. 13867 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 13868 if (BuildAndDiagnose) { 13869 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 13870 << /*block*/ 0; 13871 S.Diag(Var->getLocation(), diag::note_previous_decl) 13872 << Var->getDeclName(); 13873 } 13874 return false; 13875 } 13876 13877 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 13878 if (const auto *PT = CaptureType->getAs<PointerType>()) { 13879 // This function finds out whether there is an AttributedType of kind 13880 // attr_objc_ownership in Ty. The existence of AttributedType of kind 13881 // attr_objc_ownership implies __autoreleasing was explicitly specified 13882 // rather than being added implicitly by the compiler. 13883 auto IsObjCOwnershipAttributedType = [](QualType Ty) { 13884 while (const auto *AttrTy = Ty->getAs<AttributedType>()) { 13885 if (AttrTy->getAttrKind() == AttributedType::attr_objc_ownership) 13886 return true; 13887 13888 // Peel off AttributedTypes that are not of kind objc_ownership. 13889 Ty = AttrTy->getModifiedType(); 13890 } 13891 13892 return false; 13893 }; 13894 13895 QualType PointeeTy = PT->getPointeeType(); 13896 13897 if (PointeeTy->getAs<ObjCObjectPointerType>() && 13898 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 13899 !IsObjCOwnershipAttributedType(PointeeTy)) { 13900 if (BuildAndDiagnose) { 13901 SourceLocation VarLoc = Var->getLocation(); 13902 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 13903 { 13904 auto AddAutoreleaseNote = 13905 S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing); 13906 // Provide a fix-it for the '__autoreleasing' keyword at the 13907 // appropriate location in the variable's type. 13908 if (const auto *TSI = Var->getTypeSourceInfo()) { 13909 PointerTypeLoc PTL = 13910 TSI->getTypeLoc().getAsAdjusted<PointerTypeLoc>(); 13911 if (PTL) { 13912 SourceLocation Loc = PTL.getPointeeLoc().getEndLoc(); 13913 Loc = Lexer::getLocForEndOfToken(Loc, 0, S.getSourceManager(), 13914 S.getLangOpts()); 13915 if (Loc.isValid()) { 13916 StringRef CharAtLoc = Lexer::getSourceText( 13917 CharSourceRange::getCharRange(Loc, Loc.getLocWithOffset(1)), 13918 S.getSourceManager(), S.getLangOpts()); 13919 AddAutoreleaseNote << FixItHint::CreateInsertion( 13920 Loc, CharAtLoc.empty() || !isWhitespace(CharAtLoc[0]) 13921 ? " __autoreleasing " 13922 : " __autoreleasing"); 13923 } 13924 } 13925 } 13926 } 13927 S.Diag(VarLoc, diag::note_declare_parameter_strong); 13928 } 13929 } 13930 } 13931 13932 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 13933 if (HasBlocksAttr || CaptureType->isReferenceType() || 13934 (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) { 13935 // Block capture by reference does not change the capture or 13936 // declaration reference types. 13937 ByRef = true; 13938 } else { 13939 // Block capture by copy introduces 'const'. 13940 CaptureType = CaptureType.getNonReferenceType().withConst(); 13941 DeclRefType = CaptureType; 13942 13943 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 13944 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 13945 // The capture logic needs the destructor, so make sure we mark it. 13946 // Usually this is unnecessary because most local variables have 13947 // their destructors marked at declaration time, but parameters are 13948 // an exception because it's technically only the call site that 13949 // actually requires the destructor. 13950 if (isa<ParmVarDecl>(Var)) 13951 S.FinalizeVarWithDestructor(Var, Record); 13952 13953 // Enter a new evaluation context to insulate the copy 13954 // full-expression. 13955 EnterExpressionEvaluationContext scope( 13956 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 13957 13958 // According to the blocks spec, the capture of a variable from 13959 // the stack requires a const copy constructor. This is not true 13960 // of the copy/move done to move a __block variable to the heap. 13961 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 13962 DeclRefType.withConst(), 13963 VK_LValue, Loc); 13964 13965 ExprResult Result 13966 = S.PerformCopyInitialization( 13967 InitializedEntity::InitializeBlock(Var->getLocation(), 13968 CaptureType, false), 13969 Loc, DeclRef); 13970 13971 // Build a full-expression copy expression if initialization 13972 // succeeded and used a non-trivial constructor. Recover from 13973 // errors by pretending that the copy isn't necessary. 13974 if (!Result.isInvalid() && 13975 !cast<CXXConstructExpr>(Result.get())->getConstructor() 13976 ->isTrivial()) { 13977 Result = S.MaybeCreateExprWithCleanups(Result); 13978 CopyExpr = Result.get(); 13979 } 13980 } 13981 } 13982 } 13983 13984 // Actually capture the variable. 13985 if (BuildAndDiagnose) 13986 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 13987 SourceLocation(), CaptureType, CopyExpr); 13988 13989 return true; 13990 13991 } 13992 13993 13994 /// \brief Capture the given variable in the captured region. 13995 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 13996 VarDecl *Var, 13997 SourceLocation Loc, 13998 const bool BuildAndDiagnose, 13999 QualType &CaptureType, 14000 QualType &DeclRefType, 14001 const bool RefersToCapturedVariable, 14002 Sema &S) { 14003 // By default, capture variables by reference. 14004 bool ByRef = true; 14005 // Using an LValue reference type is consistent with Lambdas (see below). 14006 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 14007 if (S.IsOpenMPCapturedDecl(Var)) 14008 DeclRefType = DeclRefType.getUnqualifiedType(); 14009 ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel); 14010 } 14011 14012 if (ByRef) 14013 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 14014 else 14015 CaptureType = DeclRefType; 14016 14017 Expr *CopyExpr = nullptr; 14018 if (BuildAndDiagnose) { 14019 // The current implementation assumes that all variables are captured 14020 // by references. Since there is no capture by copy, no expression 14021 // evaluation will be needed. 14022 RecordDecl *RD = RSI->TheRecordDecl; 14023 14024 FieldDecl *Field 14025 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 14026 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 14027 nullptr, false, ICIS_NoInit); 14028 Field->setImplicit(true); 14029 Field->setAccess(AS_private); 14030 RD->addDecl(Field); 14031 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) 14032 S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel); 14033 14034 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, 14035 DeclRefType, VK_LValue, Loc); 14036 Var->setReferenced(true); 14037 Var->markUsed(S.Context); 14038 } 14039 14040 // Actually capture the variable. 14041 if (BuildAndDiagnose) 14042 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 14043 SourceLocation(), CaptureType, CopyExpr); 14044 14045 14046 return true; 14047 } 14048 14049 /// \brief Create a field within the lambda class for the variable 14050 /// being captured. 14051 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, 14052 QualType FieldType, QualType DeclRefType, 14053 SourceLocation Loc, 14054 bool RefersToCapturedVariable) { 14055 CXXRecordDecl *Lambda = LSI->Lambda; 14056 14057 // Build the non-static data member. 14058 FieldDecl *Field 14059 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 14060 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 14061 nullptr, false, ICIS_NoInit); 14062 Field->setImplicit(true); 14063 Field->setAccess(AS_private); 14064 Lambda->addDecl(Field); 14065 } 14066 14067 /// \brief Capture the given variable in the lambda. 14068 static bool captureInLambda(LambdaScopeInfo *LSI, 14069 VarDecl *Var, 14070 SourceLocation Loc, 14071 const bool BuildAndDiagnose, 14072 QualType &CaptureType, 14073 QualType &DeclRefType, 14074 const bool RefersToCapturedVariable, 14075 const Sema::TryCaptureKind Kind, 14076 SourceLocation EllipsisLoc, 14077 const bool IsTopScope, 14078 Sema &S) { 14079 14080 // Determine whether we are capturing by reference or by value. 14081 bool ByRef = false; 14082 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 14083 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 14084 } else { 14085 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 14086 } 14087 14088 // Compute the type of the field that will capture this variable. 14089 if (ByRef) { 14090 // C++11 [expr.prim.lambda]p15: 14091 // An entity is captured by reference if it is implicitly or 14092 // explicitly captured but not captured by copy. It is 14093 // unspecified whether additional unnamed non-static data 14094 // members are declared in the closure type for entities 14095 // captured by reference. 14096 // 14097 // FIXME: It is not clear whether we want to build an lvalue reference 14098 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 14099 // to do the former, while EDG does the latter. Core issue 1249 will 14100 // clarify, but for now we follow GCC because it's a more permissive and 14101 // easily defensible position. 14102 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 14103 } else { 14104 // C++11 [expr.prim.lambda]p14: 14105 // For each entity captured by copy, an unnamed non-static 14106 // data member is declared in the closure type. The 14107 // declaration order of these members is unspecified. The type 14108 // of such a data member is the type of the corresponding 14109 // captured entity if the entity is not a reference to an 14110 // object, or the referenced type otherwise. [Note: If the 14111 // captured entity is a reference to a function, the 14112 // corresponding data member is also a reference to a 14113 // function. - end note ] 14114 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 14115 if (!RefType->getPointeeType()->isFunctionType()) 14116 CaptureType = RefType->getPointeeType(); 14117 } 14118 14119 // Forbid the lambda copy-capture of autoreleasing variables. 14120 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 14121 if (BuildAndDiagnose) { 14122 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 14123 S.Diag(Var->getLocation(), diag::note_previous_decl) 14124 << Var->getDeclName(); 14125 } 14126 return false; 14127 } 14128 14129 // Make sure that by-copy captures are of a complete and non-abstract type. 14130 if (BuildAndDiagnose) { 14131 if (!CaptureType->isDependentType() && 14132 S.RequireCompleteType(Loc, CaptureType, 14133 diag::err_capture_of_incomplete_type, 14134 Var->getDeclName())) 14135 return false; 14136 14137 if (S.RequireNonAbstractType(Loc, CaptureType, 14138 diag::err_capture_of_abstract_type)) 14139 return false; 14140 } 14141 } 14142 14143 // Capture this variable in the lambda. 14144 if (BuildAndDiagnose) 14145 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc, 14146 RefersToCapturedVariable); 14147 14148 // Compute the type of a reference to this captured variable. 14149 if (ByRef) 14150 DeclRefType = CaptureType.getNonReferenceType(); 14151 else { 14152 // C++ [expr.prim.lambda]p5: 14153 // The closure type for a lambda-expression has a public inline 14154 // function call operator [...]. This function call operator is 14155 // declared const (9.3.1) if and only if the lambda-expression's 14156 // parameter-declaration-clause is not followed by mutable. 14157 DeclRefType = CaptureType.getNonReferenceType(); 14158 if (!LSI->Mutable && !CaptureType->isReferenceType()) 14159 DeclRefType.addConst(); 14160 } 14161 14162 // Add the capture. 14163 if (BuildAndDiagnose) 14164 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 14165 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 14166 14167 return true; 14168 } 14169 14170 bool Sema::tryCaptureVariable( 14171 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 14172 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 14173 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 14174 // An init-capture is notionally from the context surrounding its 14175 // declaration, but its parent DC is the lambda class. 14176 DeclContext *VarDC = Var->getDeclContext(); 14177 if (Var->isInitCapture()) 14178 VarDC = VarDC->getParent(); 14179 14180 DeclContext *DC = CurContext; 14181 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 14182 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 14183 // We need to sync up the Declaration Context with the 14184 // FunctionScopeIndexToStopAt 14185 if (FunctionScopeIndexToStopAt) { 14186 unsigned FSIndex = FunctionScopes.size() - 1; 14187 while (FSIndex != MaxFunctionScopesIndex) { 14188 DC = getLambdaAwareParentOfDeclContext(DC); 14189 --FSIndex; 14190 } 14191 } 14192 14193 14194 // If the variable is declared in the current context, there is no need to 14195 // capture it. 14196 if (VarDC == DC) return true; 14197 14198 // Capture global variables if it is required to use private copy of this 14199 // variable. 14200 bool IsGlobal = !Var->hasLocalStorage(); 14201 if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var))) 14202 return true; 14203 14204 // Walk up the stack to determine whether we can capture the variable, 14205 // performing the "simple" checks that don't depend on type. We stop when 14206 // we've either hit the declared scope of the variable or find an existing 14207 // capture of that variable. We start from the innermost capturing-entity 14208 // (the DC) and ensure that all intervening capturing-entities 14209 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 14210 // declcontext can either capture the variable or have already captured 14211 // the variable. 14212 CaptureType = Var->getType(); 14213 DeclRefType = CaptureType.getNonReferenceType(); 14214 bool Nested = false; 14215 bool Explicit = (Kind != TryCapture_Implicit); 14216 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 14217 do { 14218 // Only block literals, captured statements, and lambda expressions can 14219 // capture; other scopes don't work. 14220 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 14221 ExprLoc, 14222 BuildAndDiagnose, 14223 *this); 14224 // We need to check for the parent *first* because, if we *have* 14225 // private-captured a global variable, we need to recursively capture it in 14226 // intermediate blocks, lambdas, etc. 14227 if (!ParentDC) { 14228 if (IsGlobal) { 14229 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 14230 break; 14231 } 14232 return true; 14233 } 14234 14235 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 14236 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 14237 14238 14239 // Check whether we've already captured it. 14240 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 14241 DeclRefType)) { 14242 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 14243 break; 14244 } 14245 // If we are instantiating a generic lambda call operator body, 14246 // we do not want to capture new variables. What was captured 14247 // during either a lambdas transformation or initial parsing 14248 // should be used. 14249 if (isGenericLambdaCallOperatorSpecialization(DC)) { 14250 if (BuildAndDiagnose) { 14251 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 14252 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 14253 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 14254 Diag(Var->getLocation(), diag::note_previous_decl) 14255 << Var->getDeclName(); 14256 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); 14257 } else 14258 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 14259 } 14260 return true; 14261 } 14262 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 14263 // certain types of variables (unnamed, variably modified types etc.) 14264 // so check for eligibility. 14265 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 14266 return true; 14267 14268 // Try to capture variable-length arrays types. 14269 if (Var->getType()->isVariablyModifiedType()) { 14270 // We're going to walk down into the type and look for VLA 14271 // expressions. 14272 QualType QTy = Var->getType(); 14273 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 14274 QTy = PVD->getOriginalType(); 14275 captureVariablyModifiedType(Context, QTy, CSI); 14276 } 14277 14278 if (getLangOpts().OpenMP) { 14279 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 14280 // OpenMP private variables should not be captured in outer scope, so 14281 // just break here. Similarly, global variables that are captured in a 14282 // target region should not be captured outside the scope of the region. 14283 if (RSI->CapRegionKind == CR_OpenMP) { 14284 auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 14285 // When we detect target captures we are looking from inside the 14286 // target region, therefore we need to propagate the capture from the 14287 // enclosing region. Therefore, the capture is not initially nested. 14288 if (IsTargetCap) 14289 FunctionScopesIndex--; 14290 14291 if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) { 14292 Nested = !IsTargetCap; 14293 DeclRefType = DeclRefType.getUnqualifiedType(); 14294 CaptureType = Context.getLValueReferenceType(DeclRefType); 14295 break; 14296 } 14297 } 14298 } 14299 } 14300 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 14301 // No capture-default, and this is not an explicit capture 14302 // so cannot capture this variable. 14303 if (BuildAndDiagnose) { 14304 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 14305 Diag(Var->getLocation(), diag::note_previous_decl) 14306 << Var->getDeclName(); 14307 if (cast<LambdaScopeInfo>(CSI)->Lambda) 14308 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 14309 diag::note_lambda_decl); 14310 // FIXME: If we error out because an outer lambda can not implicitly 14311 // capture a variable that an inner lambda explicitly captures, we 14312 // should have the inner lambda do the explicit capture - because 14313 // it makes for cleaner diagnostics later. This would purely be done 14314 // so that the diagnostic does not misleadingly claim that a variable 14315 // can not be captured by a lambda implicitly even though it is captured 14316 // explicitly. Suggestion: 14317 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 14318 // at the function head 14319 // - cache the StartingDeclContext - this must be a lambda 14320 // - captureInLambda in the innermost lambda the variable. 14321 } 14322 return true; 14323 } 14324 14325 FunctionScopesIndex--; 14326 DC = ParentDC; 14327 Explicit = false; 14328 } while (!VarDC->Equals(DC)); 14329 14330 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 14331 // computing the type of the capture at each step, checking type-specific 14332 // requirements, and adding captures if requested. 14333 // If the variable had already been captured previously, we start capturing 14334 // at the lambda nested within that one. 14335 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 14336 ++I) { 14337 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 14338 14339 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 14340 if (!captureInBlock(BSI, Var, ExprLoc, 14341 BuildAndDiagnose, CaptureType, 14342 DeclRefType, Nested, *this)) 14343 return true; 14344 Nested = true; 14345 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 14346 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 14347 BuildAndDiagnose, CaptureType, 14348 DeclRefType, Nested, *this)) 14349 return true; 14350 Nested = true; 14351 } else { 14352 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 14353 if (!captureInLambda(LSI, Var, ExprLoc, 14354 BuildAndDiagnose, CaptureType, 14355 DeclRefType, Nested, Kind, EllipsisLoc, 14356 /*IsTopScope*/I == N - 1, *this)) 14357 return true; 14358 Nested = true; 14359 } 14360 } 14361 return false; 14362 } 14363 14364 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 14365 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 14366 QualType CaptureType; 14367 QualType DeclRefType; 14368 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 14369 /*BuildAndDiagnose=*/true, CaptureType, 14370 DeclRefType, nullptr); 14371 } 14372 14373 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 14374 QualType CaptureType; 14375 QualType DeclRefType; 14376 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 14377 /*BuildAndDiagnose=*/false, CaptureType, 14378 DeclRefType, nullptr); 14379 } 14380 14381 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 14382 QualType CaptureType; 14383 QualType DeclRefType; 14384 14385 // Determine whether we can capture this variable. 14386 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 14387 /*BuildAndDiagnose=*/false, CaptureType, 14388 DeclRefType, nullptr)) 14389 return QualType(); 14390 14391 return DeclRefType; 14392 } 14393 14394 14395 14396 // If either the type of the variable or the initializer is dependent, 14397 // return false. Otherwise, determine whether the variable is a constant 14398 // expression. Use this if you need to know if a variable that might or 14399 // might not be dependent is truly a constant expression. 14400 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 14401 ASTContext &Context) { 14402 14403 if (Var->getType()->isDependentType()) 14404 return false; 14405 const VarDecl *DefVD = nullptr; 14406 Var->getAnyInitializer(DefVD); 14407 if (!DefVD) 14408 return false; 14409 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 14410 Expr *Init = cast<Expr>(Eval->Value); 14411 if (Init->isValueDependent()) 14412 return false; 14413 return IsVariableAConstantExpression(Var, Context); 14414 } 14415 14416 14417 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 14418 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 14419 // an object that satisfies the requirements for appearing in a 14420 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 14421 // is immediately applied." This function handles the lvalue-to-rvalue 14422 // conversion part. 14423 MaybeODRUseExprs.erase(E->IgnoreParens()); 14424 14425 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 14426 // to a variable that is a constant expression, and if so, identify it as 14427 // a reference to a variable that does not involve an odr-use of that 14428 // variable. 14429 if (LambdaScopeInfo *LSI = getCurLambda()) { 14430 Expr *SansParensExpr = E->IgnoreParens(); 14431 VarDecl *Var = nullptr; 14432 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 14433 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 14434 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 14435 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 14436 14437 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 14438 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 14439 } 14440 } 14441 14442 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 14443 Res = CorrectDelayedTyposInExpr(Res); 14444 14445 if (!Res.isUsable()) 14446 return Res; 14447 14448 // If a constant-expression is a reference to a variable where we delay 14449 // deciding whether it is an odr-use, just assume we will apply the 14450 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 14451 // (a non-type template argument), we have special handling anyway. 14452 UpdateMarkingForLValueToRValue(Res.get()); 14453 return Res; 14454 } 14455 14456 void Sema::CleanupVarDeclMarking() { 14457 for (Expr *E : MaybeODRUseExprs) { 14458 VarDecl *Var; 14459 SourceLocation Loc; 14460 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 14461 Var = cast<VarDecl>(DRE->getDecl()); 14462 Loc = DRE->getLocation(); 14463 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 14464 Var = cast<VarDecl>(ME->getMemberDecl()); 14465 Loc = ME->getMemberLoc(); 14466 } else { 14467 llvm_unreachable("Unexpected expression"); 14468 } 14469 14470 MarkVarDeclODRUsed(Var, Loc, *this, 14471 /*MaxFunctionScopeIndex Pointer*/ nullptr); 14472 } 14473 14474 MaybeODRUseExprs.clear(); 14475 } 14476 14477 14478 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 14479 VarDecl *Var, Expr *E) { 14480 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 14481 "Invalid Expr argument to DoMarkVarDeclReferenced"); 14482 Var->setReferenced(); 14483 14484 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 14485 14486 bool OdrUseContext = isOdrUseContext(SemaRef); 14487 bool NeedDefinition = 14488 OdrUseContext || (isEvaluatableContext(SemaRef) && 14489 Var->isUsableInConstantExpressions(SemaRef.Context)); 14490 14491 VarTemplateSpecializationDecl *VarSpec = 14492 dyn_cast<VarTemplateSpecializationDecl>(Var); 14493 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 14494 "Can't instantiate a partial template specialization."); 14495 14496 // If this might be a member specialization of a static data member, check 14497 // the specialization is visible. We already did the checks for variable 14498 // template specializations when we created them. 14499 if (NeedDefinition && TSK != TSK_Undeclared && 14500 !isa<VarTemplateSpecializationDecl>(Var)) 14501 SemaRef.checkSpecializationVisibility(Loc, Var); 14502 14503 // Perform implicit instantiation of static data members, static data member 14504 // templates of class templates, and variable template specializations. Delay 14505 // instantiations of variable templates, except for those that could be used 14506 // in a constant expression. 14507 if (NeedDefinition && isTemplateInstantiation(TSK)) { 14508 bool TryInstantiating = TSK == TSK_ImplicitInstantiation; 14509 14510 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) { 14511 if (Var->getPointOfInstantiation().isInvalid()) { 14512 // This is a modification of an existing AST node. Notify listeners. 14513 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 14514 L->StaticDataMemberInstantiated(Var); 14515 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context)) 14516 // Don't bother trying to instantiate it again, unless we might need 14517 // its initializer before we get to the end of the TU. 14518 TryInstantiating = false; 14519 } 14520 14521 if (Var->getPointOfInstantiation().isInvalid()) 14522 Var->setTemplateSpecializationKind(TSK, Loc); 14523 14524 if (TryInstantiating) { 14525 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 14526 bool InstantiationDependent = false; 14527 bool IsNonDependent = 14528 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 14529 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 14530 : true; 14531 14532 // Do not instantiate specializations that are still type-dependent. 14533 if (IsNonDependent) { 14534 if (Var->isUsableInConstantExpressions(SemaRef.Context)) { 14535 // Do not defer instantiations of variables which could be used in a 14536 // constant expression. 14537 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 14538 } else { 14539 SemaRef.PendingInstantiations 14540 .push_back(std::make_pair(Var, PointOfInstantiation)); 14541 } 14542 } 14543 } 14544 } 14545 14546 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 14547 // the requirements for appearing in a constant expression (5.19) and, if 14548 // it is an object, the lvalue-to-rvalue conversion (4.1) 14549 // is immediately applied." We check the first part here, and 14550 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 14551 // Note that we use the C++11 definition everywhere because nothing in 14552 // C++03 depends on whether we get the C++03 version correct. The second 14553 // part does not apply to references, since they are not objects. 14554 if (OdrUseContext && E && 14555 IsVariableAConstantExpression(Var, SemaRef.Context)) { 14556 // A reference initialized by a constant expression can never be 14557 // odr-used, so simply ignore it. 14558 if (!Var->getType()->isReferenceType()) 14559 SemaRef.MaybeODRUseExprs.insert(E); 14560 } else if (OdrUseContext) { 14561 MarkVarDeclODRUsed(Var, Loc, SemaRef, 14562 /*MaxFunctionScopeIndex ptr*/ nullptr); 14563 } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) { 14564 // If this is a dependent context, we don't need to mark variables as 14565 // odr-used, but we may still need to track them for lambda capture. 14566 // FIXME: Do we also need to do this inside dependent typeid expressions 14567 // (which are modeled as unevaluated at this point)? 14568 const bool RefersToEnclosingScope = 14569 (SemaRef.CurContext != Var->getDeclContext() && 14570 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 14571 if (RefersToEnclosingScope) { 14572 LambdaScopeInfo *const LSI = 14573 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 14574 if (LSI && !LSI->CallOperator->Encloses(Var->getDeclContext())) { 14575 // If a variable could potentially be odr-used, defer marking it so 14576 // until we finish analyzing the full expression for any 14577 // lvalue-to-rvalue 14578 // or discarded value conversions that would obviate odr-use. 14579 // Add it to the list of potential captures that will be analyzed 14580 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 14581 // unless the variable is a reference that was initialized by a constant 14582 // expression (this will never need to be captured or odr-used). 14583 assert(E && "Capture variable should be used in an expression."); 14584 if (!Var->getType()->isReferenceType() || 14585 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 14586 LSI->addPotentialCapture(E->IgnoreParens()); 14587 } 14588 } 14589 } 14590 } 14591 14592 /// \brief Mark a variable referenced, and check whether it is odr-used 14593 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 14594 /// used directly for normal expressions referring to VarDecl. 14595 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 14596 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 14597 } 14598 14599 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 14600 Decl *D, Expr *E, bool MightBeOdrUse) { 14601 if (SemaRef.isInOpenMPDeclareTargetContext()) 14602 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 14603 14604 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 14605 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 14606 return; 14607 } 14608 14609 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 14610 14611 // If this is a call to a method via a cast, also mark the method in the 14612 // derived class used in case codegen can devirtualize the call. 14613 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 14614 if (!ME) 14615 return; 14616 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 14617 if (!MD) 14618 return; 14619 // Only attempt to devirtualize if this is truly a virtual call. 14620 bool IsVirtualCall = MD->isVirtual() && 14621 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 14622 if (!IsVirtualCall) 14623 return; 14624 14625 // If it's possible to devirtualize the call, mark the called function 14626 // referenced. 14627 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 14628 ME->getBase(), SemaRef.getLangOpts().AppleKext); 14629 if (DM) 14630 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 14631 } 14632 14633 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 14634 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 14635 // TODO: update this with DR# once a defect report is filed. 14636 // C++11 defect. The address of a pure member should not be an ODR use, even 14637 // if it's a qualified reference. 14638 bool OdrUse = true; 14639 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 14640 if (Method->isVirtual() && 14641 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 14642 OdrUse = false; 14643 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 14644 } 14645 14646 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 14647 void Sema::MarkMemberReferenced(MemberExpr *E) { 14648 // C++11 [basic.def.odr]p2: 14649 // A non-overloaded function whose name appears as a potentially-evaluated 14650 // expression or a member of a set of candidate functions, if selected by 14651 // overload resolution when referred to from a potentially-evaluated 14652 // expression, is odr-used, unless it is a pure virtual function and its 14653 // name is not explicitly qualified. 14654 bool MightBeOdrUse = true; 14655 if (E->performsVirtualDispatch(getLangOpts())) { 14656 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 14657 if (Method->isPure()) 14658 MightBeOdrUse = false; 14659 } 14660 SourceLocation Loc = E->getMemberLoc().isValid() ? 14661 E->getMemberLoc() : E->getLocStart(); 14662 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 14663 } 14664 14665 /// \brief Perform marking for a reference to an arbitrary declaration. It 14666 /// marks the declaration referenced, and performs odr-use checking for 14667 /// functions and variables. This method should not be used when building a 14668 /// normal expression which refers to a variable. 14669 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 14670 bool MightBeOdrUse) { 14671 if (MightBeOdrUse) { 14672 if (auto *VD = dyn_cast<VarDecl>(D)) { 14673 MarkVariableReferenced(Loc, VD); 14674 return; 14675 } 14676 } 14677 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 14678 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 14679 return; 14680 } 14681 D->setReferenced(); 14682 } 14683 14684 namespace { 14685 // Mark all of the declarations used by a type as referenced. 14686 // FIXME: Not fully implemented yet! We need to have a better understanding 14687 // of when we're entering a context we should not recurse into. 14688 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 14689 // TreeTransforms rebuilding the type in a new context. Rather than 14690 // duplicating the TreeTransform logic, we should consider reusing it here. 14691 // Currently that causes problems when rebuilding LambdaExprs. 14692 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 14693 Sema &S; 14694 SourceLocation Loc; 14695 14696 public: 14697 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 14698 14699 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 14700 14701 bool TraverseTemplateArgument(const TemplateArgument &Arg); 14702 }; 14703 } 14704 14705 bool MarkReferencedDecls::TraverseTemplateArgument( 14706 const TemplateArgument &Arg) { 14707 { 14708 // A non-type template argument is a constant-evaluated context. 14709 EnterExpressionEvaluationContext Evaluated( 14710 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 14711 if (Arg.getKind() == TemplateArgument::Declaration) { 14712 if (Decl *D = Arg.getAsDecl()) 14713 S.MarkAnyDeclReferenced(Loc, D, true); 14714 } else if (Arg.getKind() == TemplateArgument::Expression) { 14715 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 14716 } 14717 } 14718 14719 return Inherited::TraverseTemplateArgument(Arg); 14720 } 14721 14722 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 14723 MarkReferencedDecls Marker(*this, Loc); 14724 Marker.TraverseType(T); 14725 } 14726 14727 namespace { 14728 /// \brief Helper class that marks all of the declarations referenced by 14729 /// potentially-evaluated subexpressions as "referenced". 14730 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 14731 Sema &S; 14732 bool SkipLocalVariables; 14733 14734 public: 14735 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 14736 14737 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 14738 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 14739 14740 void VisitDeclRefExpr(DeclRefExpr *E) { 14741 // If we were asked not to visit local variables, don't. 14742 if (SkipLocalVariables) { 14743 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 14744 if (VD->hasLocalStorage()) 14745 return; 14746 } 14747 14748 S.MarkDeclRefReferenced(E); 14749 } 14750 14751 void VisitMemberExpr(MemberExpr *E) { 14752 S.MarkMemberReferenced(E); 14753 Inherited::VisitMemberExpr(E); 14754 } 14755 14756 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 14757 S.MarkFunctionReferenced(E->getLocStart(), 14758 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 14759 Visit(E->getSubExpr()); 14760 } 14761 14762 void VisitCXXNewExpr(CXXNewExpr *E) { 14763 if (E->getOperatorNew()) 14764 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 14765 if (E->getOperatorDelete()) 14766 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 14767 Inherited::VisitCXXNewExpr(E); 14768 } 14769 14770 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 14771 if (E->getOperatorDelete()) 14772 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 14773 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 14774 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 14775 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 14776 S.MarkFunctionReferenced(E->getLocStart(), 14777 S.LookupDestructor(Record)); 14778 } 14779 14780 Inherited::VisitCXXDeleteExpr(E); 14781 } 14782 14783 void VisitCXXConstructExpr(CXXConstructExpr *E) { 14784 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 14785 Inherited::VisitCXXConstructExpr(E); 14786 } 14787 14788 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 14789 Visit(E->getExpr()); 14790 } 14791 14792 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 14793 Inherited::VisitImplicitCastExpr(E); 14794 14795 if (E->getCastKind() == CK_LValueToRValue) 14796 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 14797 } 14798 }; 14799 } 14800 14801 /// \brief Mark any declarations that appear within this expression or any 14802 /// potentially-evaluated subexpressions as "referenced". 14803 /// 14804 /// \param SkipLocalVariables If true, don't mark local variables as 14805 /// 'referenced'. 14806 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 14807 bool SkipLocalVariables) { 14808 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 14809 } 14810 14811 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 14812 /// of the program being compiled. 14813 /// 14814 /// This routine emits the given diagnostic when the code currently being 14815 /// type-checked is "potentially evaluated", meaning that there is a 14816 /// possibility that the code will actually be executable. Code in sizeof() 14817 /// expressions, code used only during overload resolution, etc., are not 14818 /// potentially evaluated. This routine will suppress such diagnostics or, 14819 /// in the absolutely nutty case of potentially potentially evaluated 14820 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 14821 /// later. 14822 /// 14823 /// This routine should be used for all diagnostics that describe the run-time 14824 /// behavior of a program, such as passing a non-POD value through an ellipsis. 14825 /// Failure to do so will likely result in spurious diagnostics or failures 14826 /// during overload resolution or within sizeof/alignof/typeof/typeid. 14827 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 14828 const PartialDiagnostic &PD) { 14829 switch (ExprEvalContexts.back().Context) { 14830 case ExpressionEvaluationContext::Unevaluated: 14831 case ExpressionEvaluationContext::UnevaluatedList: 14832 case ExpressionEvaluationContext::UnevaluatedAbstract: 14833 case ExpressionEvaluationContext::DiscardedStatement: 14834 // The argument will never be evaluated, so don't complain. 14835 break; 14836 14837 case ExpressionEvaluationContext::ConstantEvaluated: 14838 // Relevant diagnostics should be produced by constant evaluation. 14839 break; 14840 14841 case ExpressionEvaluationContext::PotentiallyEvaluated: 14842 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 14843 if (Statement && getCurFunctionOrMethodDecl()) { 14844 FunctionScopes.back()->PossiblyUnreachableDiags. 14845 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 14846 } 14847 else 14848 Diag(Loc, PD); 14849 14850 return true; 14851 } 14852 14853 return false; 14854 } 14855 14856 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 14857 CallExpr *CE, FunctionDecl *FD) { 14858 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 14859 return false; 14860 14861 // If we're inside a decltype's expression, don't check for a valid return 14862 // type or construct temporaries until we know whether this is the last call. 14863 if (ExprEvalContexts.back().IsDecltype) { 14864 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 14865 return false; 14866 } 14867 14868 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 14869 FunctionDecl *FD; 14870 CallExpr *CE; 14871 14872 public: 14873 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 14874 : FD(FD), CE(CE) { } 14875 14876 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 14877 if (!FD) { 14878 S.Diag(Loc, diag::err_call_incomplete_return) 14879 << T << CE->getSourceRange(); 14880 return; 14881 } 14882 14883 S.Diag(Loc, diag::err_call_function_incomplete_return) 14884 << CE->getSourceRange() << FD->getDeclName() << T; 14885 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 14886 << FD->getDeclName(); 14887 } 14888 } Diagnoser(FD, CE); 14889 14890 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 14891 return true; 14892 14893 return false; 14894 } 14895 14896 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 14897 // will prevent this condition from triggering, which is what we want. 14898 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 14899 SourceLocation Loc; 14900 14901 unsigned diagnostic = diag::warn_condition_is_assignment; 14902 bool IsOrAssign = false; 14903 14904 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 14905 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 14906 return; 14907 14908 IsOrAssign = Op->getOpcode() == BO_OrAssign; 14909 14910 // Greylist some idioms by putting them into a warning subcategory. 14911 if (ObjCMessageExpr *ME 14912 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 14913 Selector Sel = ME->getSelector(); 14914 14915 // self = [<foo> init...] 14916 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 14917 diagnostic = diag::warn_condition_is_idiomatic_assignment; 14918 14919 // <foo> = [<bar> nextObject] 14920 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 14921 diagnostic = diag::warn_condition_is_idiomatic_assignment; 14922 } 14923 14924 Loc = Op->getOperatorLoc(); 14925 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 14926 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 14927 return; 14928 14929 IsOrAssign = Op->getOperator() == OO_PipeEqual; 14930 Loc = Op->getOperatorLoc(); 14931 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 14932 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 14933 else { 14934 // Not an assignment. 14935 return; 14936 } 14937 14938 Diag(Loc, diagnostic) << E->getSourceRange(); 14939 14940 SourceLocation Open = E->getLocStart(); 14941 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 14942 Diag(Loc, diag::note_condition_assign_silence) 14943 << FixItHint::CreateInsertion(Open, "(") 14944 << FixItHint::CreateInsertion(Close, ")"); 14945 14946 if (IsOrAssign) 14947 Diag(Loc, diag::note_condition_or_assign_to_comparison) 14948 << FixItHint::CreateReplacement(Loc, "!="); 14949 else 14950 Diag(Loc, diag::note_condition_assign_to_comparison) 14951 << FixItHint::CreateReplacement(Loc, "=="); 14952 } 14953 14954 /// \brief Redundant parentheses over an equality comparison can indicate 14955 /// that the user intended an assignment used as condition. 14956 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 14957 // Don't warn if the parens came from a macro. 14958 SourceLocation parenLoc = ParenE->getLocStart(); 14959 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 14960 return; 14961 // Don't warn for dependent expressions. 14962 if (ParenE->isTypeDependent()) 14963 return; 14964 14965 Expr *E = ParenE->IgnoreParens(); 14966 14967 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 14968 if (opE->getOpcode() == BO_EQ && 14969 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 14970 == Expr::MLV_Valid) { 14971 SourceLocation Loc = opE->getOperatorLoc(); 14972 14973 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 14974 SourceRange ParenERange = ParenE->getSourceRange(); 14975 Diag(Loc, diag::note_equality_comparison_silence) 14976 << FixItHint::CreateRemoval(ParenERange.getBegin()) 14977 << FixItHint::CreateRemoval(ParenERange.getEnd()); 14978 Diag(Loc, diag::note_equality_comparison_to_assign) 14979 << FixItHint::CreateReplacement(Loc, "="); 14980 } 14981 } 14982 14983 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 14984 bool IsConstexpr) { 14985 DiagnoseAssignmentAsCondition(E); 14986 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 14987 DiagnoseEqualityWithExtraParens(parenE); 14988 14989 ExprResult result = CheckPlaceholderExpr(E); 14990 if (result.isInvalid()) return ExprError(); 14991 E = result.get(); 14992 14993 if (!E->isTypeDependent()) { 14994 if (getLangOpts().CPlusPlus) 14995 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 14996 14997 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 14998 if (ERes.isInvalid()) 14999 return ExprError(); 15000 E = ERes.get(); 15001 15002 QualType T = E->getType(); 15003 if (!T->isScalarType()) { // C99 6.8.4.1p1 15004 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 15005 << T << E->getSourceRange(); 15006 return ExprError(); 15007 } 15008 CheckBoolLikeConversion(E, Loc); 15009 } 15010 15011 return E; 15012 } 15013 15014 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 15015 Expr *SubExpr, ConditionKind CK) { 15016 // Empty conditions are valid in for-statements. 15017 if (!SubExpr) 15018 return ConditionResult(); 15019 15020 ExprResult Cond; 15021 switch (CK) { 15022 case ConditionKind::Boolean: 15023 Cond = CheckBooleanCondition(Loc, SubExpr); 15024 break; 15025 15026 case ConditionKind::ConstexprIf: 15027 Cond = CheckBooleanCondition(Loc, SubExpr, true); 15028 break; 15029 15030 case ConditionKind::Switch: 15031 Cond = CheckSwitchCondition(Loc, SubExpr); 15032 break; 15033 } 15034 if (Cond.isInvalid()) 15035 return ConditionError(); 15036 15037 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 15038 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 15039 if (!FullExpr.get()) 15040 return ConditionError(); 15041 15042 return ConditionResult(*this, nullptr, FullExpr, 15043 CK == ConditionKind::ConstexprIf); 15044 } 15045 15046 namespace { 15047 /// A visitor for rebuilding a call to an __unknown_any expression 15048 /// to have an appropriate type. 15049 struct RebuildUnknownAnyFunction 15050 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 15051 15052 Sema &S; 15053 15054 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 15055 15056 ExprResult VisitStmt(Stmt *S) { 15057 llvm_unreachable("unexpected statement!"); 15058 } 15059 15060 ExprResult VisitExpr(Expr *E) { 15061 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 15062 << E->getSourceRange(); 15063 return ExprError(); 15064 } 15065 15066 /// Rebuild an expression which simply semantically wraps another 15067 /// expression which it shares the type and value kind of. 15068 template <class T> ExprResult rebuildSugarExpr(T *E) { 15069 ExprResult SubResult = Visit(E->getSubExpr()); 15070 if (SubResult.isInvalid()) return ExprError(); 15071 15072 Expr *SubExpr = SubResult.get(); 15073 E->setSubExpr(SubExpr); 15074 E->setType(SubExpr->getType()); 15075 E->setValueKind(SubExpr->getValueKind()); 15076 assert(E->getObjectKind() == OK_Ordinary); 15077 return E; 15078 } 15079 15080 ExprResult VisitParenExpr(ParenExpr *E) { 15081 return rebuildSugarExpr(E); 15082 } 15083 15084 ExprResult VisitUnaryExtension(UnaryOperator *E) { 15085 return rebuildSugarExpr(E); 15086 } 15087 15088 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 15089 ExprResult SubResult = Visit(E->getSubExpr()); 15090 if (SubResult.isInvalid()) return ExprError(); 15091 15092 Expr *SubExpr = SubResult.get(); 15093 E->setSubExpr(SubExpr); 15094 E->setType(S.Context.getPointerType(SubExpr->getType())); 15095 assert(E->getValueKind() == VK_RValue); 15096 assert(E->getObjectKind() == OK_Ordinary); 15097 return E; 15098 } 15099 15100 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 15101 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 15102 15103 E->setType(VD->getType()); 15104 15105 assert(E->getValueKind() == VK_RValue); 15106 if (S.getLangOpts().CPlusPlus && 15107 !(isa<CXXMethodDecl>(VD) && 15108 cast<CXXMethodDecl>(VD)->isInstance())) 15109 E->setValueKind(VK_LValue); 15110 15111 return E; 15112 } 15113 15114 ExprResult VisitMemberExpr(MemberExpr *E) { 15115 return resolveDecl(E, E->getMemberDecl()); 15116 } 15117 15118 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 15119 return resolveDecl(E, E->getDecl()); 15120 } 15121 }; 15122 } 15123 15124 /// Given a function expression of unknown-any type, try to rebuild it 15125 /// to have a function type. 15126 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 15127 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 15128 if (Result.isInvalid()) return ExprError(); 15129 return S.DefaultFunctionArrayConversion(Result.get()); 15130 } 15131 15132 namespace { 15133 /// A visitor for rebuilding an expression of type __unknown_anytype 15134 /// into one which resolves the type directly on the referring 15135 /// expression. Strict preservation of the original source 15136 /// structure is not a goal. 15137 struct RebuildUnknownAnyExpr 15138 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 15139 15140 Sema &S; 15141 15142 /// The current destination type. 15143 QualType DestType; 15144 15145 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 15146 : S(S), DestType(CastType) {} 15147 15148 ExprResult VisitStmt(Stmt *S) { 15149 llvm_unreachable("unexpected statement!"); 15150 } 15151 15152 ExprResult VisitExpr(Expr *E) { 15153 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 15154 << E->getSourceRange(); 15155 return ExprError(); 15156 } 15157 15158 ExprResult VisitCallExpr(CallExpr *E); 15159 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 15160 15161 /// Rebuild an expression which simply semantically wraps another 15162 /// expression which it shares the type and value kind of. 15163 template <class T> ExprResult rebuildSugarExpr(T *E) { 15164 ExprResult SubResult = Visit(E->getSubExpr()); 15165 if (SubResult.isInvalid()) return ExprError(); 15166 Expr *SubExpr = SubResult.get(); 15167 E->setSubExpr(SubExpr); 15168 E->setType(SubExpr->getType()); 15169 E->setValueKind(SubExpr->getValueKind()); 15170 assert(E->getObjectKind() == OK_Ordinary); 15171 return E; 15172 } 15173 15174 ExprResult VisitParenExpr(ParenExpr *E) { 15175 return rebuildSugarExpr(E); 15176 } 15177 15178 ExprResult VisitUnaryExtension(UnaryOperator *E) { 15179 return rebuildSugarExpr(E); 15180 } 15181 15182 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 15183 const PointerType *Ptr = DestType->getAs<PointerType>(); 15184 if (!Ptr) { 15185 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 15186 << E->getSourceRange(); 15187 return ExprError(); 15188 } 15189 15190 if (isa<CallExpr>(E->getSubExpr())) { 15191 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 15192 << E->getSourceRange(); 15193 return ExprError(); 15194 } 15195 15196 assert(E->getValueKind() == VK_RValue); 15197 assert(E->getObjectKind() == OK_Ordinary); 15198 E->setType(DestType); 15199 15200 // Build the sub-expression as if it were an object of the pointee type. 15201 DestType = Ptr->getPointeeType(); 15202 ExprResult SubResult = Visit(E->getSubExpr()); 15203 if (SubResult.isInvalid()) return ExprError(); 15204 E->setSubExpr(SubResult.get()); 15205 return E; 15206 } 15207 15208 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 15209 15210 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 15211 15212 ExprResult VisitMemberExpr(MemberExpr *E) { 15213 return resolveDecl(E, E->getMemberDecl()); 15214 } 15215 15216 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 15217 return resolveDecl(E, E->getDecl()); 15218 } 15219 }; 15220 } 15221 15222 /// Rebuilds a call expression which yielded __unknown_anytype. 15223 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 15224 Expr *CalleeExpr = E->getCallee(); 15225 15226 enum FnKind { 15227 FK_MemberFunction, 15228 FK_FunctionPointer, 15229 FK_BlockPointer 15230 }; 15231 15232 FnKind Kind; 15233 QualType CalleeType = CalleeExpr->getType(); 15234 if (CalleeType == S.Context.BoundMemberTy) { 15235 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 15236 Kind = FK_MemberFunction; 15237 CalleeType = Expr::findBoundMemberType(CalleeExpr); 15238 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 15239 CalleeType = Ptr->getPointeeType(); 15240 Kind = FK_FunctionPointer; 15241 } else { 15242 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 15243 Kind = FK_BlockPointer; 15244 } 15245 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 15246 15247 // Verify that this is a legal result type of a function. 15248 if (DestType->isArrayType() || DestType->isFunctionType()) { 15249 unsigned diagID = diag::err_func_returning_array_function; 15250 if (Kind == FK_BlockPointer) 15251 diagID = diag::err_block_returning_array_function; 15252 15253 S.Diag(E->getExprLoc(), diagID) 15254 << DestType->isFunctionType() << DestType; 15255 return ExprError(); 15256 } 15257 15258 // Otherwise, go ahead and set DestType as the call's result. 15259 E->setType(DestType.getNonLValueExprType(S.Context)); 15260 E->setValueKind(Expr::getValueKindForType(DestType)); 15261 assert(E->getObjectKind() == OK_Ordinary); 15262 15263 // Rebuild the function type, replacing the result type with DestType. 15264 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 15265 if (Proto) { 15266 // __unknown_anytype(...) is a special case used by the debugger when 15267 // it has no idea what a function's signature is. 15268 // 15269 // We want to build this call essentially under the K&R 15270 // unprototyped rules, but making a FunctionNoProtoType in C++ 15271 // would foul up all sorts of assumptions. However, we cannot 15272 // simply pass all arguments as variadic arguments, nor can we 15273 // portably just call the function under a non-variadic type; see 15274 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 15275 // However, it turns out that in practice it is generally safe to 15276 // call a function declared as "A foo(B,C,D);" under the prototype 15277 // "A foo(B,C,D,...);". The only known exception is with the 15278 // Windows ABI, where any variadic function is implicitly cdecl 15279 // regardless of its normal CC. Therefore we change the parameter 15280 // types to match the types of the arguments. 15281 // 15282 // This is a hack, but it is far superior to moving the 15283 // corresponding target-specific code from IR-gen to Sema/AST. 15284 15285 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 15286 SmallVector<QualType, 8> ArgTypes; 15287 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 15288 ArgTypes.reserve(E->getNumArgs()); 15289 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 15290 Expr *Arg = E->getArg(i); 15291 QualType ArgType = Arg->getType(); 15292 if (E->isLValue()) { 15293 ArgType = S.Context.getLValueReferenceType(ArgType); 15294 } else if (E->isXValue()) { 15295 ArgType = S.Context.getRValueReferenceType(ArgType); 15296 } 15297 ArgTypes.push_back(ArgType); 15298 } 15299 ParamTypes = ArgTypes; 15300 } 15301 DestType = S.Context.getFunctionType(DestType, ParamTypes, 15302 Proto->getExtProtoInfo()); 15303 } else { 15304 DestType = S.Context.getFunctionNoProtoType(DestType, 15305 FnType->getExtInfo()); 15306 } 15307 15308 // Rebuild the appropriate pointer-to-function type. 15309 switch (Kind) { 15310 case FK_MemberFunction: 15311 // Nothing to do. 15312 break; 15313 15314 case FK_FunctionPointer: 15315 DestType = S.Context.getPointerType(DestType); 15316 break; 15317 15318 case FK_BlockPointer: 15319 DestType = S.Context.getBlockPointerType(DestType); 15320 break; 15321 } 15322 15323 // Finally, we can recurse. 15324 ExprResult CalleeResult = Visit(CalleeExpr); 15325 if (!CalleeResult.isUsable()) return ExprError(); 15326 E->setCallee(CalleeResult.get()); 15327 15328 // Bind a temporary if necessary. 15329 return S.MaybeBindToTemporary(E); 15330 } 15331 15332 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 15333 // Verify that this is a legal result type of a call. 15334 if (DestType->isArrayType() || DestType->isFunctionType()) { 15335 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 15336 << DestType->isFunctionType() << DestType; 15337 return ExprError(); 15338 } 15339 15340 // Rewrite the method result type if available. 15341 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 15342 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 15343 Method->setReturnType(DestType); 15344 } 15345 15346 // Change the type of the message. 15347 E->setType(DestType.getNonReferenceType()); 15348 E->setValueKind(Expr::getValueKindForType(DestType)); 15349 15350 return S.MaybeBindToTemporary(E); 15351 } 15352 15353 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 15354 // The only case we should ever see here is a function-to-pointer decay. 15355 if (E->getCastKind() == CK_FunctionToPointerDecay) { 15356 assert(E->getValueKind() == VK_RValue); 15357 assert(E->getObjectKind() == OK_Ordinary); 15358 15359 E->setType(DestType); 15360 15361 // Rebuild the sub-expression as the pointee (function) type. 15362 DestType = DestType->castAs<PointerType>()->getPointeeType(); 15363 15364 ExprResult Result = Visit(E->getSubExpr()); 15365 if (!Result.isUsable()) return ExprError(); 15366 15367 E->setSubExpr(Result.get()); 15368 return E; 15369 } else if (E->getCastKind() == CK_LValueToRValue) { 15370 assert(E->getValueKind() == VK_RValue); 15371 assert(E->getObjectKind() == OK_Ordinary); 15372 15373 assert(isa<BlockPointerType>(E->getType())); 15374 15375 E->setType(DestType); 15376 15377 // The sub-expression has to be a lvalue reference, so rebuild it as such. 15378 DestType = S.Context.getLValueReferenceType(DestType); 15379 15380 ExprResult Result = Visit(E->getSubExpr()); 15381 if (!Result.isUsable()) return ExprError(); 15382 15383 E->setSubExpr(Result.get()); 15384 return E; 15385 } else { 15386 llvm_unreachable("Unhandled cast type!"); 15387 } 15388 } 15389 15390 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 15391 ExprValueKind ValueKind = VK_LValue; 15392 QualType Type = DestType; 15393 15394 // We know how to make this work for certain kinds of decls: 15395 15396 // - functions 15397 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 15398 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 15399 DestType = Ptr->getPointeeType(); 15400 ExprResult Result = resolveDecl(E, VD); 15401 if (Result.isInvalid()) return ExprError(); 15402 return S.ImpCastExprToType(Result.get(), Type, 15403 CK_FunctionToPointerDecay, VK_RValue); 15404 } 15405 15406 if (!Type->isFunctionType()) { 15407 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 15408 << VD << E->getSourceRange(); 15409 return ExprError(); 15410 } 15411 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 15412 // We must match the FunctionDecl's type to the hack introduced in 15413 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 15414 // type. See the lengthy commentary in that routine. 15415 QualType FDT = FD->getType(); 15416 const FunctionType *FnType = FDT->castAs<FunctionType>(); 15417 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 15418 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 15419 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 15420 SourceLocation Loc = FD->getLocation(); 15421 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(), 15422 FD->getDeclContext(), 15423 Loc, Loc, FD->getNameInfo().getName(), 15424 DestType, FD->getTypeSourceInfo(), 15425 SC_None, false/*isInlineSpecified*/, 15426 FD->hasPrototype(), 15427 false/*isConstexprSpecified*/); 15428 15429 if (FD->getQualifier()) 15430 NewFD->setQualifierInfo(FD->getQualifierLoc()); 15431 15432 SmallVector<ParmVarDecl*, 16> Params; 15433 for (const auto &AI : FT->param_types()) { 15434 ParmVarDecl *Param = 15435 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 15436 Param->setScopeInfo(0, Params.size()); 15437 Params.push_back(Param); 15438 } 15439 NewFD->setParams(Params); 15440 DRE->setDecl(NewFD); 15441 VD = DRE->getDecl(); 15442 } 15443 } 15444 15445 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 15446 if (MD->isInstance()) { 15447 ValueKind = VK_RValue; 15448 Type = S.Context.BoundMemberTy; 15449 } 15450 15451 // Function references aren't l-values in C. 15452 if (!S.getLangOpts().CPlusPlus) 15453 ValueKind = VK_RValue; 15454 15455 // - variables 15456 } else if (isa<VarDecl>(VD)) { 15457 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 15458 Type = RefTy->getPointeeType(); 15459 } else if (Type->isFunctionType()) { 15460 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 15461 << VD << E->getSourceRange(); 15462 return ExprError(); 15463 } 15464 15465 // - nothing else 15466 } else { 15467 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 15468 << VD << E->getSourceRange(); 15469 return ExprError(); 15470 } 15471 15472 // Modifying the declaration like this is friendly to IR-gen but 15473 // also really dangerous. 15474 VD->setType(DestType); 15475 E->setType(Type); 15476 E->setValueKind(ValueKind); 15477 return E; 15478 } 15479 15480 /// Check a cast of an unknown-any type. We intentionally only 15481 /// trigger this for C-style casts. 15482 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 15483 Expr *CastExpr, CastKind &CastKind, 15484 ExprValueKind &VK, CXXCastPath &Path) { 15485 // The type we're casting to must be either void or complete. 15486 if (!CastType->isVoidType() && 15487 RequireCompleteType(TypeRange.getBegin(), CastType, 15488 diag::err_typecheck_cast_to_incomplete)) 15489 return ExprError(); 15490 15491 // Rewrite the casted expression from scratch. 15492 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 15493 if (!result.isUsable()) return ExprError(); 15494 15495 CastExpr = result.get(); 15496 VK = CastExpr->getValueKind(); 15497 CastKind = CK_NoOp; 15498 15499 return CastExpr; 15500 } 15501 15502 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 15503 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 15504 } 15505 15506 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 15507 Expr *arg, QualType ¶mType) { 15508 // If the syntactic form of the argument is not an explicit cast of 15509 // any sort, just do default argument promotion. 15510 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 15511 if (!castArg) { 15512 ExprResult result = DefaultArgumentPromotion(arg); 15513 if (result.isInvalid()) return ExprError(); 15514 paramType = result.get()->getType(); 15515 return result; 15516 } 15517 15518 // Otherwise, use the type that was written in the explicit cast. 15519 assert(!arg->hasPlaceholderType()); 15520 paramType = castArg->getTypeAsWritten(); 15521 15522 // Copy-initialize a parameter of that type. 15523 InitializedEntity entity = 15524 InitializedEntity::InitializeParameter(Context, paramType, 15525 /*consumed*/ false); 15526 return PerformCopyInitialization(entity, callLoc, arg); 15527 } 15528 15529 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 15530 Expr *orig = E; 15531 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 15532 while (true) { 15533 E = E->IgnoreParenImpCasts(); 15534 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 15535 E = call->getCallee(); 15536 diagID = diag::err_uncasted_call_of_unknown_any; 15537 } else { 15538 break; 15539 } 15540 } 15541 15542 SourceLocation loc; 15543 NamedDecl *d; 15544 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 15545 loc = ref->getLocation(); 15546 d = ref->getDecl(); 15547 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 15548 loc = mem->getMemberLoc(); 15549 d = mem->getMemberDecl(); 15550 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 15551 diagID = diag::err_uncasted_call_of_unknown_any; 15552 loc = msg->getSelectorStartLoc(); 15553 d = msg->getMethodDecl(); 15554 if (!d) { 15555 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 15556 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 15557 << orig->getSourceRange(); 15558 return ExprError(); 15559 } 15560 } else { 15561 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 15562 << E->getSourceRange(); 15563 return ExprError(); 15564 } 15565 15566 S.Diag(loc, diagID) << d << orig->getSourceRange(); 15567 15568 // Never recoverable. 15569 return ExprError(); 15570 } 15571 15572 /// Check for operands with placeholder types and complain if found. 15573 /// Returns ExprError() if there was an error and no recovery was possible. 15574 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 15575 if (!getLangOpts().CPlusPlus) { 15576 // C cannot handle TypoExpr nodes on either side of a binop because it 15577 // doesn't handle dependent types properly, so make sure any TypoExprs have 15578 // been dealt with before checking the operands. 15579 ExprResult Result = CorrectDelayedTyposInExpr(E); 15580 if (!Result.isUsable()) return ExprError(); 15581 E = Result.get(); 15582 } 15583 15584 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 15585 if (!placeholderType) return E; 15586 15587 switch (placeholderType->getKind()) { 15588 15589 // Overloaded expressions. 15590 case BuiltinType::Overload: { 15591 // Try to resolve a single function template specialization. 15592 // This is obligatory. 15593 ExprResult Result = E; 15594 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 15595 return Result; 15596 15597 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 15598 // leaves Result unchanged on failure. 15599 Result = E; 15600 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) 15601 return Result; 15602 15603 // If that failed, try to recover with a call. 15604 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 15605 /*complain*/ true); 15606 return Result; 15607 } 15608 15609 // Bound member functions. 15610 case BuiltinType::BoundMember: { 15611 ExprResult result = E; 15612 const Expr *BME = E->IgnoreParens(); 15613 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 15614 // Try to give a nicer diagnostic if it is a bound member that we recognize. 15615 if (isa<CXXPseudoDestructorExpr>(BME)) { 15616 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 15617 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 15618 if (ME->getMemberNameInfo().getName().getNameKind() == 15619 DeclarationName::CXXDestructorName) 15620 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 15621 } 15622 tryToRecoverWithCall(result, PD, 15623 /*complain*/ true); 15624 return result; 15625 } 15626 15627 // ARC unbridged casts. 15628 case BuiltinType::ARCUnbridgedCast: { 15629 Expr *realCast = stripARCUnbridgedCast(E); 15630 diagnoseARCUnbridgedCast(realCast); 15631 return realCast; 15632 } 15633 15634 // Expressions of unknown type. 15635 case BuiltinType::UnknownAny: 15636 return diagnoseUnknownAnyExpr(*this, E); 15637 15638 // Pseudo-objects. 15639 case BuiltinType::PseudoObject: 15640 return checkPseudoObjectRValue(E); 15641 15642 case BuiltinType::BuiltinFn: { 15643 // Accept __noop without parens by implicitly converting it to a call expr. 15644 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 15645 if (DRE) { 15646 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 15647 if (FD->getBuiltinID() == Builtin::BI__noop) { 15648 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 15649 CK_BuiltinFnToFnPtr).get(); 15650 return new (Context) CallExpr(Context, E, None, Context.IntTy, 15651 VK_RValue, SourceLocation()); 15652 } 15653 } 15654 15655 Diag(E->getLocStart(), diag::err_builtin_fn_use); 15656 return ExprError(); 15657 } 15658 15659 // Expressions of unknown type. 15660 case BuiltinType::OMPArraySection: 15661 Diag(E->getLocStart(), diag::err_omp_array_section_use); 15662 return ExprError(); 15663 15664 // Everything else should be impossible. 15665 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 15666 case BuiltinType::Id: 15667 #include "clang/Basic/OpenCLImageTypes.def" 15668 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 15669 #define PLACEHOLDER_TYPE(Id, SingletonId) 15670 #include "clang/AST/BuiltinTypes.def" 15671 break; 15672 } 15673 15674 llvm_unreachable("invalid placeholder type!"); 15675 } 15676 15677 bool Sema::CheckCaseExpression(Expr *E) { 15678 if (E->isTypeDependent()) 15679 return true; 15680 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 15681 return E->getType()->isIntegralOrEnumerationType(); 15682 return false; 15683 } 15684 15685 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 15686 ExprResult 15687 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 15688 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 15689 "Unknown Objective-C Boolean value!"); 15690 QualType BoolT = Context.ObjCBuiltinBoolTy; 15691 if (!Context.getBOOLDecl()) { 15692 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 15693 Sema::LookupOrdinaryName); 15694 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 15695 NamedDecl *ND = Result.getFoundDecl(); 15696 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 15697 Context.setBOOLDecl(TD); 15698 } 15699 } 15700 if (Context.getBOOLDecl()) 15701 BoolT = Context.getBOOLType(); 15702 return new (Context) 15703 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 15704 } 15705 15706 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 15707 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 15708 SourceLocation RParen) { 15709 15710 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 15711 15712 auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(), 15713 [&](const AvailabilitySpec &Spec) { 15714 return Spec.getPlatform() == Platform; 15715 }); 15716 15717 VersionTuple Version; 15718 if (Spec != AvailSpecs.end()) 15719 Version = Spec->getVersion(); 15720 15721 // The use of `@available` in the enclosing function should be analyzed to 15722 // warn when it's used inappropriately (i.e. not if(@available)). 15723 if (getCurFunctionOrMethodDecl()) 15724 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 15725 else if (getCurBlock() || getCurLambda()) 15726 getCurFunction()->HasPotentialAvailabilityViolations = true; 15727 15728 return new (Context) 15729 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 15730 } 15731