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 (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 429 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 430 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 431 return ExprError(); 432 433 E = ImpCastExprToType(E, Context.getPointerType(Ty), 434 CK_FunctionToPointerDecay).get(); 435 } else if (Ty->isArrayType()) { 436 // In C90 mode, arrays only promote to pointers if the array expression is 437 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 438 // type 'array of type' is converted to an expression that has type 'pointer 439 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 440 // that has type 'array of type' ...". The relevant change is "an lvalue" 441 // (C90) to "an expression" (C99). 442 // 443 // C++ 4.2p1: 444 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 445 // T" can be converted to an rvalue of type "pointer to T". 446 // 447 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 448 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 449 CK_ArrayToPointerDecay).get(); 450 } 451 return E; 452 } 453 454 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 455 // Check to see if we are dereferencing a null pointer. If so, 456 // and if not volatile-qualified, this is undefined behavior that the 457 // optimizer will delete, so warn about it. People sometimes try to use this 458 // to get a deterministic trap and are surprised by clang's behavior. This 459 // only handles the pattern "*null", which is a very syntactic check. 460 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 461 if (UO->getOpcode() == UO_Deref && 462 UO->getSubExpr()->IgnoreParenCasts()-> 463 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 464 !UO->getType().isVolatileQualified()) { 465 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 466 S.PDiag(diag::warn_indirection_through_null) 467 << UO->getSubExpr()->getSourceRange()); 468 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 469 S.PDiag(diag::note_indirection_through_null)); 470 } 471 } 472 473 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 474 SourceLocation AssignLoc, 475 const Expr* RHS) { 476 const ObjCIvarDecl *IV = OIRE->getDecl(); 477 if (!IV) 478 return; 479 480 DeclarationName MemberName = IV->getDeclName(); 481 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 482 if (!Member || !Member->isStr("isa")) 483 return; 484 485 const Expr *Base = OIRE->getBase(); 486 QualType BaseType = Base->getType(); 487 if (OIRE->isArrow()) 488 BaseType = BaseType->getPointeeType(); 489 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 490 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 491 ObjCInterfaceDecl *ClassDeclared = nullptr; 492 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 493 if (!ClassDeclared->getSuperClass() 494 && (*ClassDeclared->ivar_begin()) == IV) { 495 if (RHS) { 496 NamedDecl *ObjectSetClass = 497 S.LookupSingleName(S.TUScope, 498 &S.Context.Idents.get("object_setClass"), 499 SourceLocation(), S.LookupOrdinaryName); 500 if (ObjectSetClass) { 501 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd()); 502 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 503 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 504 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 505 AssignLoc), ",") << 506 FixItHint::CreateInsertion(RHSLocEnd, ")"); 507 } 508 else 509 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 510 } else { 511 NamedDecl *ObjectGetClass = 512 S.LookupSingleName(S.TUScope, 513 &S.Context.Idents.get("object_getClass"), 514 SourceLocation(), S.LookupOrdinaryName); 515 if (ObjectGetClass) 516 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 517 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 518 FixItHint::CreateReplacement( 519 SourceRange(OIRE->getOpLoc(), 520 OIRE->getLocEnd()), ")"); 521 else 522 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 523 } 524 S.Diag(IV->getLocation(), diag::note_ivar_decl); 525 } 526 } 527 } 528 529 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 530 // Handle any placeholder expressions which made it here. 531 if (E->getType()->isPlaceholderType()) { 532 ExprResult result = CheckPlaceholderExpr(E); 533 if (result.isInvalid()) return ExprError(); 534 E = result.get(); 535 } 536 537 // C++ [conv.lval]p1: 538 // A glvalue of a non-function, non-array type T can be 539 // converted to a prvalue. 540 if (!E->isGLValue()) return E; 541 542 QualType T = E->getType(); 543 assert(!T.isNull() && "r-value conversion on typeless expression?"); 544 545 // We don't want to throw lvalue-to-rvalue casts on top of 546 // expressions of certain types in C++. 547 if (getLangOpts().CPlusPlus && 548 (E->getType() == Context.OverloadTy || 549 T->isDependentType() || 550 T->isRecordType())) 551 return E; 552 553 // The C standard is actually really unclear on this point, and 554 // DR106 tells us what the result should be but not why. It's 555 // generally best to say that void types just doesn't undergo 556 // lvalue-to-rvalue at all. Note that expressions of unqualified 557 // 'void' type are never l-values, but qualified void can be. 558 if (T->isVoidType()) 559 return E; 560 561 // OpenCL usually rejects direct accesses to values of 'half' type. 562 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 563 T->isHalfType()) { 564 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 565 << 0 << T; 566 return ExprError(); 567 } 568 569 CheckForNullPointerDereference(*this, E); 570 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 571 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 572 &Context.Idents.get("object_getClass"), 573 SourceLocation(), LookupOrdinaryName); 574 if (ObjectGetClass) 575 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 576 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 577 FixItHint::CreateReplacement( 578 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 579 else 580 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 581 } 582 else if (const ObjCIvarRefExpr *OIRE = 583 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 584 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 585 586 // C++ [conv.lval]p1: 587 // [...] If T is a non-class type, the type of the prvalue is the 588 // cv-unqualified version of T. Otherwise, the type of the 589 // rvalue is T. 590 // 591 // C99 6.3.2.1p2: 592 // If the lvalue has qualified type, the value has the unqualified 593 // version of the type of the lvalue; otherwise, the value has the 594 // type of the lvalue. 595 if (T.hasQualifiers()) 596 T = T.getUnqualifiedType(); 597 598 // Under the MS ABI, lock down the inheritance model now. 599 if (T->isMemberPointerType() && 600 Context.getTargetInfo().getCXXABI().isMicrosoft()) 601 (void)isCompleteType(E->getExprLoc(), T); 602 603 UpdateMarkingForLValueToRValue(E); 604 605 // Loading a __weak object implicitly retains the value, so we need a cleanup to 606 // balance that. 607 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 608 Cleanup.setExprNeedsCleanups(true); 609 610 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 611 nullptr, VK_RValue); 612 613 // C11 6.3.2.1p2: 614 // ... if the lvalue has atomic type, the value has the non-atomic version 615 // of the type of the lvalue ... 616 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 617 T = Atomic->getValueType().getUnqualifiedType(); 618 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 619 nullptr, VK_RValue); 620 } 621 622 return Res; 623 } 624 625 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 626 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 627 if (Res.isInvalid()) 628 return ExprError(); 629 Res = DefaultLvalueConversion(Res.get()); 630 if (Res.isInvalid()) 631 return ExprError(); 632 return Res; 633 } 634 635 /// CallExprUnaryConversions - a special case of an unary conversion 636 /// performed on a function designator of a call expression. 637 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 638 QualType Ty = E->getType(); 639 ExprResult Res = E; 640 // Only do implicit cast for a function type, but not for a pointer 641 // to function type. 642 if (Ty->isFunctionType()) { 643 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 644 CK_FunctionToPointerDecay).get(); 645 if (Res.isInvalid()) 646 return ExprError(); 647 } 648 Res = DefaultLvalueConversion(Res.get()); 649 if (Res.isInvalid()) 650 return ExprError(); 651 return Res.get(); 652 } 653 654 /// UsualUnaryConversions - Performs various conversions that are common to most 655 /// operators (C99 6.3). The conversions of array and function types are 656 /// sometimes suppressed. For example, the array->pointer conversion doesn't 657 /// apply if the array is an argument to the sizeof or address (&) operators. 658 /// In these instances, this routine should *not* be called. 659 ExprResult Sema::UsualUnaryConversions(Expr *E) { 660 // First, convert to an r-value. 661 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 662 if (Res.isInvalid()) 663 return ExprError(); 664 E = Res.get(); 665 666 QualType Ty = E->getType(); 667 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 668 669 // Half FP have to be promoted to float unless it is natively supported 670 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 671 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 672 673 // Try to perform integral promotions if the object has a theoretically 674 // promotable type. 675 if (Ty->isIntegralOrUnscopedEnumerationType()) { 676 // C99 6.3.1.1p2: 677 // 678 // The following may be used in an expression wherever an int or 679 // unsigned int may be used: 680 // - an object or expression with an integer type whose integer 681 // conversion rank is less than or equal to the rank of int 682 // and unsigned int. 683 // - A bit-field of type _Bool, int, signed int, or unsigned int. 684 // 685 // If an int can represent all values of the original type, the 686 // value is converted to an int; otherwise, it is converted to an 687 // unsigned int. These are called the integer promotions. All 688 // other types are unchanged by the integer promotions. 689 690 QualType PTy = Context.isPromotableBitField(E); 691 if (!PTy.isNull()) { 692 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 693 return E; 694 } 695 if (Ty->isPromotableIntegerType()) { 696 QualType PT = Context.getPromotedIntegerType(Ty); 697 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 698 return E; 699 } 700 } 701 return E; 702 } 703 704 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 705 /// do not have a prototype. Arguments that have type float or __fp16 706 /// are promoted to double. All other argument types are converted by 707 /// UsualUnaryConversions(). 708 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 709 QualType Ty = E->getType(); 710 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 711 712 ExprResult Res = UsualUnaryConversions(E); 713 if (Res.isInvalid()) 714 return ExprError(); 715 E = Res.get(); 716 717 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 718 // promote to double. 719 // Note that default argument promotion applies only to float (and 720 // half/fp16); it does not apply to _Float16. 721 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 722 if (BTy && (BTy->getKind() == BuiltinType::Half || 723 BTy->getKind() == BuiltinType::Float)) { 724 if (getLangOpts().OpenCL && 725 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 726 if (BTy->getKind() == BuiltinType::Half) { 727 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 728 } 729 } else { 730 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 731 } 732 } 733 734 // C++ performs lvalue-to-rvalue conversion as a default argument 735 // promotion, even on class types, but note: 736 // C++11 [conv.lval]p2: 737 // When an lvalue-to-rvalue conversion occurs in an unevaluated 738 // operand or a subexpression thereof the value contained in the 739 // referenced object is not accessed. Otherwise, if the glvalue 740 // has a class type, the conversion copy-initializes a temporary 741 // of type T from the glvalue and the result of the conversion 742 // is a prvalue for the temporary. 743 // FIXME: add some way to gate this entire thing for correctness in 744 // potentially potentially evaluated contexts. 745 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 746 ExprResult Temp = PerformCopyInitialization( 747 InitializedEntity::InitializeTemporary(E->getType()), 748 E->getExprLoc(), E); 749 if (Temp.isInvalid()) 750 return ExprError(); 751 E = Temp.get(); 752 } 753 754 return E; 755 } 756 757 /// Determine the degree of POD-ness for an expression. 758 /// Incomplete types are considered POD, since this check can be performed 759 /// when we're in an unevaluated context. 760 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 761 if (Ty->isIncompleteType()) { 762 // C++11 [expr.call]p7: 763 // After these conversions, if the argument does not have arithmetic, 764 // enumeration, pointer, pointer to member, or class type, the program 765 // is ill-formed. 766 // 767 // Since we've already performed array-to-pointer and function-to-pointer 768 // decay, the only such type in C++ is cv void. This also handles 769 // initializer lists as variadic arguments. 770 if (Ty->isVoidType()) 771 return VAK_Invalid; 772 773 if (Ty->isObjCObjectType()) 774 return VAK_Invalid; 775 return VAK_Valid; 776 } 777 778 if (Ty.isCXX98PODType(Context)) 779 return VAK_Valid; 780 781 // C++11 [expr.call]p7: 782 // Passing a potentially-evaluated argument of class type (Clause 9) 783 // having a non-trivial copy constructor, a non-trivial move constructor, 784 // or a non-trivial destructor, with no corresponding parameter, 785 // is conditionally-supported with implementation-defined semantics. 786 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 787 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 788 if (!Record->hasNonTrivialCopyConstructor() && 789 !Record->hasNonTrivialMoveConstructor() && 790 !Record->hasNonTrivialDestructor()) 791 return VAK_ValidInCXX11; 792 793 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 794 return VAK_Valid; 795 796 if (Ty->isObjCObjectType()) 797 return VAK_Invalid; 798 799 if (getLangOpts().MSVCCompat) 800 return VAK_MSVCUndefined; 801 802 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 803 // permitted to reject them. We should consider doing so. 804 return VAK_Undefined; 805 } 806 807 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 808 // Don't allow one to pass an Objective-C interface to a vararg. 809 const QualType &Ty = E->getType(); 810 VarArgKind VAK = isValidVarArgType(Ty); 811 812 // Complain about passing non-POD types through varargs. 813 switch (VAK) { 814 case VAK_ValidInCXX11: 815 DiagRuntimeBehavior( 816 E->getLocStart(), nullptr, 817 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 818 << Ty << CT); 819 // Fall through. 820 case VAK_Valid: 821 if (Ty->isRecordType()) { 822 // This is unlikely to be what the user intended. If the class has a 823 // 'c_str' member function, the user probably meant to call that. 824 DiagRuntimeBehavior(E->getLocStart(), nullptr, 825 PDiag(diag::warn_pass_class_arg_to_vararg) 826 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 827 } 828 break; 829 830 case VAK_Undefined: 831 case VAK_MSVCUndefined: 832 DiagRuntimeBehavior( 833 E->getLocStart(), nullptr, 834 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 835 << getLangOpts().CPlusPlus11 << Ty << CT); 836 break; 837 838 case VAK_Invalid: 839 if (Ty->isObjCObjectType()) 840 DiagRuntimeBehavior( 841 E->getLocStart(), nullptr, 842 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 843 << Ty << CT); 844 else 845 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg) 846 << isa<InitListExpr>(E) << Ty << CT; 847 break; 848 } 849 } 850 851 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 852 /// will create a trap if the resulting type is not a POD type. 853 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 854 FunctionDecl *FDecl) { 855 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 856 // Strip the unbridged-cast placeholder expression off, if applicable. 857 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 858 (CT == VariadicMethod || 859 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 860 E = stripARCUnbridgedCast(E); 861 862 // Otherwise, do normal placeholder checking. 863 } else { 864 ExprResult ExprRes = CheckPlaceholderExpr(E); 865 if (ExprRes.isInvalid()) 866 return ExprError(); 867 E = ExprRes.get(); 868 } 869 } 870 871 ExprResult ExprRes = DefaultArgumentPromotion(E); 872 if (ExprRes.isInvalid()) 873 return ExprError(); 874 E = ExprRes.get(); 875 876 // Diagnostics regarding non-POD argument types are 877 // emitted along with format string checking in Sema::CheckFunctionCall(). 878 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 879 // Turn this into a trap. 880 CXXScopeSpec SS; 881 SourceLocation TemplateKWLoc; 882 UnqualifiedId Name; 883 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 884 E->getLocStart()); 885 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 886 Name, true, false); 887 if (TrapFn.isInvalid()) 888 return ExprError(); 889 890 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 891 E->getLocStart(), None, 892 E->getLocEnd()); 893 if (Call.isInvalid()) 894 return ExprError(); 895 896 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 897 Call.get(), E); 898 if (Comma.isInvalid()) 899 return ExprError(); 900 return Comma.get(); 901 } 902 903 if (!getLangOpts().CPlusPlus && 904 RequireCompleteType(E->getExprLoc(), E->getType(), 905 diag::err_call_incomplete_argument)) 906 return ExprError(); 907 908 return E; 909 } 910 911 /// \brief Converts an integer to complex float type. Helper function of 912 /// UsualArithmeticConversions() 913 /// 914 /// \return false if the integer expression is an integer type and is 915 /// successfully converted to the complex type. 916 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 917 ExprResult &ComplexExpr, 918 QualType IntTy, 919 QualType ComplexTy, 920 bool SkipCast) { 921 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 922 if (SkipCast) return false; 923 if (IntTy->isIntegerType()) { 924 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 925 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 926 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 927 CK_FloatingRealToComplex); 928 } else { 929 assert(IntTy->isComplexIntegerType()); 930 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 931 CK_IntegralComplexToFloatingComplex); 932 } 933 return false; 934 } 935 936 /// \brief Handle arithmetic conversion with complex types. Helper function of 937 /// UsualArithmeticConversions() 938 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 939 ExprResult &RHS, QualType LHSType, 940 QualType RHSType, 941 bool IsCompAssign) { 942 // if we have an integer operand, the result is the complex type. 943 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 944 /*skipCast*/false)) 945 return LHSType; 946 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 947 /*skipCast*/IsCompAssign)) 948 return RHSType; 949 950 // This handles complex/complex, complex/float, or float/complex. 951 // When both operands are complex, the shorter operand is converted to the 952 // type of the longer, and that is the type of the result. This corresponds 953 // to what is done when combining two real floating-point operands. 954 // The fun begins when size promotion occur across type domains. 955 // From H&S 6.3.4: When one operand is complex and the other is a real 956 // floating-point type, the less precise type is converted, within it's 957 // real or complex domain, to the precision of the other type. For example, 958 // when combining a "long double" with a "double _Complex", the 959 // "double _Complex" is promoted to "long double _Complex". 960 961 // Compute the rank of the two types, regardless of whether they are complex. 962 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 963 964 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 965 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 966 QualType LHSElementType = 967 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 968 QualType RHSElementType = 969 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 970 971 QualType ResultType = S.Context.getComplexType(LHSElementType); 972 if (Order < 0) { 973 // Promote the precision of the LHS if not an assignment. 974 ResultType = S.Context.getComplexType(RHSElementType); 975 if (!IsCompAssign) { 976 if (LHSComplexType) 977 LHS = 978 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 979 else 980 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 981 } 982 } else if (Order > 0) { 983 // Promote the precision of the RHS. 984 if (RHSComplexType) 985 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 986 else 987 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 988 } 989 return ResultType; 990 } 991 992 /// \brief Handle arithmetic conversion from integer to float. Helper function 993 /// of UsualArithmeticConversions() 994 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 995 ExprResult &IntExpr, 996 QualType FloatTy, QualType IntTy, 997 bool ConvertFloat, bool ConvertInt) { 998 if (IntTy->isIntegerType()) { 999 if (ConvertInt) 1000 // Convert intExpr to the lhs floating point type. 1001 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1002 CK_IntegralToFloating); 1003 return FloatTy; 1004 } 1005 1006 // Convert both sides to the appropriate complex float. 1007 assert(IntTy->isComplexIntegerType()); 1008 QualType result = S.Context.getComplexType(FloatTy); 1009 1010 // _Complex int -> _Complex float 1011 if (ConvertInt) 1012 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1013 CK_IntegralComplexToFloatingComplex); 1014 1015 // float -> _Complex float 1016 if (ConvertFloat) 1017 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1018 CK_FloatingRealToComplex); 1019 1020 return result; 1021 } 1022 1023 /// \brief Handle arithmethic conversion with floating point types. Helper 1024 /// function of UsualArithmeticConversions() 1025 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1026 ExprResult &RHS, QualType LHSType, 1027 QualType RHSType, bool IsCompAssign) { 1028 bool LHSFloat = LHSType->isRealFloatingType(); 1029 bool RHSFloat = RHSType->isRealFloatingType(); 1030 1031 // If we have two real floating types, convert the smaller operand 1032 // to the bigger result. 1033 if (LHSFloat && RHSFloat) { 1034 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1035 if (order > 0) { 1036 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1037 return LHSType; 1038 } 1039 1040 assert(order < 0 && "illegal float comparison"); 1041 if (!IsCompAssign) 1042 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1043 return RHSType; 1044 } 1045 1046 if (LHSFloat) { 1047 // Half FP has to be promoted to float unless it is natively supported 1048 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1049 LHSType = S.Context.FloatTy; 1050 1051 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1052 /*convertFloat=*/!IsCompAssign, 1053 /*convertInt=*/ true); 1054 } 1055 assert(RHSFloat); 1056 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1057 /*convertInt=*/ true, 1058 /*convertFloat=*/!IsCompAssign); 1059 } 1060 1061 /// \brief Diagnose attempts to convert between __float128 and long double if 1062 /// there is no support for such conversion. Helper function of 1063 /// UsualArithmeticConversions(). 1064 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1065 QualType RHSType) { 1066 /* No issue converting if at least one of the types is not a floating point 1067 type or the two types have the same rank. 1068 */ 1069 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1070 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1071 return false; 1072 1073 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1074 "The remaining types must be floating point types."); 1075 1076 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1077 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1078 1079 QualType LHSElemType = LHSComplex ? 1080 LHSComplex->getElementType() : LHSType; 1081 QualType RHSElemType = RHSComplex ? 1082 RHSComplex->getElementType() : RHSType; 1083 1084 // No issue if the two types have the same representation 1085 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1086 &S.Context.getFloatTypeSemantics(RHSElemType)) 1087 return false; 1088 1089 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1090 RHSElemType == S.Context.LongDoubleTy); 1091 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1092 RHSElemType == S.Context.Float128Ty); 1093 1094 /* We've handled the situation where __float128 and long double have the same 1095 representation. The only other allowable conversion is if long double is 1096 really just double. 1097 */ 1098 return Float128AndLongDouble && 1099 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) != 1100 &llvm::APFloat::IEEEdouble()); 1101 } 1102 1103 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1104 1105 namespace { 1106 /// These helper callbacks are placed in an anonymous namespace to 1107 /// permit their use as function template parameters. 1108 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1109 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1110 } 1111 1112 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1113 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1114 CK_IntegralComplexCast); 1115 } 1116 } 1117 1118 /// \brief Handle integer arithmetic conversions. Helper function of 1119 /// UsualArithmeticConversions() 1120 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1121 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1122 ExprResult &RHS, QualType LHSType, 1123 QualType RHSType, bool IsCompAssign) { 1124 // The rules for this case are in C99 6.3.1.8 1125 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1126 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1127 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1128 if (LHSSigned == RHSSigned) { 1129 // Same signedness; use the higher-ranked type 1130 if (order >= 0) { 1131 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1132 return LHSType; 1133 } else if (!IsCompAssign) 1134 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1135 return RHSType; 1136 } else if (order != (LHSSigned ? 1 : -1)) { 1137 // The unsigned type has greater than or equal rank to the 1138 // signed type, so use the unsigned type 1139 if (RHSSigned) { 1140 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1141 return LHSType; 1142 } else if (!IsCompAssign) 1143 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1144 return RHSType; 1145 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1146 // The two types are different widths; if we are here, that 1147 // means the signed type is larger than the unsigned type, so 1148 // use the signed type. 1149 if (LHSSigned) { 1150 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1151 return LHSType; 1152 } else if (!IsCompAssign) 1153 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1154 return RHSType; 1155 } else { 1156 // The signed type is higher-ranked than the unsigned type, 1157 // but isn't actually any bigger (like unsigned int and long 1158 // on most 32-bit systems). Use the unsigned type corresponding 1159 // to the signed type. 1160 QualType result = 1161 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1162 RHS = (*doRHSCast)(S, RHS.get(), result); 1163 if (!IsCompAssign) 1164 LHS = (*doLHSCast)(S, LHS.get(), result); 1165 return result; 1166 } 1167 } 1168 1169 /// \brief Handle conversions with GCC complex int extension. Helper function 1170 /// of UsualArithmeticConversions() 1171 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1172 ExprResult &RHS, QualType LHSType, 1173 QualType RHSType, 1174 bool IsCompAssign) { 1175 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1176 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1177 1178 if (LHSComplexInt && RHSComplexInt) { 1179 QualType LHSEltType = LHSComplexInt->getElementType(); 1180 QualType RHSEltType = RHSComplexInt->getElementType(); 1181 QualType ScalarType = 1182 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1183 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1184 1185 return S.Context.getComplexType(ScalarType); 1186 } 1187 1188 if (LHSComplexInt) { 1189 QualType LHSEltType = LHSComplexInt->getElementType(); 1190 QualType ScalarType = 1191 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1192 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1193 QualType ComplexType = S.Context.getComplexType(ScalarType); 1194 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1195 CK_IntegralRealToComplex); 1196 1197 return ComplexType; 1198 } 1199 1200 assert(RHSComplexInt); 1201 1202 QualType RHSEltType = RHSComplexInt->getElementType(); 1203 QualType ScalarType = 1204 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1205 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1206 QualType ComplexType = S.Context.getComplexType(ScalarType); 1207 1208 if (!IsCompAssign) 1209 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1210 CK_IntegralRealToComplex); 1211 return ComplexType; 1212 } 1213 1214 /// UsualArithmeticConversions - Performs various conversions that are common to 1215 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1216 /// routine returns the first non-arithmetic type found. The client is 1217 /// responsible for emitting appropriate error diagnostics. 1218 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1219 bool IsCompAssign) { 1220 if (!IsCompAssign) { 1221 LHS = UsualUnaryConversions(LHS.get()); 1222 if (LHS.isInvalid()) 1223 return QualType(); 1224 } 1225 1226 RHS = UsualUnaryConversions(RHS.get()); 1227 if (RHS.isInvalid()) 1228 return QualType(); 1229 1230 // For conversion purposes, we ignore any qualifiers. 1231 // For example, "const float" and "float" are equivalent. 1232 QualType LHSType = 1233 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1234 QualType RHSType = 1235 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1236 1237 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1238 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1239 LHSType = AtomicLHS->getValueType(); 1240 1241 // If both types are identical, no conversion is needed. 1242 if (LHSType == RHSType) 1243 return LHSType; 1244 1245 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1246 // The caller can deal with this (e.g. pointer + int). 1247 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1248 return QualType(); 1249 1250 // Apply unary and bitfield promotions to the LHS's type. 1251 QualType LHSUnpromotedType = LHSType; 1252 if (LHSType->isPromotableIntegerType()) 1253 LHSType = Context.getPromotedIntegerType(LHSType); 1254 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1255 if (!LHSBitfieldPromoteTy.isNull()) 1256 LHSType = LHSBitfieldPromoteTy; 1257 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1258 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1259 1260 // If both types are identical, no conversion is needed. 1261 if (LHSType == RHSType) 1262 return LHSType; 1263 1264 // At this point, we have two different arithmetic types. 1265 1266 // Diagnose attempts to convert between __float128 and long double where 1267 // such conversions currently can't be handled. 1268 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1269 return QualType(); 1270 1271 // Handle complex types first (C99 6.3.1.8p1). 1272 if (LHSType->isComplexType() || RHSType->isComplexType()) 1273 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1274 IsCompAssign); 1275 1276 // Now handle "real" floating types (i.e. float, double, long double). 1277 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1278 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1279 IsCompAssign); 1280 1281 // Handle GCC complex int extension. 1282 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1283 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1284 IsCompAssign); 1285 1286 // Finally, we have two differing integer types. 1287 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1288 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1289 } 1290 1291 1292 //===----------------------------------------------------------------------===// 1293 // Semantic Analysis for various Expression Types 1294 //===----------------------------------------------------------------------===// 1295 1296 1297 ExprResult 1298 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1299 SourceLocation DefaultLoc, 1300 SourceLocation RParenLoc, 1301 Expr *ControllingExpr, 1302 ArrayRef<ParsedType> ArgTypes, 1303 ArrayRef<Expr *> ArgExprs) { 1304 unsigned NumAssocs = ArgTypes.size(); 1305 assert(NumAssocs == ArgExprs.size()); 1306 1307 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1308 for (unsigned i = 0; i < NumAssocs; ++i) { 1309 if (ArgTypes[i]) 1310 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1311 else 1312 Types[i] = nullptr; 1313 } 1314 1315 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1316 ControllingExpr, 1317 llvm::makeArrayRef(Types, NumAssocs), 1318 ArgExprs); 1319 delete [] Types; 1320 return ER; 1321 } 1322 1323 ExprResult 1324 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1325 SourceLocation DefaultLoc, 1326 SourceLocation RParenLoc, 1327 Expr *ControllingExpr, 1328 ArrayRef<TypeSourceInfo *> Types, 1329 ArrayRef<Expr *> Exprs) { 1330 unsigned NumAssocs = Types.size(); 1331 assert(NumAssocs == Exprs.size()); 1332 1333 // Decay and strip qualifiers for the controlling expression type, and handle 1334 // placeholder type replacement. See committee discussion from WG14 DR423. 1335 { 1336 EnterExpressionEvaluationContext Unevaluated( 1337 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1338 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1339 if (R.isInvalid()) 1340 return ExprError(); 1341 ControllingExpr = R.get(); 1342 } 1343 1344 // The controlling expression is an unevaluated operand, so side effects are 1345 // likely unintended. 1346 if (!inTemplateInstantiation() && 1347 ControllingExpr->HasSideEffects(Context, false)) 1348 Diag(ControllingExpr->getExprLoc(), 1349 diag::warn_side_effects_unevaluated_context); 1350 1351 bool TypeErrorFound = false, 1352 IsResultDependent = ControllingExpr->isTypeDependent(), 1353 ContainsUnexpandedParameterPack 1354 = ControllingExpr->containsUnexpandedParameterPack(); 1355 1356 for (unsigned i = 0; i < NumAssocs; ++i) { 1357 if (Exprs[i]->containsUnexpandedParameterPack()) 1358 ContainsUnexpandedParameterPack = true; 1359 1360 if (Types[i]) { 1361 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1362 ContainsUnexpandedParameterPack = true; 1363 1364 if (Types[i]->getType()->isDependentType()) { 1365 IsResultDependent = true; 1366 } else { 1367 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1368 // complete object type other than a variably modified type." 1369 unsigned D = 0; 1370 if (Types[i]->getType()->isIncompleteType()) 1371 D = diag::err_assoc_type_incomplete; 1372 else if (!Types[i]->getType()->isObjectType()) 1373 D = diag::err_assoc_type_nonobject; 1374 else if (Types[i]->getType()->isVariablyModifiedType()) 1375 D = diag::err_assoc_type_variably_modified; 1376 1377 if (D != 0) { 1378 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1379 << Types[i]->getTypeLoc().getSourceRange() 1380 << Types[i]->getType(); 1381 TypeErrorFound = true; 1382 } 1383 1384 // C11 6.5.1.1p2 "No two generic associations in the same generic 1385 // selection shall specify compatible types." 1386 for (unsigned j = i+1; j < NumAssocs; ++j) 1387 if (Types[j] && !Types[j]->getType()->isDependentType() && 1388 Context.typesAreCompatible(Types[i]->getType(), 1389 Types[j]->getType())) { 1390 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1391 diag::err_assoc_compatible_types) 1392 << Types[j]->getTypeLoc().getSourceRange() 1393 << Types[j]->getType() 1394 << Types[i]->getType(); 1395 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1396 diag::note_compat_assoc) 1397 << Types[i]->getTypeLoc().getSourceRange() 1398 << Types[i]->getType(); 1399 TypeErrorFound = true; 1400 } 1401 } 1402 } 1403 } 1404 if (TypeErrorFound) 1405 return ExprError(); 1406 1407 // If we determined that the generic selection is result-dependent, don't 1408 // try to compute the result expression. 1409 if (IsResultDependent) 1410 return new (Context) GenericSelectionExpr( 1411 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1412 ContainsUnexpandedParameterPack); 1413 1414 SmallVector<unsigned, 1> CompatIndices; 1415 unsigned DefaultIndex = -1U; 1416 for (unsigned i = 0; i < NumAssocs; ++i) { 1417 if (!Types[i]) 1418 DefaultIndex = i; 1419 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1420 Types[i]->getType())) 1421 CompatIndices.push_back(i); 1422 } 1423 1424 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1425 // type compatible with at most one of the types named in its generic 1426 // association list." 1427 if (CompatIndices.size() > 1) { 1428 // We strip parens here because the controlling expression is typically 1429 // parenthesized in macro definitions. 1430 ControllingExpr = ControllingExpr->IgnoreParens(); 1431 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1432 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1433 << (unsigned) CompatIndices.size(); 1434 for (unsigned I : CompatIndices) { 1435 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1436 diag::note_compat_assoc) 1437 << Types[I]->getTypeLoc().getSourceRange() 1438 << Types[I]->getType(); 1439 } 1440 return ExprError(); 1441 } 1442 1443 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1444 // its controlling expression shall have type compatible with exactly one of 1445 // the types named in its generic association list." 1446 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1447 // We strip parens here because the controlling expression is typically 1448 // parenthesized in macro definitions. 1449 ControllingExpr = ControllingExpr->IgnoreParens(); 1450 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1451 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1452 return ExprError(); 1453 } 1454 1455 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1456 // type name that is compatible with the type of the controlling expression, 1457 // then the result expression of the generic selection is the expression 1458 // in that generic association. Otherwise, the result expression of the 1459 // generic selection is the expression in the default generic association." 1460 unsigned ResultIndex = 1461 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1462 1463 return new (Context) GenericSelectionExpr( 1464 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1465 ContainsUnexpandedParameterPack, ResultIndex); 1466 } 1467 1468 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1469 /// location of the token and the offset of the ud-suffix within it. 1470 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1471 unsigned Offset) { 1472 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1473 S.getLangOpts()); 1474 } 1475 1476 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1477 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1478 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1479 IdentifierInfo *UDSuffix, 1480 SourceLocation UDSuffixLoc, 1481 ArrayRef<Expr*> Args, 1482 SourceLocation LitEndLoc) { 1483 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1484 1485 QualType ArgTy[2]; 1486 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1487 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1488 if (ArgTy[ArgIdx]->isArrayType()) 1489 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1490 } 1491 1492 DeclarationName OpName = 1493 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1494 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1495 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1496 1497 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1498 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1499 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1500 /*AllowStringTemplate*/ false, 1501 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1502 return ExprError(); 1503 1504 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1505 } 1506 1507 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1508 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1509 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1510 /// multiple tokens. However, the common case is that StringToks points to one 1511 /// string. 1512 /// 1513 ExprResult 1514 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1515 assert(!StringToks.empty() && "Must have at least one string!"); 1516 1517 StringLiteralParser Literal(StringToks, PP); 1518 if (Literal.hadError) 1519 return ExprError(); 1520 1521 SmallVector<SourceLocation, 4> StringTokLocs; 1522 for (const Token &Tok : StringToks) 1523 StringTokLocs.push_back(Tok.getLocation()); 1524 1525 QualType CharTy = Context.CharTy; 1526 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1527 if (Literal.isWide()) { 1528 CharTy = Context.getWideCharType(); 1529 Kind = StringLiteral::Wide; 1530 } else if (Literal.isUTF8()) { 1531 Kind = StringLiteral::UTF8; 1532 } else if (Literal.isUTF16()) { 1533 CharTy = Context.Char16Ty; 1534 Kind = StringLiteral::UTF16; 1535 } else if (Literal.isUTF32()) { 1536 CharTy = Context.Char32Ty; 1537 Kind = StringLiteral::UTF32; 1538 } else if (Literal.isPascal()) { 1539 CharTy = Context.UnsignedCharTy; 1540 } 1541 1542 QualType CharTyConst = CharTy; 1543 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1544 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1545 CharTyConst.addConst(); 1546 1547 // Get an array type for the string, according to C99 6.4.5. This includes 1548 // the nul terminator character as well as the string length for pascal 1549 // strings. 1550 QualType StrTy = Context.getConstantArrayType(CharTyConst, 1551 llvm::APInt(32, Literal.GetNumStringChars()+1), 1552 ArrayType::Normal, 0); 1553 1554 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 1555 if (getLangOpts().OpenCL) { 1556 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant); 1557 } 1558 1559 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1560 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1561 Kind, Literal.Pascal, StrTy, 1562 &StringTokLocs[0], 1563 StringTokLocs.size()); 1564 if (Literal.getUDSuffix().empty()) 1565 return Lit; 1566 1567 // We're building a user-defined literal. 1568 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1569 SourceLocation UDSuffixLoc = 1570 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1571 Literal.getUDSuffixOffset()); 1572 1573 // Make sure we're allowed user-defined literals here. 1574 if (!UDLScope) 1575 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1576 1577 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1578 // operator "" X (str, len) 1579 QualType SizeType = Context.getSizeType(); 1580 1581 DeclarationName OpName = 1582 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1583 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1584 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1585 1586 QualType ArgTy[] = { 1587 Context.getArrayDecayedType(StrTy), SizeType 1588 }; 1589 1590 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1591 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1592 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1593 /*AllowStringTemplate*/ true, 1594 /*DiagnoseMissing*/ true)) { 1595 1596 case LOLR_Cooked: { 1597 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1598 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1599 StringTokLocs[0]); 1600 Expr *Args[] = { Lit, LenArg }; 1601 1602 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1603 } 1604 1605 case LOLR_StringTemplate: { 1606 TemplateArgumentListInfo ExplicitArgs; 1607 1608 unsigned CharBits = Context.getIntWidth(CharTy); 1609 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1610 llvm::APSInt Value(CharBits, CharIsUnsigned); 1611 1612 TemplateArgument TypeArg(CharTy); 1613 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1614 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1615 1616 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1617 Value = Lit->getCodeUnit(I); 1618 TemplateArgument Arg(Context, Value, CharTy); 1619 TemplateArgumentLocInfo ArgInfo; 1620 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1621 } 1622 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1623 &ExplicitArgs); 1624 } 1625 case LOLR_Raw: 1626 case LOLR_Template: 1627 case LOLR_ErrorNoDiagnostic: 1628 llvm_unreachable("unexpected literal operator lookup result"); 1629 case LOLR_Error: 1630 return ExprError(); 1631 } 1632 llvm_unreachable("unexpected literal operator lookup result"); 1633 } 1634 1635 ExprResult 1636 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1637 SourceLocation Loc, 1638 const CXXScopeSpec *SS) { 1639 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1640 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1641 } 1642 1643 /// BuildDeclRefExpr - Build an expression that references a 1644 /// declaration that does not require a closure capture. 1645 ExprResult 1646 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1647 const DeclarationNameInfo &NameInfo, 1648 const CXXScopeSpec *SS, NamedDecl *FoundD, 1649 const TemplateArgumentListInfo *TemplateArgs) { 1650 bool RefersToCapturedVariable = 1651 isa<VarDecl>(D) && 1652 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1653 1654 DeclRefExpr *E; 1655 if (isa<VarTemplateSpecializationDecl>(D)) { 1656 VarTemplateSpecializationDecl *VarSpec = 1657 cast<VarTemplateSpecializationDecl>(D); 1658 1659 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1660 : NestedNameSpecifierLoc(), 1661 VarSpec->getTemplateKeywordLoc(), D, 1662 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK, 1663 FoundD, TemplateArgs); 1664 } else { 1665 assert(!TemplateArgs && "No template arguments for non-variable" 1666 " template specialization references"); 1667 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1668 : NestedNameSpecifierLoc(), 1669 SourceLocation(), D, RefersToCapturedVariable, 1670 NameInfo, Ty, VK, FoundD); 1671 } 1672 1673 MarkDeclRefReferenced(E); 1674 1675 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1676 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && 1677 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart())) 1678 recordUseOfEvaluatedWeak(E); 1679 1680 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1681 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 1682 FD = IFD->getAnonField(); 1683 if (FD) { 1684 UnusedPrivateFields.remove(FD); 1685 // Just in case we're building an illegal pointer-to-member. 1686 if (FD->isBitField()) 1687 E->setObjectKind(OK_BitField); 1688 } 1689 1690 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1691 // designates a bit-field. 1692 if (auto *BD = dyn_cast<BindingDecl>(D)) 1693 if (auto *BE = BD->getBinding()) 1694 E->setObjectKind(BE->getObjectKind()); 1695 1696 return E; 1697 } 1698 1699 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1700 /// possibly a list of template arguments. 1701 /// 1702 /// If this produces template arguments, it is permitted to call 1703 /// DecomposeTemplateName. 1704 /// 1705 /// This actually loses a lot of source location information for 1706 /// non-standard name kinds; we should consider preserving that in 1707 /// some way. 1708 void 1709 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1710 TemplateArgumentListInfo &Buffer, 1711 DeclarationNameInfo &NameInfo, 1712 const TemplateArgumentListInfo *&TemplateArgs) { 1713 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1714 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1715 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1716 1717 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1718 Id.TemplateId->NumArgs); 1719 translateTemplateArguments(TemplateArgsPtr, Buffer); 1720 1721 TemplateName TName = Id.TemplateId->Template.get(); 1722 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1723 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1724 TemplateArgs = &Buffer; 1725 } else { 1726 NameInfo = GetNameFromUnqualifiedId(Id); 1727 TemplateArgs = nullptr; 1728 } 1729 } 1730 1731 static void emitEmptyLookupTypoDiagnostic( 1732 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1733 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1734 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1735 DeclContext *Ctx = 1736 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1737 if (!TC) { 1738 // Emit a special diagnostic for failed member lookups. 1739 // FIXME: computing the declaration context might fail here (?) 1740 if (Ctx) 1741 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1742 << SS.getRange(); 1743 else 1744 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1745 return; 1746 } 1747 1748 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1749 bool DroppedSpecifier = 1750 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1751 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1752 ? diag::note_implicit_param_decl 1753 : diag::note_previous_decl; 1754 if (!Ctx) 1755 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1756 SemaRef.PDiag(NoteID)); 1757 else 1758 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1759 << Typo << Ctx << DroppedSpecifier 1760 << SS.getRange(), 1761 SemaRef.PDiag(NoteID)); 1762 } 1763 1764 /// Diagnose an empty lookup. 1765 /// 1766 /// \return false if new lookup candidates were found 1767 bool 1768 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1769 std::unique_ptr<CorrectionCandidateCallback> CCC, 1770 TemplateArgumentListInfo *ExplicitTemplateArgs, 1771 ArrayRef<Expr *> Args, TypoExpr **Out) { 1772 DeclarationName Name = R.getLookupName(); 1773 1774 unsigned diagnostic = diag::err_undeclared_var_use; 1775 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1776 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1777 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1778 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1779 diagnostic = diag::err_undeclared_use; 1780 diagnostic_suggest = diag::err_undeclared_use_suggest; 1781 } 1782 1783 // If the original lookup was an unqualified lookup, fake an 1784 // unqualified lookup. This is useful when (for example) the 1785 // original lookup would not have found something because it was a 1786 // dependent name. 1787 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1788 while (DC) { 1789 if (isa<CXXRecordDecl>(DC)) { 1790 LookupQualifiedName(R, DC); 1791 1792 if (!R.empty()) { 1793 // Don't give errors about ambiguities in this lookup. 1794 R.suppressDiagnostics(); 1795 1796 // During a default argument instantiation the CurContext points 1797 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1798 // function parameter list, hence add an explicit check. 1799 bool isDefaultArgument = 1800 !CodeSynthesisContexts.empty() && 1801 CodeSynthesisContexts.back().Kind == 1802 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 1803 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1804 bool isInstance = CurMethod && 1805 CurMethod->isInstance() && 1806 DC == CurMethod->getParent() && !isDefaultArgument; 1807 1808 // Give a code modification hint to insert 'this->'. 1809 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1810 // Actually quite difficult! 1811 if (getLangOpts().MSVCCompat) 1812 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1813 if (isInstance) { 1814 Diag(R.getNameLoc(), diagnostic) << Name 1815 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1816 CheckCXXThisCapture(R.getNameLoc()); 1817 } else { 1818 Diag(R.getNameLoc(), diagnostic) << Name; 1819 } 1820 1821 // Do we really want to note all of these? 1822 for (NamedDecl *D : R) 1823 Diag(D->getLocation(), diag::note_dependent_var_use); 1824 1825 // Return true if we are inside a default argument instantiation 1826 // and the found name refers to an instance member function, otherwise 1827 // the function calling DiagnoseEmptyLookup will try to create an 1828 // implicit member call and this is wrong for default argument. 1829 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1830 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1831 return true; 1832 } 1833 1834 // Tell the callee to try to recover. 1835 return false; 1836 } 1837 1838 R.clear(); 1839 } 1840 1841 // In Microsoft mode, if we are performing lookup from within a friend 1842 // function definition declared at class scope then we must set 1843 // DC to the lexical parent to be able to search into the parent 1844 // class. 1845 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1846 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1847 DC->getLexicalParent()->isRecord()) 1848 DC = DC->getLexicalParent(); 1849 else 1850 DC = DC->getParent(); 1851 } 1852 1853 // We didn't find anything, so try to correct for a typo. 1854 TypoCorrection Corrected; 1855 if (S && Out) { 1856 SourceLocation TypoLoc = R.getNameLoc(); 1857 assert(!ExplicitTemplateArgs && 1858 "Diagnosing an empty lookup with explicit template args!"); 1859 *Out = CorrectTypoDelayed( 1860 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC), 1861 [=](const TypoCorrection &TC) { 1862 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 1863 diagnostic, diagnostic_suggest); 1864 }, 1865 nullptr, CTK_ErrorRecovery); 1866 if (*Out) 1867 return true; 1868 } else if (S && (Corrected = 1869 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, 1870 &SS, std::move(CCC), CTK_ErrorRecovery))) { 1871 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1872 bool DroppedSpecifier = 1873 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1874 R.setLookupName(Corrected.getCorrection()); 1875 1876 bool AcceptableWithRecovery = false; 1877 bool AcceptableWithoutRecovery = false; 1878 NamedDecl *ND = Corrected.getFoundDecl(); 1879 if (ND) { 1880 if (Corrected.isOverloaded()) { 1881 OverloadCandidateSet OCS(R.getNameLoc(), 1882 OverloadCandidateSet::CSK_Normal); 1883 OverloadCandidateSet::iterator Best; 1884 for (NamedDecl *CD : Corrected) { 1885 if (FunctionTemplateDecl *FTD = 1886 dyn_cast<FunctionTemplateDecl>(CD)) 1887 AddTemplateOverloadCandidate( 1888 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1889 Args, OCS); 1890 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 1891 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1892 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1893 Args, OCS); 1894 } 1895 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1896 case OR_Success: 1897 ND = Best->FoundDecl; 1898 Corrected.setCorrectionDecl(ND); 1899 break; 1900 default: 1901 // FIXME: Arbitrarily pick the first declaration for the note. 1902 Corrected.setCorrectionDecl(ND); 1903 break; 1904 } 1905 } 1906 R.addDecl(ND); 1907 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 1908 CXXRecordDecl *Record = nullptr; 1909 if (Corrected.getCorrectionSpecifier()) { 1910 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 1911 Record = Ty->getAsCXXRecordDecl(); 1912 } 1913 if (!Record) 1914 Record = cast<CXXRecordDecl>( 1915 ND->getDeclContext()->getRedeclContext()); 1916 R.setNamingClass(Record); 1917 } 1918 1919 auto *UnderlyingND = ND->getUnderlyingDecl(); 1920 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 1921 isa<FunctionTemplateDecl>(UnderlyingND); 1922 // FIXME: If we ended up with a typo for a type name or 1923 // Objective-C class name, we're in trouble because the parser 1924 // is in the wrong place to recover. Suggest the typo 1925 // correction, but don't make it a fix-it since we're not going 1926 // to recover well anyway. 1927 AcceptableWithoutRecovery = 1928 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND); 1929 } else { 1930 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1931 // because we aren't able to recover. 1932 AcceptableWithoutRecovery = true; 1933 } 1934 1935 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 1936 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 1937 ? diag::note_implicit_param_decl 1938 : diag::note_previous_decl; 1939 if (SS.isEmpty()) 1940 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 1941 PDiag(NoteID), AcceptableWithRecovery); 1942 else 1943 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 1944 << Name << computeDeclContext(SS, false) 1945 << DroppedSpecifier << SS.getRange(), 1946 PDiag(NoteID), AcceptableWithRecovery); 1947 1948 // Tell the callee whether to try to recover. 1949 return !AcceptableWithRecovery; 1950 } 1951 } 1952 R.clear(); 1953 1954 // Emit a special diagnostic for failed member lookups. 1955 // FIXME: computing the declaration context might fail here (?) 1956 if (!SS.isEmpty()) { 1957 Diag(R.getNameLoc(), diag::err_no_member) 1958 << Name << computeDeclContext(SS, false) 1959 << SS.getRange(); 1960 return true; 1961 } 1962 1963 // Give up, we can't recover. 1964 Diag(R.getNameLoc(), diagnostic) << Name; 1965 return true; 1966 } 1967 1968 /// In Microsoft mode, if we are inside a template class whose parent class has 1969 /// dependent base classes, and we can't resolve an unqualified identifier, then 1970 /// assume the identifier is a member of a dependent base class. We can only 1971 /// recover successfully in static methods, instance methods, and other contexts 1972 /// where 'this' is available. This doesn't precisely match MSVC's 1973 /// instantiation model, but it's close enough. 1974 static Expr * 1975 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 1976 DeclarationNameInfo &NameInfo, 1977 SourceLocation TemplateKWLoc, 1978 const TemplateArgumentListInfo *TemplateArgs) { 1979 // Only try to recover from lookup into dependent bases in static methods or 1980 // contexts where 'this' is available. 1981 QualType ThisType = S.getCurrentThisType(); 1982 const CXXRecordDecl *RD = nullptr; 1983 if (!ThisType.isNull()) 1984 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 1985 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 1986 RD = MD->getParent(); 1987 if (!RD || !RD->hasAnyDependentBases()) 1988 return nullptr; 1989 1990 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 1991 // is available, suggest inserting 'this->' as a fixit. 1992 SourceLocation Loc = NameInfo.getLoc(); 1993 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 1994 DB << NameInfo.getName() << RD; 1995 1996 if (!ThisType.isNull()) { 1997 DB << FixItHint::CreateInsertion(Loc, "this->"); 1998 return CXXDependentScopeMemberExpr::Create( 1999 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2000 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2001 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 2002 } 2003 2004 // Synthesize a fake NNS that points to the derived class. This will 2005 // perform name lookup during template instantiation. 2006 CXXScopeSpec SS; 2007 auto *NNS = 2008 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2009 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2010 return DependentScopeDeclRefExpr::Create( 2011 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2012 TemplateArgs); 2013 } 2014 2015 ExprResult 2016 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2017 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2018 bool HasTrailingLParen, bool IsAddressOfOperand, 2019 std::unique_ptr<CorrectionCandidateCallback> CCC, 2020 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2021 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2022 "cannot be direct & operand and have a trailing lparen"); 2023 if (SS.isInvalid()) 2024 return ExprError(); 2025 2026 TemplateArgumentListInfo TemplateArgsBuffer; 2027 2028 // Decompose the UnqualifiedId into the following data. 2029 DeclarationNameInfo NameInfo; 2030 const TemplateArgumentListInfo *TemplateArgs; 2031 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2032 2033 DeclarationName Name = NameInfo.getName(); 2034 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2035 SourceLocation NameLoc = NameInfo.getLoc(); 2036 2037 if (II && II->isEditorPlaceholder()) { 2038 // FIXME: When typed placeholders are supported we can create a typed 2039 // placeholder expression node. 2040 return ExprError(); 2041 } 2042 2043 // C++ [temp.dep.expr]p3: 2044 // An id-expression is type-dependent if it contains: 2045 // -- an identifier that was declared with a dependent type, 2046 // (note: handled after lookup) 2047 // -- a template-id that is dependent, 2048 // (note: handled in BuildTemplateIdExpr) 2049 // -- a conversion-function-id that specifies a dependent type, 2050 // -- a nested-name-specifier that contains a class-name that 2051 // names a dependent type. 2052 // Determine whether this is a member of an unknown specialization; 2053 // we need to handle these differently. 2054 bool DependentID = false; 2055 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2056 Name.getCXXNameType()->isDependentType()) { 2057 DependentID = true; 2058 } else if (SS.isSet()) { 2059 if (DeclContext *DC = computeDeclContext(SS, false)) { 2060 if (RequireCompleteDeclContext(SS, DC)) 2061 return ExprError(); 2062 } else { 2063 DependentID = true; 2064 } 2065 } 2066 2067 if (DependentID) 2068 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2069 IsAddressOfOperand, TemplateArgs); 2070 2071 // Perform the required lookup. 2072 LookupResult R(*this, NameInfo, 2073 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 2074 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 2075 if (TemplateArgs) { 2076 // Lookup the template name again to correctly establish the context in 2077 // which it was found. This is really unfortunate as we already did the 2078 // lookup to determine that it was a template name in the first place. If 2079 // this becomes a performance hit, we can work harder to preserve those 2080 // results until we get here but it's likely not worth it. 2081 bool MemberOfUnknownSpecialization; 2082 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2083 MemberOfUnknownSpecialization); 2084 2085 if (MemberOfUnknownSpecialization || 2086 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2087 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2088 IsAddressOfOperand, TemplateArgs); 2089 } else { 2090 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2091 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2092 2093 // If the result might be in a dependent base class, this is a dependent 2094 // id-expression. 2095 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2096 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2097 IsAddressOfOperand, TemplateArgs); 2098 2099 // If this reference is in an Objective-C method, then we need to do 2100 // some special Objective-C lookup, too. 2101 if (IvarLookupFollowUp) { 2102 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2103 if (E.isInvalid()) 2104 return ExprError(); 2105 2106 if (Expr *Ex = E.getAs<Expr>()) 2107 return Ex; 2108 } 2109 } 2110 2111 if (R.isAmbiguous()) 2112 return ExprError(); 2113 2114 // This could be an implicitly declared function reference (legal in C90, 2115 // extension in C99, forbidden in C++). 2116 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2117 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2118 if (D) R.addDecl(D); 2119 } 2120 2121 // Determine whether this name might be a candidate for 2122 // argument-dependent lookup. 2123 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2124 2125 if (R.empty() && !ADL) { 2126 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2127 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2128 TemplateKWLoc, TemplateArgs)) 2129 return E; 2130 } 2131 2132 // Don't diagnose an empty lookup for inline assembly. 2133 if (IsInlineAsmIdentifier) 2134 return ExprError(); 2135 2136 // If this name wasn't predeclared and if this is not a function 2137 // call, diagnose the problem. 2138 TypoExpr *TE = nullptr; 2139 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2140 II, SS.isValid() ? SS.getScopeRep() : nullptr); 2141 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; 2142 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2143 "Typo correction callback misconfigured"); 2144 if (CCC) { 2145 // Make sure the callback knows what the typo being diagnosed is. 2146 CCC->setTypoName(II); 2147 if (SS.isValid()) 2148 CCC->setTypoNNS(SS.getScopeRep()); 2149 } 2150 if (DiagnoseEmptyLookup(S, SS, R, 2151 CCC ? std::move(CCC) : std::move(DefaultValidator), 2152 nullptr, None, &TE)) { 2153 if (TE && KeywordReplacement) { 2154 auto &State = getTypoExprState(TE); 2155 auto BestTC = State.Consumer->getNextCorrection(); 2156 if (BestTC.isKeyword()) { 2157 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2158 if (State.DiagHandler) 2159 State.DiagHandler(BestTC); 2160 KeywordReplacement->startToken(); 2161 KeywordReplacement->setKind(II->getTokenID()); 2162 KeywordReplacement->setIdentifierInfo(II); 2163 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2164 // Clean up the state associated with the TypoExpr, since it has 2165 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2166 clearDelayedTypo(TE); 2167 // Signal that a correction to a keyword was performed by returning a 2168 // valid-but-null ExprResult. 2169 return (Expr*)nullptr; 2170 } 2171 State.Consumer->resetCorrectionStream(); 2172 } 2173 return TE ? TE : ExprError(); 2174 } 2175 2176 assert(!R.empty() && 2177 "DiagnoseEmptyLookup returned false but added no results"); 2178 2179 // If we found an Objective-C instance variable, let 2180 // LookupInObjCMethod build the appropriate expression to 2181 // reference the ivar. 2182 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2183 R.clear(); 2184 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2185 // In a hopelessly buggy code, Objective-C instance variable 2186 // lookup fails and no expression will be built to reference it. 2187 if (!E.isInvalid() && !E.get()) 2188 return ExprError(); 2189 return E; 2190 } 2191 } 2192 2193 // This is guaranteed from this point on. 2194 assert(!R.empty() || ADL); 2195 2196 // Check whether this might be a C++ implicit instance member access. 2197 // C++ [class.mfct.non-static]p3: 2198 // When an id-expression that is not part of a class member access 2199 // syntax and not used to form a pointer to member is used in the 2200 // body of a non-static member function of class X, if name lookup 2201 // resolves the name in the id-expression to a non-static non-type 2202 // member of some class C, the id-expression is transformed into a 2203 // class member access expression using (*this) as the 2204 // postfix-expression to the left of the . operator. 2205 // 2206 // But we don't actually need to do this for '&' operands if R 2207 // resolved to a function or overloaded function set, because the 2208 // expression is ill-formed if it actually works out to be a 2209 // non-static member function: 2210 // 2211 // C++ [expr.ref]p4: 2212 // Otherwise, if E1.E2 refers to a non-static member function. . . 2213 // [t]he expression can be used only as the left-hand operand of a 2214 // member function call. 2215 // 2216 // There are other safeguards against such uses, but it's important 2217 // to get this right here so that we don't end up making a 2218 // spuriously dependent expression if we're inside a dependent 2219 // instance method. 2220 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2221 bool MightBeImplicitMember; 2222 if (!IsAddressOfOperand) 2223 MightBeImplicitMember = true; 2224 else if (!SS.isEmpty()) 2225 MightBeImplicitMember = false; 2226 else if (R.isOverloadedResult()) 2227 MightBeImplicitMember = false; 2228 else if (R.isUnresolvableResult()) 2229 MightBeImplicitMember = true; 2230 else 2231 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2232 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2233 isa<MSPropertyDecl>(R.getFoundDecl()); 2234 2235 if (MightBeImplicitMember) 2236 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2237 R, TemplateArgs, S); 2238 } 2239 2240 if (TemplateArgs || TemplateKWLoc.isValid()) { 2241 2242 // In C++1y, if this is a variable template id, then check it 2243 // in BuildTemplateIdExpr(). 2244 // The single lookup result must be a variable template declaration. 2245 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId && 2246 Id.TemplateId->Kind == TNK_Var_template) { 2247 assert(R.getAsSingle<VarTemplateDecl>() && 2248 "There should only be one declaration found."); 2249 } 2250 2251 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2252 } 2253 2254 return BuildDeclarationNameExpr(SS, R, ADL); 2255 } 2256 2257 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2258 /// declaration name, generally during template instantiation. 2259 /// There's a large number of things which don't need to be done along 2260 /// this path. 2261 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2262 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2263 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2264 DeclContext *DC = computeDeclContext(SS, false); 2265 if (!DC) 2266 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2267 NameInfo, /*TemplateArgs=*/nullptr); 2268 2269 if (RequireCompleteDeclContext(SS, DC)) 2270 return ExprError(); 2271 2272 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2273 LookupQualifiedName(R, DC); 2274 2275 if (R.isAmbiguous()) 2276 return ExprError(); 2277 2278 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2279 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2280 NameInfo, /*TemplateArgs=*/nullptr); 2281 2282 if (R.empty()) { 2283 Diag(NameInfo.getLoc(), diag::err_no_member) 2284 << NameInfo.getName() << DC << SS.getRange(); 2285 return ExprError(); 2286 } 2287 2288 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2289 // Diagnose a missing typename if this resolved unambiguously to a type in 2290 // a dependent context. If we can recover with a type, downgrade this to 2291 // a warning in Microsoft compatibility mode. 2292 unsigned DiagID = diag::err_typename_missing; 2293 if (RecoveryTSI && getLangOpts().MSVCCompat) 2294 DiagID = diag::ext_typename_missing; 2295 SourceLocation Loc = SS.getBeginLoc(); 2296 auto D = Diag(Loc, DiagID); 2297 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2298 << SourceRange(Loc, NameInfo.getEndLoc()); 2299 2300 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2301 // context. 2302 if (!RecoveryTSI) 2303 return ExprError(); 2304 2305 // Only issue the fixit if we're prepared to recover. 2306 D << FixItHint::CreateInsertion(Loc, "typename "); 2307 2308 // Recover by pretending this was an elaborated type. 2309 QualType Ty = Context.getTypeDeclType(TD); 2310 TypeLocBuilder TLB; 2311 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2312 2313 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2314 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2315 QTL.setElaboratedKeywordLoc(SourceLocation()); 2316 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2317 2318 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2319 2320 return ExprEmpty(); 2321 } 2322 2323 // Defend against this resolving to an implicit member access. We usually 2324 // won't get here if this might be a legitimate a class member (we end up in 2325 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2326 // a pointer-to-member or in an unevaluated context in C++11. 2327 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2328 return BuildPossibleImplicitMemberExpr(SS, 2329 /*TemplateKWLoc=*/SourceLocation(), 2330 R, /*TemplateArgs=*/nullptr, S); 2331 2332 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2333 } 2334 2335 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2336 /// detected that we're currently inside an ObjC method. Perform some 2337 /// additional lookup. 2338 /// 2339 /// Ideally, most of this would be done by lookup, but there's 2340 /// actually quite a lot of extra work involved. 2341 /// 2342 /// Returns a null sentinel to indicate trivial success. 2343 ExprResult 2344 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2345 IdentifierInfo *II, bool AllowBuiltinCreation) { 2346 SourceLocation Loc = Lookup.getNameLoc(); 2347 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2348 2349 // Check for error condition which is already reported. 2350 if (!CurMethod) 2351 return ExprError(); 2352 2353 // There are two cases to handle here. 1) scoped lookup could have failed, 2354 // in which case we should look for an ivar. 2) scoped lookup could have 2355 // found a decl, but that decl is outside the current instance method (i.e. 2356 // a global variable). In these two cases, we do a lookup for an ivar with 2357 // this name, if the lookup sucedes, we replace it our current decl. 2358 2359 // If we're in a class method, we don't normally want to look for 2360 // ivars. But if we don't find anything else, and there's an 2361 // ivar, that's an error. 2362 bool IsClassMethod = CurMethod->isClassMethod(); 2363 2364 bool LookForIvars; 2365 if (Lookup.empty()) 2366 LookForIvars = true; 2367 else if (IsClassMethod) 2368 LookForIvars = false; 2369 else 2370 LookForIvars = (Lookup.isSingleResult() && 2371 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2372 ObjCInterfaceDecl *IFace = nullptr; 2373 if (LookForIvars) { 2374 IFace = CurMethod->getClassInterface(); 2375 ObjCInterfaceDecl *ClassDeclared; 2376 ObjCIvarDecl *IV = nullptr; 2377 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2378 // Diagnose using an ivar in a class method. 2379 if (IsClassMethod) 2380 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2381 << IV->getDeclName()); 2382 2383 // If we're referencing an invalid decl, just return this as a silent 2384 // error node. The error diagnostic was already emitted on the decl. 2385 if (IV->isInvalidDecl()) 2386 return ExprError(); 2387 2388 // Check if referencing a field with __attribute__((deprecated)). 2389 if (DiagnoseUseOfDecl(IV, Loc)) 2390 return ExprError(); 2391 2392 // Diagnose the use of an ivar outside of the declaring class. 2393 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2394 !declaresSameEntity(ClassDeclared, IFace) && 2395 !getLangOpts().DebuggerSupport) 2396 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2397 2398 // FIXME: This should use a new expr for a direct reference, don't 2399 // turn this into Self->ivar, just return a BareIVarExpr or something. 2400 IdentifierInfo &II = Context.Idents.get("self"); 2401 UnqualifiedId SelfName; 2402 SelfName.setIdentifier(&II, SourceLocation()); 2403 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2404 CXXScopeSpec SelfScopeSpec; 2405 SourceLocation TemplateKWLoc; 2406 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2407 SelfName, false, false); 2408 if (SelfExpr.isInvalid()) 2409 return ExprError(); 2410 2411 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2412 if (SelfExpr.isInvalid()) 2413 return ExprError(); 2414 2415 MarkAnyDeclReferenced(Loc, IV, true); 2416 2417 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2418 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2419 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2420 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2421 2422 ObjCIvarRefExpr *Result = new (Context) 2423 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2424 IV->getLocation(), SelfExpr.get(), true, true); 2425 2426 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2427 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2428 recordUseOfEvaluatedWeak(Result); 2429 } 2430 if (getLangOpts().ObjCAutoRefCount) { 2431 if (CurContext->isClosure()) 2432 Diag(Loc, diag::warn_implicitly_retains_self) 2433 << FixItHint::CreateInsertion(Loc, "self->"); 2434 } 2435 2436 return Result; 2437 } 2438 } else if (CurMethod->isInstanceMethod()) { 2439 // We should warn if a local variable hides an ivar. 2440 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2441 ObjCInterfaceDecl *ClassDeclared; 2442 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2443 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2444 declaresSameEntity(IFace, ClassDeclared)) 2445 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2446 } 2447 } 2448 } else if (Lookup.isSingleResult() && 2449 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2450 // If accessing a stand-alone ivar in a class method, this is an error. 2451 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2452 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2453 << IV->getDeclName()); 2454 } 2455 2456 if (Lookup.empty() && II && AllowBuiltinCreation) { 2457 // FIXME. Consolidate this with similar code in LookupName. 2458 if (unsigned BuiltinID = II->getBuiltinID()) { 2459 if (!(getLangOpts().CPlusPlus && 2460 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2461 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2462 S, Lookup.isForRedeclaration(), 2463 Lookup.getNameLoc()); 2464 if (D) Lookup.addDecl(D); 2465 } 2466 } 2467 } 2468 // Sentinel value saying that we didn't do anything special. 2469 return ExprResult((Expr *)nullptr); 2470 } 2471 2472 /// \brief Cast a base object to a member's actual type. 2473 /// 2474 /// Logically this happens in three phases: 2475 /// 2476 /// * First we cast from the base type to the naming class. 2477 /// The naming class is the class into which we were looking 2478 /// when we found the member; it's the qualifier type if a 2479 /// qualifier was provided, and otherwise it's the base type. 2480 /// 2481 /// * Next we cast from the naming class to the declaring class. 2482 /// If the member we found was brought into a class's scope by 2483 /// a using declaration, this is that class; otherwise it's 2484 /// the class declaring the member. 2485 /// 2486 /// * Finally we cast from the declaring class to the "true" 2487 /// declaring class of the member. This conversion does not 2488 /// obey access control. 2489 ExprResult 2490 Sema::PerformObjectMemberConversion(Expr *From, 2491 NestedNameSpecifier *Qualifier, 2492 NamedDecl *FoundDecl, 2493 NamedDecl *Member) { 2494 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2495 if (!RD) 2496 return From; 2497 2498 QualType DestRecordType; 2499 QualType DestType; 2500 QualType FromRecordType; 2501 QualType FromType = From->getType(); 2502 bool PointerConversions = false; 2503 if (isa<FieldDecl>(Member)) { 2504 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2505 2506 if (FromType->getAs<PointerType>()) { 2507 DestType = Context.getPointerType(DestRecordType); 2508 FromRecordType = FromType->getPointeeType(); 2509 PointerConversions = true; 2510 } else { 2511 DestType = DestRecordType; 2512 FromRecordType = FromType; 2513 } 2514 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2515 if (Method->isStatic()) 2516 return From; 2517 2518 DestType = Method->getThisType(Context); 2519 DestRecordType = DestType->getPointeeType(); 2520 2521 if (FromType->getAs<PointerType>()) { 2522 FromRecordType = FromType->getPointeeType(); 2523 PointerConversions = true; 2524 } else { 2525 FromRecordType = FromType; 2526 DestType = DestRecordType; 2527 } 2528 } else { 2529 // No conversion necessary. 2530 return From; 2531 } 2532 2533 if (DestType->isDependentType() || FromType->isDependentType()) 2534 return From; 2535 2536 // If the unqualified types are the same, no conversion is necessary. 2537 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2538 return From; 2539 2540 SourceRange FromRange = From->getSourceRange(); 2541 SourceLocation FromLoc = FromRange.getBegin(); 2542 2543 ExprValueKind VK = From->getValueKind(); 2544 2545 // C++ [class.member.lookup]p8: 2546 // [...] Ambiguities can often be resolved by qualifying a name with its 2547 // class name. 2548 // 2549 // If the member was a qualified name and the qualified referred to a 2550 // specific base subobject type, we'll cast to that intermediate type 2551 // first and then to the object in which the member is declared. That allows 2552 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2553 // 2554 // class Base { public: int x; }; 2555 // class Derived1 : public Base { }; 2556 // class Derived2 : public Base { }; 2557 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2558 // 2559 // void VeryDerived::f() { 2560 // x = 17; // error: ambiguous base subobjects 2561 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2562 // } 2563 if (Qualifier && Qualifier->getAsType()) { 2564 QualType QType = QualType(Qualifier->getAsType(), 0); 2565 assert(QType->isRecordType() && "lookup done with non-record type"); 2566 2567 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2568 2569 // In C++98, the qualifier type doesn't actually have to be a base 2570 // type of the object type, in which case we just ignore it. 2571 // Otherwise build the appropriate casts. 2572 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2573 CXXCastPath BasePath; 2574 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2575 FromLoc, FromRange, &BasePath)) 2576 return ExprError(); 2577 2578 if (PointerConversions) 2579 QType = Context.getPointerType(QType); 2580 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2581 VK, &BasePath).get(); 2582 2583 FromType = QType; 2584 FromRecordType = QRecordType; 2585 2586 // If the qualifier type was the same as the destination type, 2587 // we're done. 2588 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2589 return From; 2590 } 2591 } 2592 2593 bool IgnoreAccess = false; 2594 2595 // If we actually found the member through a using declaration, cast 2596 // down to the using declaration's type. 2597 // 2598 // Pointer equality is fine here because only one declaration of a 2599 // class ever has member declarations. 2600 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2601 assert(isa<UsingShadowDecl>(FoundDecl)); 2602 QualType URecordType = Context.getTypeDeclType( 2603 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2604 2605 // We only need to do this if the naming-class to declaring-class 2606 // conversion is non-trivial. 2607 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2608 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2609 CXXCastPath BasePath; 2610 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2611 FromLoc, FromRange, &BasePath)) 2612 return ExprError(); 2613 2614 QualType UType = URecordType; 2615 if (PointerConversions) 2616 UType = Context.getPointerType(UType); 2617 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2618 VK, &BasePath).get(); 2619 FromType = UType; 2620 FromRecordType = URecordType; 2621 } 2622 2623 // We don't do access control for the conversion from the 2624 // declaring class to the true declaring class. 2625 IgnoreAccess = true; 2626 } 2627 2628 CXXCastPath BasePath; 2629 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2630 FromLoc, FromRange, &BasePath, 2631 IgnoreAccess)) 2632 return ExprError(); 2633 2634 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2635 VK, &BasePath); 2636 } 2637 2638 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2639 const LookupResult &R, 2640 bool HasTrailingLParen) { 2641 // Only when used directly as the postfix-expression of a call. 2642 if (!HasTrailingLParen) 2643 return false; 2644 2645 // Never if a scope specifier was provided. 2646 if (SS.isSet()) 2647 return false; 2648 2649 // Only in C++ or ObjC++. 2650 if (!getLangOpts().CPlusPlus) 2651 return false; 2652 2653 // Turn off ADL when we find certain kinds of declarations during 2654 // normal lookup: 2655 for (NamedDecl *D : R) { 2656 // C++0x [basic.lookup.argdep]p3: 2657 // -- a declaration of a class member 2658 // Since using decls preserve this property, we check this on the 2659 // original decl. 2660 if (D->isCXXClassMember()) 2661 return false; 2662 2663 // C++0x [basic.lookup.argdep]p3: 2664 // -- a block-scope function declaration that is not a 2665 // using-declaration 2666 // NOTE: we also trigger this for function templates (in fact, we 2667 // don't check the decl type at all, since all other decl types 2668 // turn off ADL anyway). 2669 if (isa<UsingShadowDecl>(D)) 2670 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2671 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2672 return false; 2673 2674 // C++0x [basic.lookup.argdep]p3: 2675 // -- a declaration that is neither a function or a function 2676 // template 2677 // And also for builtin functions. 2678 if (isa<FunctionDecl>(D)) { 2679 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2680 2681 // But also builtin functions. 2682 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2683 return false; 2684 } else if (!isa<FunctionTemplateDecl>(D)) 2685 return false; 2686 } 2687 2688 return true; 2689 } 2690 2691 2692 /// Diagnoses obvious problems with the use of the given declaration 2693 /// as an expression. This is only actually called for lookups that 2694 /// were not overloaded, and it doesn't promise that the declaration 2695 /// will in fact be used. 2696 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2697 if (D->isInvalidDecl()) 2698 return true; 2699 2700 if (isa<TypedefNameDecl>(D)) { 2701 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2702 return true; 2703 } 2704 2705 if (isa<ObjCInterfaceDecl>(D)) { 2706 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2707 return true; 2708 } 2709 2710 if (isa<NamespaceDecl>(D)) { 2711 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2712 return true; 2713 } 2714 2715 return false; 2716 } 2717 2718 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2719 LookupResult &R, bool NeedsADL, 2720 bool AcceptInvalidDecl) { 2721 // If this is a single, fully-resolved result and we don't need ADL, 2722 // just build an ordinary singleton decl ref. 2723 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2724 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2725 R.getRepresentativeDecl(), nullptr, 2726 AcceptInvalidDecl); 2727 2728 // We only need to check the declaration if there's exactly one 2729 // result, because in the overloaded case the results can only be 2730 // functions and function templates. 2731 if (R.isSingleResult() && 2732 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2733 return ExprError(); 2734 2735 // Otherwise, just build an unresolved lookup expression. Suppress 2736 // any lookup-related diagnostics; we'll hash these out later, when 2737 // we've picked a target. 2738 R.suppressDiagnostics(); 2739 2740 UnresolvedLookupExpr *ULE 2741 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2742 SS.getWithLocInContext(Context), 2743 R.getLookupNameInfo(), 2744 NeedsADL, R.isOverloadedResult(), 2745 R.begin(), R.end()); 2746 2747 return ULE; 2748 } 2749 2750 static void 2751 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 2752 ValueDecl *var, DeclContext *DC); 2753 2754 /// \brief Complete semantic analysis for a reference to the given declaration. 2755 ExprResult Sema::BuildDeclarationNameExpr( 2756 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2757 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2758 bool AcceptInvalidDecl) { 2759 assert(D && "Cannot refer to a NULL declaration"); 2760 assert(!isa<FunctionTemplateDecl>(D) && 2761 "Cannot refer unambiguously to a function template"); 2762 2763 SourceLocation Loc = NameInfo.getLoc(); 2764 if (CheckDeclInExpr(*this, Loc, D)) 2765 return ExprError(); 2766 2767 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2768 // Specifically diagnose references to class templates that are missing 2769 // a template argument list. 2770 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2771 << Template << SS.getRange(); 2772 Diag(Template->getLocation(), diag::note_template_decl_here); 2773 return ExprError(); 2774 } 2775 2776 // Make sure that we're referring to a value. 2777 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2778 if (!VD) { 2779 Diag(Loc, diag::err_ref_non_value) 2780 << D << SS.getRange(); 2781 Diag(D->getLocation(), diag::note_declared_at); 2782 return ExprError(); 2783 } 2784 2785 // Check whether this declaration can be used. Note that we suppress 2786 // this check when we're going to perform argument-dependent lookup 2787 // on this function name, because this might not be the function 2788 // that overload resolution actually selects. 2789 if (DiagnoseUseOfDecl(VD, Loc)) 2790 return ExprError(); 2791 2792 // Only create DeclRefExpr's for valid Decl's. 2793 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2794 return ExprError(); 2795 2796 // Handle members of anonymous structs and unions. If we got here, 2797 // and the reference is to a class member indirect field, then this 2798 // must be the subject of a pointer-to-member expression. 2799 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2800 if (!indirectField->isCXXClassMember()) 2801 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2802 indirectField); 2803 2804 { 2805 QualType type = VD->getType(); 2806 if (auto *FPT = type->getAs<FunctionProtoType>()) { 2807 // C++ [except.spec]p17: 2808 // An exception-specification is considered to be needed when: 2809 // - in an expression, the function is the unique lookup result or 2810 // the selected member of a set of overloaded functions. 2811 ResolveExceptionSpec(Loc, FPT); 2812 type = VD->getType(); 2813 } 2814 ExprValueKind valueKind = VK_RValue; 2815 2816 switch (D->getKind()) { 2817 // Ignore all the non-ValueDecl kinds. 2818 #define ABSTRACT_DECL(kind) 2819 #define VALUE(type, base) 2820 #define DECL(type, base) \ 2821 case Decl::type: 2822 #include "clang/AST/DeclNodes.inc" 2823 llvm_unreachable("invalid value decl kind"); 2824 2825 // These shouldn't make it here. 2826 case Decl::ObjCAtDefsField: 2827 case Decl::ObjCIvar: 2828 llvm_unreachable("forming non-member reference to ivar?"); 2829 2830 // Enum constants are always r-values and never references. 2831 // Unresolved using declarations are dependent. 2832 case Decl::EnumConstant: 2833 case Decl::UnresolvedUsingValue: 2834 case Decl::OMPDeclareReduction: 2835 valueKind = VK_RValue; 2836 break; 2837 2838 // Fields and indirect fields that got here must be for 2839 // pointer-to-member expressions; we just call them l-values for 2840 // internal consistency, because this subexpression doesn't really 2841 // exist in the high-level semantics. 2842 case Decl::Field: 2843 case Decl::IndirectField: 2844 assert(getLangOpts().CPlusPlus && 2845 "building reference to field in C?"); 2846 2847 // These can't have reference type in well-formed programs, but 2848 // for internal consistency we do this anyway. 2849 type = type.getNonReferenceType(); 2850 valueKind = VK_LValue; 2851 break; 2852 2853 // Non-type template parameters are either l-values or r-values 2854 // depending on the type. 2855 case Decl::NonTypeTemplateParm: { 2856 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2857 type = reftype->getPointeeType(); 2858 valueKind = VK_LValue; // even if the parameter is an r-value reference 2859 break; 2860 } 2861 2862 // For non-references, we need to strip qualifiers just in case 2863 // the template parameter was declared as 'const int' or whatever. 2864 valueKind = VK_RValue; 2865 type = type.getUnqualifiedType(); 2866 break; 2867 } 2868 2869 case Decl::Var: 2870 case Decl::VarTemplateSpecialization: 2871 case Decl::VarTemplatePartialSpecialization: 2872 case Decl::Decomposition: 2873 case Decl::OMPCapturedExpr: 2874 // In C, "extern void blah;" is valid and is an r-value. 2875 if (!getLangOpts().CPlusPlus && 2876 !type.hasQualifiers() && 2877 type->isVoidType()) { 2878 valueKind = VK_RValue; 2879 break; 2880 } 2881 // fallthrough 2882 2883 case Decl::ImplicitParam: 2884 case Decl::ParmVar: { 2885 // These are always l-values. 2886 valueKind = VK_LValue; 2887 type = type.getNonReferenceType(); 2888 2889 // FIXME: Does the addition of const really only apply in 2890 // potentially-evaluated contexts? Since the variable isn't actually 2891 // captured in an unevaluated context, it seems that the answer is no. 2892 if (!isUnevaluatedContext()) { 2893 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2894 if (!CapturedType.isNull()) 2895 type = CapturedType; 2896 } 2897 2898 break; 2899 } 2900 2901 case Decl::Binding: { 2902 // These are always lvalues. 2903 valueKind = VK_LValue; 2904 type = type.getNonReferenceType(); 2905 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 2906 // decides how that's supposed to work. 2907 auto *BD = cast<BindingDecl>(VD); 2908 if (BD->getDeclContext()->isFunctionOrMethod() && 2909 BD->getDeclContext() != CurContext) 2910 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 2911 break; 2912 } 2913 2914 case Decl::Function: { 2915 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2916 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2917 type = Context.BuiltinFnTy; 2918 valueKind = VK_RValue; 2919 break; 2920 } 2921 } 2922 2923 const FunctionType *fty = type->castAs<FunctionType>(); 2924 2925 // If we're referring to a function with an __unknown_anytype 2926 // result type, make the entire expression __unknown_anytype. 2927 if (fty->getReturnType() == Context.UnknownAnyTy) { 2928 type = Context.UnknownAnyTy; 2929 valueKind = VK_RValue; 2930 break; 2931 } 2932 2933 // Functions are l-values in C++. 2934 if (getLangOpts().CPlusPlus) { 2935 valueKind = VK_LValue; 2936 break; 2937 } 2938 2939 // C99 DR 316 says that, if a function type comes from a 2940 // function definition (without a prototype), that type is only 2941 // used for checking compatibility. Therefore, when referencing 2942 // the function, we pretend that we don't have the full function 2943 // type. 2944 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2945 isa<FunctionProtoType>(fty)) 2946 type = Context.getFunctionNoProtoType(fty->getReturnType(), 2947 fty->getExtInfo()); 2948 2949 // Functions are r-values in C. 2950 valueKind = VK_RValue; 2951 break; 2952 } 2953 2954 case Decl::CXXDeductionGuide: 2955 llvm_unreachable("building reference to deduction guide"); 2956 2957 case Decl::MSProperty: 2958 valueKind = VK_LValue; 2959 break; 2960 2961 case Decl::CXXMethod: 2962 // If we're referring to a method with an __unknown_anytype 2963 // result type, make the entire expression __unknown_anytype. 2964 // This should only be possible with a type written directly. 2965 if (const FunctionProtoType *proto 2966 = dyn_cast<FunctionProtoType>(VD->getType())) 2967 if (proto->getReturnType() == Context.UnknownAnyTy) { 2968 type = Context.UnknownAnyTy; 2969 valueKind = VK_RValue; 2970 break; 2971 } 2972 2973 // C++ methods are l-values if static, r-values if non-static. 2974 if (cast<CXXMethodDecl>(VD)->isStatic()) { 2975 valueKind = VK_LValue; 2976 break; 2977 } 2978 // fallthrough 2979 2980 case Decl::CXXConversion: 2981 case Decl::CXXDestructor: 2982 case Decl::CXXConstructor: 2983 valueKind = VK_RValue; 2984 break; 2985 } 2986 2987 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 2988 TemplateArgs); 2989 } 2990 } 2991 2992 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 2993 SmallString<32> &Target) { 2994 Target.resize(CharByteWidth * (Source.size() + 1)); 2995 char *ResultPtr = &Target[0]; 2996 const llvm::UTF8 *ErrorPtr; 2997 bool success = 2998 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 2999 (void)success; 3000 assert(success); 3001 Target.resize(ResultPtr - &Target[0]); 3002 } 3003 3004 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3005 PredefinedExpr::IdentType IT) { 3006 // Pick the current block, lambda, captured statement or function. 3007 Decl *currentDecl = nullptr; 3008 if (const BlockScopeInfo *BSI = getCurBlock()) 3009 currentDecl = BSI->TheDecl; 3010 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3011 currentDecl = LSI->CallOperator; 3012 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3013 currentDecl = CSI->TheCapturedDecl; 3014 else 3015 currentDecl = getCurFunctionOrMethodDecl(); 3016 3017 if (!currentDecl) { 3018 Diag(Loc, diag::ext_predef_outside_function); 3019 currentDecl = Context.getTranslationUnitDecl(); 3020 } 3021 3022 QualType ResTy; 3023 StringLiteral *SL = nullptr; 3024 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3025 ResTy = Context.DependentTy; 3026 else { 3027 // Pre-defined identifiers are of type char[x], where x is the length of 3028 // the string. 3029 auto Str = PredefinedExpr::ComputeName(IT, currentDecl); 3030 unsigned Length = Str.length(); 3031 3032 llvm::APInt LengthI(32, Length + 1); 3033 if (IT == PredefinedExpr::LFunction) { 3034 ResTy = Context.WideCharTy.withConst(); 3035 SmallString<32> RawChars; 3036 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3037 Str, RawChars); 3038 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3039 /*IndexTypeQuals*/ 0); 3040 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3041 /*Pascal*/ false, ResTy, Loc); 3042 } else { 3043 ResTy = Context.CharTy.withConst(); 3044 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3045 /*IndexTypeQuals*/ 0); 3046 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3047 /*Pascal*/ false, ResTy, Loc); 3048 } 3049 } 3050 3051 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL); 3052 } 3053 3054 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3055 PredefinedExpr::IdentType IT; 3056 3057 switch (Kind) { 3058 default: llvm_unreachable("Unknown simple primary expr!"); 3059 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3060 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 3061 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 3062 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS] 3063 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 3064 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 3065 } 3066 3067 return BuildPredefinedExpr(Loc, IT); 3068 } 3069 3070 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3071 SmallString<16> CharBuffer; 3072 bool Invalid = false; 3073 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3074 if (Invalid) 3075 return ExprError(); 3076 3077 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3078 PP, Tok.getKind()); 3079 if (Literal.hadError()) 3080 return ExprError(); 3081 3082 QualType Ty; 3083 if (Literal.isWide()) 3084 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3085 else if (Literal.isUTF16()) 3086 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3087 else if (Literal.isUTF32()) 3088 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3089 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3090 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3091 else 3092 Ty = Context.CharTy; // 'x' -> char in C++ 3093 3094 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3095 if (Literal.isWide()) 3096 Kind = CharacterLiteral::Wide; 3097 else if (Literal.isUTF16()) 3098 Kind = CharacterLiteral::UTF16; 3099 else if (Literal.isUTF32()) 3100 Kind = CharacterLiteral::UTF32; 3101 else if (Literal.isUTF8()) 3102 Kind = CharacterLiteral::UTF8; 3103 3104 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3105 Tok.getLocation()); 3106 3107 if (Literal.getUDSuffix().empty()) 3108 return Lit; 3109 3110 // We're building a user-defined literal. 3111 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3112 SourceLocation UDSuffixLoc = 3113 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3114 3115 // Make sure we're allowed user-defined literals here. 3116 if (!UDLScope) 3117 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3118 3119 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3120 // operator "" X (ch) 3121 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3122 Lit, Tok.getLocation()); 3123 } 3124 3125 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3126 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3127 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3128 Context.IntTy, Loc); 3129 } 3130 3131 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3132 QualType Ty, SourceLocation Loc) { 3133 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3134 3135 using llvm::APFloat; 3136 APFloat Val(Format); 3137 3138 APFloat::opStatus result = Literal.GetFloatValue(Val); 3139 3140 // Overflow is always an error, but underflow is only an error if 3141 // we underflowed to zero (APFloat reports denormals as underflow). 3142 if ((result & APFloat::opOverflow) || 3143 ((result & APFloat::opUnderflow) && Val.isZero())) { 3144 unsigned diagnostic; 3145 SmallString<20> buffer; 3146 if (result & APFloat::opOverflow) { 3147 diagnostic = diag::warn_float_overflow; 3148 APFloat::getLargest(Format).toString(buffer); 3149 } else { 3150 diagnostic = diag::warn_float_underflow; 3151 APFloat::getSmallest(Format).toString(buffer); 3152 } 3153 3154 S.Diag(Loc, diagnostic) 3155 << Ty 3156 << StringRef(buffer.data(), buffer.size()); 3157 } 3158 3159 bool isExact = (result == APFloat::opOK); 3160 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3161 } 3162 3163 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3164 assert(E && "Invalid expression"); 3165 3166 if (E->isValueDependent()) 3167 return false; 3168 3169 QualType QT = E->getType(); 3170 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3171 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3172 return true; 3173 } 3174 3175 llvm::APSInt ValueAPS; 3176 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3177 3178 if (R.isInvalid()) 3179 return true; 3180 3181 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3182 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3183 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3184 << ValueAPS.toString(10) << ValueIsPositive; 3185 return true; 3186 } 3187 3188 return false; 3189 } 3190 3191 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3192 // Fast path for a single digit (which is quite common). A single digit 3193 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3194 if (Tok.getLength() == 1) { 3195 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3196 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3197 } 3198 3199 SmallString<128> SpellingBuffer; 3200 // NumericLiteralParser wants to overread by one character. Add padding to 3201 // the buffer in case the token is copied to the buffer. If getSpelling() 3202 // returns a StringRef to the memory buffer, it should have a null char at 3203 // the EOF, so it is also safe. 3204 SpellingBuffer.resize(Tok.getLength() + 1); 3205 3206 // Get the spelling of the token, which eliminates trigraphs, etc. 3207 bool Invalid = false; 3208 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3209 if (Invalid) 3210 return ExprError(); 3211 3212 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3213 if (Literal.hadError) 3214 return ExprError(); 3215 3216 if (Literal.hasUDSuffix()) { 3217 // We're building a user-defined literal. 3218 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3219 SourceLocation UDSuffixLoc = 3220 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3221 3222 // Make sure we're allowed user-defined literals here. 3223 if (!UDLScope) 3224 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3225 3226 QualType CookedTy; 3227 if (Literal.isFloatingLiteral()) { 3228 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3229 // long double, the literal is treated as a call of the form 3230 // operator "" X (f L) 3231 CookedTy = Context.LongDoubleTy; 3232 } else { 3233 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3234 // unsigned long long, the literal is treated as a call of the form 3235 // operator "" X (n ULL) 3236 CookedTy = Context.UnsignedLongLongTy; 3237 } 3238 3239 DeclarationName OpName = 3240 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3241 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3242 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3243 3244 SourceLocation TokLoc = Tok.getLocation(); 3245 3246 // Perform literal operator lookup to determine if we're building a raw 3247 // literal or a cooked one. 3248 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3249 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3250 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3251 /*AllowStringTemplate*/ false, 3252 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3253 case LOLR_ErrorNoDiagnostic: 3254 // Lookup failure for imaginary constants isn't fatal, there's still the 3255 // GNU extension producing _Complex types. 3256 break; 3257 case LOLR_Error: 3258 return ExprError(); 3259 case LOLR_Cooked: { 3260 Expr *Lit; 3261 if (Literal.isFloatingLiteral()) { 3262 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3263 } else { 3264 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3265 if (Literal.GetIntegerValue(ResultVal)) 3266 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3267 << /* Unsigned */ 1; 3268 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3269 Tok.getLocation()); 3270 } 3271 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3272 } 3273 3274 case LOLR_Raw: { 3275 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3276 // literal is treated as a call of the form 3277 // operator "" X ("n") 3278 unsigned Length = Literal.getUDSuffixOffset(); 3279 QualType StrTy = Context.getConstantArrayType( 3280 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 3281 ArrayType::Normal, 0); 3282 Expr *Lit = StringLiteral::Create( 3283 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3284 /*Pascal*/false, StrTy, &TokLoc, 1); 3285 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3286 } 3287 3288 case LOLR_Template: { 3289 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3290 // template), L is treated as a call fo the form 3291 // operator "" X <'c1', 'c2', ... 'ck'>() 3292 // where n is the source character sequence c1 c2 ... ck. 3293 TemplateArgumentListInfo ExplicitArgs; 3294 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3295 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3296 llvm::APSInt Value(CharBits, CharIsUnsigned); 3297 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3298 Value = TokSpelling[I]; 3299 TemplateArgument Arg(Context, Value, Context.CharTy); 3300 TemplateArgumentLocInfo ArgInfo; 3301 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3302 } 3303 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3304 &ExplicitArgs); 3305 } 3306 case LOLR_StringTemplate: 3307 llvm_unreachable("unexpected literal operator lookup result"); 3308 } 3309 } 3310 3311 Expr *Res; 3312 3313 if (Literal.isFloatingLiteral()) { 3314 QualType Ty; 3315 if (Literal.isHalf){ 3316 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3317 Ty = Context.HalfTy; 3318 else { 3319 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3320 return ExprError(); 3321 } 3322 } else if (Literal.isFloat) 3323 Ty = Context.FloatTy; 3324 else if (Literal.isLong) 3325 Ty = Context.LongDoubleTy; 3326 else if (Literal.isFloat16) 3327 Ty = Context.Float16Ty; 3328 else if (Literal.isFloat128) 3329 Ty = Context.Float128Ty; 3330 else 3331 Ty = Context.DoubleTy; 3332 3333 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3334 3335 if (Ty == Context.DoubleTy) { 3336 if (getLangOpts().SinglePrecisionConstants) { 3337 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3338 if (BTy->getKind() != BuiltinType::Float) { 3339 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3340 } 3341 } else if (getLangOpts().OpenCL && 3342 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3343 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3344 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3345 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3346 } 3347 } 3348 } else if (!Literal.isIntegerLiteral()) { 3349 return ExprError(); 3350 } else { 3351 QualType Ty; 3352 3353 // 'long long' is a C99 or C++11 feature. 3354 if (!getLangOpts().C99 && Literal.isLongLong) { 3355 if (getLangOpts().CPlusPlus) 3356 Diag(Tok.getLocation(), 3357 getLangOpts().CPlusPlus11 ? 3358 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3359 else 3360 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3361 } 3362 3363 // Get the value in the widest-possible width. 3364 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3365 llvm::APInt ResultVal(MaxWidth, 0); 3366 3367 if (Literal.GetIntegerValue(ResultVal)) { 3368 // If this value didn't fit into uintmax_t, error and force to ull. 3369 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3370 << /* Unsigned */ 1; 3371 Ty = Context.UnsignedLongLongTy; 3372 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3373 "long long is not intmax_t?"); 3374 } else { 3375 // If this value fits into a ULL, try to figure out what else it fits into 3376 // according to the rules of C99 6.4.4.1p5. 3377 3378 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3379 // be an unsigned int. 3380 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3381 3382 // Check from smallest to largest, picking the smallest type we can. 3383 unsigned Width = 0; 3384 3385 // Microsoft specific integer suffixes are explicitly sized. 3386 if (Literal.MicrosoftInteger) { 3387 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3388 Width = 8; 3389 Ty = Context.CharTy; 3390 } else { 3391 Width = Literal.MicrosoftInteger; 3392 Ty = Context.getIntTypeForBitwidth(Width, 3393 /*Signed=*/!Literal.isUnsigned); 3394 } 3395 } 3396 3397 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3398 // Are int/unsigned possibilities? 3399 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3400 3401 // Does it fit in a unsigned int? 3402 if (ResultVal.isIntN(IntSize)) { 3403 // Does it fit in a signed int? 3404 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3405 Ty = Context.IntTy; 3406 else if (AllowUnsigned) 3407 Ty = Context.UnsignedIntTy; 3408 Width = IntSize; 3409 } 3410 } 3411 3412 // Are long/unsigned long possibilities? 3413 if (Ty.isNull() && !Literal.isLongLong) { 3414 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3415 3416 // Does it fit in a unsigned long? 3417 if (ResultVal.isIntN(LongSize)) { 3418 // Does it fit in a signed long? 3419 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3420 Ty = Context.LongTy; 3421 else if (AllowUnsigned) 3422 Ty = Context.UnsignedLongTy; 3423 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3424 // is compatible. 3425 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3426 const unsigned LongLongSize = 3427 Context.getTargetInfo().getLongLongWidth(); 3428 Diag(Tok.getLocation(), 3429 getLangOpts().CPlusPlus 3430 ? Literal.isLong 3431 ? diag::warn_old_implicitly_unsigned_long_cxx 3432 : /*C++98 UB*/ diag:: 3433 ext_old_implicitly_unsigned_long_cxx 3434 : diag::warn_old_implicitly_unsigned_long) 3435 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3436 : /*will be ill-formed*/ 1); 3437 Ty = Context.UnsignedLongTy; 3438 } 3439 Width = LongSize; 3440 } 3441 } 3442 3443 // Check long long if needed. 3444 if (Ty.isNull()) { 3445 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3446 3447 // Does it fit in a unsigned long long? 3448 if (ResultVal.isIntN(LongLongSize)) { 3449 // Does it fit in a signed long long? 3450 // To be compatible with MSVC, hex integer literals ending with the 3451 // LL or i64 suffix are always signed in Microsoft mode. 3452 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3453 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3454 Ty = Context.LongLongTy; 3455 else if (AllowUnsigned) 3456 Ty = Context.UnsignedLongLongTy; 3457 Width = LongLongSize; 3458 } 3459 } 3460 3461 // If we still couldn't decide a type, we probably have something that 3462 // does not fit in a signed long long, but has no U suffix. 3463 if (Ty.isNull()) { 3464 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3465 Ty = Context.UnsignedLongLongTy; 3466 Width = Context.getTargetInfo().getLongLongWidth(); 3467 } 3468 3469 if (ResultVal.getBitWidth() != Width) 3470 ResultVal = ResultVal.trunc(Width); 3471 } 3472 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3473 } 3474 3475 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3476 if (Literal.isImaginary) { 3477 Res = new (Context) ImaginaryLiteral(Res, 3478 Context.getComplexType(Res->getType())); 3479 3480 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3481 } 3482 return Res; 3483 } 3484 3485 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3486 assert(E && "ActOnParenExpr() missing expr"); 3487 return new (Context) ParenExpr(L, R, E); 3488 } 3489 3490 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3491 SourceLocation Loc, 3492 SourceRange ArgRange) { 3493 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3494 // scalar or vector data type argument..." 3495 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3496 // type (C99 6.2.5p18) or void. 3497 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3498 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3499 << T << ArgRange; 3500 return true; 3501 } 3502 3503 assert((T->isVoidType() || !T->isIncompleteType()) && 3504 "Scalar types should always be complete"); 3505 return false; 3506 } 3507 3508 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3509 SourceLocation Loc, 3510 SourceRange ArgRange, 3511 UnaryExprOrTypeTrait TraitKind) { 3512 // Invalid types must be hard errors for SFINAE in C++. 3513 if (S.LangOpts.CPlusPlus) 3514 return true; 3515 3516 // C99 6.5.3.4p1: 3517 if (T->isFunctionType() && 3518 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3519 // sizeof(function)/alignof(function) is allowed as an extension. 3520 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3521 << TraitKind << ArgRange; 3522 return false; 3523 } 3524 3525 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3526 // this is an error (OpenCL v1.1 s6.3.k) 3527 if (T->isVoidType()) { 3528 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3529 : diag::ext_sizeof_alignof_void_type; 3530 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3531 return false; 3532 } 3533 3534 return true; 3535 } 3536 3537 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3538 SourceLocation Loc, 3539 SourceRange ArgRange, 3540 UnaryExprOrTypeTrait TraitKind) { 3541 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3542 // runtime doesn't allow it. 3543 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3544 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3545 << T << (TraitKind == UETT_SizeOf) 3546 << ArgRange; 3547 return true; 3548 } 3549 3550 return false; 3551 } 3552 3553 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3554 /// pointer type is equal to T) and emit a warning if it is. 3555 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3556 Expr *E) { 3557 // Don't warn if the operation changed the type. 3558 if (T != E->getType()) 3559 return; 3560 3561 // Now look for array decays. 3562 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3563 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3564 return; 3565 3566 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3567 << ICE->getType() 3568 << ICE->getSubExpr()->getType(); 3569 } 3570 3571 /// \brief Check the constraints on expression operands to unary type expression 3572 /// and type traits. 3573 /// 3574 /// Completes any types necessary and validates the constraints on the operand 3575 /// expression. The logic mostly mirrors the type-based overload, but may modify 3576 /// the expression as it completes the type for that expression through template 3577 /// instantiation, etc. 3578 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3579 UnaryExprOrTypeTrait ExprKind) { 3580 QualType ExprTy = E->getType(); 3581 assert(!ExprTy->isReferenceType()); 3582 3583 if (ExprKind == UETT_VecStep) 3584 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3585 E->getSourceRange()); 3586 3587 // Whitelist some types as extensions 3588 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3589 E->getSourceRange(), ExprKind)) 3590 return false; 3591 3592 // 'alignof' applied to an expression only requires the base element type of 3593 // the expression to be complete. 'sizeof' requires the expression's type to 3594 // be complete (and will attempt to complete it if it's an array of unknown 3595 // bound). 3596 if (ExprKind == UETT_AlignOf) { 3597 if (RequireCompleteType(E->getExprLoc(), 3598 Context.getBaseElementType(E->getType()), 3599 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3600 E->getSourceRange())) 3601 return true; 3602 } else { 3603 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3604 ExprKind, E->getSourceRange())) 3605 return true; 3606 } 3607 3608 // Completing the expression's type may have changed it. 3609 ExprTy = E->getType(); 3610 assert(!ExprTy->isReferenceType()); 3611 3612 if (ExprTy->isFunctionType()) { 3613 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3614 << ExprKind << E->getSourceRange(); 3615 return true; 3616 } 3617 3618 // The operand for sizeof and alignof is in an unevaluated expression context, 3619 // so side effects could result in unintended consequences. 3620 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) && 3621 !inTemplateInstantiation() && E->HasSideEffects(Context, false)) 3622 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3623 3624 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3625 E->getSourceRange(), ExprKind)) 3626 return true; 3627 3628 if (ExprKind == UETT_SizeOf) { 3629 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3630 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3631 QualType OType = PVD->getOriginalType(); 3632 QualType Type = PVD->getType(); 3633 if (Type->isPointerType() && OType->isArrayType()) { 3634 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3635 << Type << OType; 3636 Diag(PVD->getLocation(), diag::note_declared_at); 3637 } 3638 } 3639 } 3640 3641 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3642 // decays into a pointer and returns an unintended result. This is most 3643 // likely a typo for "sizeof(array) op x". 3644 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3645 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3646 BO->getLHS()); 3647 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3648 BO->getRHS()); 3649 } 3650 } 3651 3652 return false; 3653 } 3654 3655 /// \brief Check the constraints on operands to unary expression and type 3656 /// traits. 3657 /// 3658 /// This will complete any types necessary, and validate the various constraints 3659 /// on those operands. 3660 /// 3661 /// The UsualUnaryConversions() function is *not* called by this routine. 3662 /// C99 6.3.2.1p[2-4] all state: 3663 /// Except when it is the operand of the sizeof operator ... 3664 /// 3665 /// C++ [expr.sizeof]p4 3666 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3667 /// standard conversions are not applied to the operand of sizeof. 3668 /// 3669 /// This policy is followed for all of the unary trait expressions. 3670 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3671 SourceLocation OpLoc, 3672 SourceRange ExprRange, 3673 UnaryExprOrTypeTrait ExprKind) { 3674 if (ExprType->isDependentType()) 3675 return false; 3676 3677 // C++ [expr.sizeof]p2: 3678 // When applied to a reference or a reference type, the result 3679 // is the size of the referenced type. 3680 // C++11 [expr.alignof]p3: 3681 // When alignof is applied to a reference type, the result 3682 // shall be the alignment of the referenced type. 3683 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3684 ExprType = Ref->getPointeeType(); 3685 3686 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3687 // When alignof or _Alignof is applied to an array type, the result 3688 // is the alignment of the element type. 3689 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign) 3690 ExprType = Context.getBaseElementType(ExprType); 3691 3692 if (ExprKind == UETT_VecStep) 3693 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3694 3695 // Whitelist some types as extensions 3696 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3697 ExprKind)) 3698 return false; 3699 3700 if (RequireCompleteType(OpLoc, ExprType, 3701 diag::err_sizeof_alignof_incomplete_type, 3702 ExprKind, ExprRange)) 3703 return true; 3704 3705 if (ExprType->isFunctionType()) { 3706 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3707 << ExprKind << ExprRange; 3708 return true; 3709 } 3710 3711 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3712 ExprKind)) 3713 return true; 3714 3715 return false; 3716 } 3717 3718 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3719 E = E->IgnoreParens(); 3720 3721 // Cannot know anything else if the expression is dependent. 3722 if (E->isTypeDependent()) 3723 return false; 3724 3725 if (E->getObjectKind() == OK_BitField) { 3726 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3727 << 1 << E->getSourceRange(); 3728 return true; 3729 } 3730 3731 ValueDecl *D = nullptr; 3732 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3733 D = DRE->getDecl(); 3734 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3735 D = ME->getMemberDecl(); 3736 } 3737 3738 // If it's a field, require the containing struct to have a 3739 // complete definition so that we can compute the layout. 3740 // 3741 // This can happen in C++11 onwards, either by naming the member 3742 // in a way that is not transformed into a member access expression 3743 // (in an unevaluated operand, for instance), or by naming the member 3744 // in a trailing-return-type. 3745 // 3746 // For the record, since __alignof__ on expressions is a GCC 3747 // extension, GCC seems to permit this but always gives the 3748 // nonsensical answer 0. 3749 // 3750 // We don't really need the layout here --- we could instead just 3751 // directly check for all the appropriate alignment-lowing 3752 // attributes --- but that would require duplicating a lot of 3753 // logic that just isn't worth duplicating for such a marginal 3754 // use-case. 3755 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3756 // Fast path this check, since we at least know the record has a 3757 // definition if we can find a member of it. 3758 if (!FD->getParent()->isCompleteDefinition()) { 3759 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3760 << E->getSourceRange(); 3761 return true; 3762 } 3763 3764 // Otherwise, if it's a field, and the field doesn't have 3765 // reference type, then it must have a complete type (or be a 3766 // flexible array member, which we explicitly want to 3767 // white-list anyway), which makes the following checks trivial. 3768 if (!FD->getType()->isReferenceType()) 3769 return false; 3770 } 3771 3772 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3773 } 3774 3775 bool Sema::CheckVecStepExpr(Expr *E) { 3776 E = E->IgnoreParens(); 3777 3778 // Cannot know anything else if the expression is dependent. 3779 if (E->isTypeDependent()) 3780 return false; 3781 3782 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3783 } 3784 3785 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 3786 CapturingScopeInfo *CSI) { 3787 assert(T->isVariablyModifiedType()); 3788 assert(CSI != nullptr); 3789 3790 // We're going to walk down into the type and look for VLA expressions. 3791 do { 3792 const Type *Ty = T.getTypePtr(); 3793 switch (Ty->getTypeClass()) { 3794 #define TYPE(Class, Base) 3795 #define ABSTRACT_TYPE(Class, Base) 3796 #define NON_CANONICAL_TYPE(Class, Base) 3797 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 3798 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 3799 #include "clang/AST/TypeNodes.def" 3800 T = QualType(); 3801 break; 3802 // These types are never variably-modified. 3803 case Type::Builtin: 3804 case Type::Complex: 3805 case Type::Vector: 3806 case Type::ExtVector: 3807 case Type::Record: 3808 case Type::Enum: 3809 case Type::Elaborated: 3810 case Type::TemplateSpecialization: 3811 case Type::ObjCObject: 3812 case Type::ObjCInterface: 3813 case Type::ObjCObjectPointer: 3814 case Type::ObjCTypeParam: 3815 case Type::Pipe: 3816 llvm_unreachable("type class is never variably-modified!"); 3817 case Type::Adjusted: 3818 T = cast<AdjustedType>(Ty)->getOriginalType(); 3819 break; 3820 case Type::Decayed: 3821 T = cast<DecayedType>(Ty)->getPointeeType(); 3822 break; 3823 case Type::Pointer: 3824 T = cast<PointerType>(Ty)->getPointeeType(); 3825 break; 3826 case Type::BlockPointer: 3827 T = cast<BlockPointerType>(Ty)->getPointeeType(); 3828 break; 3829 case Type::LValueReference: 3830 case Type::RValueReference: 3831 T = cast<ReferenceType>(Ty)->getPointeeType(); 3832 break; 3833 case Type::MemberPointer: 3834 T = cast<MemberPointerType>(Ty)->getPointeeType(); 3835 break; 3836 case Type::ConstantArray: 3837 case Type::IncompleteArray: 3838 // Losing element qualification here is fine. 3839 T = cast<ArrayType>(Ty)->getElementType(); 3840 break; 3841 case Type::VariableArray: { 3842 // Losing element qualification here is fine. 3843 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 3844 3845 // Unknown size indication requires no size computation. 3846 // Otherwise, evaluate and record it. 3847 if (auto Size = VAT->getSizeExpr()) { 3848 if (!CSI->isVLATypeCaptured(VAT)) { 3849 RecordDecl *CapRecord = nullptr; 3850 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 3851 CapRecord = LSI->Lambda; 3852 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 3853 CapRecord = CRSI->TheRecordDecl; 3854 } 3855 if (CapRecord) { 3856 auto ExprLoc = Size->getExprLoc(); 3857 auto SizeType = Context.getSizeType(); 3858 // Build the non-static data member. 3859 auto Field = 3860 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc, 3861 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 3862 /*BW*/ nullptr, /*Mutable*/ false, 3863 /*InitStyle*/ ICIS_NoInit); 3864 Field->setImplicit(true); 3865 Field->setAccess(AS_private); 3866 Field->setCapturedVLAType(VAT); 3867 CapRecord->addDecl(Field); 3868 3869 CSI->addVLATypeCapture(ExprLoc, SizeType); 3870 } 3871 } 3872 } 3873 T = VAT->getElementType(); 3874 break; 3875 } 3876 case Type::FunctionProto: 3877 case Type::FunctionNoProto: 3878 T = cast<FunctionType>(Ty)->getReturnType(); 3879 break; 3880 case Type::Paren: 3881 case Type::TypeOf: 3882 case Type::UnaryTransform: 3883 case Type::Attributed: 3884 case Type::SubstTemplateTypeParm: 3885 case Type::PackExpansion: 3886 // Keep walking after single level desugaring. 3887 T = T.getSingleStepDesugaredType(Context); 3888 break; 3889 case Type::Typedef: 3890 T = cast<TypedefType>(Ty)->desugar(); 3891 break; 3892 case Type::Decltype: 3893 T = cast<DecltypeType>(Ty)->desugar(); 3894 break; 3895 case Type::Auto: 3896 case Type::DeducedTemplateSpecialization: 3897 T = cast<DeducedType>(Ty)->getDeducedType(); 3898 break; 3899 case Type::TypeOfExpr: 3900 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 3901 break; 3902 case Type::Atomic: 3903 T = cast<AtomicType>(Ty)->getValueType(); 3904 break; 3905 } 3906 } while (!T.isNull() && T->isVariablyModifiedType()); 3907 } 3908 3909 /// \brief Build a sizeof or alignof expression given a type operand. 3910 ExprResult 3911 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3912 SourceLocation OpLoc, 3913 UnaryExprOrTypeTrait ExprKind, 3914 SourceRange R) { 3915 if (!TInfo) 3916 return ExprError(); 3917 3918 QualType T = TInfo->getType(); 3919 3920 if (!T->isDependentType() && 3921 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3922 return ExprError(); 3923 3924 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 3925 if (auto *TT = T->getAs<TypedefType>()) { 3926 for (auto I = FunctionScopes.rbegin(), 3927 E = std::prev(FunctionScopes.rend()); 3928 I != E; ++I) { 3929 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 3930 if (CSI == nullptr) 3931 break; 3932 DeclContext *DC = nullptr; 3933 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 3934 DC = LSI->CallOperator; 3935 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 3936 DC = CRSI->TheCapturedDecl; 3937 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 3938 DC = BSI->TheDecl; 3939 if (DC) { 3940 if (DC->containsDecl(TT->getDecl())) 3941 break; 3942 captureVariablyModifiedType(Context, T, CSI); 3943 } 3944 } 3945 } 3946 } 3947 3948 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3949 return new (Context) UnaryExprOrTypeTraitExpr( 3950 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 3951 } 3952 3953 /// \brief Build a sizeof or alignof expression given an expression 3954 /// operand. 3955 ExprResult 3956 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 3957 UnaryExprOrTypeTrait ExprKind) { 3958 ExprResult PE = CheckPlaceholderExpr(E); 3959 if (PE.isInvalid()) 3960 return ExprError(); 3961 3962 E = PE.get(); 3963 3964 // Verify that the operand is valid. 3965 bool isInvalid = false; 3966 if (E->isTypeDependent()) { 3967 // Delay type-checking for type-dependent expressions. 3968 } else if (ExprKind == UETT_AlignOf) { 3969 isInvalid = CheckAlignOfExpr(*this, E); 3970 } else if (ExprKind == UETT_VecStep) { 3971 isInvalid = CheckVecStepExpr(E); 3972 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 3973 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 3974 isInvalid = true; 3975 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 3976 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 3977 isInvalid = true; 3978 } else { 3979 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 3980 } 3981 3982 if (isInvalid) 3983 return ExprError(); 3984 3985 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 3986 PE = TransformToPotentiallyEvaluated(E); 3987 if (PE.isInvalid()) return ExprError(); 3988 E = PE.get(); 3989 } 3990 3991 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3992 return new (Context) UnaryExprOrTypeTraitExpr( 3993 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 3994 } 3995 3996 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 3997 /// expr and the same for @c alignof and @c __alignof 3998 /// Note that the ArgRange is invalid if isType is false. 3999 ExprResult 4000 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4001 UnaryExprOrTypeTrait ExprKind, bool IsType, 4002 void *TyOrEx, SourceRange ArgRange) { 4003 // If error parsing type, ignore. 4004 if (!TyOrEx) return ExprError(); 4005 4006 if (IsType) { 4007 TypeSourceInfo *TInfo; 4008 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4009 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4010 } 4011 4012 Expr *ArgEx = (Expr *)TyOrEx; 4013 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4014 return Result; 4015 } 4016 4017 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4018 bool IsReal) { 4019 if (V.get()->isTypeDependent()) 4020 return S.Context.DependentTy; 4021 4022 // _Real and _Imag are only l-values for normal l-values. 4023 if (V.get()->getObjectKind() != OK_Ordinary) { 4024 V = S.DefaultLvalueConversion(V.get()); 4025 if (V.isInvalid()) 4026 return QualType(); 4027 } 4028 4029 // These operators return the element type of a complex type. 4030 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4031 return CT->getElementType(); 4032 4033 // Otherwise they pass through real integer and floating point types here. 4034 if (V.get()->getType()->isArithmeticType()) 4035 return V.get()->getType(); 4036 4037 // Test for placeholders. 4038 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4039 if (PR.isInvalid()) return QualType(); 4040 if (PR.get() != V.get()) { 4041 V = PR; 4042 return CheckRealImagOperand(S, V, Loc, IsReal); 4043 } 4044 4045 // Reject anything else. 4046 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4047 << (IsReal ? "__real" : "__imag"); 4048 return QualType(); 4049 } 4050 4051 4052 4053 ExprResult 4054 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4055 tok::TokenKind Kind, Expr *Input) { 4056 UnaryOperatorKind Opc; 4057 switch (Kind) { 4058 default: llvm_unreachable("Unknown unary op!"); 4059 case tok::plusplus: Opc = UO_PostInc; break; 4060 case tok::minusminus: Opc = UO_PostDec; break; 4061 } 4062 4063 // Since this might is a postfix expression, get rid of ParenListExprs. 4064 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4065 if (Result.isInvalid()) return ExprError(); 4066 Input = Result.get(); 4067 4068 return BuildUnaryOp(S, OpLoc, Opc, Input); 4069 } 4070 4071 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 4072 /// 4073 /// \return true on error 4074 static bool checkArithmeticOnObjCPointer(Sema &S, 4075 SourceLocation opLoc, 4076 Expr *op) { 4077 assert(op->getType()->isObjCObjectPointerType()); 4078 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4079 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4080 return false; 4081 4082 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4083 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4084 << op->getSourceRange(); 4085 return true; 4086 } 4087 4088 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4089 auto *BaseNoParens = Base->IgnoreParens(); 4090 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4091 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4092 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4093 } 4094 4095 ExprResult 4096 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4097 Expr *idx, SourceLocation rbLoc) { 4098 if (base && !base->getType().isNull() && 4099 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4100 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4101 /*Length=*/nullptr, rbLoc); 4102 4103 // Since this might be a postfix expression, get rid of ParenListExprs. 4104 if (isa<ParenListExpr>(base)) { 4105 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4106 if (result.isInvalid()) return ExprError(); 4107 base = result.get(); 4108 } 4109 4110 // Handle any non-overload placeholder types in the base and index 4111 // expressions. We can't handle overloads here because the other 4112 // operand might be an overloadable type, in which case the overload 4113 // resolution for the operator overload should get the first crack 4114 // at the overload. 4115 bool IsMSPropertySubscript = false; 4116 if (base->getType()->isNonOverloadPlaceholderType()) { 4117 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4118 if (!IsMSPropertySubscript) { 4119 ExprResult result = CheckPlaceholderExpr(base); 4120 if (result.isInvalid()) 4121 return ExprError(); 4122 base = result.get(); 4123 } 4124 } 4125 if (idx->getType()->isNonOverloadPlaceholderType()) { 4126 ExprResult result = CheckPlaceholderExpr(idx); 4127 if (result.isInvalid()) return ExprError(); 4128 idx = result.get(); 4129 } 4130 4131 // Build an unanalyzed expression if either operand is type-dependent. 4132 if (getLangOpts().CPlusPlus && 4133 (base->isTypeDependent() || idx->isTypeDependent())) { 4134 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4135 VK_LValue, OK_Ordinary, rbLoc); 4136 } 4137 4138 // MSDN, property (C++) 4139 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4140 // This attribute can also be used in the declaration of an empty array in a 4141 // class or structure definition. For example: 4142 // __declspec(property(get=GetX, put=PutX)) int x[]; 4143 // The above statement indicates that x[] can be used with one or more array 4144 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4145 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4146 if (IsMSPropertySubscript) { 4147 // Build MS property subscript expression if base is MS property reference 4148 // or MS property subscript. 4149 return new (Context) MSPropertySubscriptExpr( 4150 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4151 } 4152 4153 // Use C++ overloaded-operator rules if either operand has record 4154 // type. The spec says to do this if either type is *overloadable*, 4155 // but enum types can't declare subscript operators or conversion 4156 // operators, so there's nothing interesting for overload resolution 4157 // to do if there aren't any record types involved. 4158 // 4159 // ObjC pointers have their own subscripting logic that is not tied 4160 // to overload resolution and so should not take this path. 4161 if (getLangOpts().CPlusPlus && 4162 (base->getType()->isRecordType() || 4163 (!base->getType()->isObjCObjectPointerType() && 4164 idx->getType()->isRecordType()))) { 4165 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4166 } 4167 4168 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4169 } 4170 4171 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4172 Expr *LowerBound, 4173 SourceLocation ColonLoc, Expr *Length, 4174 SourceLocation RBLoc) { 4175 if (Base->getType()->isPlaceholderType() && 4176 !Base->getType()->isSpecificPlaceholderType( 4177 BuiltinType::OMPArraySection)) { 4178 ExprResult Result = CheckPlaceholderExpr(Base); 4179 if (Result.isInvalid()) 4180 return ExprError(); 4181 Base = Result.get(); 4182 } 4183 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4184 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4185 if (Result.isInvalid()) 4186 return ExprError(); 4187 Result = DefaultLvalueConversion(Result.get()); 4188 if (Result.isInvalid()) 4189 return ExprError(); 4190 LowerBound = Result.get(); 4191 } 4192 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4193 ExprResult Result = CheckPlaceholderExpr(Length); 4194 if (Result.isInvalid()) 4195 return ExprError(); 4196 Result = DefaultLvalueConversion(Result.get()); 4197 if (Result.isInvalid()) 4198 return ExprError(); 4199 Length = Result.get(); 4200 } 4201 4202 // Build an unanalyzed expression if either operand is type-dependent. 4203 if (Base->isTypeDependent() || 4204 (LowerBound && 4205 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4206 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4207 return new (Context) 4208 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4209 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4210 } 4211 4212 // Perform default conversions. 4213 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4214 QualType ResultTy; 4215 if (OriginalTy->isAnyPointerType()) { 4216 ResultTy = OriginalTy->getPointeeType(); 4217 } else if (OriginalTy->isArrayType()) { 4218 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4219 } else { 4220 return ExprError( 4221 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4222 << Base->getSourceRange()); 4223 } 4224 // C99 6.5.2.1p1 4225 if (LowerBound) { 4226 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4227 LowerBound); 4228 if (Res.isInvalid()) 4229 return ExprError(Diag(LowerBound->getExprLoc(), 4230 diag::err_omp_typecheck_section_not_integer) 4231 << 0 << LowerBound->getSourceRange()); 4232 LowerBound = Res.get(); 4233 4234 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4235 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4236 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4237 << 0 << LowerBound->getSourceRange(); 4238 } 4239 if (Length) { 4240 auto Res = 4241 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4242 if (Res.isInvalid()) 4243 return ExprError(Diag(Length->getExprLoc(), 4244 diag::err_omp_typecheck_section_not_integer) 4245 << 1 << Length->getSourceRange()); 4246 Length = Res.get(); 4247 4248 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4249 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4250 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4251 << 1 << Length->getSourceRange(); 4252 } 4253 4254 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4255 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4256 // type. Note that functions are not objects, and that (in C99 parlance) 4257 // incomplete types are not object types. 4258 if (ResultTy->isFunctionType()) { 4259 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4260 << ResultTy << Base->getSourceRange(); 4261 return ExprError(); 4262 } 4263 4264 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4265 diag::err_omp_section_incomplete_type, Base)) 4266 return ExprError(); 4267 4268 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4269 llvm::APSInt LowerBoundValue; 4270 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) { 4271 // OpenMP 4.5, [2.4 Array Sections] 4272 // The array section must be a subset of the original array. 4273 if (LowerBoundValue.isNegative()) { 4274 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4275 << LowerBound->getSourceRange(); 4276 return ExprError(); 4277 } 4278 } 4279 } 4280 4281 if (Length) { 4282 llvm::APSInt LengthValue; 4283 if (Length->EvaluateAsInt(LengthValue, Context)) { 4284 // OpenMP 4.5, [2.4 Array Sections] 4285 // The length must evaluate to non-negative integers. 4286 if (LengthValue.isNegative()) { 4287 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4288 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4289 << Length->getSourceRange(); 4290 return ExprError(); 4291 } 4292 } 4293 } else if (ColonLoc.isValid() && 4294 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4295 !OriginalTy->isVariableArrayType()))) { 4296 // OpenMP 4.5, [2.4 Array Sections] 4297 // When the size of the array dimension is not known, the length must be 4298 // specified explicitly. 4299 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4300 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4301 return ExprError(); 4302 } 4303 4304 if (!Base->getType()->isSpecificPlaceholderType( 4305 BuiltinType::OMPArraySection)) { 4306 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4307 if (Result.isInvalid()) 4308 return ExprError(); 4309 Base = Result.get(); 4310 } 4311 return new (Context) 4312 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4313 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4314 } 4315 4316 ExprResult 4317 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4318 Expr *Idx, SourceLocation RLoc) { 4319 Expr *LHSExp = Base; 4320 Expr *RHSExp = Idx; 4321 4322 ExprValueKind VK = VK_LValue; 4323 ExprObjectKind OK = OK_Ordinary; 4324 4325 // Per C++ core issue 1213, the result is an xvalue if either operand is 4326 // a non-lvalue array, and an lvalue otherwise. 4327 if (getLangOpts().CPlusPlus11 && 4328 ((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) || 4329 (RHSExp->getType()->isArrayType() && !RHSExp->isLValue()))) 4330 VK = VK_XValue; 4331 4332 // Perform default conversions. 4333 if (!LHSExp->getType()->getAs<VectorType>()) { 4334 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4335 if (Result.isInvalid()) 4336 return ExprError(); 4337 LHSExp = Result.get(); 4338 } 4339 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4340 if (Result.isInvalid()) 4341 return ExprError(); 4342 RHSExp = Result.get(); 4343 4344 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4345 4346 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4347 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4348 // in the subscript position. As a result, we need to derive the array base 4349 // and index from the expression types. 4350 Expr *BaseExpr, *IndexExpr; 4351 QualType ResultType; 4352 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4353 BaseExpr = LHSExp; 4354 IndexExpr = RHSExp; 4355 ResultType = Context.DependentTy; 4356 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4357 BaseExpr = LHSExp; 4358 IndexExpr = RHSExp; 4359 ResultType = PTy->getPointeeType(); 4360 } else if (const ObjCObjectPointerType *PTy = 4361 LHSTy->getAs<ObjCObjectPointerType>()) { 4362 BaseExpr = LHSExp; 4363 IndexExpr = RHSExp; 4364 4365 // Use custom logic if this should be the pseudo-object subscript 4366 // expression. 4367 if (!LangOpts.isSubscriptPointerArithmetic()) 4368 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4369 nullptr); 4370 4371 ResultType = PTy->getPointeeType(); 4372 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4373 // Handle the uncommon case of "123[Ptr]". 4374 BaseExpr = RHSExp; 4375 IndexExpr = LHSExp; 4376 ResultType = PTy->getPointeeType(); 4377 } else if (const ObjCObjectPointerType *PTy = 4378 RHSTy->getAs<ObjCObjectPointerType>()) { 4379 // Handle the uncommon case of "123[Ptr]". 4380 BaseExpr = RHSExp; 4381 IndexExpr = LHSExp; 4382 ResultType = PTy->getPointeeType(); 4383 if (!LangOpts.isSubscriptPointerArithmetic()) { 4384 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4385 << ResultType << BaseExpr->getSourceRange(); 4386 return ExprError(); 4387 } 4388 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4389 BaseExpr = LHSExp; // vectors: V[123] 4390 IndexExpr = RHSExp; 4391 VK = LHSExp->getValueKind(); 4392 if (VK != VK_RValue) 4393 OK = OK_VectorComponent; 4394 4395 // FIXME: need to deal with const... 4396 ResultType = VTy->getElementType(); 4397 } else if (LHSTy->isArrayType()) { 4398 // If we see an array that wasn't promoted by 4399 // DefaultFunctionArrayLvalueConversion, it must be an array that 4400 // wasn't promoted because of the C90 rule that doesn't 4401 // allow promoting non-lvalue arrays. Warn, then 4402 // force the promotion here. 4403 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4404 LHSExp->getSourceRange(); 4405 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4406 CK_ArrayToPointerDecay).get(); 4407 LHSTy = LHSExp->getType(); 4408 4409 BaseExpr = LHSExp; 4410 IndexExpr = RHSExp; 4411 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4412 } else if (RHSTy->isArrayType()) { 4413 // Same as previous, except for 123[f().a] case 4414 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4415 RHSExp->getSourceRange(); 4416 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4417 CK_ArrayToPointerDecay).get(); 4418 RHSTy = RHSExp->getType(); 4419 4420 BaseExpr = RHSExp; 4421 IndexExpr = LHSExp; 4422 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4423 } else { 4424 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4425 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4426 } 4427 // C99 6.5.2.1p1 4428 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4429 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4430 << IndexExpr->getSourceRange()); 4431 4432 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4433 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4434 && !IndexExpr->isTypeDependent()) 4435 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4436 4437 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4438 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4439 // type. Note that Functions are not objects, and that (in C99 parlance) 4440 // incomplete types are not object types. 4441 if (ResultType->isFunctionType()) { 4442 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 4443 << ResultType << BaseExpr->getSourceRange(); 4444 return ExprError(); 4445 } 4446 4447 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4448 // GNU extension: subscripting on pointer to void 4449 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4450 << BaseExpr->getSourceRange(); 4451 4452 // C forbids expressions of unqualified void type from being l-values. 4453 // See IsCForbiddenLValueType. 4454 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4455 } else if (!ResultType->isDependentType() && 4456 RequireCompleteType(LLoc, ResultType, 4457 diag::err_subscript_incomplete_type, BaseExpr)) 4458 return ExprError(); 4459 4460 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4461 !ResultType.isCForbiddenLValueType()); 4462 4463 return new (Context) 4464 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4465 } 4466 4467 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 4468 ParmVarDecl *Param) { 4469 if (Param->hasUnparsedDefaultArg()) { 4470 Diag(CallLoc, 4471 diag::err_use_of_default_argument_to_function_declared_later) << 4472 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4473 Diag(UnparsedDefaultArgLocs[Param], 4474 diag::note_default_argument_declared_here); 4475 return true; 4476 } 4477 4478 if (Param->hasUninstantiatedDefaultArg()) { 4479 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4480 4481 EnterExpressionEvaluationContext EvalContext( 4482 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 4483 4484 // Instantiate the expression. 4485 // 4486 // FIXME: Pass in a correct Pattern argument, otherwise 4487 // getTemplateInstantiationArgs uses the lexical context of FD, e.g. 4488 // 4489 // template<typename T> 4490 // struct A { 4491 // static int FooImpl(); 4492 // 4493 // template<typename Tp> 4494 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level 4495 // // template argument list [[T], [Tp]], should be [[Tp]]. 4496 // friend A<Tp> Foo(int a); 4497 // }; 4498 // 4499 // template<typename T> 4500 // A<T> Foo(int a = A<T>::FooImpl()); 4501 MultiLevelTemplateArgumentList MutiLevelArgList 4502 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4503 4504 InstantiatingTemplate Inst(*this, CallLoc, Param, 4505 MutiLevelArgList.getInnermost()); 4506 if (Inst.isInvalid()) 4507 return true; 4508 if (Inst.isAlreadyInstantiating()) { 4509 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4510 Param->setInvalidDecl(); 4511 return true; 4512 } 4513 4514 ExprResult Result; 4515 { 4516 // C++ [dcl.fct.default]p5: 4517 // The names in the [default argument] expression are bound, and 4518 // the semantic constraints are checked, at the point where the 4519 // default argument expression appears. 4520 ContextRAII SavedContext(*this, FD); 4521 LocalInstantiationScope Local(*this); 4522 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 4523 /*DirectInit*/false); 4524 } 4525 if (Result.isInvalid()) 4526 return true; 4527 4528 // Check the expression as an initializer for the parameter. 4529 InitializedEntity Entity 4530 = InitializedEntity::InitializeParameter(Context, Param); 4531 InitializationKind Kind 4532 = InitializationKind::CreateCopy(Param->getLocation(), 4533 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 4534 Expr *ResultE = Result.getAs<Expr>(); 4535 4536 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4537 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4538 if (Result.isInvalid()) 4539 return true; 4540 4541 Result = ActOnFinishFullExpr(Result.getAs<Expr>(), 4542 Param->getOuterLocStart()); 4543 if (Result.isInvalid()) 4544 return true; 4545 4546 // Remember the instantiated default argument. 4547 Param->setDefaultArg(Result.getAs<Expr>()); 4548 if (ASTMutationListener *L = getASTMutationListener()) { 4549 L->DefaultArgumentInstantiated(Param); 4550 } 4551 } 4552 4553 // If the default argument expression is not set yet, we are building it now. 4554 if (!Param->hasInit()) { 4555 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4556 Param->setInvalidDecl(); 4557 return true; 4558 } 4559 4560 // If the default expression creates temporaries, we need to 4561 // push them to the current stack of expression temporaries so they'll 4562 // be properly destroyed. 4563 // FIXME: We should really be rebuilding the default argument with new 4564 // bound temporaries; see the comment in PR5810. 4565 // We don't need to do that with block decls, though, because 4566 // blocks in default argument expression can never capture anything. 4567 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 4568 // Set the "needs cleanups" bit regardless of whether there are 4569 // any explicit objects. 4570 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 4571 4572 // Append all the objects to the cleanup list. Right now, this 4573 // should always be a no-op, because blocks in default argument 4574 // expressions should never be able to capture anything. 4575 assert(!Init->getNumObjects() && 4576 "default argument expression has capturing blocks?"); 4577 } 4578 4579 // We already type-checked the argument, so we know it works. 4580 // Just mark all of the declarations in this potentially-evaluated expression 4581 // as being "referenced". 4582 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4583 /*SkipLocalVariables=*/true); 4584 return false; 4585 } 4586 4587 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4588 FunctionDecl *FD, ParmVarDecl *Param) { 4589 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 4590 return ExprError(); 4591 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4592 } 4593 4594 Sema::VariadicCallType 4595 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4596 Expr *Fn) { 4597 if (Proto && Proto->isVariadic()) { 4598 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4599 return VariadicConstructor; 4600 else if (Fn && Fn->getType()->isBlockPointerType()) 4601 return VariadicBlock; 4602 else if (FDecl) { 4603 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4604 if (Method->isInstance()) 4605 return VariadicMethod; 4606 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4607 return VariadicMethod; 4608 return VariadicFunction; 4609 } 4610 return VariadicDoesNotApply; 4611 } 4612 4613 namespace { 4614 class FunctionCallCCC : public FunctionCallFilterCCC { 4615 public: 4616 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4617 unsigned NumArgs, MemberExpr *ME) 4618 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4619 FunctionName(FuncName) {} 4620 4621 bool ValidateCandidate(const TypoCorrection &candidate) override { 4622 if (!candidate.getCorrectionSpecifier() || 4623 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4624 return false; 4625 } 4626 4627 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4628 } 4629 4630 private: 4631 const IdentifierInfo *const FunctionName; 4632 }; 4633 } 4634 4635 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4636 FunctionDecl *FDecl, 4637 ArrayRef<Expr *> Args) { 4638 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4639 DeclarationName FuncName = FDecl->getDeclName(); 4640 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart(); 4641 4642 if (TypoCorrection Corrected = S.CorrectTypo( 4643 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4644 S.getScopeForContext(S.CurContext), nullptr, 4645 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4646 Args.size(), ME), 4647 Sema::CTK_ErrorRecovery)) { 4648 if (NamedDecl *ND = Corrected.getFoundDecl()) { 4649 if (Corrected.isOverloaded()) { 4650 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4651 OverloadCandidateSet::iterator Best; 4652 for (NamedDecl *CD : Corrected) { 4653 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 4654 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4655 OCS); 4656 } 4657 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4658 case OR_Success: 4659 ND = Best->FoundDecl; 4660 Corrected.setCorrectionDecl(ND); 4661 break; 4662 default: 4663 break; 4664 } 4665 } 4666 ND = ND->getUnderlyingDecl(); 4667 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 4668 return Corrected; 4669 } 4670 } 4671 return TypoCorrection(); 4672 } 4673 4674 /// ConvertArgumentsForCall - Converts the arguments specified in 4675 /// Args/NumArgs to the parameter types of the function FDecl with 4676 /// function prototype Proto. Call is the call expression itself, and 4677 /// Fn is the function expression. For a C++ member function, this 4678 /// routine does not attempt to convert the object argument. Returns 4679 /// true if the call is ill-formed. 4680 bool 4681 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4682 FunctionDecl *FDecl, 4683 const FunctionProtoType *Proto, 4684 ArrayRef<Expr *> Args, 4685 SourceLocation RParenLoc, 4686 bool IsExecConfig) { 4687 // Bail out early if calling a builtin with custom typechecking. 4688 if (FDecl) 4689 if (unsigned ID = FDecl->getBuiltinID()) 4690 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4691 return false; 4692 4693 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4694 // assignment, to the types of the corresponding parameter, ... 4695 unsigned NumParams = Proto->getNumParams(); 4696 bool Invalid = false; 4697 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4698 unsigned FnKind = Fn->getType()->isBlockPointerType() 4699 ? 1 /* block */ 4700 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4701 : 0 /* function */); 4702 4703 // If too few arguments are available (and we don't have default 4704 // arguments for the remaining parameters), don't make the call. 4705 if (Args.size() < NumParams) { 4706 if (Args.size() < MinArgs) { 4707 TypoCorrection TC; 4708 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4709 unsigned diag_id = 4710 MinArgs == NumParams && !Proto->isVariadic() 4711 ? diag::err_typecheck_call_too_few_args_suggest 4712 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4713 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4714 << static_cast<unsigned>(Args.size()) 4715 << TC.getCorrectionRange()); 4716 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4717 Diag(RParenLoc, 4718 MinArgs == NumParams && !Proto->isVariadic() 4719 ? diag::err_typecheck_call_too_few_args_one 4720 : diag::err_typecheck_call_too_few_args_at_least_one) 4721 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4722 else 4723 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4724 ? diag::err_typecheck_call_too_few_args 4725 : diag::err_typecheck_call_too_few_args_at_least) 4726 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4727 << Fn->getSourceRange(); 4728 4729 // Emit the location of the prototype. 4730 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4731 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4732 << FDecl; 4733 4734 return true; 4735 } 4736 Call->setNumArgs(Context, NumParams); 4737 } 4738 4739 // If too many are passed and not variadic, error on the extras and drop 4740 // them. 4741 if (Args.size() > NumParams) { 4742 if (!Proto->isVariadic()) { 4743 TypoCorrection TC; 4744 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4745 unsigned diag_id = 4746 MinArgs == NumParams && !Proto->isVariadic() 4747 ? diag::err_typecheck_call_too_many_args_suggest 4748 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4749 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4750 << static_cast<unsigned>(Args.size()) 4751 << TC.getCorrectionRange()); 4752 } else if (NumParams == 1 && FDecl && 4753 FDecl->getParamDecl(0)->getDeclName()) 4754 Diag(Args[NumParams]->getLocStart(), 4755 MinArgs == NumParams 4756 ? diag::err_typecheck_call_too_many_args_one 4757 : diag::err_typecheck_call_too_many_args_at_most_one) 4758 << FnKind << FDecl->getParamDecl(0) 4759 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4760 << SourceRange(Args[NumParams]->getLocStart(), 4761 Args.back()->getLocEnd()); 4762 else 4763 Diag(Args[NumParams]->getLocStart(), 4764 MinArgs == NumParams 4765 ? diag::err_typecheck_call_too_many_args 4766 : diag::err_typecheck_call_too_many_args_at_most) 4767 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4768 << Fn->getSourceRange() 4769 << SourceRange(Args[NumParams]->getLocStart(), 4770 Args.back()->getLocEnd()); 4771 4772 // Emit the location of the prototype. 4773 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4774 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4775 << FDecl; 4776 4777 // This deletes the extra arguments. 4778 Call->setNumArgs(Context, NumParams); 4779 return true; 4780 } 4781 } 4782 SmallVector<Expr *, 8> AllArgs; 4783 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4784 4785 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4786 Proto, 0, Args, AllArgs, CallType); 4787 if (Invalid) 4788 return true; 4789 unsigned TotalNumArgs = AllArgs.size(); 4790 for (unsigned i = 0; i < TotalNumArgs; ++i) 4791 Call->setArg(i, AllArgs[i]); 4792 4793 return false; 4794 } 4795 4796 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4797 const FunctionProtoType *Proto, 4798 unsigned FirstParam, ArrayRef<Expr *> Args, 4799 SmallVectorImpl<Expr *> &AllArgs, 4800 VariadicCallType CallType, bool AllowExplicit, 4801 bool IsListInitialization) { 4802 unsigned NumParams = Proto->getNumParams(); 4803 bool Invalid = false; 4804 size_t ArgIx = 0; 4805 // Continue to check argument types (even if we have too few/many args). 4806 for (unsigned i = FirstParam; i < NumParams; i++) { 4807 QualType ProtoArgType = Proto->getParamType(i); 4808 4809 Expr *Arg; 4810 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4811 if (ArgIx < Args.size()) { 4812 Arg = Args[ArgIx++]; 4813 4814 if (RequireCompleteType(Arg->getLocStart(), 4815 ProtoArgType, 4816 diag::err_call_incomplete_argument, Arg)) 4817 return true; 4818 4819 // Strip the unbridged-cast placeholder expression off, if applicable. 4820 bool CFAudited = false; 4821 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4822 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4823 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4824 Arg = stripARCUnbridgedCast(Arg); 4825 else if (getLangOpts().ObjCAutoRefCount && 4826 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4827 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4828 CFAudited = true; 4829 4830 InitializedEntity Entity = 4831 Param ? InitializedEntity::InitializeParameter(Context, Param, 4832 ProtoArgType) 4833 : InitializedEntity::InitializeParameter( 4834 Context, ProtoArgType, Proto->isParamConsumed(i)); 4835 4836 // Remember that parameter belongs to a CF audited API. 4837 if (CFAudited) 4838 Entity.setParameterCFAudited(); 4839 4840 ExprResult ArgE = PerformCopyInitialization( 4841 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 4842 if (ArgE.isInvalid()) 4843 return true; 4844 4845 Arg = ArgE.getAs<Expr>(); 4846 } else { 4847 assert(Param && "can't use default arguments without a known callee"); 4848 4849 ExprResult ArgExpr = 4850 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4851 if (ArgExpr.isInvalid()) 4852 return true; 4853 4854 Arg = ArgExpr.getAs<Expr>(); 4855 } 4856 4857 // Check for array bounds violations for each argument to the call. This 4858 // check only triggers warnings when the argument isn't a more complex Expr 4859 // with its own checking, such as a BinaryOperator. 4860 CheckArrayAccess(Arg); 4861 4862 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4863 CheckStaticArrayArgument(CallLoc, Param, Arg); 4864 4865 AllArgs.push_back(Arg); 4866 } 4867 4868 // If this is a variadic call, handle args passed through "...". 4869 if (CallType != VariadicDoesNotApply) { 4870 // Assume that extern "C" functions with variadic arguments that 4871 // return __unknown_anytype aren't *really* variadic. 4872 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4873 FDecl->isExternC()) { 4874 for (Expr *A : Args.slice(ArgIx)) { 4875 QualType paramType; // ignored 4876 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 4877 Invalid |= arg.isInvalid(); 4878 AllArgs.push_back(arg.get()); 4879 } 4880 4881 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4882 } else { 4883 for (Expr *A : Args.slice(ArgIx)) { 4884 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 4885 Invalid |= Arg.isInvalid(); 4886 AllArgs.push_back(Arg.get()); 4887 } 4888 } 4889 4890 // Check for array bounds violations. 4891 for (Expr *A : Args.slice(ArgIx)) 4892 CheckArrayAccess(A); 4893 } 4894 return Invalid; 4895 } 4896 4897 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4898 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4899 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4900 TL = DTL.getOriginalLoc(); 4901 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4902 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4903 << ATL.getLocalSourceRange(); 4904 } 4905 4906 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4907 /// array parameter, check that it is non-null, and that if it is formed by 4908 /// array-to-pointer decay, the underlying array is sufficiently large. 4909 /// 4910 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4911 /// array type derivation, then for each call to the function, the value of the 4912 /// corresponding actual argument shall provide access to the first element of 4913 /// an array with at least as many elements as specified by the size expression. 4914 void 4915 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4916 ParmVarDecl *Param, 4917 const Expr *ArgExpr) { 4918 // Static array parameters are not supported in C++. 4919 if (!Param || getLangOpts().CPlusPlus) 4920 return; 4921 4922 QualType OrigTy = Param->getOriginalType(); 4923 4924 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4925 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4926 return; 4927 4928 if (ArgExpr->isNullPointerConstant(Context, 4929 Expr::NPC_NeverValueDependent)) { 4930 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4931 DiagnoseCalleeStaticArrayParam(*this, Param); 4932 return; 4933 } 4934 4935 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 4936 if (!CAT) 4937 return; 4938 4939 const ConstantArrayType *ArgCAT = 4940 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 4941 if (!ArgCAT) 4942 return; 4943 4944 if (ArgCAT->getSize().ult(CAT->getSize())) { 4945 Diag(CallLoc, diag::warn_static_array_too_small) 4946 << ArgExpr->getSourceRange() 4947 << (unsigned) ArgCAT->getSize().getZExtValue() 4948 << (unsigned) CAT->getSize().getZExtValue(); 4949 DiagnoseCalleeStaticArrayParam(*this, Param); 4950 } 4951 } 4952 4953 /// Given a function expression of unknown-any type, try to rebuild it 4954 /// to have a function type. 4955 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 4956 4957 /// Is the given type a placeholder that we need to lower out 4958 /// immediately during argument processing? 4959 static bool isPlaceholderToRemoveAsArg(QualType type) { 4960 // Placeholders are never sugared. 4961 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 4962 if (!placeholder) return false; 4963 4964 switch (placeholder->getKind()) { 4965 // Ignore all the non-placeholder types. 4966 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 4967 case BuiltinType::Id: 4968 #include "clang/Basic/OpenCLImageTypes.def" 4969 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 4970 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 4971 #include "clang/AST/BuiltinTypes.def" 4972 return false; 4973 4974 // We cannot lower out overload sets; they might validly be resolved 4975 // by the call machinery. 4976 case BuiltinType::Overload: 4977 return false; 4978 4979 // Unbridged casts in ARC can be handled in some call positions and 4980 // should be left in place. 4981 case BuiltinType::ARCUnbridgedCast: 4982 return false; 4983 4984 // Pseudo-objects should be converted as soon as possible. 4985 case BuiltinType::PseudoObject: 4986 return true; 4987 4988 // The debugger mode could theoretically but currently does not try 4989 // to resolve unknown-typed arguments based on known parameter types. 4990 case BuiltinType::UnknownAny: 4991 return true; 4992 4993 // These are always invalid as call arguments and should be reported. 4994 case BuiltinType::BoundMember: 4995 case BuiltinType::BuiltinFn: 4996 case BuiltinType::OMPArraySection: 4997 return true; 4998 4999 } 5000 llvm_unreachable("bad builtin type kind"); 5001 } 5002 5003 /// Check an argument list for placeholders that we won't try to 5004 /// handle later. 5005 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5006 // Apply this processing to all the arguments at once instead of 5007 // dying at the first failure. 5008 bool hasInvalid = false; 5009 for (size_t i = 0, e = args.size(); i != e; i++) { 5010 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5011 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5012 if (result.isInvalid()) hasInvalid = true; 5013 else args[i] = result.get(); 5014 } else if (hasInvalid) { 5015 (void)S.CorrectDelayedTyposInExpr(args[i]); 5016 } 5017 } 5018 return hasInvalid; 5019 } 5020 5021 /// If a builtin function has a pointer argument with no explicit address 5022 /// space, then it should be able to accept a pointer to any address 5023 /// space as input. In order to do this, we need to replace the 5024 /// standard builtin declaration with one that uses the same address space 5025 /// as the call. 5026 /// 5027 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5028 /// it does not contain any pointer arguments without 5029 /// an address space qualifer. Otherwise the rewritten 5030 /// FunctionDecl is returned. 5031 /// TODO: Handle pointer return types. 5032 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5033 const FunctionDecl *FDecl, 5034 MultiExprArg ArgExprs) { 5035 5036 QualType DeclType = FDecl->getType(); 5037 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5038 5039 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 5040 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 5041 return nullptr; 5042 5043 bool NeedsNewDecl = false; 5044 unsigned i = 0; 5045 SmallVector<QualType, 8> OverloadParams; 5046 5047 for (QualType ParamType : FT->param_types()) { 5048 5049 // Convert array arguments to pointer to simplify type lookup. 5050 ExprResult ArgRes = 5051 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5052 if (ArgRes.isInvalid()) 5053 return nullptr; 5054 Expr *Arg = ArgRes.get(); 5055 QualType ArgType = Arg->getType(); 5056 if (!ParamType->isPointerType() || 5057 ParamType.getQualifiers().hasAddressSpace() || 5058 !ArgType->isPointerType() || 5059 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 5060 OverloadParams.push_back(ParamType); 5061 continue; 5062 } 5063 5064 NeedsNewDecl = true; 5065 unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace(); 5066 5067 QualType PointeeType = ParamType->getPointeeType(); 5068 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5069 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5070 } 5071 5072 if (!NeedsNewDecl) 5073 return nullptr; 5074 5075 FunctionProtoType::ExtProtoInfo EPI; 5076 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5077 OverloadParams, EPI); 5078 DeclContext *Parent = Context.getTranslationUnitDecl(); 5079 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5080 FDecl->getLocation(), 5081 FDecl->getLocation(), 5082 FDecl->getIdentifier(), 5083 OverloadTy, 5084 /*TInfo=*/nullptr, 5085 SC_Extern, false, 5086 /*hasPrototype=*/true); 5087 SmallVector<ParmVarDecl*, 16> Params; 5088 FT = cast<FunctionProtoType>(OverloadTy); 5089 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5090 QualType ParamType = FT->getParamType(i); 5091 ParmVarDecl *Parm = 5092 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5093 SourceLocation(), nullptr, ParamType, 5094 /*TInfo=*/nullptr, SC_None, nullptr); 5095 Parm->setScopeInfo(0, i); 5096 Params.push_back(Parm); 5097 } 5098 OverloadDecl->setParams(Params); 5099 return OverloadDecl; 5100 } 5101 5102 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 5103 FunctionDecl *Callee, 5104 MultiExprArg ArgExprs) { 5105 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 5106 // similar attributes) really don't like it when functions are called with an 5107 // invalid number of args. 5108 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 5109 /*PartialOverloading=*/false) && 5110 !Callee->isVariadic()) 5111 return; 5112 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 5113 return; 5114 5115 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) { 5116 S.Diag(Fn->getLocStart(), 5117 isa<CXXMethodDecl>(Callee) 5118 ? diag::err_ovl_no_viable_member_function_in_call 5119 : diag::err_ovl_no_viable_function_in_call) 5120 << Callee << Callee->getSourceRange(); 5121 S.Diag(Callee->getLocation(), 5122 diag::note_ovl_candidate_disabled_by_function_cond_attr) 5123 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5124 return; 5125 } 5126 } 5127 5128 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 5129 const UnresolvedMemberExpr *const UME, Sema &S) { 5130 5131 const auto GetFunctionLevelDCIfCXXClass = 5132 [](Sema &S) -> const CXXRecordDecl * { 5133 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 5134 if (!DC || !DC->getParent()) 5135 return nullptr; 5136 5137 // If the call to some member function was made from within a member 5138 // function body 'M' return return 'M's parent. 5139 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 5140 return MD->getParent()->getCanonicalDecl(); 5141 // else the call was made from within a default member initializer of a 5142 // class, so return the class. 5143 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 5144 return RD->getCanonicalDecl(); 5145 return nullptr; 5146 }; 5147 // If our DeclContext is neither a member function nor a class (in the 5148 // case of a lambda in a default member initializer), we can't have an 5149 // enclosing 'this'. 5150 5151 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 5152 if (!CurParentClass) 5153 return false; 5154 5155 // The naming class for implicit member functions call is the class in which 5156 // name lookup starts. 5157 const CXXRecordDecl *const NamingClass = 5158 UME->getNamingClass()->getCanonicalDecl(); 5159 assert(NamingClass && "Must have naming class even for implicit access"); 5160 5161 // If the unresolved member functions were found in a 'naming class' that is 5162 // related (either the same or derived from) to the class that contains the 5163 // member function that itself contained the implicit member access. 5164 5165 return CurParentClass == NamingClass || 5166 CurParentClass->isDerivedFrom(NamingClass); 5167 } 5168 5169 static void 5170 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5171 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 5172 5173 if (!UME) 5174 return; 5175 5176 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 5177 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 5178 // already been captured, or if this is an implicit member function call (if 5179 // it isn't, an attempt to capture 'this' should already have been made). 5180 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 5181 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 5182 return; 5183 5184 // Check if the naming class in which the unresolved members were found is 5185 // related (same as or is a base of) to the enclosing class. 5186 5187 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 5188 return; 5189 5190 5191 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 5192 // If the enclosing function is not dependent, then this lambda is 5193 // capture ready, so if we can capture this, do so. 5194 if (!EnclosingFunctionCtx->isDependentContext()) { 5195 // If the current lambda and all enclosing lambdas can capture 'this' - 5196 // then go ahead and capture 'this' (since our unresolved overload set 5197 // contains at least one non-static member function). 5198 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 5199 S.CheckCXXThisCapture(CallLoc); 5200 } else if (S.CurContext->isDependentContext()) { 5201 // ... since this is an implicit member reference, that might potentially 5202 // involve a 'this' capture, mark 'this' for potential capture in 5203 // enclosing lambdas. 5204 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 5205 CurLSI->addPotentialThisCapture(CallLoc); 5206 } 5207 } 5208 5209 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 5210 /// This provides the location of the left/right parens and a list of comma 5211 /// locations. 5212 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5213 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5214 Expr *ExecConfig, bool IsExecConfig) { 5215 // Since this might be a postfix expression, get rid of ParenListExprs. 5216 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 5217 if (Result.isInvalid()) return ExprError(); 5218 Fn = Result.get(); 5219 5220 if (checkArgsForPlaceholders(*this, ArgExprs)) 5221 return ExprError(); 5222 5223 if (getLangOpts().CPlusPlus) { 5224 // If this is a pseudo-destructor expression, build the call immediately. 5225 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5226 if (!ArgExprs.empty()) { 5227 // Pseudo-destructor calls should not have any arguments. 5228 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 5229 << FixItHint::CreateRemoval( 5230 SourceRange(ArgExprs.front()->getLocStart(), 5231 ArgExprs.back()->getLocEnd())); 5232 } 5233 5234 return new (Context) 5235 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc); 5236 } 5237 if (Fn->getType() == Context.PseudoObjectTy) { 5238 ExprResult result = CheckPlaceholderExpr(Fn); 5239 if (result.isInvalid()) return ExprError(); 5240 Fn = result.get(); 5241 } 5242 5243 // Determine whether this is a dependent call inside a C++ template, 5244 // in which case we won't do any semantic analysis now. 5245 bool Dependent = false; 5246 if (Fn->isTypeDependent()) 5247 Dependent = true; 5248 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5249 Dependent = true; 5250 5251 if (Dependent) { 5252 if (ExecConfig) { 5253 return new (Context) CUDAKernelCallExpr( 5254 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5255 Context.DependentTy, VK_RValue, RParenLoc); 5256 } else { 5257 5258 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5259 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 5260 Fn->getLocStart()); 5261 5262 return new (Context) CallExpr( 5263 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5264 } 5265 } 5266 5267 // Determine whether this is a call to an object (C++ [over.call.object]). 5268 if (Fn->getType()->isRecordType()) 5269 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 5270 RParenLoc); 5271 5272 if (Fn->getType() == Context.UnknownAnyTy) { 5273 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5274 if (result.isInvalid()) return ExprError(); 5275 Fn = result.get(); 5276 } 5277 5278 if (Fn->getType() == Context.BoundMemberTy) { 5279 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5280 RParenLoc); 5281 } 5282 } 5283 5284 // Check for overloaded calls. This can happen even in C due to extensions. 5285 if (Fn->getType() == Context.OverloadTy) { 5286 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5287 5288 // We aren't supposed to apply this logic if there's an '&' involved. 5289 if (!find.HasFormOfMemberPointer) { 5290 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5291 return new (Context) CallExpr( 5292 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5293 OverloadExpr *ovl = find.Expression; 5294 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5295 return BuildOverloadedCallExpr( 5296 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 5297 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 5298 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5299 RParenLoc); 5300 } 5301 } 5302 5303 // If we're directly calling a function, get the appropriate declaration. 5304 if (Fn->getType() == Context.UnknownAnyTy) { 5305 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5306 if (result.isInvalid()) return ExprError(); 5307 Fn = result.get(); 5308 } 5309 5310 Expr *NakedFn = Fn->IgnoreParens(); 5311 5312 bool CallingNDeclIndirectly = false; 5313 NamedDecl *NDecl = nullptr; 5314 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5315 if (UnOp->getOpcode() == UO_AddrOf) { 5316 CallingNDeclIndirectly = true; 5317 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5318 } 5319 } 5320 5321 if (isa<DeclRefExpr>(NakedFn)) { 5322 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 5323 5324 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5325 if (FDecl && FDecl->getBuiltinID()) { 5326 // Rewrite the function decl for this builtin by replacing parameters 5327 // with no explicit address space with the address space of the arguments 5328 // in ArgExprs. 5329 if ((FDecl = 5330 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5331 NDecl = FDecl; 5332 Fn = DeclRefExpr::Create( 5333 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 5334 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl); 5335 } 5336 } 5337 } else if (isa<MemberExpr>(NakedFn)) 5338 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5339 5340 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5341 if (CallingNDeclIndirectly && 5342 !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 5343 Fn->getLocStart())) 5344 return ExprError(); 5345 5346 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 5347 return ExprError(); 5348 5349 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 5350 } 5351 5352 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5353 ExecConfig, IsExecConfig); 5354 } 5355 5356 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5357 /// 5358 /// __builtin_astype( value, dst type ) 5359 /// 5360 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5361 SourceLocation BuiltinLoc, 5362 SourceLocation RParenLoc) { 5363 ExprValueKind VK = VK_RValue; 5364 ExprObjectKind OK = OK_Ordinary; 5365 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5366 QualType SrcTy = E->getType(); 5367 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5368 return ExprError(Diag(BuiltinLoc, 5369 diag::err_invalid_astype_of_different_size) 5370 << DstTy 5371 << SrcTy 5372 << E->getSourceRange()); 5373 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5374 } 5375 5376 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5377 /// provided arguments. 5378 /// 5379 /// __builtin_convertvector( value, dst type ) 5380 /// 5381 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5382 SourceLocation BuiltinLoc, 5383 SourceLocation RParenLoc) { 5384 TypeSourceInfo *TInfo; 5385 GetTypeFromParser(ParsedDestTy, &TInfo); 5386 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5387 } 5388 5389 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5390 /// i.e. an expression not of \p OverloadTy. The expression should 5391 /// unary-convert to an expression of function-pointer or 5392 /// block-pointer type. 5393 /// 5394 /// \param NDecl the declaration being called, if available 5395 ExprResult 5396 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5397 SourceLocation LParenLoc, 5398 ArrayRef<Expr *> Args, 5399 SourceLocation RParenLoc, 5400 Expr *Config, bool IsExecConfig) { 5401 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5402 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5403 5404 // Functions with 'interrupt' attribute cannot be called directly. 5405 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5406 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5407 return ExprError(); 5408 } 5409 5410 // Interrupt handlers don't save off the VFP regs automatically on ARM, 5411 // so there's some risk when calling out to non-interrupt handler functions 5412 // that the callee might not preserve them. This is easy to diagnose here, 5413 // but can be very challenging to debug. 5414 if (auto *Caller = getCurFunctionDecl()) 5415 if (Caller->hasAttr<ARMInterruptAttr>()) { 5416 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 5417 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) 5418 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 5419 } 5420 5421 // Promote the function operand. 5422 // We special-case function promotion here because we only allow promoting 5423 // builtin functions to function pointers in the callee of a call. 5424 ExprResult Result; 5425 if (BuiltinID && 5426 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5427 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 5428 CK_BuiltinFnToFnPtr).get(); 5429 } else { 5430 Result = CallExprUnaryConversions(Fn); 5431 } 5432 if (Result.isInvalid()) 5433 return ExprError(); 5434 Fn = Result.get(); 5435 5436 // Make the call expr early, before semantic checks. This guarantees cleanup 5437 // of arguments and function on error. 5438 CallExpr *TheCall; 5439 if (Config) 5440 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 5441 cast<CallExpr>(Config), Args, 5442 Context.BoolTy, VK_RValue, 5443 RParenLoc); 5444 else 5445 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 5446 VK_RValue, RParenLoc); 5447 5448 if (!getLangOpts().CPlusPlus) { 5449 // C cannot always handle TypoExpr nodes in builtin calls and direct 5450 // function calls as their argument checking don't necessarily handle 5451 // dependent types properly, so make sure any TypoExprs have been 5452 // dealt with. 5453 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5454 if (!Result.isUsable()) return ExprError(); 5455 TheCall = dyn_cast<CallExpr>(Result.get()); 5456 if (!TheCall) return Result; 5457 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5458 } 5459 5460 // Bail out early if calling a builtin with custom typechecking. 5461 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5462 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5463 5464 retry: 5465 const FunctionType *FuncT; 5466 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5467 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5468 // have type pointer to function". 5469 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5470 if (!FuncT) 5471 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5472 << Fn->getType() << Fn->getSourceRange()); 5473 } else if (const BlockPointerType *BPT = 5474 Fn->getType()->getAs<BlockPointerType>()) { 5475 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5476 } else { 5477 // Handle calls to expressions of unknown-any type. 5478 if (Fn->getType() == Context.UnknownAnyTy) { 5479 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5480 if (rewrite.isInvalid()) return ExprError(); 5481 Fn = rewrite.get(); 5482 TheCall->setCallee(Fn); 5483 goto retry; 5484 } 5485 5486 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5487 << Fn->getType() << Fn->getSourceRange()); 5488 } 5489 5490 if (getLangOpts().CUDA) { 5491 if (Config) { 5492 // CUDA: Kernel calls must be to global functions 5493 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5494 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5495 << FDecl->getName() << Fn->getSourceRange()); 5496 5497 // CUDA: Kernel function must have 'void' return type 5498 if (!FuncT->getReturnType()->isVoidType()) 5499 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5500 << Fn->getType() << Fn->getSourceRange()); 5501 } else { 5502 // CUDA: Calls to global functions must be configured 5503 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5504 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5505 << FDecl->getName() << Fn->getSourceRange()); 5506 } 5507 } 5508 5509 // Check for a valid return type 5510 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall, 5511 FDecl)) 5512 return ExprError(); 5513 5514 // We know the result type of the call, set it. 5515 TheCall->setType(FuncT->getCallResultType(Context)); 5516 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5517 5518 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 5519 if (Proto) { 5520 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5521 IsExecConfig)) 5522 return ExprError(); 5523 } else { 5524 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5525 5526 if (FDecl) { 5527 // Check if we have too few/too many template arguments, based 5528 // on our knowledge of the function definition. 5529 const FunctionDecl *Def = nullptr; 5530 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5531 Proto = Def->getType()->getAs<FunctionProtoType>(); 5532 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5533 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5534 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5535 } 5536 5537 // If the function we're calling isn't a function prototype, but we have 5538 // a function prototype from a prior declaratiom, use that prototype. 5539 if (!FDecl->hasPrototype()) 5540 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5541 } 5542 5543 // Promote the arguments (C99 6.5.2.2p6). 5544 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5545 Expr *Arg = Args[i]; 5546 5547 if (Proto && i < Proto->getNumParams()) { 5548 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5549 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5550 ExprResult ArgE = 5551 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5552 if (ArgE.isInvalid()) 5553 return true; 5554 5555 Arg = ArgE.getAs<Expr>(); 5556 5557 } else { 5558 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5559 5560 if (ArgE.isInvalid()) 5561 return true; 5562 5563 Arg = ArgE.getAs<Expr>(); 5564 } 5565 5566 if (RequireCompleteType(Arg->getLocStart(), 5567 Arg->getType(), 5568 diag::err_call_incomplete_argument, Arg)) 5569 return ExprError(); 5570 5571 TheCall->setArg(i, Arg); 5572 } 5573 } 5574 5575 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5576 if (!Method->isStatic()) 5577 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5578 << Fn->getSourceRange()); 5579 5580 // Check for sentinels 5581 if (NDecl) 5582 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5583 5584 // Do special checking on direct calls to functions. 5585 if (FDecl) { 5586 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5587 return ExprError(); 5588 5589 if (BuiltinID) 5590 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5591 } else if (NDecl) { 5592 if (CheckPointerCall(NDecl, TheCall, Proto)) 5593 return ExprError(); 5594 } else { 5595 if (CheckOtherCall(TheCall, Proto)) 5596 return ExprError(); 5597 } 5598 5599 return MaybeBindToTemporary(TheCall); 5600 } 5601 5602 ExprResult 5603 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5604 SourceLocation RParenLoc, Expr *InitExpr) { 5605 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5606 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 5607 5608 TypeSourceInfo *TInfo; 5609 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5610 if (!TInfo) 5611 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5612 5613 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5614 } 5615 5616 ExprResult 5617 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5618 SourceLocation RParenLoc, Expr *LiteralExpr) { 5619 QualType literalType = TInfo->getType(); 5620 5621 if (literalType->isArrayType()) { 5622 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5623 diag::err_illegal_decl_array_incomplete_type, 5624 SourceRange(LParenLoc, 5625 LiteralExpr->getSourceRange().getEnd()))) 5626 return ExprError(); 5627 if (literalType->isVariableArrayType()) 5628 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5629 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5630 } else if (!literalType->isDependentType() && 5631 RequireCompleteType(LParenLoc, literalType, 5632 diag::err_typecheck_decl_incomplete_type, 5633 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5634 return ExprError(); 5635 5636 InitializedEntity Entity 5637 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5638 InitializationKind Kind 5639 = InitializationKind::CreateCStyleCast(LParenLoc, 5640 SourceRange(LParenLoc, RParenLoc), 5641 /*InitList=*/true); 5642 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5643 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5644 &literalType); 5645 if (Result.isInvalid()) 5646 return ExprError(); 5647 LiteralExpr = Result.get(); 5648 5649 bool isFileScope = !CurContext->isFunctionOrMethod(); 5650 if (isFileScope && 5651 !LiteralExpr->isTypeDependent() && 5652 !LiteralExpr->isValueDependent() && 5653 !literalType->isDependentType()) { // 6.5.2.5p3 5654 if (CheckForConstantInitializer(LiteralExpr, literalType)) 5655 return ExprError(); 5656 } 5657 5658 // In C, compound literals are l-values for some reason. 5659 // For GCC compatibility, in C++, file-scope array compound literals with 5660 // constant initializers are also l-values, and compound literals are 5661 // otherwise prvalues. 5662 // 5663 // (GCC also treats C++ list-initialized file-scope array prvalues with 5664 // constant initializers as l-values, but that's non-conforming, so we don't 5665 // follow it there.) 5666 // 5667 // FIXME: It would be better to handle the lvalue cases as materializing and 5668 // lifetime-extending a temporary object, but our materialized temporaries 5669 // representation only supports lifetime extension from a variable, not "out 5670 // of thin air". 5671 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 5672 // is bound to the result of applying array-to-pointer decay to the compound 5673 // literal. 5674 // FIXME: GCC supports compound literals of reference type, which should 5675 // obviously have a value kind derived from the kind of reference involved. 5676 ExprValueKind VK = 5677 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 5678 ? VK_RValue 5679 : VK_LValue; 5680 5681 return MaybeBindToTemporary( 5682 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 5683 VK, LiteralExpr, isFileScope)); 5684 } 5685 5686 ExprResult 5687 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 5688 SourceLocation RBraceLoc) { 5689 // Immediately handle non-overload placeholders. Overloads can be 5690 // resolved contextually, but everything else here can't. 5691 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 5692 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 5693 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 5694 5695 // Ignore failures; dropping the entire initializer list because 5696 // of one failure would be terrible for indexing/etc. 5697 if (result.isInvalid()) continue; 5698 5699 InitArgList[I] = result.get(); 5700 } 5701 } 5702 5703 // Semantic analysis for initializers is done by ActOnDeclarator() and 5704 // CheckInitializer() - it requires knowledge of the object being intialized. 5705 5706 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 5707 RBraceLoc); 5708 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 5709 return E; 5710 } 5711 5712 /// Do an explicit extend of the given block pointer if we're in ARC. 5713 void Sema::maybeExtendBlockObject(ExprResult &E) { 5714 assert(E.get()->getType()->isBlockPointerType()); 5715 assert(E.get()->isRValue()); 5716 5717 // Only do this in an r-value context. 5718 if (!getLangOpts().ObjCAutoRefCount) return; 5719 5720 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 5721 CK_ARCExtendBlockObject, E.get(), 5722 /*base path*/ nullptr, VK_RValue); 5723 Cleanup.setExprNeedsCleanups(true); 5724 } 5725 5726 /// Prepare a conversion of the given expression to an ObjC object 5727 /// pointer type. 5728 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 5729 QualType type = E.get()->getType(); 5730 if (type->isObjCObjectPointerType()) { 5731 return CK_BitCast; 5732 } else if (type->isBlockPointerType()) { 5733 maybeExtendBlockObject(E); 5734 return CK_BlockPointerToObjCPointerCast; 5735 } else { 5736 assert(type->isPointerType()); 5737 return CK_CPointerToObjCPointerCast; 5738 } 5739 } 5740 5741 /// Prepares for a scalar cast, performing all the necessary stages 5742 /// except the final cast and returning the kind required. 5743 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 5744 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 5745 // Also, callers should have filtered out the invalid cases with 5746 // pointers. Everything else should be possible. 5747 5748 QualType SrcTy = Src.get()->getType(); 5749 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 5750 return CK_NoOp; 5751 5752 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 5753 case Type::STK_MemberPointer: 5754 llvm_unreachable("member pointer type in C"); 5755 5756 case Type::STK_CPointer: 5757 case Type::STK_BlockPointer: 5758 case Type::STK_ObjCObjectPointer: 5759 switch (DestTy->getScalarTypeKind()) { 5760 case Type::STK_CPointer: { 5761 unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace(); 5762 unsigned DestAS = DestTy->getPointeeType().getAddressSpace(); 5763 if (SrcAS != DestAS) 5764 return CK_AddressSpaceConversion; 5765 return CK_BitCast; 5766 } 5767 case Type::STK_BlockPointer: 5768 return (SrcKind == Type::STK_BlockPointer 5769 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 5770 case Type::STK_ObjCObjectPointer: 5771 if (SrcKind == Type::STK_ObjCObjectPointer) 5772 return CK_BitCast; 5773 if (SrcKind == Type::STK_CPointer) 5774 return CK_CPointerToObjCPointerCast; 5775 maybeExtendBlockObject(Src); 5776 return CK_BlockPointerToObjCPointerCast; 5777 case Type::STK_Bool: 5778 return CK_PointerToBoolean; 5779 case Type::STK_Integral: 5780 return CK_PointerToIntegral; 5781 case Type::STK_Floating: 5782 case Type::STK_FloatingComplex: 5783 case Type::STK_IntegralComplex: 5784 case Type::STK_MemberPointer: 5785 llvm_unreachable("illegal cast from pointer"); 5786 } 5787 llvm_unreachable("Should have returned before this"); 5788 5789 case Type::STK_Bool: // casting from bool is like casting from an integer 5790 case Type::STK_Integral: 5791 switch (DestTy->getScalarTypeKind()) { 5792 case Type::STK_CPointer: 5793 case Type::STK_ObjCObjectPointer: 5794 case Type::STK_BlockPointer: 5795 if (Src.get()->isNullPointerConstant(Context, 5796 Expr::NPC_ValueDependentIsNull)) 5797 return CK_NullToPointer; 5798 return CK_IntegralToPointer; 5799 case Type::STK_Bool: 5800 return CK_IntegralToBoolean; 5801 case Type::STK_Integral: 5802 return CK_IntegralCast; 5803 case Type::STK_Floating: 5804 return CK_IntegralToFloating; 5805 case Type::STK_IntegralComplex: 5806 Src = ImpCastExprToType(Src.get(), 5807 DestTy->castAs<ComplexType>()->getElementType(), 5808 CK_IntegralCast); 5809 return CK_IntegralRealToComplex; 5810 case Type::STK_FloatingComplex: 5811 Src = ImpCastExprToType(Src.get(), 5812 DestTy->castAs<ComplexType>()->getElementType(), 5813 CK_IntegralToFloating); 5814 return CK_FloatingRealToComplex; 5815 case Type::STK_MemberPointer: 5816 llvm_unreachable("member pointer type in C"); 5817 } 5818 llvm_unreachable("Should have returned before this"); 5819 5820 case Type::STK_Floating: 5821 switch (DestTy->getScalarTypeKind()) { 5822 case Type::STK_Floating: 5823 return CK_FloatingCast; 5824 case Type::STK_Bool: 5825 return CK_FloatingToBoolean; 5826 case Type::STK_Integral: 5827 return CK_FloatingToIntegral; 5828 case Type::STK_FloatingComplex: 5829 Src = ImpCastExprToType(Src.get(), 5830 DestTy->castAs<ComplexType>()->getElementType(), 5831 CK_FloatingCast); 5832 return CK_FloatingRealToComplex; 5833 case Type::STK_IntegralComplex: 5834 Src = ImpCastExprToType(Src.get(), 5835 DestTy->castAs<ComplexType>()->getElementType(), 5836 CK_FloatingToIntegral); 5837 return CK_IntegralRealToComplex; 5838 case Type::STK_CPointer: 5839 case Type::STK_ObjCObjectPointer: 5840 case Type::STK_BlockPointer: 5841 llvm_unreachable("valid float->pointer cast?"); 5842 case Type::STK_MemberPointer: 5843 llvm_unreachable("member pointer type in C"); 5844 } 5845 llvm_unreachable("Should have returned before this"); 5846 5847 case Type::STK_FloatingComplex: 5848 switch (DestTy->getScalarTypeKind()) { 5849 case Type::STK_FloatingComplex: 5850 return CK_FloatingComplexCast; 5851 case Type::STK_IntegralComplex: 5852 return CK_FloatingComplexToIntegralComplex; 5853 case Type::STK_Floating: { 5854 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5855 if (Context.hasSameType(ET, DestTy)) 5856 return CK_FloatingComplexToReal; 5857 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 5858 return CK_FloatingCast; 5859 } 5860 case Type::STK_Bool: 5861 return CK_FloatingComplexToBoolean; 5862 case Type::STK_Integral: 5863 Src = ImpCastExprToType(Src.get(), 5864 SrcTy->castAs<ComplexType>()->getElementType(), 5865 CK_FloatingComplexToReal); 5866 return CK_FloatingToIntegral; 5867 case Type::STK_CPointer: 5868 case Type::STK_ObjCObjectPointer: 5869 case Type::STK_BlockPointer: 5870 llvm_unreachable("valid complex float->pointer cast?"); 5871 case Type::STK_MemberPointer: 5872 llvm_unreachable("member pointer type in C"); 5873 } 5874 llvm_unreachable("Should have returned before this"); 5875 5876 case Type::STK_IntegralComplex: 5877 switch (DestTy->getScalarTypeKind()) { 5878 case Type::STK_FloatingComplex: 5879 return CK_IntegralComplexToFloatingComplex; 5880 case Type::STK_IntegralComplex: 5881 return CK_IntegralComplexCast; 5882 case Type::STK_Integral: { 5883 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5884 if (Context.hasSameType(ET, DestTy)) 5885 return CK_IntegralComplexToReal; 5886 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 5887 return CK_IntegralCast; 5888 } 5889 case Type::STK_Bool: 5890 return CK_IntegralComplexToBoolean; 5891 case Type::STK_Floating: 5892 Src = ImpCastExprToType(Src.get(), 5893 SrcTy->castAs<ComplexType>()->getElementType(), 5894 CK_IntegralComplexToReal); 5895 return CK_IntegralToFloating; 5896 case Type::STK_CPointer: 5897 case Type::STK_ObjCObjectPointer: 5898 case Type::STK_BlockPointer: 5899 llvm_unreachable("valid complex int->pointer cast?"); 5900 case Type::STK_MemberPointer: 5901 llvm_unreachable("member pointer type in C"); 5902 } 5903 llvm_unreachable("Should have returned before this"); 5904 } 5905 5906 llvm_unreachable("Unhandled scalar cast"); 5907 } 5908 5909 static bool breakDownVectorType(QualType type, uint64_t &len, 5910 QualType &eltType) { 5911 // Vectors are simple. 5912 if (const VectorType *vecType = type->getAs<VectorType>()) { 5913 len = vecType->getNumElements(); 5914 eltType = vecType->getElementType(); 5915 assert(eltType->isScalarType()); 5916 return true; 5917 } 5918 5919 // We allow lax conversion to and from non-vector types, but only if 5920 // they're real types (i.e. non-complex, non-pointer scalar types). 5921 if (!type->isRealType()) return false; 5922 5923 len = 1; 5924 eltType = type; 5925 return true; 5926 } 5927 5928 /// Are the two types lax-compatible vector types? That is, given 5929 /// that one of them is a vector, do they have equal storage sizes, 5930 /// where the storage size is the number of elements times the element 5931 /// size? 5932 /// 5933 /// This will also return false if either of the types is neither a 5934 /// vector nor a real type. 5935 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 5936 assert(destTy->isVectorType() || srcTy->isVectorType()); 5937 5938 // Disallow lax conversions between scalars and ExtVectors (these 5939 // conversions are allowed for other vector types because common headers 5940 // depend on them). Most scalar OP ExtVector cases are handled by the 5941 // splat path anyway, which does what we want (convert, not bitcast). 5942 // What this rules out for ExtVectors is crazy things like char4*float. 5943 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 5944 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 5945 5946 uint64_t srcLen, destLen; 5947 QualType srcEltTy, destEltTy; 5948 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 5949 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 5950 5951 // ASTContext::getTypeSize will return the size rounded up to a 5952 // power of 2, so instead of using that, we need to use the raw 5953 // element size multiplied by the element count. 5954 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 5955 uint64_t destEltSize = Context.getTypeSize(destEltTy); 5956 5957 return (srcLen * srcEltSize == destLen * destEltSize); 5958 } 5959 5960 /// Is this a legal conversion between two types, one of which is 5961 /// known to be a vector type? 5962 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 5963 assert(destTy->isVectorType() || srcTy->isVectorType()); 5964 5965 if (!Context.getLangOpts().LaxVectorConversions) 5966 return false; 5967 return areLaxCompatibleVectorTypes(srcTy, destTy); 5968 } 5969 5970 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5971 CastKind &Kind) { 5972 assert(VectorTy->isVectorType() && "Not a vector type!"); 5973 5974 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 5975 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 5976 return Diag(R.getBegin(), 5977 Ty->isVectorType() ? 5978 diag::err_invalid_conversion_between_vectors : 5979 diag::err_invalid_conversion_between_vector_and_integer) 5980 << VectorTy << Ty << R; 5981 } else 5982 return Diag(R.getBegin(), 5983 diag::err_invalid_conversion_between_vector_and_scalar) 5984 << VectorTy << Ty << R; 5985 5986 Kind = CK_BitCast; 5987 return false; 5988 } 5989 5990 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 5991 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 5992 5993 if (DestElemTy == SplattedExpr->getType()) 5994 return SplattedExpr; 5995 5996 assert(DestElemTy->isFloatingType() || 5997 DestElemTy->isIntegralOrEnumerationType()); 5998 5999 CastKind CK; 6000 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 6001 // OpenCL requires that we convert `true` boolean expressions to -1, but 6002 // only when splatting vectors. 6003 if (DestElemTy->isFloatingType()) { 6004 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 6005 // in two steps: boolean to signed integral, then to floating. 6006 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 6007 CK_BooleanToSignedIntegral); 6008 SplattedExpr = CastExprRes.get(); 6009 CK = CK_IntegralToFloating; 6010 } else { 6011 CK = CK_BooleanToSignedIntegral; 6012 } 6013 } else { 6014 ExprResult CastExprRes = SplattedExpr; 6015 CK = PrepareScalarCast(CastExprRes, DestElemTy); 6016 if (CastExprRes.isInvalid()) 6017 return ExprError(); 6018 SplattedExpr = CastExprRes.get(); 6019 } 6020 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 6021 } 6022 6023 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 6024 Expr *CastExpr, CastKind &Kind) { 6025 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 6026 6027 QualType SrcTy = CastExpr->getType(); 6028 6029 // If SrcTy is a VectorType, the total size must match to explicitly cast to 6030 // an ExtVectorType. 6031 // In OpenCL, casts between vectors of different types are not allowed. 6032 // (See OpenCL 6.2). 6033 if (SrcTy->isVectorType()) { 6034 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) 6035 || (getLangOpts().OpenCL && 6036 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 6037 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 6038 << DestTy << SrcTy << R; 6039 return ExprError(); 6040 } 6041 Kind = CK_BitCast; 6042 return CastExpr; 6043 } 6044 6045 // All non-pointer scalars can be cast to ExtVector type. The appropriate 6046 // conversion will take place first from scalar to elt type, and then 6047 // splat from elt type to vector. 6048 if (SrcTy->isPointerType()) 6049 return Diag(R.getBegin(), 6050 diag::err_invalid_conversion_between_vector_and_scalar) 6051 << DestTy << SrcTy << R; 6052 6053 Kind = CK_VectorSplat; 6054 return prepareVectorSplat(DestTy, CastExpr); 6055 } 6056 6057 ExprResult 6058 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 6059 Declarator &D, ParsedType &Ty, 6060 SourceLocation RParenLoc, Expr *CastExpr) { 6061 assert(!D.isInvalidType() && (CastExpr != nullptr) && 6062 "ActOnCastExpr(): missing type or expr"); 6063 6064 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 6065 if (D.isInvalidType()) 6066 return ExprError(); 6067 6068 if (getLangOpts().CPlusPlus) { 6069 // Check that there are no default arguments (C++ only). 6070 CheckExtraCXXDefaultArguments(D); 6071 } else { 6072 // Make sure any TypoExprs have been dealt with. 6073 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 6074 if (!Res.isUsable()) 6075 return ExprError(); 6076 CastExpr = Res.get(); 6077 } 6078 6079 checkUnusedDeclAttributes(D); 6080 6081 QualType castType = castTInfo->getType(); 6082 Ty = CreateParsedType(castType, castTInfo); 6083 6084 bool isVectorLiteral = false; 6085 6086 // Check for an altivec or OpenCL literal, 6087 // i.e. all the elements are integer constants. 6088 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 6089 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 6090 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 6091 && castType->isVectorType() && (PE || PLE)) { 6092 if (PLE && PLE->getNumExprs() == 0) { 6093 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 6094 return ExprError(); 6095 } 6096 if (PE || PLE->getNumExprs() == 1) { 6097 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 6098 if (!E->getType()->isVectorType()) 6099 isVectorLiteral = true; 6100 } 6101 else 6102 isVectorLiteral = true; 6103 } 6104 6105 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 6106 // then handle it as such. 6107 if (isVectorLiteral) 6108 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 6109 6110 // If the Expr being casted is a ParenListExpr, handle it specially. 6111 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 6112 // sequence of BinOp comma operators. 6113 if (isa<ParenListExpr>(CastExpr)) { 6114 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 6115 if (Result.isInvalid()) return ExprError(); 6116 CastExpr = Result.get(); 6117 } 6118 6119 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6120 !getSourceManager().isInSystemMacro(LParenLoc)) 6121 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6122 6123 CheckTollFreeBridgeCast(castType, CastExpr); 6124 6125 CheckObjCBridgeRelatedCast(castType, CastExpr); 6126 6127 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 6128 6129 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6130 } 6131 6132 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6133 SourceLocation RParenLoc, Expr *E, 6134 TypeSourceInfo *TInfo) { 6135 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6136 "Expected paren or paren list expression"); 6137 6138 Expr **exprs; 6139 unsigned numExprs; 6140 Expr *subExpr; 6141 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6142 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6143 LiteralLParenLoc = PE->getLParenLoc(); 6144 LiteralRParenLoc = PE->getRParenLoc(); 6145 exprs = PE->getExprs(); 6146 numExprs = PE->getNumExprs(); 6147 } else { // isa<ParenExpr> by assertion at function entrance 6148 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6149 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6150 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6151 exprs = &subExpr; 6152 numExprs = 1; 6153 } 6154 6155 QualType Ty = TInfo->getType(); 6156 assert(Ty->isVectorType() && "Expected vector type"); 6157 6158 SmallVector<Expr *, 8> initExprs; 6159 const VectorType *VTy = Ty->getAs<VectorType>(); 6160 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 6161 6162 // '(...)' form of vector initialization in AltiVec: the number of 6163 // initializers must be one or must match the size of the vector. 6164 // If a single value is specified in the initializer then it will be 6165 // replicated to all the components of the vector 6166 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6167 // The number of initializers must be one or must match the size of the 6168 // vector. If a single value is specified in the initializer then it will 6169 // be replicated to all the components of the vector 6170 if (numExprs == 1) { 6171 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6172 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6173 if (Literal.isInvalid()) 6174 return ExprError(); 6175 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6176 PrepareScalarCast(Literal, ElemTy)); 6177 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6178 } 6179 else if (numExprs < numElems) { 6180 Diag(E->getExprLoc(), 6181 diag::err_incorrect_number_of_vector_initializers); 6182 return ExprError(); 6183 } 6184 else 6185 initExprs.append(exprs, exprs + numExprs); 6186 } 6187 else { 6188 // For OpenCL, when the number of initializers is a single value, 6189 // it will be replicated to all components of the vector. 6190 if (getLangOpts().OpenCL && 6191 VTy->getVectorKind() == VectorType::GenericVector && 6192 numExprs == 1) { 6193 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6194 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6195 if (Literal.isInvalid()) 6196 return ExprError(); 6197 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6198 PrepareScalarCast(Literal, ElemTy)); 6199 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6200 } 6201 6202 initExprs.append(exprs, exprs + numExprs); 6203 } 6204 // FIXME: This means that pretty-printing the final AST will produce curly 6205 // braces instead of the original commas. 6206 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6207 initExprs, LiteralRParenLoc); 6208 initE->setType(Ty); 6209 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6210 } 6211 6212 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6213 /// the ParenListExpr into a sequence of comma binary operators. 6214 ExprResult 6215 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6216 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6217 if (!E) 6218 return OrigExpr; 6219 6220 ExprResult Result(E->getExpr(0)); 6221 6222 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6223 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6224 E->getExpr(i)); 6225 6226 if (Result.isInvalid()) return ExprError(); 6227 6228 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6229 } 6230 6231 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6232 SourceLocation R, 6233 MultiExprArg Val) { 6234 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 6235 return expr; 6236 } 6237 6238 /// \brief Emit a specialized diagnostic when one expression is a null pointer 6239 /// constant and the other is not a pointer. Returns true if a diagnostic is 6240 /// emitted. 6241 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6242 SourceLocation QuestionLoc) { 6243 Expr *NullExpr = LHSExpr; 6244 Expr *NonPointerExpr = RHSExpr; 6245 Expr::NullPointerConstantKind NullKind = 6246 NullExpr->isNullPointerConstant(Context, 6247 Expr::NPC_ValueDependentIsNotNull); 6248 6249 if (NullKind == Expr::NPCK_NotNull) { 6250 NullExpr = RHSExpr; 6251 NonPointerExpr = LHSExpr; 6252 NullKind = 6253 NullExpr->isNullPointerConstant(Context, 6254 Expr::NPC_ValueDependentIsNotNull); 6255 } 6256 6257 if (NullKind == Expr::NPCK_NotNull) 6258 return false; 6259 6260 if (NullKind == Expr::NPCK_ZeroExpression) 6261 return false; 6262 6263 if (NullKind == Expr::NPCK_ZeroLiteral) { 6264 // In this case, check to make sure that we got here from a "NULL" 6265 // string in the source code. 6266 NullExpr = NullExpr->IgnoreParenImpCasts(); 6267 SourceLocation loc = NullExpr->getExprLoc(); 6268 if (!findMacroSpelling(loc, "NULL")) 6269 return false; 6270 } 6271 6272 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6273 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6274 << NonPointerExpr->getType() << DiagType 6275 << NonPointerExpr->getSourceRange(); 6276 return true; 6277 } 6278 6279 /// \brief Return false if the condition expression is valid, true otherwise. 6280 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6281 QualType CondTy = Cond->getType(); 6282 6283 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6284 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6285 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6286 << CondTy << Cond->getSourceRange(); 6287 return true; 6288 } 6289 6290 // C99 6.5.15p2 6291 if (CondTy->isScalarType()) return false; 6292 6293 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6294 << CondTy << Cond->getSourceRange(); 6295 return true; 6296 } 6297 6298 /// \brief Handle when one or both operands are void type. 6299 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6300 ExprResult &RHS) { 6301 Expr *LHSExpr = LHS.get(); 6302 Expr *RHSExpr = RHS.get(); 6303 6304 if (!LHSExpr->getType()->isVoidType()) 6305 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6306 << RHSExpr->getSourceRange(); 6307 if (!RHSExpr->getType()->isVoidType()) 6308 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6309 << LHSExpr->getSourceRange(); 6310 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6311 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6312 return S.Context.VoidTy; 6313 } 6314 6315 /// \brief Return false if the NullExpr can be promoted to PointerTy, 6316 /// true otherwise. 6317 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6318 QualType PointerTy) { 6319 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6320 !NullExpr.get()->isNullPointerConstant(S.Context, 6321 Expr::NPC_ValueDependentIsNull)) 6322 return true; 6323 6324 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6325 return false; 6326 } 6327 6328 /// \brief Checks compatibility between two pointers and return the resulting 6329 /// type. 6330 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6331 ExprResult &RHS, 6332 SourceLocation Loc) { 6333 QualType LHSTy = LHS.get()->getType(); 6334 QualType RHSTy = RHS.get()->getType(); 6335 6336 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6337 // Two identical pointers types are always compatible. 6338 return LHSTy; 6339 } 6340 6341 QualType lhptee, rhptee; 6342 6343 // Get the pointee types. 6344 bool IsBlockPointer = false; 6345 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6346 lhptee = LHSBTy->getPointeeType(); 6347 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6348 IsBlockPointer = true; 6349 } else { 6350 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6351 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6352 } 6353 6354 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6355 // differently qualified versions of compatible types, the result type is 6356 // a pointer to an appropriately qualified version of the composite 6357 // type. 6358 6359 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6360 // clause doesn't make sense for our extensions. E.g. address space 2 should 6361 // be incompatible with address space 3: they may live on different devices or 6362 // anything. 6363 Qualifiers lhQual = lhptee.getQualifiers(); 6364 Qualifiers rhQual = rhptee.getQualifiers(); 6365 6366 unsigned ResultAddrSpace = 0; 6367 unsigned LAddrSpace = lhQual.getAddressSpace(); 6368 unsigned RAddrSpace = rhQual.getAddressSpace(); 6369 if (S.getLangOpts().OpenCL) { 6370 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 6371 // spaces is disallowed. 6372 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 6373 ResultAddrSpace = LAddrSpace; 6374 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 6375 ResultAddrSpace = RAddrSpace; 6376 else { 6377 S.Diag(Loc, 6378 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 6379 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 6380 << RHS.get()->getSourceRange(); 6381 return QualType(); 6382 } 6383 } 6384 6385 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6386 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 6387 lhQual.removeCVRQualifiers(); 6388 rhQual.removeCVRQualifiers(); 6389 6390 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 6391 // (C99 6.7.3) for address spaces. We assume that the check should behave in 6392 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 6393 // qual types are compatible iff 6394 // * corresponded types are compatible 6395 // * CVR qualifiers are equal 6396 // * address spaces are equal 6397 // Thus for conditional operator we merge CVR and address space unqualified 6398 // pointees and if there is a composite type we return a pointer to it with 6399 // merged qualifiers. 6400 if (S.getLangOpts().OpenCL) { 6401 LHSCastKind = LAddrSpace == ResultAddrSpace 6402 ? CK_BitCast 6403 : CK_AddressSpaceConversion; 6404 RHSCastKind = RAddrSpace == ResultAddrSpace 6405 ? CK_BitCast 6406 : CK_AddressSpaceConversion; 6407 lhQual.removeAddressSpace(); 6408 rhQual.removeAddressSpace(); 6409 } 6410 6411 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 6412 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 6413 6414 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 6415 6416 if (CompositeTy.isNull()) { 6417 // In this situation, we assume void* type. No especially good 6418 // reason, but this is what gcc does, and we do have to pick 6419 // to get a consistent AST. 6420 QualType incompatTy; 6421 incompatTy = S.Context.getPointerType( 6422 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 6423 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 6424 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 6425 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 6426 // for casts between types with incompatible address space qualifiers. 6427 // For the following code the compiler produces casts between global and 6428 // local address spaces of the corresponded innermost pointees: 6429 // local int *global *a; 6430 // global int *global *b; 6431 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 6432 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 6433 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6434 << RHS.get()->getSourceRange(); 6435 return incompatTy; 6436 } 6437 6438 // The pointer types are compatible. 6439 // In case of OpenCL ResultTy should have the address space qualifier 6440 // which is a superset of address spaces of both the 2nd and the 3rd 6441 // operands of the conditional operator. 6442 QualType ResultTy = [&, ResultAddrSpace]() { 6443 if (S.getLangOpts().OpenCL) { 6444 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 6445 CompositeQuals.setAddressSpace(ResultAddrSpace); 6446 return S.Context 6447 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 6448 .withCVRQualifiers(MergedCVRQual); 6449 } 6450 return CompositeTy.withCVRQualifiers(MergedCVRQual); 6451 }(); 6452 if (IsBlockPointer) 6453 ResultTy = S.Context.getBlockPointerType(ResultTy); 6454 else 6455 ResultTy = S.Context.getPointerType(ResultTy); 6456 6457 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 6458 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 6459 return ResultTy; 6460 } 6461 6462 /// \brief Return the resulting type when the operands are both block pointers. 6463 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 6464 ExprResult &LHS, 6465 ExprResult &RHS, 6466 SourceLocation Loc) { 6467 QualType LHSTy = LHS.get()->getType(); 6468 QualType RHSTy = RHS.get()->getType(); 6469 6470 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 6471 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 6472 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 6473 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6474 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6475 return destType; 6476 } 6477 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 6478 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6479 << RHS.get()->getSourceRange(); 6480 return QualType(); 6481 } 6482 6483 // We have 2 block pointer types. 6484 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6485 } 6486 6487 /// \brief Return the resulting type when the operands are both pointers. 6488 static QualType 6489 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 6490 ExprResult &RHS, 6491 SourceLocation Loc) { 6492 // get the pointer types 6493 QualType LHSTy = LHS.get()->getType(); 6494 QualType RHSTy = RHS.get()->getType(); 6495 6496 // get the "pointed to" types 6497 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6498 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6499 6500 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 6501 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 6502 // Figure out necessary qualifiers (C99 6.5.15p6) 6503 QualType destPointee 6504 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6505 QualType destType = S.Context.getPointerType(destPointee); 6506 // Add qualifiers if necessary. 6507 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6508 // Promote to void*. 6509 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6510 return destType; 6511 } 6512 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 6513 QualType destPointee 6514 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6515 QualType destType = S.Context.getPointerType(destPointee); 6516 // Add qualifiers if necessary. 6517 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6518 // Promote to void*. 6519 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6520 return destType; 6521 } 6522 6523 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6524 } 6525 6526 /// \brief Return false if the first expression is not an integer and the second 6527 /// expression is not a pointer, true otherwise. 6528 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 6529 Expr* PointerExpr, SourceLocation Loc, 6530 bool IsIntFirstExpr) { 6531 if (!PointerExpr->getType()->isPointerType() || 6532 !Int.get()->getType()->isIntegerType()) 6533 return false; 6534 6535 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 6536 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 6537 6538 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 6539 << Expr1->getType() << Expr2->getType() 6540 << Expr1->getSourceRange() << Expr2->getSourceRange(); 6541 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 6542 CK_IntegralToPointer); 6543 return true; 6544 } 6545 6546 /// \brief Simple conversion between integer and floating point types. 6547 /// 6548 /// Used when handling the OpenCL conditional operator where the 6549 /// condition is a vector while the other operands are scalar. 6550 /// 6551 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 6552 /// types are either integer or floating type. Between the two 6553 /// operands, the type with the higher rank is defined as the "result 6554 /// type". The other operand needs to be promoted to the same type. No 6555 /// other type promotion is allowed. We cannot use 6556 /// UsualArithmeticConversions() for this purpose, since it always 6557 /// promotes promotable types. 6558 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 6559 ExprResult &RHS, 6560 SourceLocation QuestionLoc) { 6561 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 6562 if (LHS.isInvalid()) 6563 return QualType(); 6564 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 6565 if (RHS.isInvalid()) 6566 return QualType(); 6567 6568 // For conversion purposes, we ignore any qualifiers. 6569 // For example, "const float" and "float" are equivalent. 6570 QualType LHSType = 6571 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6572 QualType RHSType = 6573 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6574 6575 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 6576 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6577 << LHSType << LHS.get()->getSourceRange(); 6578 return QualType(); 6579 } 6580 6581 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 6582 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6583 << RHSType << RHS.get()->getSourceRange(); 6584 return QualType(); 6585 } 6586 6587 // If both types are identical, no conversion is needed. 6588 if (LHSType == RHSType) 6589 return LHSType; 6590 6591 // Now handle "real" floating types (i.e. float, double, long double). 6592 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 6593 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 6594 /*IsCompAssign = */ false); 6595 6596 // Finally, we have two differing integer types. 6597 return handleIntegerConversion<doIntegralCast, doIntegralCast> 6598 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 6599 } 6600 6601 /// \brief Convert scalar operands to a vector that matches the 6602 /// condition in length. 6603 /// 6604 /// Used when handling the OpenCL conditional operator where the 6605 /// condition is a vector while the other operands are scalar. 6606 /// 6607 /// We first compute the "result type" for the scalar operands 6608 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 6609 /// into a vector of that type where the length matches the condition 6610 /// vector type. s6.11.6 requires that the element types of the result 6611 /// and the condition must have the same number of bits. 6612 static QualType 6613 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 6614 QualType CondTy, SourceLocation QuestionLoc) { 6615 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 6616 if (ResTy.isNull()) return QualType(); 6617 6618 const VectorType *CV = CondTy->getAs<VectorType>(); 6619 assert(CV); 6620 6621 // Determine the vector result type 6622 unsigned NumElements = CV->getNumElements(); 6623 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 6624 6625 // Ensure that all types have the same number of bits 6626 if (S.Context.getTypeSize(CV->getElementType()) 6627 != S.Context.getTypeSize(ResTy)) { 6628 // Since VectorTy is created internally, it does not pretty print 6629 // with an OpenCL name. Instead, we just print a description. 6630 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 6631 SmallString<64> Str; 6632 llvm::raw_svector_ostream OS(Str); 6633 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 6634 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6635 << CondTy << OS.str(); 6636 return QualType(); 6637 } 6638 6639 // Convert operands to the vector result type 6640 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 6641 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 6642 6643 return VectorTy; 6644 } 6645 6646 /// \brief Return false if this is a valid OpenCL condition vector 6647 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 6648 SourceLocation QuestionLoc) { 6649 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 6650 // integral type. 6651 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 6652 assert(CondTy); 6653 QualType EleTy = CondTy->getElementType(); 6654 if (EleTy->isIntegerType()) return false; 6655 6656 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6657 << Cond->getType() << Cond->getSourceRange(); 6658 return true; 6659 } 6660 6661 /// \brief Return false if the vector condition type and the vector 6662 /// result type are compatible. 6663 /// 6664 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 6665 /// number of elements, and their element types have the same number 6666 /// of bits. 6667 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 6668 SourceLocation QuestionLoc) { 6669 const VectorType *CV = CondTy->getAs<VectorType>(); 6670 const VectorType *RV = VecResTy->getAs<VectorType>(); 6671 assert(CV && RV); 6672 6673 if (CV->getNumElements() != RV->getNumElements()) { 6674 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 6675 << CondTy << VecResTy; 6676 return true; 6677 } 6678 6679 QualType CVE = CV->getElementType(); 6680 QualType RVE = RV->getElementType(); 6681 6682 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 6683 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6684 << CondTy << VecResTy; 6685 return true; 6686 } 6687 6688 return false; 6689 } 6690 6691 /// \brief Return the resulting type for the conditional operator in 6692 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 6693 /// s6.3.i) when the condition is a vector type. 6694 static QualType 6695 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 6696 ExprResult &LHS, ExprResult &RHS, 6697 SourceLocation QuestionLoc) { 6698 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 6699 if (Cond.isInvalid()) 6700 return QualType(); 6701 QualType CondTy = Cond.get()->getType(); 6702 6703 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 6704 return QualType(); 6705 6706 // If either operand is a vector then find the vector type of the 6707 // result as specified in OpenCL v1.1 s6.3.i. 6708 if (LHS.get()->getType()->isVectorType() || 6709 RHS.get()->getType()->isVectorType()) { 6710 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 6711 /*isCompAssign*/false, 6712 /*AllowBothBool*/true, 6713 /*AllowBoolConversions*/false); 6714 if (VecResTy.isNull()) return QualType(); 6715 // The result type must match the condition type as specified in 6716 // OpenCL v1.1 s6.11.6. 6717 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 6718 return QualType(); 6719 return VecResTy; 6720 } 6721 6722 // Both operands are scalar. 6723 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 6724 } 6725 6726 /// \brief Return true if the Expr is block type 6727 static bool checkBlockType(Sema &S, const Expr *E) { 6728 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 6729 QualType Ty = CE->getCallee()->getType(); 6730 if (Ty->isBlockPointerType()) { 6731 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 6732 return true; 6733 } 6734 } 6735 return false; 6736 } 6737 6738 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 6739 /// In that case, LHS = cond. 6740 /// C99 6.5.15 6741 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 6742 ExprResult &RHS, ExprValueKind &VK, 6743 ExprObjectKind &OK, 6744 SourceLocation QuestionLoc) { 6745 6746 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 6747 if (!LHSResult.isUsable()) return QualType(); 6748 LHS = LHSResult; 6749 6750 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 6751 if (!RHSResult.isUsable()) return QualType(); 6752 RHS = RHSResult; 6753 6754 // C++ is sufficiently different to merit its own checker. 6755 if (getLangOpts().CPlusPlus) 6756 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 6757 6758 VK = VK_RValue; 6759 OK = OK_Ordinary; 6760 6761 // The OpenCL operator with a vector condition is sufficiently 6762 // different to merit its own checker. 6763 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 6764 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 6765 6766 // First, check the condition. 6767 Cond = UsualUnaryConversions(Cond.get()); 6768 if (Cond.isInvalid()) 6769 return QualType(); 6770 if (checkCondition(*this, Cond.get(), QuestionLoc)) 6771 return QualType(); 6772 6773 // Now check the two expressions. 6774 if (LHS.get()->getType()->isVectorType() || 6775 RHS.get()->getType()->isVectorType()) 6776 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 6777 /*AllowBothBool*/true, 6778 /*AllowBoolConversions*/false); 6779 6780 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 6781 if (LHS.isInvalid() || RHS.isInvalid()) 6782 return QualType(); 6783 6784 QualType LHSTy = LHS.get()->getType(); 6785 QualType RHSTy = RHS.get()->getType(); 6786 6787 // Diagnose attempts to convert between __float128 and long double where 6788 // such conversions currently can't be handled. 6789 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 6790 Diag(QuestionLoc, 6791 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 6792 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6793 return QualType(); 6794 } 6795 6796 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 6797 // selection operator (?:). 6798 if (getLangOpts().OpenCL && 6799 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 6800 return QualType(); 6801 } 6802 6803 // If both operands have arithmetic type, do the usual arithmetic conversions 6804 // to find a common type: C99 6.5.15p3,5. 6805 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 6806 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 6807 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 6808 6809 return ResTy; 6810 } 6811 6812 // If both operands are the same structure or union type, the result is that 6813 // type. 6814 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 6815 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 6816 if (LHSRT->getDecl() == RHSRT->getDecl()) 6817 // "If both the operands have structure or union type, the result has 6818 // that type." This implies that CV qualifiers are dropped. 6819 return LHSTy.getUnqualifiedType(); 6820 // FIXME: Type of conditional expression must be complete in C mode. 6821 } 6822 6823 // C99 6.5.15p5: "If both operands have void type, the result has void type." 6824 // The following || allows only one side to be void (a GCC-ism). 6825 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 6826 return checkConditionalVoidType(*this, LHS, RHS); 6827 } 6828 6829 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 6830 // the type of the other operand." 6831 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 6832 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 6833 6834 // All objective-c pointer type analysis is done here. 6835 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 6836 QuestionLoc); 6837 if (LHS.isInvalid() || RHS.isInvalid()) 6838 return QualType(); 6839 if (!compositeType.isNull()) 6840 return compositeType; 6841 6842 6843 // Handle block pointer types. 6844 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 6845 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 6846 QuestionLoc); 6847 6848 // Check constraints for C object pointers types (C99 6.5.15p3,6). 6849 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 6850 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 6851 QuestionLoc); 6852 6853 // GCC compatibility: soften pointer/integer mismatch. Note that 6854 // null pointers have been filtered out by this point. 6855 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 6856 /*isIntFirstExpr=*/true)) 6857 return RHSTy; 6858 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 6859 /*isIntFirstExpr=*/false)) 6860 return LHSTy; 6861 6862 // Emit a better diagnostic if one of the expressions is a null pointer 6863 // constant and the other is not a pointer type. In this case, the user most 6864 // likely forgot to take the address of the other expression. 6865 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 6866 return QualType(); 6867 6868 // Otherwise, the operands are not compatible. 6869 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 6870 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6871 << RHS.get()->getSourceRange(); 6872 return QualType(); 6873 } 6874 6875 /// FindCompositeObjCPointerType - Helper method to find composite type of 6876 /// two objective-c pointer types of the two input expressions. 6877 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 6878 SourceLocation QuestionLoc) { 6879 QualType LHSTy = LHS.get()->getType(); 6880 QualType RHSTy = RHS.get()->getType(); 6881 6882 // Handle things like Class and struct objc_class*. Here we case the result 6883 // to the pseudo-builtin, because that will be implicitly cast back to the 6884 // redefinition type if an attempt is made to access its fields. 6885 if (LHSTy->isObjCClassType() && 6886 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 6887 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6888 return LHSTy; 6889 } 6890 if (RHSTy->isObjCClassType() && 6891 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 6892 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6893 return RHSTy; 6894 } 6895 // And the same for struct objc_object* / id 6896 if (LHSTy->isObjCIdType() && 6897 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 6898 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6899 return LHSTy; 6900 } 6901 if (RHSTy->isObjCIdType() && 6902 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 6903 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6904 return RHSTy; 6905 } 6906 // And the same for struct objc_selector* / SEL 6907 if (Context.isObjCSelType(LHSTy) && 6908 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 6909 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 6910 return LHSTy; 6911 } 6912 if (Context.isObjCSelType(RHSTy) && 6913 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 6914 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 6915 return RHSTy; 6916 } 6917 // Check constraints for Objective-C object pointers types. 6918 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 6919 6920 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 6921 // Two identical object pointer types are always compatible. 6922 return LHSTy; 6923 } 6924 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 6925 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 6926 QualType compositeType = LHSTy; 6927 6928 // If both operands are interfaces and either operand can be 6929 // assigned to the other, use that type as the composite 6930 // type. This allows 6931 // xxx ? (A*) a : (B*) b 6932 // where B is a subclass of A. 6933 // 6934 // Additionally, as for assignment, if either type is 'id' 6935 // allow silent coercion. Finally, if the types are 6936 // incompatible then make sure to use 'id' as the composite 6937 // type so the result is acceptable for sending messages to. 6938 6939 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 6940 // It could return the composite type. 6941 if (!(compositeType = 6942 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 6943 // Nothing more to do. 6944 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 6945 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 6946 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 6947 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 6948 } else if ((LHSTy->isObjCQualifiedIdType() || 6949 RHSTy->isObjCQualifiedIdType()) && 6950 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 6951 // Need to handle "id<xx>" explicitly. 6952 // GCC allows qualified id and any Objective-C type to devolve to 6953 // id. Currently localizing to here until clear this should be 6954 // part of ObjCQualifiedIdTypesAreCompatible. 6955 compositeType = Context.getObjCIdType(); 6956 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 6957 compositeType = Context.getObjCIdType(); 6958 } else { 6959 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 6960 << LHSTy << RHSTy 6961 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6962 QualType incompatTy = Context.getObjCIdType(); 6963 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6964 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6965 return incompatTy; 6966 } 6967 // The object pointer types are compatible. 6968 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 6969 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 6970 return compositeType; 6971 } 6972 // Check Objective-C object pointer types and 'void *' 6973 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 6974 if (getLangOpts().ObjCAutoRefCount) { 6975 // ARC forbids the implicit conversion of object pointers to 'void *', 6976 // so these types are not compatible. 6977 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6978 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6979 LHS = RHS = true; 6980 return QualType(); 6981 } 6982 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6983 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6984 QualType destPointee 6985 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6986 QualType destType = Context.getPointerType(destPointee); 6987 // Add qualifiers if necessary. 6988 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6989 // Promote to void*. 6990 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6991 return destType; 6992 } 6993 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 6994 if (getLangOpts().ObjCAutoRefCount) { 6995 // ARC forbids the implicit conversion of object pointers to 'void *', 6996 // so these types are not compatible. 6997 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6998 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6999 LHS = RHS = true; 7000 return QualType(); 7001 } 7002 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 7003 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 7004 QualType destPointee 7005 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7006 QualType destType = Context.getPointerType(destPointee); 7007 // Add qualifiers if necessary. 7008 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7009 // Promote to void*. 7010 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7011 return destType; 7012 } 7013 return QualType(); 7014 } 7015 7016 /// SuggestParentheses - Emit a note with a fixit hint that wraps 7017 /// ParenRange in parentheses. 7018 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 7019 const PartialDiagnostic &Note, 7020 SourceRange ParenRange) { 7021 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 7022 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 7023 EndLoc.isValid()) { 7024 Self.Diag(Loc, Note) 7025 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 7026 << FixItHint::CreateInsertion(EndLoc, ")"); 7027 } else { 7028 // We can't display the parentheses, so just show the bare note. 7029 Self.Diag(Loc, Note) << ParenRange; 7030 } 7031 } 7032 7033 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 7034 return BinaryOperator::isAdditiveOp(Opc) || 7035 BinaryOperator::isMultiplicativeOp(Opc) || 7036 BinaryOperator::isShiftOp(Opc); 7037 } 7038 7039 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 7040 /// expression, either using a built-in or overloaded operator, 7041 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 7042 /// expression. 7043 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 7044 Expr **RHSExprs) { 7045 // Don't strip parenthesis: we should not warn if E is in parenthesis. 7046 E = E->IgnoreImpCasts(); 7047 E = E->IgnoreConversionOperator(); 7048 E = E->IgnoreImpCasts(); 7049 7050 // Built-in binary operator. 7051 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 7052 if (IsArithmeticOp(OP->getOpcode())) { 7053 *Opcode = OP->getOpcode(); 7054 *RHSExprs = OP->getRHS(); 7055 return true; 7056 } 7057 } 7058 7059 // Overloaded operator. 7060 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 7061 if (Call->getNumArgs() != 2) 7062 return false; 7063 7064 // Make sure this is really a binary operator that is safe to pass into 7065 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 7066 OverloadedOperatorKind OO = Call->getOperator(); 7067 if (OO < OO_Plus || OO > OO_Arrow || 7068 OO == OO_PlusPlus || OO == OO_MinusMinus) 7069 return false; 7070 7071 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 7072 if (IsArithmeticOp(OpKind)) { 7073 *Opcode = OpKind; 7074 *RHSExprs = Call->getArg(1); 7075 return true; 7076 } 7077 } 7078 7079 return false; 7080 } 7081 7082 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 7083 /// or is a logical expression such as (x==y) which has int type, but is 7084 /// commonly interpreted as boolean. 7085 static bool ExprLooksBoolean(Expr *E) { 7086 E = E->IgnoreParenImpCasts(); 7087 7088 if (E->getType()->isBooleanType()) 7089 return true; 7090 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 7091 return OP->isComparisonOp() || OP->isLogicalOp(); 7092 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 7093 return OP->getOpcode() == UO_LNot; 7094 if (E->getType()->isPointerType()) 7095 return true; 7096 7097 return false; 7098 } 7099 7100 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 7101 /// and binary operator are mixed in a way that suggests the programmer assumed 7102 /// the conditional operator has higher precedence, for example: 7103 /// "int x = a + someBinaryCondition ? 1 : 2". 7104 static void DiagnoseConditionalPrecedence(Sema &Self, 7105 SourceLocation OpLoc, 7106 Expr *Condition, 7107 Expr *LHSExpr, 7108 Expr *RHSExpr) { 7109 BinaryOperatorKind CondOpcode; 7110 Expr *CondRHS; 7111 7112 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 7113 return; 7114 if (!ExprLooksBoolean(CondRHS)) 7115 return; 7116 7117 // The condition is an arithmetic binary expression, with a right- 7118 // hand side that looks boolean, so warn. 7119 7120 Self.Diag(OpLoc, diag::warn_precedence_conditional) 7121 << Condition->getSourceRange() 7122 << BinaryOperator::getOpcodeStr(CondOpcode); 7123 7124 SuggestParentheses(Self, OpLoc, 7125 Self.PDiag(diag::note_precedence_silence) 7126 << BinaryOperator::getOpcodeStr(CondOpcode), 7127 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 7128 7129 SuggestParentheses(Self, OpLoc, 7130 Self.PDiag(diag::note_precedence_conditional_first), 7131 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 7132 } 7133 7134 /// Compute the nullability of a conditional expression. 7135 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 7136 QualType LHSTy, QualType RHSTy, 7137 ASTContext &Ctx) { 7138 if (!ResTy->isAnyPointerType()) 7139 return ResTy; 7140 7141 auto GetNullability = [&Ctx](QualType Ty) { 7142 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 7143 if (Kind) 7144 return *Kind; 7145 return NullabilityKind::Unspecified; 7146 }; 7147 7148 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 7149 NullabilityKind MergedKind; 7150 7151 // Compute nullability of a binary conditional expression. 7152 if (IsBin) { 7153 if (LHSKind == NullabilityKind::NonNull) 7154 MergedKind = NullabilityKind::NonNull; 7155 else 7156 MergedKind = RHSKind; 7157 // Compute nullability of a normal conditional expression. 7158 } else { 7159 if (LHSKind == NullabilityKind::Nullable || 7160 RHSKind == NullabilityKind::Nullable) 7161 MergedKind = NullabilityKind::Nullable; 7162 else if (LHSKind == NullabilityKind::NonNull) 7163 MergedKind = RHSKind; 7164 else if (RHSKind == NullabilityKind::NonNull) 7165 MergedKind = LHSKind; 7166 else 7167 MergedKind = NullabilityKind::Unspecified; 7168 } 7169 7170 // Return if ResTy already has the correct nullability. 7171 if (GetNullability(ResTy) == MergedKind) 7172 return ResTy; 7173 7174 // Strip all nullability from ResTy. 7175 while (ResTy->getNullability(Ctx)) 7176 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 7177 7178 // Create a new AttributedType with the new nullability kind. 7179 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 7180 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 7181 } 7182 7183 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7184 /// in the case of a the GNU conditional expr extension. 7185 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7186 SourceLocation ColonLoc, 7187 Expr *CondExpr, Expr *LHSExpr, 7188 Expr *RHSExpr) { 7189 if (!getLangOpts().CPlusPlus) { 7190 // C cannot handle TypoExpr nodes in the condition because it 7191 // doesn't handle dependent types properly, so make sure any TypoExprs have 7192 // been dealt with before checking the operands. 7193 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7194 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7195 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7196 7197 if (!CondResult.isUsable()) 7198 return ExprError(); 7199 7200 if (LHSExpr) { 7201 if (!LHSResult.isUsable()) 7202 return ExprError(); 7203 } 7204 7205 if (!RHSResult.isUsable()) 7206 return ExprError(); 7207 7208 CondExpr = CondResult.get(); 7209 LHSExpr = LHSResult.get(); 7210 RHSExpr = RHSResult.get(); 7211 } 7212 7213 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7214 // was the condition. 7215 OpaqueValueExpr *opaqueValue = nullptr; 7216 Expr *commonExpr = nullptr; 7217 if (!LHSExpr) { 7218 commonExpr = CondExpr; 7219 // Lower out placeholder types first. This is important so that we don't 7220 // try to capture a placeholder. This happens in few cases in C++; such 7221 // as Objective-C++'s dictionary subscripting syntax. 7222 if (commonExpr->hasPlaceholderType()) { 7223 ExprResult result = CheckPlaceholderExpr(commonExpr); 7224 if (!result.isUsable()) return ExprError(); 7225 commonExpr = result.get(); 7226 } 7227 // We usually want to apply unary conversions *before* saving, except 7228 // in the special case of a C++ l-value conditional. 7229 if (!(getLangOpts().CPlusPlus 7230 && !commonExpr->isTypeDependent() 7231 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7232 && commonExpr->isGLValue() 7233 && commonExpr->isOrdinaryOrBitFieldObject() 7234 && RHSExpr->isOrdinaryOrBitFieldObject() 7235 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7236 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7237 if (commonRes.isInvalid()) 7238 return ExprError(); 7239 commonExpr = commonRes.get(); 7240 } 7241 7242 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7243 commonExpr->getType(), 7244 commonExpr->getValueKind(), 7245 commonExpr->getObjectKind(), 7246 commonExpr); 7247 LHSExpr = CondExpr = opaqueValue; 7248 } 7249 7250 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 7251 ExprValueKind VK = VK_RValue; 7252 ExprObjectKind OK = OK_Ordinary; 7253 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7254 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7255 VK, OK, QuestionLoc); 7256 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7257 RHS.isInvalid()) 7258 return ExprError(); 7259 7260 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7261 RHS.get()); 7262 7263 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 7264 7265 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 7266 Context); 7267 7268 if (!commonExpr) 7269 return new (Context) 7270 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 7271 RHS.get(), result, VK, OK); 7272 7273 return new (Context) BinaryConditionalOperator( 7274 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 7275 ColonLoc, result, VK, OK); 7276 } 7277 7278 // checkPointerTypesForAssignment - This is a very tricky routine (despite 7279 // being closely modeled after the C99 spec:-). The odd characteristic of this 7280 // routine is it effectively iqnores the qualifiers on the top level pointee. 7281 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 7282 // FIXME: add a couple examples in this comment. 7283 static Sema::AssignConvertType 7284 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 7285 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7286 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7287 7288 // get the "pointed to" type (ignoring qualifiers at the top level) 7289 const Type *lhptee, *rhptee; 7290 Qualifiers lhq, rhq; 7291 std::tie(lhptee, lhq) = 7292 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 7293 std::tie(rhptee, rhq) = 7294 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 7295 7296 Sema::AssignConvertType ConvTy = Sema::Compatible; 7297 7298 // C99 6.5.16.1p1: This following citation is common to constraints 7299 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 7300 // qualifiers of the type *pointed to* by the right; 7301 7302 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 7303 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 7304 lhq.compatiblyIncludesObjCLifetime(rhq)) { 7305 // Ignore lifetime for further calculation. 7306 lhq.removeObjCLifetime(); 7307 rhq.removeObjCLifetime(); 7308 } 7309 7310 if (!lhq.compatiblyIncludes(rhq)) { 7311 // Treat address-space mismatches as fatal. TODO: address subspaces 7312 if (!lhq.isAddressSpaceSupersetOf(rhq)) 7313 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7314 7315 // It's okay to add or remove GC or lifetime qualifiers when converting to 7316 // and from void*. 7317 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 7318 .compatiblyIncludes( 7319 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 7320 && (lhptee->isVoidType() || rhptee->isVoidType())) 7321 ; // keep old 7322 7323 // Treat lifetime mismatches as fatal. 7324 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 7325 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7326 7327 // For GCC/MS compatibility, other qualifier mismatches are treated 7328 // as still compatible in C. 7329 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7330 } 7331 7332 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 7333 // incomplete type and the other is a pointer to a qualified or unqualified 7334 // version of void... 7335 if (lhptee->isVoidType()) { 7336 if (rhptee->isIncompleteOrObjectType()) 7337 return ConvTy; 7338 7339 // As an extension, we allow cast to/from void* to function pointer. 7340 assert(rhptee->isFunctionType()); 7341 return Sema::FunctionVoidPointer; 7342 } 7343 7344 if (rhptee->isVoidType()) { 7345 if (lhptee->isIncompleteOrObjectType()) 7346 return ConvTy; 7347 7348 // As an extension, we allow cast to/from void* to function pointer. 7349 assert(lhptee->isFunctionType()); 7350 return Sema::FunctionVoidPointer; 7351 } 7352 7353 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7354 // unqualified versions of compatible types, ... 7355 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7356 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7357 // Check if the pointee types are compatible ignoring the sign. 7358 // We explicitly check for char so that we catch "char" vs 7359 // "unsigned char" on systems where "char" is unsigned. 7360 if (lhptee->isCharType()) 7361 ltrans = S.Context.UnsignedCharTy; 7362 else if (lhptee->hasSignedIntegerRepresentation()) 7363 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7364 7365 if (rhptee->isCharType()) 7366 rtrans = S.Context.UnsignedCharTy; 7367 else if (rhptee->hasSignedIntegerRepresentation()) 7368 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 7369 7370 if (ltrans == rtrans) { 7371 // Types are compatible ignoring the sign. Qualifier incompatibility 7372 // takes priority over sign incompatibility because the sign 7373 // warning can be disabled. 7374 if (ConvTy != Sema::Compatible) 7375 return ConvTy; 7376 7377 return Sema::IncompatiblePointerSign; 7378 } 7379 7380 // If we are a multi-level pointer, it's possible that our issue is simply 7381 // one of qualification - e.g. char ** -> const char ** is not allowed. If 7382 // the eventual target type is the same and the pointers have the same 7383 // level of indirection, this must be the issue. 7384 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 7385 do { 7386 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 7387 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 7388 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 7389 7390 if (lhptee == rhptee) 7391 return Sema::IncompatibleNestedPointerQualifiers; 7392 } 7393 7394 // General pointer incompatibility takes priority over qualifiers. 7395 return Sema::IncompatiblePointer; 7396 } 7397 if (!S.getLangOpts().CPlusPlus && 7398 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 7399 return Sema::IncompatiblePointer; 7400 return ConvTy; 7401 } 7402 7403 /// checkBlockPointerTypesForAssignment - This routine determines whether two 7404 /// block pointer types are compatible or whether a block and normal pointer 7405 /// are compatible. It is more restrict than comparing two function pointer 7406 // types. 7407 static Sema::AssignConvertType 7408 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 7409 QualType RHSType) { 7410 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7411 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7412 7413 QualType lhptee, rhptee; 7414 7415 // get the "pointed to" type (ignoring qualifiers at the top level) 7416 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 7417 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 7418 7419 // In C++, the types have to match exactly. 7420 if (S.getLangOpts().CPlusPlus) 7421 return Sema::IncompatibleBlockPointer; 7422 7423 Sema::AssignConvertType ConvTy = Sema::Compatible; 7424 7425 // For blocks we enforce that qualifiers are identical. 7426 Qualifiers LQuals = lhptee.getLocalQualifiers(); 7427 Qualifiers RQuals = rhptee.getLocalQualifiers(); 7428 if (S.getLangOpts().OpenCL) { 7429 LQuals.removeAddressSpace(); 7430 RQuals.removeAddressSpace(); 7431 } 7432 if (LQuals != RQuals) 7433 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7434 7435 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 7436 // assignment. 7437 // The current behavior is similar to C++ lambdas. A block might be 7438 // assigned to a variable iff its return type and parameters are compatible 7439 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 7440 // an assignment. Presumably it should behave in way that a function pointer 7441 // assignment does in C, so for each parameter and return type: 7442 // * CVR and address space of LHS should be a superset of CVR and address 7443 // space of RHS. 7444 // * unqualified types should be compatible. 7445 if (S.getLangOpts().OpenCL) { 7446 if (!S.Context.typesAreBlockPointerCompatible( 7447 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 7448 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 7449 return Sema::IncompatibleBlockPointer; 7450 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 7451 return Sema::IncompatibleBlockPointer; 7452 7453 return ConvTy; 7454 } 7455 7456 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 7457 /// for assignment compatibility. 7458 static Sema::AssignConvertType 7459 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 7460 QualType RHSType) { 7461 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 7462 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 7463 7464 if (LHSType->isObjCBuiltinType()) { 7465 // Class is not compatible with ObjC object pointers. 7466 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 7467 !RHSType->isObjCQualifiedClassType()) 7468 return Sema::IncompatiblePointer; 7469 return Sema::Compatible; 7470 } 7471 if (RHSType->isObjCBuiltinType()) { 7472 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 7473 !LHSType->isObjCQualifiedClassType()) 7474 return Sema::IncompatiblePointer; 7475 return Sema::Compatible; 7476 } 7477 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7478 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7479 7480 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 7481 // make an exception for id<P> 7482 !LHSType->isObjCQualifiedIdType()) 7483 return Sema::CompatiblePointerDiscardsQualifiers; 7484 7485 if (S.Context.typesAreCompatible(LHSType, RHSType)) 7486 return Sema::Compatible; 7487 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 7488 return Sema::IncompatibleObjCQualifiedId; 7489 return Sema::IncompatiblePointer; 7490 } 7491 7492 Sema::AssignConvertType 7493 Sema::CheckAssignmentConstraints(SourceLocation Loc, 7494 QualType LHSType, QualType RHSType) { 7495 // Fake up an opaque expression. We don't actually care about what 7496 // cast operations are required, so if CheckAssignmentConstraints 7497 // adds casts to this they'll be wasted, but fortunately that doesn't 7498 // usually happen on valid code. 7499 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 7500 ExprResult RHSPtr = &RHSExpr; 7501 CastKind K = CK_Invalid; 7502 7503 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 7504 } 7505 7506 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 7507 /// has code to accommodate several GCC extensions when type checking 7508 /// pointers. Here are some objectionable examples that GCC considers warnings: 7509 /// 7510 /// int a, *pint; 7511 /// short *pshort; 7512 /// struct foo *pfoo; 7513 /// 7514 /// pint = pshort; // warning: assignment from incompatible pointer type 7515 /// a = pint; // warning: assignment makes integer from pointer without a cast 7516 /// pint = a; // warning: assignment makes pointer from integer without a cast 7517 /// pint = pfoo; // warning: assignment from incompatible pointer type 7518 /// 7519 /// As a result, the code for dealing with pointers is more complex than the 7520 /// C99 spec dictates. 7521 /// 7522 /// Sets 'Kind' for any result kind except Incompatible. 7523 Sema::AssignConvertType 7524 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 7525 CastKind &Kind, bool ConvertRHS) { 7526 QualType RHSType = RHS.get()->getType(); 7527 QualType OrigLHSType = LHSType; 7528 7529 // Get canonical types. We're not formatting these types, just comparing 7530 // them. 7531 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 7532 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 7533 7534 // Common case: no conversion required. 7535 if (LHSType == RHSType) { 7536 Kind = CK_NoOp; 7537 return Compatible; 7538 } 7539 7540 // If we have an atomic type, try a non-atomic assignment, then just add an 7541 // atomic qualification step. 7542 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 7543 Sema::AssignConvertType result = 7544 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 7545 if (result != Compatible) 7546 return result; 7547 if (Kind != CK_NoOp && ConvertRHS) 7548 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 7549 Kind = CK_NonAtomicToAtomic; 7550 return Compatible; 7551 } 7552 7553 // If the left-hand side is a reference type, then we are in a 7554 // (rare!) case where we've allowed the use of references in C, 7555 // e.g., as a parameter type in a built-in function. In this case, 7556 // just make sure that the type referenced is compatible with the 7557 // right-hand side type. The caller is responsible for adjusting 7558 // LHSType so that the resulting expression does not have reference 7559 // type. 7560 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 7561 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 7562 Kind = CK_LValueBitCast; 7563 return Compatible; 7564 } 7565 return Incompatible; 7566 } 7567 7568 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 7569 // to the same ExtVector type. 7570 if (LHSType->isExtVectorType()) { 7571 if (RHSType->isExtVectorType()) 7572 return Incompatible; 7573 if (RHSType->isArithmeticType()) { 7574 // CK_VectorSplat does T -> vector T, so first cast to the element type. 7575 if (ConvertRHS) 7576 RHS = prepareVectorSplat(LHSType, RHS.get()); 7577 Kind = CK_VectorSplat; 7578 return Compatible; 7579 } 7580 } 7581 7582 // Conversions to or from vector type. 7583 if (LHSType->isVectorType() || RHSType->isVectorType()) { 7584 if (LHSType->isVectorType() && RHSType->isVectorType()) { 7585 // Allow assignments of an AltiVec vector type to an equivalent GCC 7586 // vector type and vice versa 7587 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7588 Kind = CK_BitCast; 7589 return Compatible; 7590 } 7591 7592 // If we are allowing lax vector conversions, and LHS and RHS are both 7593 // vectors, the total size only needs to be the same. This is a bitcast; 7594 // no bits are changed but the result type is different. 7595 if (isLaxVectorConversion(RHSType, LHSType)) { 7596 Kind = CK_BitCast; 7597 return IncompatibleVectors; 7598 } 7599 } 7600 7601 // When the RHS comes from another lax conversion (e.g. binops between 7602 // scalars and vectors) the result is canonicalized as a vector. When the 7603 // LHS is also a vector, the lax is allowed by the condition above. Handle 7604 // the case where LHS is a scalar. 7605 if (LHSType->isScalarType()) { 7606 const VectorType *VecType = RHSType->getAs<VectorType>(); 7607 if (VecType && VecType->getNumElements() == 1 && 7608 isLaxVectorConversion(RHSType, LHSType)) { 7609 ExprResult *VecExpr = &RHS; 7610 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 7611 Kind = CK_BitCast; 7612 return Compatible; 7613 } 7614 } 7615 7616 return Incompatible; 7617 } 7618 7619 // Diagnose attempts to convert between __float128 and long double where 7620 // such conversions currently can't be handled. 7621 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 7622 return Incompatible; 7623 7624 // Disallow assigning a _Complex to a real type in C++ mode since it simply 7625 // discards the imaginary part. 7626 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 7627 !LHSType->getAs<ComplexType>()) 7628 return Incompatible; 7629 7630 // Arithmetic conversions. 7631 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 7632 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 7633 if (ConvertRHS) 7634 Kind = PrepareScalarCast(RHS, LHSType); 7635 return Compatible; 7636 } 7637 7638 // Conversions to normal pointers. 7639 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 7640 // U* -> T* 7641 if (isa<PointerType>(RHSType)) { 7642 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7643 unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 7644 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7645 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 7646 } 7647 7648 // int -> T* 7649 if (RHSType->isIntegerType()) { 7650 Kind = CK_IntegralToPointer; // FIXME: null? 7651 return IntToPointer; 7652 } 7653 7654 // C pointers are not compatible with ObjC object pointers, 7655 // with two exceptions: 7656 if (isa<ObjCObjectPointerType>(RHSType)) { 7657 // - conversions to void* 7658 if (LHSPointer->getPointeeType()->isVoidType()) { 7659 Kind = CK_BitCast; 7660 return Compatible; 7661 } 7662 7663 // - conversions from 'Class' to the redefinition type 7664 if (RHSType->isObjCClassType() && 7665 Context.hasSameType(LHSType, 7666 Context.getObjCClassRedefinitionType())) { 7667 Kind = CK_BitCast; 7668 return Compatible; 7669 } 7670 7671 Kind = CK_BitCast; 7672 return IncompatiblePointer; 7673 } 7674 7675 // U^ -> void* 7676 if (RHSType->getAs<BlockPointerType>()) { 7677 if (LHSPointer->getPointeeType()->isVoidType()) { 7678 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7679 unsigned AddrSpaceR = RHSType->getAs<BlockPointerType>() 7680 ->getPointeeType() 7681 .getAddressSpace(); 7682 Kind = 7683 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7684 return Compatible; 7685 } 7686 } 7687 7688 return Incompatible; 7689 } 7690 7691 // Conversions to block pointers. 7692 if (isa<BlockPointerType>(LHSType)) { 7693 // U^ -> T^ 7694 if (RHSType->isBlockPointerType()) { 7695 unsigned AddrSpaceL = LHSType->getAs<BlockPointerType>() 7696 ->getPointeeType() 7697 .getAddressSpace(); 7698 unsigned AddrSpaceR = RHSType->getAs<BlockPointerType>() 7699 ->getPointeeType() 7700 .getAddressSpace(); 7701 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7702 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 7703 } 7704 7705 // int or null -> T^ 7706 if (RHSType->isIntegerType()) { 7707 Kind = CK_IntegralToPointer; // FIXME: null 7708 return IntToBlockPointer; 7709 } 7710 7711 // id -> T^ 7712 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 7713 Kind = CK_AnyPointerToBlockPointerCast; 7714 return Compatible; 7715 } 7716 7717 // void* -> T^ 7718 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 7719 if (RHSPT->getPointeeType()->isVoidType()) { 7720 Kind = CK_AnyPointerToBlockPointerCast; 7721 return Compatible; 7722 } 7723 7724 return Incompatible; 7725 } 7726 7727 // Conversions to Objective-C pointers. 7728 if (isa<ObjCObjectPointerType>(LHSType)) { 7729 // A* -> B* 7730 if (RHSType->isObjCObjectPointerType()) { 7731 Kind = CK_BitCast; 7732 Sema::AssignConvertType result = 7733 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 7734 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 7735 result == Compatible && 7736 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 7737 result = IncompatibleObjCWeakRef; 7738 return result; 7739 } 7740 7741 // int or null -> A* 7742 if (RHSType->isIntegerType()) { 7743 Kind = CK_IntegralToPointer; // FIXME: null 7744 return IntToPointer; 7745 } 7746 7747 // In general, C pointers are not compatible with ObjC object pointers, 7748 // with two exceptions: 7749 if (isa<PointerType>(RHSType)) { 7750 Kind = CK_CPointerToObjCPointerCast; 7751 7752 // - conversions from 'void*' 7753 if (RHSType->isVoidPointerType()) { 7754 return Compatible; 7755 } 7756 7757 // - conversions to 'Class' from its redefinition type 7758 if (LHSType->isObjCClassType() && 7759 Context.hasSameType(RHSType, 7760 Context.getObjCClassRedefinitionType())) { 7761 return Compatible; 7762 } 7763 7764 return IncompatiblePointer; 7765 } 7766 7767 // Only under strict condition T^ is compatible with an Objective-C pointer. 7768 if (RHSType->isBlockPointerType() && 7769 LHSType->isBlockCompatibleObjCPointerType(Context)) { 7770 if (ConvertRHS) 7771 maybeExtendBlockObject(RHS); 7772 Kind = CK_BlockPointerToObjCPointerCast; 7773 return Compatible; 7774 } 7775 7776 return Incompatible; 7777 } 7778 7779 // Conversions from pointers that are not covered by the above. 7780 if (isa<PointerType>(RHSType)) { 7781 // T* -> _Bool 7782 if (LHSType == Context.BoolTy) { 7783 Kind = CK_PointerToBoolean; 7784 return Compatible; 7785 } 7786 7787 // T* -> int 7788 if (LHSType->isIntegerType()) { 7789 Kind = CK_PointerToIntegral; 7790 return PointerToInt; 7791 } 7792 7793 return Incompatible; 7794 } 7795 7796 // Conversions from Objective-C pointers that are not covered by the above. 7797 if (isa<ObjCObjectPointerType>(RHSType)) { 7798 // T* -> _Bool 7799 if (LHSType == Context.BoolTy) { 7800 Kind = CK_PointerToBoolean; 7801 return Compatible; 7802 } 7803 7804 // T* -> int 7805 if (LHSType->isIntegerType()) { 7806 Kind = CK_PointerToIntegral; 7807 return PointerToInt; 7808 } 7809 7810 return Incompatible; 7811 } 7812 7813 // struct A -> struct B 7814 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 7815 if (Context.typesAreCompatible(LHSType, RHSType)) { 7816 Kind = CK_NoOp; 7817 return Compatible; 7818 } 7819 } 7820 7821 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 7822 Kind = CK_IntToOCLSampler; 7823 return Compatible; 7824 } 7825 7826 return Incompatible; 7827 } 7828 7829 /// \brief Constructs a transparent union from an expression that is 7830 /// used to initialize the transparent union. 7831 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 7832 ExprResult &EResult, QualType UnionType, 7833 FieldDecl *Field) { 7834 // Build an initializer list that designates the appropriate member 7835 // of the transparent union. 7836 Expr *E = EResult.get(); 7837 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 7838 E, SourceLocation()); 7839 Initializer->setType(UnionType); 7840 Initializer->setInitializedFieldInUnion(Field); 7841 7842 // Build a compound literal constructing a value of the transparent 7843 // union type from this initializer list. 7844 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 7845 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 7846 VK_RValue, Initializer, false); 7847 } 7848 7849 Sema::AssignConvertType 7850 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 7851 ExprResult &RHS) { 7852 QualType RHSType = RHS.get()->getType(); 7853 7854 // If the ArgType is a Union type, we want to handle a potential 7855 // transparent_union GCC extension. 7856 const RecordType *UT = ArgType->getAsUnionType(); 7857 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 7858 return Incompatible; 7859 7860 // The field to initialize within the transparent union. 7861 RecordDecl *UD = UT->getDecl(); 7862 FieldDecl *InitField = nullptr; 7863 // It's compatible if the expression matches any of the fields. 7864 for (auto *it : UD->fields()) { 7865 if (it->getType()->isPointerType()) { 7866 // If the transparent union contains a pointer type, we allow: 7867 // 1) void pointer 7868 // 2) null pointer constant 7869 if (RHSType->isPointerType()) 7870 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 7871 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 7872 InitField = it; 7873 break; 7874 } 7875 7876 if (RHS.get()->isNullPointerConstant(Context, 7877 Expr::NPC_ValueDependentIsNull)) { 7878 RHS = ImpCastExprToType(RHS.get(), it->getType(), 7879 CK_NullToPointer); 7880 InitField = it; 7881 break; 7882 } 7883 } 7884 7885 CastKind Kind = CK_Invalid; 7886 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 7887 == Compatible) { 7888 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 7889 InitField = it; 7890 break; 7891 } 7892 } 7893 7894 if (!InitField) 7895 return Incompatible; 7896 7897 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 7898 return Compatible; 7899 } 7900 7901 Sema::AssignConvertType 7902 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 7903 bool Diagnose, 7904 bool DiagnoseCFAudited, 7905 bool ConvertRHS) { 7906 // We need to be able to tell the caller whether we diagnosed a problem, if 7907 // they ask us to issue diagnostics. 7908 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 7909 7910 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 7911 // we can't avoid *all* modifications at the moment, so we need some somewhere 7912 // to put the updated value. 7913 ExprResult LocalRHS = CallerRHS; 7914 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 7915 7916 if (getLangOpts().CPlusPlus) { 7917 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 7918 // C++ 5.17p3: If the left operand is not of class type, the 7919 // expression is implicitly converted (C++ 4) to the 7920 // cv-unqualified type of the left operand. 7921 QualType RHSType = RHS.get()->getType(); 7922 if (Diagnose) { 7923 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7924 AA_Assigning); 7925 } else { 7926 ImplicitConversionSequence ICS = 7927 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7928 /*SuppressUserConversions=*/false, 7929 /*AllowExplicit=*/false, 7930 /*InOverloadResolution=*/false, 7931 /*CStyle=*/false, 7932 /*AllowObjCWritebackConversion=*/false); 7933 if (ICS.isFailure()) 7934 return Incompatible; 7935 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7936 ICS, AA_Assigning); 7937 } 7938 if (RHS.isInvalid()) 7939 return Incompatible; 7940 Sema::AssignConvertType result = Compatible; 7941 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 7942 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 7943 result = IncompatibleObjCWeakRef; 7944 return result; 7945 } 7946 7947 // FIXME: Currently, we fall through and treat C++ classes like C 7948 // structures. 7949 // FIXME: We also fall through for atomics; not sure what should 7950 // happen there, though. 7951 } else if (RHS.get()->getType() == Context.OverloadTy) { 7952 // As a set of extensions to C, we support overloading on functions. These 7953 // functions need to be resolved here. 7954 DeclAccessPair DAP; 7955 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 7956 RHS.get(), LHSType, /*Complain=*/false, DAP)) 7957 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 7958 else 7959 return Incompatible; 7960 } 7961 7962 // C99 6.5.16.1p1: the left operand is a pointer and the right is 7963 // a null pointer constant. 7964 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 7965 LHSType->isBlockPointerType()) && 7966 RHS.get()->isNullPointerConstant(Context, 7967 Expr::NPC_ValueDependentIsNull)) { 7968 if (Diagnose || ConvertRHS) { 7969 CastKind Kind; 7970 CXXCastPath Path; 7971 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 7972 /*IgnoreBaseAccess=*/false, Diagnose); 7973 if (ConvertRHS) 7974 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 7975 } 7976 return Compatible; 7977 } 7978 7979 // This check seems unnatural, however it is necessary to ensure the proper 7980 // conversion of functions/arrays. If the conversion were done for all 7981 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 7982 // expressions that suppress this implicit conversion (&, sizeof). 7983 // 7984 // Suppress this for references: C++ 8.5.3p5. 7985 if (!LHSType->isReferenceType()) { 7986 // FIXME: We potentially allocate here even if ConvertRHS is false. 7987 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 7988 if (RHS.isInvalid()) 7989 return Incompatible; 7990 } 7991 7992 Expr *PRE = RHS.get()->IgnoreParenCasts(); 7993 if (Diagnose && isa<ObjCProtocolExpr>(PRE)) { 7994 ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol(); 7995 if (PDecl && !PDecl->hasDefinition()) { 7996 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName(); 7997 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl; 7998 } 7999 } 8000 8001 CastKind Kind = CK_Invalid; 8002 Sema::AssignConvertType result = 8003 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 8004 8005 // C99 6.5.16.1p2: The value of the right operand is converted to the 8006 // type of the assignment expression. 8007 // CheckAssignmentConstraints allows the left-hand side to be a reference, 8008 // so that we can use references in built-in functions even in C. 8009 // The getNonReferenceType() call makes sure that the resulting expression 8010 // does not have reference type. 8011 if (result != Incompatible && RHS.get()->getType() != LHSType) { 8012 QualType Ty = LHSType.getNonLValueExprType(Context); 8013 Expr *E = RHS.get(); 8014 8015 // Check for various Objective-C errors. If we are not reporting 8016 // diagnostics and just checking for errors, e.g., during overload 8017 // resolution, return Incompatible to indicate the failure. 8018 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8019 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 8020 Diagnose, DiagnoseCFAudited) != ACR_okay) { 8021 if (!Diagnose) 8022 return Incompatible; 8023 } 8024 if (getLangOpts().ObjC1 && 8025 (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType, 8026 E->getType(), E, Diagnose) || 8027 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 8028 if (!Diagnose) 8029 return Incompatible; 8030 // Replace the expression with a corrected version and continue so we 8031 // can find further errors. 8032 RHS = E; 8033 return Compatible; 8034 } 8035 8036 if (ConvertRHS) 8037 RHS = ImpCastExprToType(E, Ty, Kind); 8038 } 8039 return result; 8040 } 8041 8042 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 8043 ExprResult &RHS) { 8044 Diag(Loc, diag::err_typecheck_invalid_operands) 8045 << LHS.get()->getType() << RHS.get()->getType() 8046 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8047 return QualType(); 8048 } 8049 8050 // Diagnose cases where a scalar was implicitly converted to a vector and 8051 // diagnose the underlying types. Otherwise, diagnose the error 8052 // as invalid vector logical operands for non-C++ cases. 8053 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 8054 ExprResult &RHS) { 8055 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 8056 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 8057 8058 bool LHSNatVec = LHSType->isVectorType(); 8059 bool RHSNatVec = RHSType->isVectorType(); 8060 8061 if (!(LHSNatVec && RHSNatVec)) { 8062 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 8063 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 8064 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8065 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 8066 << Vector->getSourceRange(); 8067 return QualType(); 8068 } 8069 8070 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8071 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 8072 << RHS.get()->getSourceRange(); 8073 8074 return QualType(); 8075 } 8076 8077 /// Try to convert a value of non-vector type to a vector type by converting 8078 /// the type to the element type of the vector and then performing a splat. 8079 /// If the language is OpenCL, we only use conversions that promote scalar 8080 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 8081 /// for float->int. 8082 /// 8083 /// OpenCL V2.0 6.2.6.p2: 8084 /// An error shall occur if any scalar operand type has greater rank 8085 /// than the type of the vector element. 8086 /// 8087 /// \param scalar - if non-null, actually perform the conversions 8088 /// \return true if the operation fails (but without diagnosing the failure) 8089 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 8090 QualType scalarTy, 8091 QualType vectorEltTy, 8092 QualType vectorTy, 8093 unsigned &DiagID) { 8094 // The conversion to apply to the scalar before splatting it, 8095 // if necessary. 8096 CastKind scalarCast = CK_Invalid; 8097 8098 if (vectorEltTy->isIntegralType(S.Context)) { 8099 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 8100 (scalarTy->isIntegerType() && 8101 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 8102 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8103 return true; 8104 } 8105 if (!scalarTy->isIntegralType(S.Context)) 8106 return true; 8107 scalarCast = CK_IntegralCast; 8108 } else if (vectorEltTy->isRealFloatingType()) { 8109 if (scalarTy->isRealFloatingType()) { 8110 if (S.getLangOpts().OpenCL && 8111 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 8112 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8113 return true; 8114 } 8115 scalarCast = CK_FloatingCast; 8116 } 8117 else if (scalarTy->isIntegralType(S.Context)) 8118 scalarCast = CK_IntegralToFloating; 8119 else 8120 return true; 8121 } else { 8122 return true; 8123 } 8124 8125 // Adjust scalar if desired. 8126 if (scalar) { 8127 if (scalarCast != CK_Invalid) 8128 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 8129 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 8130 } 8131 return false; 8132 } 8133 8134 /// Test if a (constant) integer Int can be casted to another integer type 8135 /// IntTy without losing precision. 8136 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 8137 QualType OtherIntTy) { 8138 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8139 8140 // Reject cases where the value of the Int is unknown as that would 8141 // possibly cause truncation, but accept cases where the scalar can be 8142 // demoted without loss of precision. 8143 llvm::APSInt Result; 8144 bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context); 8145 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 8146 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 8147 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 8148 8149 if (CstInt) { 8150 // If the scalar is constant and is of a higher order and has more active 8151 // bits that the vector element type, reject it. 8152 unsigned NumBits = IntSigned 8153 ? (Result.isNegative() ? Result.getMinSignedBits() 8154 : Result.getActiveBits()) 8155 : Result.getActiveBits(); 8156 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 8157 return true; 8158 8159 // If the signedness of the scalar type and the vector element type 8160 // differs and the number of bits is greater than that of the vector 8161 // element reject it. 8162 return (IntSigned != OtherIntSigned && 8163 NumBits > S.Context.getIntWidth(OtherIntTy)); 8164 } 8165 8166 // Reject cases where the value of the scalar is not constant and it's 8167 // order is greater than that of the vector element type. 8168 return (Order < 0); 8169 } 8170 8171 /// Test if a (constant) integer Int can be casted to floating point type 8172 /// FloatTy without losing precision. 8173 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 8174 QualType FloatTy) { 8175 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8176 8177 // Determine if the integer constant can be expressed as a floating point 8178 // number of the appropiate type. 8179 llvm::APSInt Result; 8180 bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context); 8181 uint64_t Bits = 0; 8182 if (CstInt) { 8183 // Reject constants that would be truncated if they were converted to 8184 // the floating point type. Test by simple to/from conversion. 8185 // FIXME: Ideally the conversion to an APFloat and from an APFloat 8186 // could be avoided if there was a convertFromAPInt method 8187 // which could signal back if implicit truncation occurred. 8188 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 8189 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 8190 llvm::APFloat::rmTowardZero); 8191 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 8192 !IntTy->hasSignedIntegerRepresentation()); 8193 bool Ignored = false; 8194 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 8195 &Ignored); 8196 if (Result != ConvertBack) 8197 return true; 8198 } else { 8199 // Reject types that cannot be fully encoded into the mantissa of 8200 // the float. 8201 Bits = S.Context.getTypeSize(IntTy); 8202 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 8203 S.Context.getFloatTypeSemantics(FloatTy)); 8204 if (Bits > FloatPrec) 8205 return true; 8206 } 8207 8208 return false; 8209 } 8210 8211 /// Attempt to convert and splat Scalar into a vector whose types matches 8212 /// Vector following GCC conversion rules. The rule is that implicit 8213 /// conversion can occur when Scalar can be casted to match Vector's element 8214 /// type without causing truncation of Scalar. 8215 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 8216 ExprResult *Vector) { 8217 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 8218 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 8219 const VectorType *VT = VectorTy->getAs<VectorType>(); 8220 8221 assert(!isa<ExtVectorType>(VT) && 8222 "ExtVectorTypes should not be handled here!"); 8223 8224 QualType VectorEltTy = VT->getElementType(); 8225 8226 // Reject cases where the vector element type or the scalar element type are 8227 // not integral or floating point types. 8228 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 8229 return true; 8230 8231 // The conversion to apply to the scalar before splatting it, 8232 // if necessary. 8233 CastKind ScalarCast = CK_NoOp; 8234 8235 // Accept cases where the vector elements are integers and the scalar is 8236 // an integer. 8237 // FIXME: Notionally if the scalar was a floating point value with a precise 8238 // integral representation, we could cast it to an appropriate integer 8239 // type and then perform the rest of the checks here. GCC will perform 8240 // this conversion in some cases as determined by the input language. 8241 // We should accept it on a language independent basis. 8242 if (VectorEltTy->isIntegralType(S.Context) && 8243 ScalarTy->isIntegralType(S.Context) && 8244 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 8245 8246 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 8247 return true; 8248 8249 ScalarCast = CK_IntegralCast; 8250 } else if (VectorEltTy->isRealFloatingType()) { 8251 if (ScalarTy->isRealFloatingType()) { 8252 8253 // Reject cases where the scalar type is not a constant and has a higher 8254 // Order than the vector element type. 8255 llvm::APFloat Result(0.0); 8256 bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context); 8257 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 8258 if (!CstScalar && Order < 0) 8259 return true; 8260 8261 // If the scalar cannot be safely casted to the vector element type, 8262 // reject it. 8263 if (CstScalar) { 8264 bool Truncated = false; 8265 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 8266 llvm::APFloat::rmNearestTiesToEven, &Truncated); 8267 if (Truncated) 8268 return true; 8269 } 8270 8271 ScalarCast = CK_FloatingCast; 8272 } else if (ScalarTy->isIntegralType(S.Context)) { 8273 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 8274 return true; 8275 8276 ScalarCast = CK_IntegralToFloating; 8277 } else 8278 return true; 8279 } 8280 8281 // Adjust scalar if desired. 8282 if (Scalar) { 8283 if (ScalarCast != CK_NoOp) 8284 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 8285 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 8286 } 8287 return false; 8288 } 8289 8290 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 8291 SourceLocation Loc, bool IsCompAssign, 8292 bool AllowBothBool, 8293 bool AllowBoolConversions) { 8294 if (!IsCompAssign) { 8295 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 8296 if (LHS.isInvalid()) 8297 return QualType(); 8298 } 8299 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 8300 if (RHS.isInvalid()) 8301 return QualType(); 8302 8303 // For conversion purposes, we ignore any qualifiers. 8304 // For example, "const float" and "float" are equivalent. 8305 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 8306 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 8307 8308 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 8309 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 8310 assert(LHSVecType || RHSVecType); 8311 8312 // AltiVec-style "vector bool op vector bool" combinations are allowed 8313 // for some operators but not others. 8314 if (!AllowBothBool && 8315 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8316 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8317 return InvalidOperands(Loc, LHS, RHS); 8318 8319 // If the vector types are identical, return. 8320 if (Context.hasSameType(LHSType, RHSType)) 8321 return LHSType; 8322 8323 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 8324 if (LHSVecType && RHSVecType && 8325 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8326 if (isa<ExtVectorType>(LHSVecType)) { 8327 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8328 return LHSType; 8329 } 8330 8331 if (!IsCompAssign) 8332 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8333 return RHSType; 8334 } 8335 8336 // AllowBoolConversions says that bool and non-bool AltiVec vectors 8337 // can be mixed, with the result being the non-bool type. The non-bool 8338 // operand must have integer element type. 8339 if (AllowBoolConversions && LHSVecType && RHSVecType && 8340 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 8341 (Context.getTypeSize(LHSVecType->getElementType()) == 8342 Context.getTypeSize(RHSVecType->getElementType()))) { 8343 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 8344 LHSVecType->getElementType()->isIntegerType() && 8345 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 8346 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8347 return LHSType; 8348 } 8349 if (!IsCompAssign && 8350 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8351 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 8352 RHSVecType->getElementType()->isIntegerType()) { 8353 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8354 return RHSType; 8355 } 8356 } 8357 8358 // If there's a vector type and a scalar, try to convert the scalar to 8359 // the vector element type and splat. 8360 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 8361 if (!RHSVecType) { 8362 if (isa<ExtVectorType>(LHSVecType)) { 8363 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 8364 LHSVecType->getElementType(), LHSType, 8365 DiagID)) 8366 return LHSType; 8367 } else { 8368 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 8369 return LHSType; 8370 } 8371 } 8372 if (!LHSVecType) { 8373 if (isa<ExtVectorType>(RHSVecType)) { 8374 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 8375 LHSType, RHSVecType->getElementType(), 8376 RHSType, DiagID)) 8377 return RHSType; 8378 } else { 8379 if (LHS.get()->getValueKind() == VK_LValue || 8380 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 8381 return RHSType; 8382 } 8383 } 8384 8385 // FIXME: The code below also handles conversion between vectors and 8386 // non-scalars, we should break this down into fine grained specific checks 8387 // and emit proper diagnostics. 8388 QualType VecType = LHSVecType ? LHSType : RHSType; 8389 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 8390 QualType OtherType = LHSVecType ? RHSType : LHSType; 8391 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 8392 if (isLaxVectorConversion(OtherType, VecType)) { 8393 // If we're allowing lax vector conversions, only the total (data) size 8394 // needs to be the same. For non compound assignment, if one of the types is 8395 // scalar, the result is always the vector type. 8396 if (!IsCompAssign) { 8397 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 8398 return VecType; 8399 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 8400 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 8401 // type. Note that this is already done by non-compound assignments in 8402 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 8403 // <1 x T> -> T. The result is also a vector type. 8404 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 8405 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 8406 ExprResult *RHSExpr = &RHS; 8407 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 8408 return VecType; 8409 } 8410 } 8411 8412 // Okay, the expression is invalid. 8413 8414 // If there's a non-vector, non-real operand, diagnose that. 8415 if ((!RHSVecType && !RHSType->isRealType()) || 8416 (!LHSVecType && !LHSType->isRealType())) { 8417 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 8418 << LHSType << RHSType 8419 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8420 return QualType(); 8421 } 8422 8423 // OpenCL V1.1 6.2.6.p1: 8424 // If the operands are of more than one vector type, then an error shall 8425 // occur. Implicit conversions between vector types are not permitted, per 8426 // section 6.2.1. 8427 if (getLangOpts().OpenCL && 8428 RHSVecType && isa<ExtVectorType>(RHSVecType) && 8429 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 8430 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 8431 << RHSType; 8432 return QualType(); 8433 } 8434 8435 8436 // If there is a vector type that is not a ExtVector and a scalar, we reach 8437 // this point if scalar could not be converted to the vector's element type 8438 // without truncation. 8439 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 8440 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 8441 QualType Scalar = LHSVecType ? RHSType : LHSType; 8442 QualType Vector = LHSVecType ? LHSType : RHSType; 8443 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 8444 Diag(Loc, 8445 diag::err_typecheck_vector_not_convertable_implict_truncation) 8446 << ScalarOrVector << Scalar << Vector; 8447 8448 return QualType(); 8449 } 8450 8451 // Otherwise, use the generic diagnostic. 8452 Diag(Loc, DiagID) 8453 << LHSType << RHSType 8454 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8455 return QualType(); 8456 } 8457 8458 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 8459 // expression. These are mainly cases where the null pointer is used as an 8460 // integer instead of a pointer. 8461 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 8462 SourceLocation Loc, bool IsCompare) { 8463 // The canonical way to check for a GNU null is with isNullPointerConstant, 8464 // but we use a bit of a hack here for speed; this is a relatively 8465 // hot path, and isNullPointerConstant is slow. 8466 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 8467 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 8468 8469 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 8470 8471 // Avoid analyzing cases where the result will either be invalid (and 8472 // diagnosed as such) or entirely valid and not something to warn about. 8473 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 8474 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 8475 return; 8476 8477 // Comparison operations would not make sense with a null pointer no matter 8478 // what the other expression is. 8479 if (!IsCompare) { 8480 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 8481 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 8482 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 8483 return; 8484 } 8485 8486 // The rest of the operations only make sense with a null pointer 8487 // if the other expression is a pointer. 8488 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 8489 NonNullType->canDecayToPointerType()) 8490 return; 8491 8492 S.Diag(Loc, diag::warn_null_in_comparison_operation) 8493 << LHSNull /* LHS is NULL */ << NonNullType 8494 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8495 } 8496 8497 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 8498 ExprResult &RHS, 8499 SourceLocation Loc, bool IsDiv) { 8500 // Check for division/remainder by zero. 8501 llvm::APSInt RHSValue; 8502 if (!RHS.get()->isValueDependent() && 8503 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0) 8504 S.DiagRuntimeBehavior(Loc, RHS.get(), 8505 S.PDiag(diag::warn_remainder_division_by_zero) 8506 << IsDiv << RHS.get()->getSourceRange()); 8507 } 8508 8509 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 8510 SourceLocation Loc, 8511 bool IsCompAssign, bool IsDiv) { 8512 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8513 8514 if (LHS.get()->getType()->isVectorType() || 8515 RHS.get()->getType()->isVectorType()) 8516 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8517 /*AllowBothBool*/getLangOpts().AltiVec, 8518 /*AllowBoolConversions*/false); 8519 8520 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8521 if (LHS.isInvalid() || RHS.isInvalid()) 8522 return QualType(); 8523 8524 8525 if (compType.isNull() || !compType->isArithmeticType()) 8526 return InvalidOperands(Loc, LHS, RHS); 8527 if (IsDiv) 8528 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 8529 return compType; 8530 } 8531 8532 QualType Sema::CheckRemainderOperands( 8533 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 8534 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8535 8536 if (LHS.get()->getType()->isVectorType() || 8537 RHS.get()->getType()->isVectorType()) { 8538 if (LHS.get()->getType()->hasIntegerRepresentation() && 8539 RHS.get()->getType()->hasIntegerRepresentation()) 8540 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8541 /*AllowBothBool*/getLangOpts().AltiVec, 8542 /*AllowBoolConversions*/false); 8543 return InvalidOperands(Loc, LHS, RHS); 8544 } 8545 8546 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8547 if (LHS.isInvalid() || RHS.isInvalid()) 8548 return QualType(); 8549 8550 if (compType.isNull() || !compType->isIntegerType()) 8551 return InvalidOperands(Loc, LHS, RHS); 8552 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 8553 return compType; 8554 } 8555 8556 /// \brief Diagnose invalid arithmetic on two void pointers. 8557 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 8558 Expr *LHSExpr, Expr *RHSExpr) { 8559 S.Diag(Loc, S.getLangOpts().CPlusPlus 8560 ? diag::err_typecheck_pointer_arith_void_type 8561 : diag::ext_gnu_void_ptr) 8562 << 1 /* two pointers */ << LHSExpr->getSourceRange() 8563 << RHSExpr->getSourceRange(); 8564 } 8565 8566 /// \brief Diagnose invalid arithmetic on a void pointer. 8567 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 8568 Expr *Pointer) { 8569 S.Diag(Loc, S.getLangOpts().CPlusPlus 8570 ? diag::err_typecheck_pointer_arith_void_type 8571 : diag::ext_gnu_void_ptr) 8572 << 0 /* one pointer */ << Pointer->getSourceRange(); 8573 } 8574 8575 /// \brief Diagnose invalid arithmetic on a null pointer. 8576 /// 8577 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 8578 /// idiom, which we recognize as a GNU extension. 8579 /// 8580 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 8581 Expr *Pointer, bool IsGNUIdiom) { 8582 if (IsGNUIdiom) 8583 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 8584 << Pointer->getSourceRange(); 8585 else 8586 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 8587 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 8588 } 8589 8590 /// \brief Diagnose invalid arithmetic on two function pointers. 8591 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 8592 Expr *LHS, Expr *RHS) { 8593 assert(LHS->getType()->isAnyPointerType()); 8594 assert(RHS->getType()->isAnyPointerType()); 8595 S.Diag(Loc, S.getLangOpts().CPlusPlus 8596 ? diag::err_typecheck_pointer_arith_function_type 8597 : diag::ext_gnu_ptr_func_arith) 8598 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 8599 // We only show the second type if it differs from the first. 8600 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 8601 RHS->getType()) 8602 << RHS->getType()->getPointeeType() 8603 << LHS->getSourceRange() << RHS->getSourceRange(); 8604 } 8605 8606 /// \brief Diagnose invalid arithmetic on a function pointer. 8607 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 8608 Expr *Pointer) { 8609 assert(Pointer->getType()->isAnyPointerType()); 8610 S.Diag(Loc, S.getLangOpts().CPlusPlus 8611 ? diag::err_typecheck_pointer_arith_function_type 8612 : diag::ext_gnu_ptr_func_arith) 8613 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 8614 << 0 /* one pointer, so only one type */ 8615 << Pointer->getSourceRange(); 8616 } 8617 8618 /// \brief Emit error if Operand is incomplete pointer type 8619 /// 8620 /// \returns True if pointer has incomplete type 8621 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 8622 Expr *Operand) { 8623 QualType ResType = Operand->getType(); 8624 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8625 ResType = ResAtomicType->getValueType(); 8626 8627 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 8628 QualType PointeeTy = ResType->getPointeeType(); 8629 return S.RequireCompleteType(Loc, PointeeTy, 8630 diag::err_typecheck_arithmetic_incomplete_type, 8631 PointeeTy, Operand->getSourceRange()); 8632 } 8633 8634 /// \brief Check the validity of an arithmetic pointer operand. 8635 /// 8636 /// If the operand has pointer type, this code will check for pointer types 8637 /// which are invalid in arithmetic operations. These will be diagnosed 8638 /// appropriately, including whether or not the use is supported as an 8639 /// extension. 8640 /// 8641 /// \returns True when the operand is valid to use (even if as an extension). 8642 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 8643 Expr *Operand) { 8644 QualType ResType = Operand->getType(); 8645 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8646 ResType = ResAtomicType->getValueType(); 8647 8648 if (!ResType->isAnyPointerType()) return true; 8649 8650 QualType PointeeTy = ResType->getPointeeType(); 8651 if (PointeeTy->isVoidType()) { 8652 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 8653 return !S.getLangOpts().CPlusPlus; 8654 } 8655 if (PointeeTy->isFunctionType()) { 8656 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 8657 return !S.getLangOpts().CPlusPlus; 8658 } 8659 8660 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 8661 8662 return true; 8663 } 8664 8665 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 8666 /// operands. 8667 /// 8668 /// This routine will diagnose any invalid arithmetic on pointer operands much 8669 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 8670 /// for emitting a single diagnostic even for operations where both LHS and RHS 8671 /// are (potentially problematic) pointers. 8672 /// 8673 /// \returns True when the operand is valid to use (even if as an extension). 8674 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 8675 Expr *LHSExpr, Expr *RHSExpr) { 8676 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 8677 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 8678 if (!isLHSPointer && !isRHSPointer) return true; 8679 8680 QualType LHSPointeeTy, RHSPointeeTy; 8681 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 8682 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 8683 8684 // if both are pointers check if operation is valid wrt address spaces 8685 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 8686 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 8687 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 8688 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 8689 S.Diag(Loc, 8690 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8691 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 8692 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 8693 return false; 8694 } 8695 } 8696 8697 // Check for arithmetic on pointers to incomplete types. 8698 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 8699 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 8700 if (isLHSVoidPtr || isRHSVoidPtr) { 8701 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 8702 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 8703 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 8704 8705 return !S.getLangOpts().CPlusPlus; 8706 } 8707 8708 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 8709 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 8710 if (isLHSFuncPtr || isRHSFuncPtr) { 8711 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 8712 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 8713 RHSExpr); 8714 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 8715 8716 return !S.getLangOpts().CPlusPlus; 8717 } 8718 8719 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 8720 return false; 8721 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 8722 return false; 8723 8724 return true; 8725 } 8726 8727 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 8728 /// literal. 8729 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 8730 Expr *LHSExpr, Expr *RHSExpr) { 8731 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 8732 Expr* IndexExpr = RHSExpr; 8733 if (!StrExpr) { 8734 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 8735 IndexExpr = LHSExpr; 8736 } 8737 8738 bool IsStringPlusInt = StrExpr && 8739 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 8740 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 8741 return; 8742 8743 llvm::APSInt index; 8744 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 8745 unsigned StrLenWithNull = StrExpr->getLength() + 1; 8746 if (index.isNonNegative() && 8747 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 8748 index.isUnsigned())) 8749 return; 8750 } 8751 8752 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8753 Self.Diag(OpLoc, diag::warn_string_plus_int) 8754 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 8755 8756 // Only print a fixit for "str" + int, not for int + "str". 8757 if (IndexExpr == RHSExpr) { 8758 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8759 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8760 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8761 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8762 << FixItHint::CreateInsertion(EndLoc, "]"); 8763 } else 8764 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8765 } 8766 8767 /// \brief Emit a warning when adding a char literal to a string. 8768 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 8769 Expr *LHSExpr, Expr *RHSExpr) { 8770 const Expr *StringRefExpr = LHSExpr; 8771 const CharacterLiteral *CharExpr = 8772 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 8773 8774 if (!CharExpr) { 8775 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 8776 StringRefExpr = RHSExpr; 8777 } 8778 8779 if (!CharExpr || !StringRefExpr) 8780 return; 8781 8782 const QualType StringType = StringRefExpr->getType(); 8783 8784 // Return if not a PointerType. 8785 if (!StringType->isAnyPointerType()) 8786 return; 8787 8788 // Return if not a CharacterType. 8789 if (!StringType->getPointeeType()->isAnyCharacterType()) 8790 return; 8791 8792 ASTContext &Ctx = Self.getASTContext(); 8793 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8794 8795 const QualType CharType = CharExpr->getType(); 8796 if (!CharType->isAnyCharacterType() && 8797 CharType->isIntegerType() && 8798 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 8799 Self.Diag(OpLoc, diag::warn_string_plus_char) 8800 << DiagRange << Ctx.CharTy; 8801 } else { 8802 Self.Diag(OpLoc, diag::warn_string_plus_char) 8803 << DiagRange << CharExpr->getType(); 8804 } 8805 8806 // Only print a fixit for str + char, not for char + str. 8807 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 8808 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8809 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8810 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8811 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8812 << FixItHint::CreateInsertion(EndLoc, "]"); 8813 } else { 8814 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8815 } 8816 } 8817 8818 /// \brief Emit error when two pointers are incompatible. 8819 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 8820 Expr *LHSExpr, Expr *RHSExpr) { 8821 assert(LHSExpr->getType()->isAnyPointerType()); 8822 assert(RHSExpr->getType()->isAnyPointerType()); 8823 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 8824 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 8825 << RHSExpr->getSourceRange(); 8826 } 8827 8828 // C99 6.5.6 8829 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 8830 SourceLocation Loc, BinaryOperatorKind Opc, 8831 QualType* CompLHSTy) { 8832 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8833 8834 if (LHS.get()->getType()->isVectorType() || 8835 RHS.get()->getType()->isVectorType()) { 8836 QualType compType = CheckVectorOperands( 8837 LHS, RHS, Loc, CompLHSTy, 8838 /*AllowBothBool*/getLangOpts().AltiVec, 8839 /*AllowBoolConversions*/getLangOpts().ZVector); 8840 if (CompLHSTy) *CompLHSTy = compType; 8841 return compType; 8842 } 8843 8844 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8845 if (LHS.isInvalid() || RHS.isInvalid()) 8846 return QualType(); 8847 8848 // Diagnose "string literal" '+' int and string '+' "char literal". 8849 if (Opc == BO_Add) { 8850 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 8851 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 8852 } 8853 8854 // handle the common case first (both operands are arithmetic). 8855 if (!compType.isNull() && compType->isArithmeticType()) { 8856 if (CompLHSTy) *CompLHSTy = compType; 8857 return compType; 8858 } 8859 8860 // Type-checking. Ultimately the pointer's going to be in PExp; 8861 // note that we bias towards the LHS being the pointer. 8862 Expr *PExp = LHS.get(), *IExp = RHS.get(); 8863 8864 bool isObjCPointer; 8865 if (PExp->getType()->isPointerType()) { 8866 isObjCPointer = false; 8867 } else if (PExp->getType()->isObjCObjectPointerType()) { 8868 isObjCPointer = true; 8869 } else { 8870 std::swap(PExp, IExp); 8871 if (PExp->getType()->isPointerType()) { 8872 isObjCPointer = false; 8873 } else if (PExp->getType()->isObjCObjectPointerType()) { 8874 isObjCPointer = true; 8875 } else { 8876 return InvalidOperands(Loc, LHS, RHS); 8877 } 8878 } 8879 assert(PExp->getType()->isAnyPointerType()); 8880 8881 if (!IExp->getType()->isIntegerType()) 8882 return InvalidOperands(Loc, LHS, RHS); 8883 8884 // Adding to a null pointer results in undefined behavior. 8885 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 8886 Context, Expr::NPC_ValueDependentIsNotNull)) { 8887 // In C++ adding zero to a null pointer is defined. 8888 llvm::APSInt KnownVal; 8889 if (!getLangOpts().CPlusPlus || 8890 (!IExp->isValueDependent() && 8891 (!IExp->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) { 8892 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 8893 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 8894 Context, BO_Add, PExp, IExp); 8895 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 8896 } 8897 } 8898 8899 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 8900 return QualType(); 8901 8902 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 8903 return QualType(); 8904 8905 // Check array bounds for pointer arithemtic 8906 CheckArrayAccess(PExp, IExp); 8907 8908 if (CompLHSTy) { 8909 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 8910 if (LHSTy.isNull()) { 8911 LHSTy = LHS.get()->getType(); 8912 if (LHSTy->isPromotableIntegerType()) 8913 LHSTy = Context.getPromotedIntegerType(LHSTy); 8914 } 8915 *CompLHSTy = LHSTy; 8916 } 8917 8918 return PExp->getType(); 8919 } 8920 8921 // C99 6.5.6 8922 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 8923 SourceLocation Loc, 8924 QualType* CompLHSTy) { 8925 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8926 8927 if (LHS.get()->getType()->isVectorType() || 8928 RHS.get()->getType()->isVectorType()) { 8929 QualType compType = CheckVectorOperands( 8930 LHS, RHS, Loc, CompLHSTy, 8931 /*AllowBothBool*/getLangOpts().AltiVec, 8932 /*AllowBoolConversions*/getLangOpts().ZVector); 8933 if (CompLHSTy) *CompLHSTy = compType; 8934 return compType; 8935 } 8936 8937 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8938 if (LHS.isInvalid() || RHS.isInvalid()) 8939 return QualType(); 8940 8941 // Enforce type constraints: C99 6.5.6p3. 8942 8943 // Handle the common case first (both operands are arithmetic). 8944 if (!compType.isNull() && compType->isArithmeticType()) { 8945 if (CompLHSTy) *CompLHSTy = compType; 8946 return compType; 8947 } 8948 8949 // Either ptr - int or ptr - ptr. 8950 if (LHS.get()->getType()->isAnyPointerType()) { 8951 QualType lpointee = LHS.get()->getType()->getPointeeType(); 8952 8953 // Diagnose bad cases where we step over interface counts. 8954 if (LHS.get()->getType()->isObjCObjectPointerType() && 8955 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 8956 return QualType(); 8957 8958 // The result type of a pointer-int computation is the pointer type. 8959 if (RHS.get()->getType()->isIntegerType()) { 8960 // Subtracting from a null pointer should produce a warning. 8961 // The last argument to the diagnose call says this doesn't match the 8962 // GNU int-to-pointer idiom. 8963 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 8964 Expr::NPC_ValueDependentIsNotNull)) { 8965 // In C++ adding zero to a null pointer is defined. 8966 llvm::APSInt KnownVal; 8967 if (!getLangOpts().CPlusPlus || 8968 (!RHS.get()->isValueDependent() && 8969 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) { 8970 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 8971 } 8972 } 8973 8974 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 8975 return QualType(); 8976 8977 // Check array bounds for pointer arithemtic 8978 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 8979 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 8980 8981 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8982 return LHS.get()->getType(); 8983 } 8984 8985 // Handle pointer-pointer subtractions. 8986 if (const PointerType *RHSPTy 8987 = RHS.get()->getType()->getAs<PointerType>()) { 8988 QualType rpointee = RHSPTy->getPointeeType(); 8989 8990 if (getLangOpts().CPlusPlus) { 8991 // Pointee types must be the same: C++ [expr.add] 8992 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 8993 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8994 } 8995 } else { 8996 // Pointee types must be compatible C99 6.5.6p3 8997 if (!Context.typesAreCompatible( 8998 Context.getCanonicalType(lpointee).getUnqualifiedType(), 8999 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 9000 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9001 return QualType(); 9002 } 9003 } 9004 9005 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 9006 LHS.get(), RHS.get())) 9007 return QualType(); 9008 9009 // FIXME: Add warnings for nullptr - ptr. 9010 9011 // The pointee type may have zero size. As an extension, a structure or 9012 // union may have zero size or an array may have zero length. In this 9013 // case subtraction does not make sense. 9014 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 9015 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 9016 if (ElementSize.isZero()) { 9017 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 9018 << rpointee.getUnqualifiedType() 9019 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9020 } 9021 } 9022 9023 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9024 return Context.getPointerDiffType(); 9025 } 9026 } 9027 9028 return InvalidOperands(Loc, LHS, RHS); 9029 } 9030 9031 static bool isScopedEnumerationType(QualType T) { 9032 if (const EnumType *ET = T->getAs<EnumType>()) 9033 return ET->getDecl()->isScoped(); 9034 return false; 9035 } 9036 9037 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 9038 SourceLocation Loc, BinaryOperatorKind Opc, 9039 QualType LHSType) { 9040 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 9041 // so skip remaining warnings as we don't want to modify values within Sema. 9042 if (S.getLangOpts().OpenCL) 9043 return; 9044 9045 llvm::APSInt Right; 9046 // Check right/shifter operand 9047 if (RHS.get()->isValueDependent() || 9048 !RHS.get()->EvaluateAsInt(Right, S.Context)) 9049 return; 9050 9051 if (Right.isNegative()) { 9052 S.DiagRuntimeBehavior(Loc, RHS.get(), 9053 S.PDiag(diag::warn_shift_negative) 9054 << RHS.get()->getSourceRange()); 9055 return; 9056 } 9057 llvm::APInt LeftBits(Right.getBitWidth(), 9058 S.Context.getTypeSize(LHS.get()->getType())); 9059 if (Right.uge(LeftBits)) { 9060 S.DiagRuntimeBehavior(Loc, RHS.get(), 9061 S.PDiag(diag::warn_shift_gt_typewidth) 9062 << RHS.get()->getSourceRange()); 9063 return; 9064 } 9065 if (Opc != BO_Shl) 9066 return; 9067 9068 // When left shifting an ICE which is signed, we can check for overflow which 9069 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 9070 // integers have defined behavior modulo one more than the maximum value 9071 // representable in the result type, so never warn for those. 9072 llvm::APSInt Left; 9073 if (LHS.get()->isValueDependent() || 9074 LHSType->hasUnsignedIntegerRepresentation() || 9075 !LHS.get()->EvaluateAsInt(Left, S.Context)) 9076 return; 9077 9078 // If LHS does not have a signed type and non-negative value 9079 // then, the behavior is undefined. Warn about it. 9080 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) { 9081 S.DiagRuntimeBehavior(Loc, LHS.get(), 9082 S.PDiag(diag::warn_shift_lhs_negative) 9083 << LHS.get()->getSourceRange()); 9084 return; 9085 } 9086 9087 llvm::APInt ResultBits = 9088 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 9089 if (LeftBits.uge(ResultBits)) 9090 return; 9091 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 9092 Result = Result.shl(Right); 9093 9094 // Print the bit representation of the signed integer as an unsigned 9095 // hexadecimal number. 9096 SmallString<40> HexResult; 9097 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 9098 9099 // If we are only missing a sign bit, this is less likely to result in actual 9100 // bugs -- if the result is cast back to an unsigned type, it will have the 9101 // expected value. Thus we place this behind a different warning that can be 9102 // turned off separately if needed. 9103 if (LeftBits == ResultBits - 1) { 9104 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 9105 << HexResult << LHSType 9106 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9107 return; 9108 } 9109 9110 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 9111 << HexResult.str() << Result.getMinSignedBits() << LHSType 9112 << Left.getBitWidth() << LHS.get()->getSourceRange() 9113 << RHS.get()->getSourceRange(); 9114 } 9115 9116 /// \brief Return the resulting type when a vector is shifted 9117 /// by a scalar or vector shift amount. 9118 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 9119 SourceLocation Loc, bool IsCompAssign) { 9120 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 9121 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 9122 !LHS.get()->getType()->isVectorType()) { 9123 S.Diag(Loc, diag::err_shift_rhs_only_vector) 9124 << RHS.get()->getType() << LHS.get()->getType() 9125 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9126 return QualType(); 9127 } 9128 9129 if (!IsCompAssign) { 9130 LHS = S.UsualUnaryConversions(LHS.get()); 9131 if (LHS.isInvalid()) return QualType(); 9132 } 9133 9134 RHS = S.UsualUnaryConversions(RHS.get()); 9135 if (RHS.isInvalid()) return QualType(); 9136 9137 QualType LHSType = LHS.get()->getType(); 9138 // Note that LHS might be a scalar because the routine calls not only in 9139 // OpenCL case. 9140 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 9141 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 9142 9143 // Note that RHS might not be a vector. 9144 QualType RHSType = RHS.get()->getType(); 9145 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 9146 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 9147 9148 // The operands need to be integers. 9149 if (!LHSEleType->isIntegerType()) { 9150 S.Diag(Loc, diag::err_typecheck_expect_int) 9151 << LHS.get()->getType() << LHS.get()->getSourceRange(); 9152 return QualType(); 9153 } 9154 9155 if (!RHSEleType->isIntegerType()) { 9156 S.Diag(Loc, diag::err_typecheck_expect_int) 9157 << RHS.get()->getType() << RHS.get()->getSourceRange(); 9158 return QualType(); 9159 } 9160 9161 if (!LHSVecTy) { 9162 assert(RHSVecTy); 9163 if (IsCompAssign) 9164 return RHSType; 9165 if (LHSEleType != RHSEleType) { 9166 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 9167 LHSEleType = RHSEleType; 9168 } 9169 QualType VecTy = 9170 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 9171 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 9172 LHSType = VecTy; 9173 } else if (RHSVecTy) { 9174 // OpenCL v1.1 s6.3.j says that for vector types, the operators 9175 // are applied component-wise. So if RHS is a vector, then ensure 9176 // that the number of elements is the same as LHS... 9177 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 9178 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 9179 << LHS.get()->getType() << RHS.get()->getType() 9180 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9181 return QualType(); 9182 } 9183 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 9184 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 9185 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 9186 if (LHSBT != RHSBT && 9187 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 9188 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 9189 << LHS.get()->getType() << RHS.get()->getType() 9190 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9191 } 9192 } 9193 } else { 9194 // ...else expand RHS to match the number of elements in LHS. 9195 QualType VecTy = 9196 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 9197 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 9198 } 9199 9200 return LHSType; 9201 } 9202 9203 // C99 6.5.7 9204 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 9205 SourceLocation Loc, BinaryOperatorKind Opc, 9206 bool IsCompAssign) { 9207 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9208 9209 // Vector shifts promote their scalar inputs to vector type. 9210 if (LHS.get()->getType()->isVectorType() || 9211 RHS.get()->getType()->isVectorType()) { 9212 if (LangOpts.ZVector) { 9213 // The shift operators for the z vector extensions work basically 9214 // like general shifts, except that neither the LHS nor the RHS is 9215 // allowed to be a "vector bool". 9216 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 9217 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 9218 return InvalidOperands(Loc, LHS, RHS); 9219 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 9220 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9221 return InvalidOperands(Loc, LHS, RHS); 9222 } 9223 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 9224 } 9225 9226 // Shifts don't perform usual arithmetic conversions, they just do integer 9227 // promotions on each operand. C99 6.5.7p3 9228 9229 // For the LHS, do usual unary conversions, but then reset them away 9230 // if this is a compound assignment. 9231 ExprResult OldLHS = LHS; 9232 LHS = UsualUnaryConversions(LHS.get()); 9233 if (LHS.isInvalid()) 9234 return QualType(); 9235 QualType LHSType = LHS.get()->getType(); 9236 if (IsCompAssign) LHS = OldLHS; 9237 9238 // The RHS is simpler. 9239 RHS = UsualUnaryConversions(RHS.get()); 9240 if (RHS.isInvalid()) 9241 return QualType(); 9242 QualType RHSType = RHS.get()->getType(); 9243 9244 // C99 6.5.7p2: Each of the operands shall have integer type. 9245 if (!LHSType->hasIntegerRepresentation() || 9246 !RHSType->hasIntegerRepresentation()) 9247 return InvalidOperands(Loc, LHS, RHS); 9248 9249 // C++0x: Don't allow scoped enums. FIXME: Use something better than 9250 // hasIntegerRepresentation() above instead of this. 9251 if (isScopedEnumerationType(LHSType) || 9252 isScopedEnumerationType(RHSType)) { 9253 return InvalidOperands(Loc, LHS, RHS); 9254 } 9255 // Sanity-check shift operands 9256 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 9257 9258 // "The type of the result is that of the promoted left operand." 9259 return LHSType; 9260 } 9261 9262 static bool IsWithinTemplateSpecialization(Decl *D) { 9263 if (DeclContext *DC = D->getDeclContext()) { 9264 if (isa<ClassTemplateSpecializationDecl>(DC)) 9265 return true; 9266 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 9267 return FD->isFunctionTemplateSpecialization(); 9268 } 9269 return false; 9270 } 9271 9272 /// If two different enums are compared, raise a warning. 9273 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 9274 Expr *RHS) { 9275 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 9276 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 9277 9278 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 9279 if (!LHSEnumType) 9280 return; 9281 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 9282 if (!RHSEnumType) 9283 return; 9284 9285 // Ignore anonymous enums. 9286 if (!LHSEnumType->getDecl()->getIdentifier() && 9287 !LHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 9288 return; 9289 if (!RHSEnumType->getDecl()->getIdentifier() && 9290 !RHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 9291 return; 9292 9293 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 9294 return; 9295 9296 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 9297 << LHSStrippedType << RHSStrippedType 9298 << LHS->getSourceRange() << RHS->getSourceRange(); 9299 } 9300 9301 /// \brief Diagnose bad pointer comparisons. 9302 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 9303 ExprResult &LHS, ExprResult &RHS, 9304 bool IsError) { 9305 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 9306 : diag::ext_typecheck_comparison_of_distinct_pointers) 9307 << LHS.get()->getType() << RHS.get()->getType() 9308 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9309 } 9310 9311 /// \brief Returns false if the pointers are converted to a composite type, 9312 /// true otherwise. 9313 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 9314 ExprResult &LHS, ExprResult &RHS) { 9315 // C++ [expr.rel]p2: 9316 // [...] Pointer conversions (4.10) and qualification 9317 // conversions (4.4) are performed on pointer operands (or on 9318 // a pointer operand and a null pointer constant) to bring 9319 // them to their composite pointer type. [...] 9320 // 9321 // C++ [expr.eq]p1 uses the same notion for (in)equality 9322 // comparisons of pointers. 9323 9324 QualType LHSType = LHS.get()->getType(); 9325 QualType RHSType = RHS.get()->getType(); 9326 assert(LHSType->isPointerType() || RHSType->isPointerType() || 9327 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 9328 9329 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 9330 if (T.isNull()) { 9331 if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) && 9332 (RHSType->isPointerType() || RHSType->isMemberPointerType())) 9333 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 9334 else 9335 S.InvalidOperands(Loc, LHS, RHS); 9336 return true; 9337 } 9338 9339 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 9340 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 9341 return false; 9342 } 9343 9344 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 9345 ExprResult &LHS, 9346 ExprResult &RHS, 9347 bool IsError) { 9348 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 9349 : diag::ext_typecheck_comparison_of_fptr_to_void) 9350 << LHS.get()->getType() << RHS.get()->getType() 9351 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9352 } 9353 9354 static bool isObjCObjectLiteral(ExprResult &E) { 9355 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 9356 case Stmt::ObjCArrayLiteralClass: 9357 case Stmt::ObjCDictionaryLiteralClass: 9358 case Stmt::ObjCStringLiteralClass: 9359 case Stmt::ObjCBoxedExprClass: 9360 return true; 9361 default: 9362 // Note that ObjCBoolLiteral is NOT an object literal! 9363 return false; 9364 } 9365 } 9366 9367 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 9368 const ObjCObjectPointerType *Type = 9369 LHS->getType()->getAs<ObjCObjectPointerType>(); 9370 9371 // If this is not actually an Objective-C object, bail out. 9372 if (!Type) 9373 return false; 9374 9375 // Get the LHS object's interface type. 9376 QualType InterfaceType = Type->getPointeeType(); 9377 9378 // If the RHS isn't an Objective-C object, bail out. 9379 if (!RHS->getType()->isObjCObjectPointerType()) 9380 return false; 9381 9382 // Try to find the -isEqual: method. 9383 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 9384 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 9385 InterfaceType, 9386 /*instance=*/true); 9387 if (!Method) { 9388 if (Type->isObjCIdType()) { 9389 // For 'id', just check the global pool. 9390 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 9391 /*receiverId=*/true); 9392 } else { 9393 // Check protocols. 9394 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 9395 /*instance=*/true); 9396 } 9397 } 9398 9399 if (!Method) 9400 return false; 9401 9402 QualType T = Method->parameters()[0]->getType(); 9403 if (!T->isObjCObjectPointerType()) 9404 return false; 9405 9406 QualType R = Method->getReturnType(); 9407 if (!R->isScalarType()) 9408 return false; 9409 9410 return true; 9411 } 9412 9413 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 9414 FromE = FromE->IgnoreParenImpCasts(); 9415 switch (FromE->getStmtClass()) { 9416 default: 9417 break; 9418 case Stmt::ObjCStringLiteralClass: 9419 // "string literal" 9420 return LK_String; 9421 case Stmt::ObjCArrayLiteralClass: 9422 // "array literal" 9423 return LK_Array; 9424 case Stmt::ObjCDictionaryLiteralClass: 9425 // "dictionary literal" 9426 return LK_Dictionary; 9427 case Stmt::BlockExprClass: 9428 return LK_Block; 9429 case Stmt::ObjCBoxedExprClass: { 9430 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 9431 switch (Inner->getStmtClass()) { 9432 case Stmt::IntegerLiteralClass: 9433 case Stmt::FloatingLiteralClass: 9434 case Stmt::CharacterLiteralClass: 9435 case Stmt::ObjCBoolLiteralExprClass: 9436 case Stmt::CXXBoolLiteralExprClass: 9437 // "numeric literal" 9438 return LK_Numeric; 9439 case Stmt::ImplicitCastExprClass: { 9440 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 9441 // Boolean literals can be represented by implicit casts. 9442 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 9443 return LK_Numeric; 9444 break; 9445 } 9446 default: 9447 break; 9448 } 9449 return LK_Boxed; 9450 } 9451 } 9452 return LK_None; 9453 } 9454 9455 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 9456 ExprResult &LHS, ExprResult &RHS, 9457 BinaryOperator::Opcode Opc){ 9458 Expr *Literal; 9459 Expr *Other; 9460 if (isObjCObjectLiteral(LHS)) { 9461 Literal = LHS.get(); 9462 Other = RHS.get(); 9463 } else { 9464 Literal = RHS.get(); 9465 Other = LHS.get(); 9466 } 9467 9468 // Don't warn on comparisons against nil. 9469 Other = Other->IgnoreParenCasts(); 9470 if (Other->isNullPointerConstant(S.getASTContext(), 9471 Expr::NPC_ValueDependentIsNotNull)) 9472 return; 9473 9474 // This should be kept in sync with warn_objc_literal_comparison. 9475 // LK_String should always be after the other literals, since it has its own 9476 // warning flag. 9477 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 9478 assert(LiteralKind != Sema::LK_Block); 9479 if (LiteralKind == Sema::LK_None) { 9480 llvm_unreachable("Unknown Objective-C object literal kind"); 9481 } 9482 9483 if (LiteralKind == Sema::LK_String) 9484 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 9485 << Literal->getSourceRange(); 9486 else 9487 S.Diag(Loc, diag::warn_objc_literal_comparison) 9488 << LiteralKind << Literal->getSourceRange(); 9489 9490 if (BinaryOperator::isEqualityOp(Opc) && 9491 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 9492 SourceLocation Start = LHS.get()->getLocStart(); 9493 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd()); 9494 CharSourceRange OpRange = 9495 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 9496 9497 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 9498 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 9499 << FixItHint::CreateReplacement(OpRange, " isEqual:") 9500 << FixItHint::CreateInsertion(End, "]"); 9501 } 9502 } 9503 9504 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 9505 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 9506 ExprResult &RHS, SourceLocation Loc, 9507 BinaryOperatorKind Opc) { 9508 // Check that left hand side is !something. 9509 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 9510 if (!UO || UO->getOpcode() != UO_LNot) return; 9511 9512 // Only check if the right hand side is non-bool arithmetic type. 9513 if (RHS.get()->isKnownToHaveBooleanValue()) return; 9514 9515 // Make sure that the something in !something is not bool. 9516 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 9517 if (SubExpr->isKnownToHaveBooleanValue()) return; 9518 9519 // Emit warning. 9520 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 9521 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 9522 << Loc << IsBitwiseOp; 9523 9524 // First note suggest !(x < y) 9525 SourceLocation FirstOpen = SubExpr->getLocStart(); 9526 SourceLocation FirstClose = RHS.get()->getLocEnd(); 9527 FirstClose = S.getLocForEndOfToken(FirstClose); 9528 if (FirstClose.isInvalid()) 9529 FirstOpen = SourceLocation(); 9530 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 9531 << IsBitwiseOp 9532 << FixItHint::CreateInsertion(FirstOpen, "(") 9533 << FixItHint::CreateInsertion(FirstClose, ")"); 9534 9535 // Second note suggests (!x) < y 9536 SourceLocation SecondOpen = LHS.get()->getLocStart(); 9537 SourceLocation SecondClose = LHS.get()->getLocEnd(); 9538 SecondClose = S.getLocForEndOfToken(SecondClose); 9539 if (SecondClose.isInvalid()) 9540 SecondOpen = SourceLocation(); 9541 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 9542 << FixItHint::CreateInsertion(SecondOpen, "(") 9543 << FixItHint::CreateInsertion(SecondClose, ")"); 9544 } 9545 9546 // Get the decl for a simple expression: a reference to a variable, 9547 // an implicit C++ field reference, or an implicit ObjC ivar reference. 9548 static ValueDecl *getCompareDecl(Expr *E) { 9549 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E)) 9550 return DR->getDecl(); 9551 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 9552 if (Ivar->isFreeIvar()) 9553 return Ivar->getDecl(); 9554 } 9555 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) { 9556 if (Mem->isImplicitAccess()) 9557 return Mem->getMemberDecl(); 9558 } 9559 return nullptr; 9560 } 9561 9562 // C99 6.5.8, C++ [expr.rel] 9563 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 9564 SourceLocation Loc, BinaryOperatorKind Opc, 9565 bool IsRelational) { 9566 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 9567 9568 // Handle vector comparisons separately. 9569 if (LHS.get()->getType()->isVectorType() || 9570 RHS.get()->getType()->isVectorType()) 9571 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 9572 9573 QualType LHSType = LHS.get()->getType(); 9574 QualType RHSType = RHS.get()->getType(); 9575 9576 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 9577 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 9578 9579 checkEnumComparison(*this, Loc, LHS.get(), RHS.get()); 9580 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 9581 9582 if (!LHSType->hasFloatingRepresentation() && 9583 !(LHSType->isBlockPointerType() && IsRelational) && 9584 !LHS.get()->getLocStart().isMacroID() && 9585 !RHS.get()->getLocStart().isMacroID() && 9586 !inTemplateInstantiation()) { 9587 // For non-floating point types, check for self-comparisons of the form 9588 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9589 // often indicate logic errors in the program. 9590 // 9591 // NOTE: Don't warn about comparison expressions resulting from macro 9592 // expansion. Also don't warn about comparisons which are only self 9593 // comparisons within a template specialization. The warnings should catch 9594 // obvious cases in the definition of the template anyways. The idea is to 9595 // warn when the typed comparison operator will always evaluate to the same 9596 // result. 9597 ValueDecl *DL = getCompareDecl(LHSStripped); 9598 ValueDecl *DR = getCompareDecl(RHSStripped); 9599 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) { 9600 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 9601 << 0 // self- 9602 << (Opc == BO_EQ 9603 || Opc == BO_LE 9604 || Opc == BO_GE)); 9605 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() && 9606 !DL->getType()->isReferenceType() && 9607 !DR->getType()->isReferenceType()) { 9608 // what is it always going to eval to? 9609 char always_evals_to; 9610 switch(Opc) { 9611 case BO_EQ: // e.g. array1 == array2 9612 always_evals_to = 0; // false 9613 break; 9614 case BO_NE: // e.g. array1 != array2 9615 always_evals_to = 1; // true 9616 break; 9617 default: 9618 // best we can say is 'a constant' 9619 always_evals_to = 2; // e.g. array1 <= array2 9620 break; 9621 } 9622 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 9623 << 1 // array 9624 << always_evals_to); 9625 } 9626 9627 if (isa<CastExpr>(LHSStripped)) 9628 LHSStripped = LHSStripped->IgnoreParenCasts(); 9629 if (isa<CastExpr>(RHSStripped)) 9630 RHSStripped = RHSStripped->IgnoreParenCasts(); 9631 9632 // Warn about comparisons against a string constant (unless the other 9633 // operand is null), the user probably wants strcmp. 9634 Expr *literalString = nullptr; 9635 Expr *literalStringStripped = nullptr; 9636 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 9637 !RHSStripped->isNullPointerConstant(Context, 9638 Expr::NPC_ValueDependentIsNull)) { 9639 literalString = LHS.get(); 9640 literalStringStripped = LHSStripped; 9641 } else if ((isa<StringLiteral>(RHSStripped) || 9642 isa<ObjCEncodeExpr>(RHSStripped)) && 9643 !LHSStripped->isNullPointerConstant(Context, 9644 Expr::NPC_ValueDependentIsNull)) { 9645 literalString = RHS.get(); 9646 literalStringStripped = RHSStripped; 9647 } 9648 9649 if (literalString) { 9650 DiagRuntimeBehavior(Loc, nullptr, 9651 PDiag(diag::warn_stringcompare) 9652 << isa<ObjCEncodeExpr>(literalStringStripped) 9653 << literalString->getSourceRange()); 9654 } 9655 } 9656 9657 // C99 6.5.8p3 / C99 6.5.9p4 9658 UsualArithmeticConversions(LHS, RHS); 9659 if (LHS.isInvalid() || RHS.isInvalid()) 9660 return QualType(); 9661 9662 LHSType = LHS.get()->getType(); 9663 RHSType = RHS.get()->getType(); 9664 9665 // The result of comparisons is 'bool' in C++, 'int' in C. 9666 QualType ResultTy = Context.getLogicalOperationType(); 9667 9668 if (IsRelational) { 9669 if (LHSType->isRealType() && RHSType->isRealType()) 9670 return ResultTy; 9671 } else { 9672 // Check for comparisons of floating point operands using != and ==. 9673 if (LHSType->hasFloatingRepresentation()) 9674 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9675 9676 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 9677 return ResultTy; 9678 } 9679 9680 const Expr::NullPointerConstantKind LHSNullKind = 9681 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9682 const Expr::NullPointerConstantKind RHSNullKind = 9683 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9684 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 9685 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 9686 9687 if (!IsRelational && LHSIsNull != RHSIsNull) { 9688 bool IsEquality = Opc == BO_EQ; 9689 if (RHSIsNull) 9690 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 9691 RHS.get()->getSourceRange()); 9692 else 9693 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 9694 LHS.get()->getSourceRange()); 9695 } 9696 9697 if ((LHSType->isIntegerType() && !LHSIsNull) || 9698 (RHSType->isIntegerType() && !RHSIsNull)) { 9699 // Skip normal pointer conversion checks in this case; we have better 9700 // diagnostics for this below. 9701 } else if (getLangOpts().CPlusPlus) { 9702 // Equality comparison of a function pointer to a void pointer is invalid, 9703 // but we allow it as an extension. 9704 // FIXME: If we really want to allow this, should it be part of composite 9705 // pointer type computation so it works in conditionals too? 9706 if (!IsRelational && 9707 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 9708 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 9709 // This is a gcc extension compatibility comparison. 9710 // In a SFINAE context, we treat this as a hard error to maintain 9711 // conformance with the C++ standard. 9712 diagnoseFunctionPointerToVoidComparison( 9713 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 9714 9715 if (isSFINAEContext()) 9716 return QualType(); 9717 9718 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9719 return ResultTy; 9720 } 9721 9722 // C++ [expr.eq]p2: 9723 // If at least one operand is a pointer [...] bring them to their 9724 // composite pointer type. 9725 // C++ [expr.rel]p2: 9726 // If both operands are pointers, [...] bring them to their composite 9727 // pointer type. 9728 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 9729 (IsRelational ? 2 : 1) && 9730 (!LangOpts.ObjCAutoRefCount || 9731 !(LHSType->isObjCObjectPointerType() || 9732 RHSType->isObjCObjectPointerType()))) { 9733 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9734 return QualType(); 9735 else 9736 return ResultTy; 9737 } 9738 } else if (LHSType->isPointerType() && 9739 RHSType->isPointerType()) { // C99 6.5.8p2 9740 // All of the following pointer-related warnings are GCC extensions, except 9741 // when handling null pointer constants. 9742 QualType LCanPointeeTy = 9743 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9744 QualType RCanPointeeTy = 9745 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9746 9747 // C99 6.5.9p2 and C99 6.5.8p2 9748 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 9749 RCanPointeeTy.getUnqualifiedType())) { 9750 // Valid unless a relational comparison of function pointers 9751 if (IsRelational && LCanPointeeTy->isFunctionType()) { 9752 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 9753 << LHSType << RHSType << LHS.get()->getSourceRange() 9754 << RHS.get()->getSourceRange(); 9755 } 9756 } else if (!IsRelational && 9757 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 9758 // Valid unless comparison between non-null pointer and function pointer 9759 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 9760 && !LHSIsNull && !RHSIsNull) 9761 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 9762 /*isError*/false); 9763 } else { 9764 // Invalid 9765 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 9766 } 9767 if (LCanPointeeTy != RCanPointeeTy) { 9768 // Treat NULL constant as a special case in OpenCL. 9769 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 9770 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 9771 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 9772 Diag(Loc, 9773 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 9774 << LHSType << RHSType << 0 /* comparison */ 9775 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9776 } 9777 } 9778 unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace(); 9779 unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace(); 9780 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 9781 : CK_BitCast; 9782 if (LHSIsNull && !RHSIsNull) 9783 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 9784 else 9785 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 9786 } 9787 return ResultTy; 9788 } 9789 9790 if (getLangOpts().CPlusPlus) { 9791 // C++ [expr.eq]p4: 9792 // Two operands of type std::nullptr_t or one operand of type 9793 // std::nullptr_t and the other a null pointer constant compare equal. 9794 if (!IsRelational && LHSIsNull && RHSIsNull) { 9795 if (LHSType->isNullPtrType()) { 9796 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9797 return ResultTy; 9798 } 9799 if (RHSType->isNullPtrType()) { 9800 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9801 return ResultTy; 9802 } 9803 } 9804 9805 // Comparison of Objective-C pointers and block pointers against nullptr_t. 9806 // These aren't covered by the composite pointer type rules. 9807 if (!IsRelational && RHSType->isNullPtrType() && 9808 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 9809 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9810 return ResultTy; 9811 } 9812 if (!IsRelational && LHSType->isNullPtrType() && 9813 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 9814 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9815 return ResultTy; 9816 } 9817 9818 if (IsRelational && 9819 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 9820 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 9821 // HACK: Relational comparison of nullptr_t against a pointer type is 9822 // invalid per DR583, but we allow it within std::less<> and friends, 9823 // since otherwise common uses of it break. 9824 // FIXME: Consider removing this hack once LWG fixes std::less<> and 9825 // friends to have std::nullptr_t overload candidates. 9826 DeclContext *DC = CurContext; 9827 if (isa<FunctionDecl>(DC)) 9828 DC = DC->getParent(); 9829 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 9830 if (CTSD->isInStdNamespace() && 9831 llvm::StringSwitch<bool>(CTSD->getName()) 9832 .Cases("less", "less_equal", "greater", "greater_equal", true) 9833 .Default(false)) { 9834 if (RHSType->isNullPtrType()) 9835 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9836 else 9837 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9838 return ResultTy; 9839 } 9840 } 9841 } 9842 9843 // C++ [expr.eq]p2: 9844 // If at least one operand is a pointer to member, [...] bring them to 9845 // their composite pointer type. 9846 if (!IsRelational && 9847 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 9848 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9849 return QualType(); 9850 else 9851 return ResultTy; 9852 } 9853 9854 // Handle scoped enumeration types specifically, since they don't promote 9855 // to integers. 9856 if (LHS.get()->getType()->isEnumeralType() && 9857 Context.hasSameUnqualifiedType(LHS.get()->getType(), 9858 RHS.get()->getType())) 9859 return ResultTy; 9860 } 9861 9862 // Handle block pointer types. 9863 if (!IsRelational && LHSType->isBlockPointerType() && 9864 RHSType->isBlockPointerType()) { 9865 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 9866 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 9867 9868 if (!LHSIsNull && !RHSIsNull && 9869 !Context.typesAreCompatible(lpointee, rpointee)) { 9870 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9871 << LHSType << RHSType << LHS.get()->getSourceRange() 9872 << RHS.get()->getSourceRange(); 9873 } 9874 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9875 return ResultTy; 9876 } 9877 9878 // Allow block pointers to be compared with null pointer constants. 9879 if (!IsRelational 9880 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 9881 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 9882 if (!LHSIsNull && !RHSIsNull) { 9883 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 9884 ->getPointeeType()->isVoidType()) 9885 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 9886 ->getPointeeType()->isVoidType()))) 9887 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9888 << LHSType << RHSType << LHS.get()->getSourceRange() 9889 << RHS.get()->getSourceRange(); 9890 } 9891 if (LHSIsNull && !RHSIsNull) 9892 LHS = ImpCastExprToType(LHS.get(), RHSType, 9893 RHSType->isPointerType() ? CK_BitCast 9894 : CK_AnyPointerToBlockPointerCast); 9895 else 9896 RHS = ImpCastExprToType(RHS.get(), LHSType, 9897 LHSType->isPointerType() ? CK_BitCast 9898 : CK_AnyPointerToBlockPointerCast); 9899 return ResultTy; 9900 } 9901 9902 if (LHSType->isObjCObjectPointerType() || 9903 RHSType->isObjCObjectPointerType()) { 9904 const PointerType *LPT = LHSType->getAs<PointerType>(); 9905 const PointerType *RPT = RHSType->getAs<PointerType>(); 9906 if (LPT || RPT) { 9907 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 9908 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 9909 9910 if (!LPtrToVoid && !RPtrToVoid && 9911 !Context.typesAreCompatible(LHSType, RHSType)) { 9912 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9913 /*isError*/false); 9914 } 9915 if (LHSIsNull && !RHSIsNull) { 9916 Expr *E = LHS.get(); 9917 if (getLangOpts().ObjCAutoRefCount) 9918 CheckObjCConversion(SourceRange(), RHSType, E, 9919 CCK_ImplicitConversion); 9920 LHS = ImpCastExprToType(E, RHSType, 9921 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9922 } 9923 else { 9924 Expr *E = RHS.get(); 9925 if (getLangOpts().ObjCAutoRefCount) 9926 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 9927 /*Diagnose=*/true, 9928 /*DiagnoseCFAudited=*/false, Opc); 9929 RHS = ImpCastExprToType(E, LHSType, 9930 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9931 } 9932 return ResultTy; 9933 } 9934 if (LHSType->isObjCObjectPointerType() && 9935 RHSType->isObjCObjectPointerType()) { 9936 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 9937 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9938 /*isError*/false); 9939 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 9940 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 9941 9942 if (LHSIsNull && !RHSIsNull) 9943 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9944 else 9945 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9946 return ResultTy; 9947 } 9948 } 9949 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 9950 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 9951 unsigned DiagID = 0; 9952 bool isError = false; 9953 if (LangOpts.DebuggerSupport) { 9954 // Under a debugger, allow the comparison of pointers to integers, 9955 // since users tend to want to compare addresses. 9956 } else if ((LHSIsNull && LHSType->isIntegerType()) || 9957 (RHSIsNull && RHSType->isIntegerType())) { 9958 if (IsRelational) { 9959 isError = getLangOpts().CPlusPlus; 9960 DiagID = 9961 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 9962 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 9963 } 9964 } else if (getLangOpts().CPlusPlus) { 9965 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 9966 isError = true; 9967 } else if (IsRelational) 9968 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 9969 else 9970 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 9971 9972 if (DiagID) { 9973 Diag(Loc, DiagID) 9974 << LHSType << RHSType << LHS.get()->getSourceRange() 9975 << RHS.get()->getSourceRange(); 9976 if (isError) 9977 return QualType(); 9978 } 9979 9980 if (LHSType->isIntegerType()) 9981 LHS = ImpCastExprToType(LHS.get(), RHSType, 9982 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 9983 else 9984 RHS = ImpCastExprToType(RHS.get(), LHSType, 9985 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 9986 return ResultTy; 9987 } 9988 9989 // Handle block pointers. 9990 if (!IsRelational && RHSIsNull 9991 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 9992 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9993 return ResultTy; 9994 } 9995 if (!IsRelational && LHSIsNull 9996 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 9997 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9998 return ResultTy; 9999 } 10000 10001 if (getLangOpts().OpenCLVersion >= 200) { 10002 if (LHSIsNull && RHSType->isQueueT()) { 10003 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10004 return ResultTy; 10005 } 10006 10007 if (LHSType->isQueueT() && RHSIsNull) { 10008 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10009 return ResultTy; 10010 } 10011 } 10012 10013 return InvalidOperands(Loc, LHS, RHS); 10014 } 10015 10016 // Return a signed ext_vector_type that is of identical size and number of 10017 // elements. For floating point vectors, return an integer type of identical 10018 // size and number of elements. In the non ext_vector_type case, search from 10019 // the largest type to the smallest type to avoid cases where long long == long, 10020 // where long gets picked over long long. 10021 QualType Sema::GetSignedVectorType(QualType V) { 10022 const VectorType *VTy = V->getAs<VectorType>(); 10023 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 10024 10025 if (isa<ExtVectorType>(VTy)) { 10026 if (TypeSize == Context.getTypeSize(Context.CharTy)) 10027 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 10028 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 10029 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 10030 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 10031 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 10032 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 10033 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 10034 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 10035 "Unhandled vector element size in vector compare"); 10036 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 10037 } 10038 10039 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 10040 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 10041 VectorType::GenericVector); 10042 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 10043 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 10044 VectorType::GenericVector); 10045 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 10046 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 10047 VectorType::GenericVector); 10048 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 10049 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 10050 VectorType::GenericVector); 10051 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 10052 "Unhandled vector element size in vector compare"); 10053 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 10054 VectorType::GenericVector); 10055 } 10056 10057 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 10058 /// operates on extended vector types. Instead of producing an IntTy result, 10059 /// like a scalar comparison, a vector comparison produces a vector of integer 10060 /// types. 10061 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 10062 SourceLocation Loc, 10063 bool IsRelational) { 10064 // Check to make sure we're operating on vectors of the same type and width, 10065 // Allowing one side to be a scalar of element type. 10066 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 10067 /*AllowBothBool*/true, 10068 /*AllowBoolConversions*/getLangOpts().ZVector); 10069 if (vType.isNull()) 10070 return vType; 10071 10072 QualType LHSType = LHS.get()->getType(); 10073 10074 // If AltiVec, the comparison results in a numeric type, i.e. 10075 // bool for C++, int for C 10076 if (getLangOpts().AltiVec && 10077 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 10078 return Context.getLogicalOperationType(); 10079 10080 // For non-floating point types, check for self-comparisons of the form 10081 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 10082 // often indicate logic errors in the program. 10083 if (!LHSType->hasFloatingRepresentation() && !inTemplateInstantiation()) { 10084 if (DeclRefExpr* DRL 10085 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 10086 if (DeclRefExpr* DRR 10087 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 10088 if (DRL->getDecl() == DRR->getDecl()) 10089 DiagRuntimeBehavior(Loc, nullptr, 10090 PDiag(diag::warn_comparison_always) 10091 << 0 // self- 10092 << 2 // "a constant" 10093 ); 10094 } 10095 10096 // Check for comparisons of floating point operands using != and ==. 10097 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 10098 assert (RHS.get()->getType()->hasFloatingRepresentation()); 10099 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 10100 } 10101 10102 // Return a signed type for the vector. 10103 return GetSignedVectorType(vType); 10104 } 10105 10106 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 10107 SourceLocation Loc) { 10108 // Ensure that either both operands are of the same vector type, or 10109 // one operand is of a vector type and the other is of its element type. 10110 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 10111 /*AllowBothBool*/true, 10112 /*AllowBoolConversions*/false); 10113 if (vType.isNull()) 10114 return InvalidOperands(Loc, LHS, RHS); 10115 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 10116 vType->hasFloatingRepresentation()) 10117 return InvalidOperands(Loc, LHS, RHS); 10118 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 10119 // usage of the logical operators && and || with vectors in C. This 10120 // check could be notionally dropped. 10121 if (!getLangOpts().CPlusPlus && 10122 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 10123 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 10124 10125 return GetSignedVectorType(LHS.get()->getType()); 10126 } 10127 10128 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 10129 SourceLocation Loc, 10130 BinaryOperatorKind Opc) { 10131 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 10132 10133 bool IsCompAssign = 10134 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 10135 10136 if (LHS.get()->getType()->isVectorType() || 10137 RHS.get()->getType()->isVectorType()) { 10138 if (LHS.get()->getType()->hasIntegerRepresentation() && 10139 RHS.get()->getType()->hasIntegerRepresentation()) 10140 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10141 /*AllowBothBool*/true, 10142 /*AllowBoolConversions*/getLangOpts().ZVector); 10143 return InvalidOperands(Loc, LHS, RHS); 10144 } 10145 10146 if (Opc == BO_And) 10147 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 10148 10149 ExprResult LHSResult = LHS, RHSResult = RHS; 10150 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 10151 IsCompAssign); 10152 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 10153 return QualType(); 10154 LHS = LHSResult.get(); 10155 RHS = RHSResult.get(); 10156 10157 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 10158 return compType; 10159 return InvalidOperands(Loc, LHS, RHS); 10160 } 10161 10162 // C99 6.5.[13,14] 10163 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 10164 SourceLocation Loc, 10165 BinaryOperatorKind Opc) { 10166 // Check vector operands differently. 10167 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 10168 return CheckVectorLogicalOperands(LHS, RHS, Loc); 10169 10170 // Diagnose cases where the user write a logical and/or but probably meant a 10171 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 10172 // is a constant. 10173 if (LHS.get()->getType()->isIntegerType() && 10174 !LHS.get()->getType()->isBooleanType() && 10175 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 10176 // Don't warn in macros or template instantiations. 10177 !Loc.isMacroID() && !inTemplateInstantiation()) { 10178 // If the RHS can be constant folded, and if it constant folds to something 10179 // that isn't 0 or 1 (which indicate a potential logical operation that 10180 // happened to fold to true/false) then warn. 10181 // Parens on the RHS are ignored. 10182 llvm::APSInt Result; 10183 if (RHS.get()->EvaluateAsInt(Result, Context)) 10184 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 10185 !RHS.get()->getExprLoc().isMacroID()) || 10186 (Result != 0 && Result != 1)) { 10187 Diag(Loc, diag::warn_logical_instead_of_bitwise) 10188 << RHS.get()->getSourceRange() 10189 << (Opc == BO_LAnd ? "&&" : "||"); 10190 // Suggest replacing the logical operator with the bitwise version 10191 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 10192 << (Opc == BO_LAnd ? "&" : "|") 10193 << FixItHint::CreateReplacement(SourceRange( 10194 Loc, getLocForEndOfToken(Loc)), 10195 Opc == BO_LAnd ? "&" : "|"); 10196 if (Opc == BO_LAnd) 10197 // Suggest replacing "Foo() && kNonZero" with "Foo()" 10198 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 10199 << FixItHint::CreateRemoval( 10200 SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()), 10201 RHS.get()->getLocEnd())); 10202 } 10203 } 10204 10205 if (!Context.getLangOpts().CPlusPlus) { 10206 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 10207 // not operate on the built-in scalar and vector float types. 10208 if (Context.getLangOpts().OpenCL && 10209 Context.getLangOpts().OpenCLVersion < 120) { 10210 if (LHS.get()->getType()->isFloatingType() || 10211 RHS.get()->getType()->isFloatingType()) 10212 return InvalidOperands(Loc, LHS, RHS); 10213 } 10214 10215 LHS = UsualUnaryConversions(LHS.get()); 10216 if (LHS.isInvalid()) 10217 return QualType(); 10218 10219 RHS = UsualUnaryConversions(RHS.get()); 10220 if (RHS.isInvalid()) 10221 return QualType(); 10222 10223 if (!LHS.get()->getType()->isScalarType() || 10224 !RHS.get()->getType()->isScalarType()) 10225 return InvalidOperands(Loc, LHS, RHS); 10226 10227 return Context.IntTy; 10228 } 10229 10230 // The following is safe because we only use this method for 10231 // non-overloadable operands. 10232 10233 // C++ [expr.log.and]p1 10234 // C++ [expr.log.or]p1 10235 // The operands are both contextually converted to type bool. 10236 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 10237 if (LHSRes.isInvalid()) 10238 return InvalidOperands(Loc, LHS, RHS); 10239 LHS = LHSRes; 10240 10241 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 10242 if (RHSRes.isInvalid()) 10243 return InvalidOperands(Loc, LHS, RHS); 10244 RHS = RHSRes; 10245 10246 // C++ [expr.log.and]p2 10247 // C++ [expr.log.or]p2 10248 // The result is a bool. 10249 return Context.BoolTy; 10250 } 10251 10252 static bool IsReadonlyMessage(Expr *E, Sema &S) { 10253 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 10254 if (!ME) return false; 10255 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 10256 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 10257 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 10258 if (!Base) return false; 10259 return Base->getMethodDecl() != nullptr; 10260 } 10261 10262 /// Is the given expression (which must be 'const') a reference to a 10263 /// variable which was originally non-const, but which has become 10264 /// 'const' due to being captured within a block? 10265 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 10266 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 10267 assert(E->isLValue() && E->getType().isConstQualified()); 10268 E = E->IgnoreParens(); 10269 10270 // Must be a reference to a declaration from an enclosing scope. 10271 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 10272 if (!DRE) return NCCK_None; 10273 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 10274 10275 // The declaration must be a variable which is not declared 'const'. 10276 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 10277 if (!var) return NCCK_None; 10278 if (var->getType().isConstQualified()) return NCCK_None; 10279 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 10280 10281 // Decide whether the first capture was for a block or a lambda. 10282 DeclContext *DC = S.CurContext, *Prev = nullptr; 10283 // Decide whether the first capture was for a block or a lambda. 10284 while (DC) { 10285 // For init-capture, it is possible that the variable belongs to the 10286 // template pattern of the current context. 10287 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 10288 if (var->isInitCapture() && 10289 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 10290 break; 10291 if (DC == var->getDeclContext()) 10292 break; 10293 Prev = DC; 10294 DC = DC->getParent(); 10295 } 10296 // Unless we have an init-capture, we've gone one step too far. 10297 if (!var->isInitCapture()) 10298 DC = Prev; 10299 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 10300 } 10301 10302 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 10303 Ty = Ty.getNonReferenceType(); 10304 if (IsDereference && Ty->isPointerType()) 10305 Ty = Ty->getPointeeType(); 10306 return !Ty.isConstQualified(); 10307 } 10308 10309 // Update err_typecheck_assign_const and note_typecheck_assign_const 10310 // when this enum is changed. 10311 enum { 10312 ConstFunction, 10313 ConstVariable, 10314 ConstMember, 10315 ConstMethod, 10316 NestedConstMember, 10317 ConstUnknown, // Keep as last element 10318 }; 10319 10320 /// Emit the "read-only variable not assignable" error and print notes to give 10321 /// more information about why the variable is not assignable, such as pointing 10322 /// to the declaration of a const variable, showing that a method is const, or 10323 /// that the function is returning a const reference. 10324 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 10325 SourceLocation Loc) { 10326 SourceRange ExprRange = E->getSourceRange(); 10327 10328 // Only emit one error on the first const found. All other consts will emit 10329 // a note to the error. 10330 bool DiagnosticEmitted = false; 10331 10332 // Track if the current expression is the result of a dereference, and if the 10333 // next checked expression is the result of a dereference. 10334 bool IsDereference = false; 10335 bool NextIsDereference = false; 10336 10337 // Loop to process MemberExpr chains. 10338 while (true) { 10339 IsDereference = NextIsDereference; 10340 10341 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 10342 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 10343 NextIsDereference = ME->isArrow(); 10344 const ValueDecl *VD = ME->getMemberDecl(); 10345 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 10346 // Mutable fields can be modified even if the class is const. 10347 if (Field->isMutable()) { 10348 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 10349 break; 10350 } 10351 10352 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 10353 if (!DiagnosticEmitted) { 10354 S.Diag(Loc, diag::err_typecheck_assign_const) 10355 << ExprRange << ConstMember << false /*static*/ << Field 10356 << Field->getType(); 10357 DiagnosticEmitted = true; 10358 } 10359 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10360 << ConstMember << false /*static*/ << Field << Field->getType() 10361 << Field->getSourceRange(); 10362 } 10363 E = ME->getBase(); 10364 continue; 10365 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 10366 if (VDecl->getType().isConstQualified()) { 10367 if (!DiagnosticEmitted) { 10368 S.Diag(Loc, diag::err_typecheck_assign_const) 10369 << ExprRange << ConstMember << true /*static*/ << VDecl 10370 << VDecl->getType(); 10371 DiagnosticEmitted = true; 10372 } 10373 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10374 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 10375 << VDecl->getSourceRange(); 10376 } 10377 // Static fields do not inherit constness from parents. 10378 break; 10379 } 10380 break; 10381 } // End MemberExpr 10382 break; 10383 } 10384 10385 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 10386 // Function calls 10387 const FunctionDecl *FD = CE->getDirectCallee(); 10388 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 10389 if (!DiagnosticEmitted) { 10390 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 10391 << ConstFunction << FD; 10392 DiagnosticEmitted = true; 10393 } 10394 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 10395 diag::note_typecheck_assign_const) 10396 << ConstFunction << FD << FD->getReturnType() 10397 << FD->getReturnTypeSourceRange(); 10398 } 10399 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 10400 // Point to variable declaration. 10401 if (const ValueDecl *VD = DRE->getDecl()) { 10402 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 10403 if (!DiagnosticEmitted) { 10404 S.Diag(Loc, diag::err_typecheck_assign_const) 10405 << ExprRange << ConstVariable << VD << VD->getType(); 10406 DiagnosticEmitted = true; 10407 } 10408 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10409 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 10410 } 10411 } 10412 } else if (isa<CXXThisExpr>(E)) { 10413 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 10414 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 10415 if (MD->isConst()) { 10416 if (!DiagnosticEmitted) { 10417 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 10418 << ConstMethod << MD; 10419 DiagnosticEmitted = true; 10420 } 10421 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 10422 << ConstMethod << MD << MD->getSourceRange(); 10423 } 10424 } 10425 } 10426 } 10427 10428 if (DiagnosticEmitted) 10429 return; 10430 10431 // Can't determine a more specific message, so display the generic error. 10432 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 10433 } 10434 10435 enum OriginalExprKind { 10436 OEK_Variable, 10437 OEK_Member, 10438 OEK_LValue 10439 }; 10440 10441 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 10442 const RecordType *Ty, 10443 SourceLocation Loc, SourceRange Range, 10444 OriginalExprKind OEK, 10445 bool &DiagnosticEmitted, 10446 bool IsNested = false) { 10447 // We walk the record hierarchy breadth-first to ensure that we print 10448 // diagnostics in field nesting order. 10449 // First, check every field for constness. 10450 for (const FieldDecl *Field : Ty->getDecl()->fields()) { 10451 if (Field->getType().isConstQualified()) { 10452 if (!DiagnosticEmitted) { 10453 S.Diag(Loc, diag::err_typecheck_assign_const) 10454 << Range << NestedConstMember << OEK << VD 10455 << IsNested << Field; 10456 DiagnosticEmitted = true; 10457 } 10458 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 10459 << NestedConstMember << IsNested << Field 10460 << Field->getType() << Field->getSourceRange(); 10461 } 10462 } 10463 // Then, recurse. 10464 for (const FieldDecl *Field : Ty->getDecl()->fields()) { 10465 QualType FTy = Field->getType(); 10466 if (const RecordType *FieldRecTy = FTy->getAs<RecordType>()) 10467 DiagnoseRecursiveConstFields(S, VD, FieldRecTy, Loc, Range, 10468 OEK, DiagnosticEmitted, true); 10469 } 10470 } 10471 10472 /// Emit an error for the case where a record we are trying to assign to has a 10473 /// const-qualified field somewhere in its hierarchy. 10474 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 10475 SourceLocation Loc) { 10476 QualType Ty = E->getType(); 10477 assert(Ty->isRecordType() && "lvalue was not record?"); 10478 SourceRange Range = E->getSourceRange(); 10479 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 10480 bool DiagEmitted = false; 10481 10482 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 10483 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 10484 Range, OEK_Member, DiagEmitted); 10485 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 10486 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 10487 Range, OEK_Variable, DiagEmitted); 10488 else 10489 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 10490 Range, OEK_LValue, DiagEmitted); 10491 if (!DiagEmitted) 10492 DiagnoseConstAssignment(S, E, Loc); 10493 } 10494 10495 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 10496 /// emit an error and return true. If so, return false. 10497 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 10498 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 10499 10500 S.CheckShadowingDeclModification(E, Loc); 10501 10502 SourceLocation OrigLoc = Loc; 10503 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 10504 &Loc); 10505 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 10506 IsLV = Expr::MLV_InvalidMessageExpression; 10507 if (IsLV == Expr::MLV_Valid) 10508 return false; 10509 10510 unsigned DiagID = 0; 10511 bool NeedType = false; 10512 switch (IsLV) { // C99 6.5.16p2 10513 case Expr::MLV_ConstQualified: 10514 // Use a specialized diagnostic when we're assigning to an object 10515 // from an enclosing function or block. 10516 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 10517 if (NCCK == NCCK_Block) 10518 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 10519 else 10520 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 10521 break; 10522 } 10523 10524 // In ARC, use some specialized diagnostics for occasions where we 10525 // infer 'const'. These are always pseudo-strong variables. 10526 if (S.getLangOpts().ObjCAutoRefCount) { 10527 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 10528 if (declRef && isa<VarDecl>(declRef->getDecl())) { 10529 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 10530 10531 // Use the normal diagnostic if it's pseudo-__strong but the 10532 // user actually wrote 'const'. 10533 if (var->isARCPseudoStrong() && 10534 (!var->getTypeSourceInfo() || 10535 !var->getTypeSourceInfo()->getType().isConstQualified())) { 10536 // There are two pseudo-strong cases: 10537 // - self 10538 ObjCMethodDecl *method = S.getCurMethodDecl(); 10539 if (method && var == method->getSelfDecl()) 10540 DiagID = method->isClassMethod() 10541 ? diag::err_typecheck_arc_assign_self_class_method 10542 : diag::err_typecheck_arc_assign_self; 10543 10544 // - fast enumeration variables 10545 else 10546 DiagID = diag::err_typecheck_arr_assign_enumeration; 10547 10548 SourceRange Assign; 10549 if (Loc != OrigLoc) 10550 Assign = SourceRange(OrigLoc, OrigLoc); 10551 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10552 // We need to preserve the AST regardless, so migration tool 10553 // can do its job. 10554 return false; 10555 } 10556 } 10557 } 10558 10559 // If none of the special cases above are triggered, then this is a 10560 // simple const assignment. 10561 if (DiagID == 0) { 10562 DiagnoseConstAssignment(S, E, Loc); 10563 return true; 10564 } 10565 10566 break; 10567 case Expr::MLV_ConstAddrSpace: 10568 DiagnoseConstAssignment(S, E, Loc); 10569 return true; 10570 case Expr::MLV_ConstQualifiedField: 10571 DiagnoseRecursiveConstFields(S, E, Loc); 10572 return true; 10573 case Expr::MLV_ArrayType: 10574 case Expr::MLV_ArrayTemporary: 10575 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 10576 NeedType = true; 10577 break; 10578 case Expr::MLV_NotObjectType: 10579 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 10580 NeedType = true; 10581 break; 10582 case Expr::MLV_LValueCast: 10583 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 10584 break; 10585 case Expr::MLV_Valid: 10586 llvm_unreachable("did not take early return for MLV_Valid"); 10587 case Expr::MLV_InvalidExpression: 10588 case Expr::MLV_MemberFunction: 10589 case Expr::MLV_ClassTemporary: 10590 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 10591 break; 10592 case Expr::MLV_IncompleteType: 10593 case Expr::MLV_IncompleteVoidType: 10594 return S.RequireCompleteType(Loc, E->getType(), 10595 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 10596 case Expr::MLV_DuplicateVectorComponents: 10597 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 10598 break; 10599 case Expr::MLV_NoSetterProperty: 10600 llvm_unreachable("readonly properties should be processed differently"); 10601 case Expr::MLV_InvalidMessageExpression: 10602 DiagID = diag::err_readonly_message_assignment; 10603 break; 10604 case Expr::MLV_SubObjCPropertySetting: 10605 DiagID = diag::err_no_subobject_property_setting; 10606 break; 10607 } 10608 10609 SourceRange Assign; 10610 if (Loc != OrigLoc) 10611 Assign = SourceRange(OrigLoc, OrigLoc); 10612 if (NeedType) 10613 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 10614 else 10615 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10616 return true; 10617 } 10618 10619 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 10620 SourceLocation Loc, 10621 Sema &Sema) { 10622 // C / C++ fields 10623 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 10624 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 10625 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 10626 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 10627 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 10628 } 10629 10630 // Objective-C instance variables 10631 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 10632 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 10633 if (OL && OR && OL->getDecl() == OR->getDecl()) { 10634 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 10635 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 10636 if (RL && RR && RL->getDecl() == RR->getDecl()) 10637 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 10638 } 10639 } 10640 10641 // C99 6.5.16.1 10642 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 10643 SourceLocation Loc, 10644 QualType CompoundType) { 10645 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 10646 10647 // Verify that LHS is a modifiable lvalue, and emit error if not. 10648 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 10649 return QualType(); 10650 10651 QualType LHSType = LHSExpr->getType(); 10652 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 10653 CompoundType; 10654 // OpenCL v1.2 s6.1.1.1 p2: 10655 // The half data type can only be used to declare a pointer to a buffer that 10656 // contains half values 10657 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 10658 LHSType->isHalfType()) { 10659 Diag(Loc, diag::err_opencl_half_load_store) << 1 10660 << LHSType.getUnqualifiedType(); 10661 return QualType(); 10662 } 10663 10664 AssignConvertType ConvTy; 10665 if (CompoundType.isNull()) { 10666 Expr *RHSCheck = RHS.get(); 10667 10668 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 10669 10670 QualType LHSTy(LHSType); 10671 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 10672 if (RHS.isInvalid()) 10673 return QualType(); 10674 // Special case of NSObject attributes on c-style pointer types. 10675 if (ConvTy == IncompatiblePointer && 10676 ((Context.isObjCNSObjectType(LHSType) && 10677 RHSType->isObjCObjectPointerType()) || 10678 (Context.isObjCNSObjectType(RHSType) && 10679 LHSType->isObjCObjectPointerType()))) 10680 ConvTy = Compatible; 10681 10682 if (ConvTy == Compatible && 10683 LHSType->isObjCObjectType()) 10684 Diag(Loc, diag::err_objc_object_assignment) 10685 << LHSType; 10686 10687 // If the RHS is a unary plus or minus, check to see if they = and + are 10688 // right next to each other. If so, the user may have typo'd "x =+ 4" 10689 // instead of "x += 4". 10690 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 10691 RHSCheck = ICE->getSubExpr(); 10692 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 10693 if ((UO->getOpcode() == UO_Plus || 10694 UO->getOpcode() == UO_Minus) && 10695 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 10696 // Only if the two operators are exactly adjacent. 10697 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 10698 // And there is a space or other character before the subexpr of the 10699 // unary +/-. We don't want to warn on "x=-1". 10700 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 10701 UO->getSubExpr()->getLocStart().isFileID()) { 10702 Diag(Loc, diag::warn_not_compound_assign) 10703 << (UO->getOpcode() == UO_Plus ? "+" : "-") 10704 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 10705 } 10706 } 10707 10708 if (ConvTy == Compatible) { 10709 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 10710 // Warn about retain cycles where a block captures the LHS, but 10711 // not if the LHS is a simple variable into which the block is 10712 // being stored...unless that variable can be captured by reference! 10713 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 10714 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 10715 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 10716 checkRetainCycles(LHSExpr, RHS.get()); 10717 } 10718 10719 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 10720 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 10721 // It is safe to assign a weak reference into a strong variable. 10722 // Although this code can still have problems: 10723 // id x = self.weakProp; 10724 // id y = self.weakProp; 10725 // we do not warn to warn spuriously when 'x' and 'y' are on separate 10726 // paths through the function. This should be revisited if 10727 // -Wrepeated-use-of-weak is made flow-sensitive. 10728 // For ObjCWeak only, we do not warn if the assign is to a non-weak 10729 // variable, which will be valid for the current autorelease scope. 10730 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 10731 RHS.get()->getLocStart())) 10732 getCurFunction()->markSafeWeakUse(RHS.get()); 10733 10734 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 10735 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 10736 } 10737 } 10738 } else { 10739 // Compound assignment "x += y" 10740 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 10741 } 10742 10743 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 10744 RHS.get(), AA_Assigning)) 10745 return QualType(); 10746 10747 CheckForNullPointerDereference(*this, LHSExpr); 10748 10749 // C99 6.5.16p3: The type of an assignment expression is the type of the 10750 // left operand unless the left operand has qualified type, in which case 10751 // it is the unqualified version of the type of the left operand. 10752 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 10753 // is converted to the type of the assignment expression (above). 10754 // C++ 5.17p1: the type of the assignment expression is that of its left 10755 // operand. 10756 return (getLangOpts().CPlusPlus 10757 ? LHSType : LHSType.getUnqualifiedType()); 10758 } 10759 10760 // Only ignore explicit casts to void. 10761 static bool IgnoreCommaOperand(const Expr *E) { 10762 E = E->IgnoreParens(); 10763 10764 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 10765 if (CE->getCastKind() == CK_ToVoid) { 10766 return true; 10767 } 10768 } 10769 10770 return false; 10771 } 10772 10773 // Look for instances where it is likely the comma operator is confused with 10774 // another operator. There is a whitelist of acceptable expressions for the 10775 // left hand side of the comma operator, otherwise emit a warning. 10776 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 10777 // No warnings in macros 10778 if (Loc.isMacroID()) 10779 return; 10780 10781 // Don't warn in template instantiations. 10782 if (inTemplateInstantiation()) 10783 return; 10784 10785 // Scope isn't fine-grained enough to whitelist the specific cases, so 10786 // instead, skip more than needed, then call back into here with the 10787 // CommaVisitor in SemaStmt.cpp. 10788 // The whitelisted locations are the initialization and increment portions 10789 // of a for loop. The additional checks are on the condition of 10790 // if statements, do/while loops, and for loops. 10791 const unsigned ForIncrementFlags = 10792 Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope; 10793 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 10794 const unsigned ScopeFlags = getCurScope()->getFlags(); 10795 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 10796 (ScopeFlags & ForInitFlags) == ForInitFlags) 10797 return; 10798 10799 // If there are multiple comma operators used together, get the RHS of the 10800 // of the comma operator as the LHS. 10801 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 10802 if (BO->getOpcode() != BO_Comma) 10803 break; 10804 LHS = BO->getRHS(); 10805 } 10806 10807 // Only allow some expressions on LHS to not warn. 10808 if (IgnoreCommaOperand(LHS)) 10809 return; 10810 10811 Diag(Loc, diag::warn_comma_operator); 10812 Diag(LHS->getLocStart(), diag::note_cast_to_void) 10813 << LHS->getSourceRange() 10814 << FixItHint::CreateInsertion(LHS->getLocStart(), 10815 LangOpts.CPlusPlus ? "static_cast<void>(" 10816 : "(void)(") 10817 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()), 10818 ")"); 10819 } 10820 10821 // C99 6.5.17 10822 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 10823 SourceLocation Loc) { 10824 LHS = S.CheckPlaceholderExpr(LHS.get()); 10825 RHS = S.CheckPlaceholderExpr(RHS.get()); 10826 if (LHS.isInvalid() || RHS.isInvalid()) 10827 return QualType(); 10828 10829 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 10830 // operands, but not unary promotions. 10831 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 10832 10833 // So we treat the LHS as a ignored value, and in C++ we allow the 10834 // containing site to determine what should be done with the RHS. 10835 LHS = S.IgnoredValueConversions(LHS.get()); 10836 if (LHS.isInvalid()) 10837 return QualType(); 10838 10839 S.DiagnoseUnusedExprResult(LHS.get()); 10840 10841 if (!S.getLangOpts().CPlusPlus) { 10842 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 10843 if (RHS.isInvalid()) 10844 return QualType(); 10845 if (!RHS.get()->getType()->isVoidType()) 10846 S.RequireCompleteType(Loc, RHS.get()->getType(), 10847 diag::err_incomplete_type); 10848 } 10849 10850 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 10851 S.DiagnoseCommaOperator(LHS.get(), Loc); 10852 10853 return RHS.get()->getType(); 10854 } 10855 10856 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 10857 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 10858 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 10859 ExprValueKind &VK, 10860 ExprObjectKind &OK, 10861 SourceLocation OpLoc, 10862 bool IsInc, bool IsPrefix) { 10863 if (Op->isTypeDependent()) 10864 return S.Context.DependentTy; 10865 10866 QualType ResType = Op->getType(); 10867 // Atomic types can be used for increment / decrement where the non-atomic 10868 // versions can, so ignore the _Atomic() specifier for the purpose of 10869 // checking. 10870 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10871 ResType = ResAtomicType->getValueType(); 10872 10873 assert(!ResType.isNull() && "no type for increment/decrement expression"); 10874 10875 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 10876 // Decrement of bool is not allowed. 10877 if (!IsInc) { 10878 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 10879 return QualType(); 10880 } 10881 // Increment of bool sets it to true, but is deprecated. 10882 S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool 10883 : diag::warn_increment_bool) 10884 << Op->getSourceRange(); 10885 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 10886 // Error on enum increments and decrements in C++ mode 10887 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 10888 return QualType(); 10889 } else if (ResType->isRealType()) { 10890 // OK! 10891 } else if (ResType->isPointerType()) { 10892 // C99 6.5.2.4p2, 6.5.6p2 10893 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 10894 return QualType(); 10895 } else if (ResType->isObjCObjectPointerType()) { 10896 // On modern runtimes, ObjC pointer arithmetic is forbidden. 10897 // Otherwise, we just need a complete type. 10898 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 10899 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 10900 return QualType(); 10901 } else if (ResType->isAnyComplexType()) { 10902 // C99 does not support ++/-- on complex types, we allow as an extension. 10903 S.Diag(OpLoc, diag::ext_integer_increment_complex) 10904 << ResType << Op->getSourceRange(); 10905 } else if (ResType->isPlaceholderType()) { 10906 ExprResult PR = S.CheckPlaceholderExpr(Op); 10907 if (PR.isInvalid()) return QualType(); 10908 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 10909 IsInc, IsPrefix); 10910 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 10911 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 10912 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 10913 (ResType->getAs<VectorType>()->getVectorKind() != 10914 VectorType::AltiVecBool)) { 10915 // The z vector extensions allow ++ and -- for non-bool vectors. 10916 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 10917 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 10918 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 10919 } else { 10920 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 10921 << ResType << int(IsInc) << Op->getSourceRange(); 10922 return QualType(); 10923 } 10924 // At this point, we know we have a real, complex or pointer type. 10925 // Now make sure the operand is a modifiable lvalue. 10926 if (CheckForModifiableLvalue(Op, OpLoc, S)) 10927 return QualType(); 10928 // In C++, a prefix increment is the same type as the operand. Otherwise 10929 // (in C or with postfix), the increment is the unqualified type of the 10930 // operand. 10931 if (IsPrefix && S.getLangOpts().CPlusPlus) { 10932 VK = VK_LValue; 10933 OK = Op->getObjectKind(); 10934 return ResType; 10935 } else { 10936 VK = VK_RValue; 10937 return ResType.getUnqualifiedType(); 10938 } 10939 } 10940 10941 10942 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 10943 /// This routine allows us to typecheck complex/recursive expressions 10944 /// where the declaration is needed for type checking. We only need to 10945 /// handle cases when the expression references a function designator 10946 /// or is an lvalue. Here are some examples: 10947 /// - &(x) => x 10948 /// - &*****f => f for f a function designator. 10949 /// - &s.xx => s 10950 /// - &s.zz[1].yy -> s, if zz is an array 10951 /// - *(x + 1) -> x, if x is an array 10952 /// - &"123"[2] -> 0 10953 /// - & __real__ x -> x 10954 static ValueDecl *getPrimaryDecl(Expr *E) { 10955 switch (E->getStmtClass()) { 10956 case Stmt::DeclRefExprClass: 10957 return cast<DeclRefExpr>(E)->getDecl(); 10958 case Stmt::MemberExprClass: 10959 // If this is an arrow operator, the address is an offset from 10960 // the base's value, so the object the base refers to is 10961 // irrelevant. 10962 if (cast<MemberExpr>(E)->isArrow()) 10963 return nullptr; 10964 // Otherwise, the expression refers to a part of the base 10965 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 10966 case Stmt::ArraySubscriptExprClass: { 10967 // FIXME: This code shouldn't be necessary! We should catch the implicit 10968 // promotion of register arrays earlier. 10969 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 10970 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 10971 if (ICE->getSubExpr()->getType()->isArrayType()) 10972 return getPrimaryDecl(ICE->getSubExpr()); 10973 } 10974 return nullptr; 10975 } 10976 case Stmt::UnaryOperatorClass: { 10977 UnaryOperator *UO = cast<UnaryOperator>(E); 10978 10979 switch(UO->getOpcode()) { 10980 case UO_Real: 10981 case UO_Imag: 10982 case UO_Extension: 10983 return getPrimaryDecl(UO->getSubExpr()); 10984 default: 10985 return nullptr; 10986 } 10987 } 10988 case Stmt::ParenExprClass: 10989 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 10990 case Stmt::ImplicitCastExprClass: 10991 // If the result of an implicit cast is an l-value, we care about 10992 // the sub-expression; otherwise, the result here doesn't matter. 10993 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 10994 default: 10995 return nullptr; 10996 } 10997 } 10998 10999 namespace { 11000 enum { 11001 AO_Bit_Field = 0, 11002 AO_Vector_Element = 1, 11003 AO_Property_Expansion = 2, 11004 AO_Register_Variable = 3, 11005 AO_No_Error = 4 11006 }; 11007 } 11008 /// \brief Diagnose invalid operand for address of operations. 11009 /// 11010 /// \param Type The type of operand which cannot have its address taken. 11011 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 11012 Expr *E, unsigned Type) { 11013 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 11014 } 11015 11016 /// CheckAddressOfOperand - The operand of & must be either a function 11017 /// designator or an lvalue designating an object. If it is an lvalue, the 11018 /// object cannot be declared with storage class register or be a bit field. 11019 /// Note: The usual conversions are *not* applied to the operand of the & 11020 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 11021 /// In C++, the operand might be an overloaded function name, in which case 11022 /// we allow the '&' but retain the overloaded-function type. 11023 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 11024 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 11025 if (PTy->getKind() == BuiltinType::Overload) { 11026 Expr *E = OrigOp.get()->IgnoreParens(); 11027 if (!isa<OverloadExpr>(E)) { 11028 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 11029 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 11030 << OrigOp.get()->getSourceRange(); 11031 return QualType(); 11032 } 11033 11034 OverloadExpr *Ovl = cast<OverloadExpr>(E); 11035 if (isa<UnresolvedMemberExpr>(Ovl)) 11036 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 11037 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11038 << OrigOp.get()->getSourceRange(); 11039 return QualType(); 11040 } 11041 11042 return Context.OverloadTy; 11043 } 11044 11045 if (PTy->getKind() == BuiltinType::UnknownAny) 11046 return Context.UnknownAnyTy; 11047 11048 if (PTy->getKind() == BuiltinType::BoundMember) { 11049 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11050 << OrigOp.get()->getSourceRange(); 11051 return QualType(); 11052 } 11053 11054 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 11055 if (OrigOp.isInvalid()) return QualType(); 11056 } 11057 11058 if (OrigOp.get()->isTypeDependent()) 11059 return Context.DependentTy; 11060 11061 assert(!OrigOp.get()->getType()->isPlaceholderType()); 11062 11063 // Make sure to ignore parentheses in subsequent checks 11064 Expr *op = OrigOp.get()->IgnoreParens(); 11065 11066 // In OpenCL captures for blocks called as lambda functions 11067 // are located in the private address space. Blocks used in 11068 // enqueue_kernel can be located in a different address space 11069 // depending on a vendor implementation. Thus preventing 11070 // taking an address of the capture to avoid invalid AS casts. 11071 if (LangOpts.OpenCL) { 11072 auto* VarRef = dyn_cast<DeclRefExpr>(op); 11073 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 11074 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 11075 return QualType(); 11076 } 11077 } 11078 11079 if (getLangOpts().C99) { 11080 // Implement C99-only parts of addressof rules. 11081 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 11082 if (uOp->getOpcode() == UO_Deref) 11083 // Per C99 6.5.3.2, the address of a deref always returns a valid result 11084 // (assuming the deref expression is valid). 11085 return uOp->getSubExpr()->getType(); 11086 } 11087 // Technically, there should be a check for array subscript 11088 // expressions here, but the result of one is always an lvalue anyway. 11089 } 11090 ValueDecl *dcl = getPrimaryDecl(op); 11091 11092 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 11093 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 11094 op->getLocStart())) 11095 return QualType(); 11096 11097 Expr::LValueClassification lval = op->ClassifyLValue(Context); 11098 unsigned AddressOfError = AO_No_Error; 11099 11100 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 11101 bool sfinae = (bool)isSFINAEContext(); 11102 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 11103 : diag::ext_typecheck_addrof_temporary) 11104 << op->getType() << op->getSourceRange(); 11105 if (sfinae) 11106 return QualType(); 11107 // Materialize the temporary as an lvalue so that we can take its address. 11108 OrigOp = op = 11109 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 11110 } else if (isa<ObjCSelectorExpr>(op)) { 11111 return Context.getPointerType(op->getType()); 11112 } else if (lval == Expr::LV_MemberFunction) { 11113 // If it's an instance method, make a member pointer. 11114 // The expression must have exactly the form &A::foo. 11115 11116 // If the underlying expression isn't a decl ref, give up. 11117 if (!isa<DeclRefExpr>(op)) { 11118 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11119 << OrigOp.get()->getSourceRange(); 11120 return QualType(); 11121 } 11122 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 11123 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 11124 11125 // The id-expression was parenthesized. 11126 if (OrigOp.get() != DRE) { 11127 Diag(OpLoc, diag::err_parens_pointer_member_function) 11128 << OrigOp.get()->getSourceRange(); 11129 11130 // The method was named without a qualifier. 11131 } else if (!DRE->getQualifier()) { 11132 if (MD->getParent()->getName().empty()) 11133 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 11134 << op->getSourceRange(); 11135 else { 11136 SmallString<32> Str; 11137 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 11138 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 11139 << op->getSourceRange() 11140 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 11141 } 11142 } 11143 11144 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 11145 if (isa<CXXDestructorDecl>(MD)) 11146 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 11147 11148 QualType MPTy = Context.getMemberPointerType( 11149 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 11150 // Under the MS ABI, lock down the inheritance model now. 11151 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11152 (void)isCompleteType(OpLoc, MPTy); 11153 return MPTy; 11154 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 11155 // C99 6.5.3.2p1 11156 // The operand must be either an l-value or a function designator 11157 if (!op->getType()->isFunctionType()) { 11158 // Use a special diagnostic for loads from property references. 11159 if (isa<PseudoObjectExpr>(op)) { 11160 AddressOfError = AO_Property_Expansion; 11161 } else { 11162 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 11163 << op->getType() << op->getSourceRange(); 11164 return QualType(); 11165 } 11166 } 11167 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 11168 // The operand cannot be a bit-field 11169 AddressOfError = AO_Bit_Field; 11170 } else if (op->getObjectKind() == OK_VectorComponent) { 11171 // The operand cannot be an element of a vector 11172 AddressOfError = AO_Vector_Element; 11173 } else if (dcl) { // C99 6.5.3.2p1 11174 // We have an lvalue with a decl. Make sure the decl is not declared 11175 // with the register storage-class specifier. 11176 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 11177 // in C++ it is not error to take address of a register 11178 // variable (c++03 7.1.1P3) 11179 if (vd->getStorageClass() == SC_Register && 11180 !getLangOpts().CPlusPlus) { 11181 AddressOfError = AO_Register_Variable; 11182 } 11183 } else if (isa<MSPropertyDecl>(dcl)) { 11184 AddressOfError = AO_Property_Expansion; 11185 } else if (isa<FunctionTemplateDecl>(dcl)) { 11186 return Context.OverloadTy; 11187 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 11188 // Okay: we can take the address of a field. 11189 // Could be a pointer to member, though, if there is an explicit 11190 // scope qualifier for the class. 11191 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 11192 DeclContext *Ctx = dcl->getDeclContext(); 11193 if (Ctx && Ctx->isRecord()) { 11194 if (dcl->getType()->isReferenceType()) { 11195 Diag(OpLoc, 11196 diag::err_cannot_form_pointer_to_member_of_reference_type) 11197 << dcl->getDeclName() << dcl->getType(); 11198 return QualType(); 11199 } 11200 11201 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 11202 Ctx = Ctx->getParent(); 11203 11204 QualType MPTy = Context.getMemberPointerType( 11205 op->getType(), 11206 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 11207 // Under the MS ABI, lock down the inheritance model now. 11208 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11209 (void)isCompleteType(OpLoc, MPTy); 11210 return MPTy; 11211 } 11212 } 11213 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 11214 !isa<BindingDecl>(dcl)) 11215 llvm_unreachable("Unknown/unexpected decl type"); 11216 } 11217 11218 if (AddressOfError != AO_No_Error) { 11219 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 11220 return QualType(); 11221 } 11222 11223 if (lval == Expr::LV_IncompleteVoidType) { 11224 // Taking the address of a void variable is technically illegal, but we 11225 // allow it in cases which are otherwise valid. 11226 // Example: "extern void x; void* y = &x;". 11227 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 11228 } 11229 11230 // If the operand has type "type", the result has type "pointer to type". 11231 if (op->getType()->isObjCObjectType()) 11232 return Context.getObjCObjectPointerType(op->getType()); 11233 11234 CheckAddressOfPackedMember(op); 11235 11236 return Context.getPointerType(op->getType()); 11237 } 11238 11239 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 11240 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 11241 if (!DRE) 11242 return; 11243 const Decl *D = DRE->getDecl(); 11244 if (!D) 11245 return; 11246 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 11247 if (!Param) 11248 return; 11249 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 11250 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 11251 return; 11252 if (FunctionScopeInfo *FD = S.getCurFunction()) 11253 if (!FD->ModifiedNonNullParams.count(Param)) 11254 FD->ModifiedNonNullParams.insert(Param); 11255 } 11256 11257 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 11258 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 11259 SourceLocation OpLoc) { 11260 if (Op->isTypeDependent()) 11261 return S.Context.DependentTy; 11262 11263 ExprResult ConvResult = S.UsualUnaryConversions(Op); 11264 if (ConvResult.isInvalid()) 11265 return QualType(); 11266 Op = ConvResult.get(); 11267 QualType OpTy = Op->getType(); 11268 QualType Result; 11269 11270 if (isa<CXXReinterpretCastExpr>(Op)) { 11271 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 11272 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 11273 Op->getSourceRange()); 11274 } 11275 11276 if (const PointerType *PT = OpTy->getAs<PointerType>()) 11277 { 11278 Result = PT->getPointeeType(); 11279 } 11280 else if (const ObjCObjectPointerType *OPT = 11281 OpTy->getAs<ObjCObjectPointerType>()) 11282 Result = OPT->getPointeeType(); 11283 else { 11284 ExprResult PR = S.CheckPlaceholderExpr(Op); 11285 if (PR.isInvalid()) return QualType(); 11286 if (PR.get() != Op) 11287 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 11288 } 11289 11290 if (Result.isNull()) { 11291 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 11292 << OpTy << Op->getSourceRange(); 11293 return QualType(); 11294 } 11295 11296 // Note that per both C89 and C99, indirection is always legal, even if Result 11297 // is an incomplete type or void. It would be possible to warn about 11298 // dereferencing a void pointer, but it's completely well-defined, and such a 11299 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 11300 // for pointers to 'void' but is fine for any other pointer type: 11301 // 11302 // C++ [expr.unary.op]p1: 11303 // [...] the expression to which [the unary * operator] is applied shall 11304 // be a pointer to an object type, or a pointer to a function type 11305 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 11306 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 11307 << OpTy << Op->getSourceRange(); 11308 11309 // Dereferences are usually l-values... 11310 VK = VK_LValue; 11311 11312 // ...except that certain expressions are never l-values in C. 11313 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 11314 VK = VK_RValue; 11315 11316 return Result; 11317 } 11318 11319 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 11320 BinaryOperatorKind Opc; 11321 switch (Kind) { 11322 default: llvm_unreachable("Unknown binop!"); 11323 case tok::periodstar: Opc = BO_PtrMemD; break; 11324 case tok::arrowstar: Opc = BO_PtrMemI; break; 11325 case tok::star: Opc = BO_Mul; break; 11326 case tok::slash: Opc = BO_Div; break; 11327 case tok::percent: Opc = BO_Rem; break; 11328 case tok::plus: Opc = BO_Add; break; 11329 case tok::minus: Opc = BO_Sub; break; 11330 case tok::lessless: Opc = BO_Shl; break; 11331 case tok::greatergreater: Opc = BO_Shr; break; 11332 case tok::lessequal: Opc = BO_LE; break; 11333 case tok::less: Opc = BO_LT; break; 11334 case tok::greaterequal: Opc = BO_GE; break; 11335 case tok::greater: Opc = BO_GT; break; 11336 case tok::exclaimequal: Opc = BO_NE; break; 11337 case tok::equalequal: Opc = BO_EQ; break; 11338 case tok::amp: Opc = BO_And; break; 11339 case tok::caret: Opc = BO_Xor; break; 11340 case tok::pipe: Opc = BO_Or; break; 11341 case tok::ampamp: Opc = BO_LAnd; break; 11342 case tok::pipepipe: Opc = BO_LOr; break; 11343 case tok::equal: Opc = BO_Assign; break; 11344 case tok::starequal: Opc = BO_MulAssign; break; 11345 case tok::slashequal: Opc = BO_DivAssign; break; 11346 case tok::percentequal: Opc = BO_RemAssign; break; 11347 case tok::plusequal: Opc = BO_AddAssign; break; 11348 case tok::minusequal: Opc = BO_SubAssign; break; 11349 case tok::lesslessequal: Opc = BO_ShlAssign; break; 11350 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 11351 case tok::ampequal: Opc = BO_AndAssign; break; 11352 case tok::caretequal: Opc = BO_XorAssign; break; 11353 case tok::pipeequal: Opc = BO_OrAssign; break; 11354 case tok::comma: Opc = BO_Comma; break; 11355 } 11356 return Opc; 11357 } 11358 11359 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 11360 tok::TokenKind Kind) { 11361 UnaryOperatorKind Opc; 11362 switch (Kind) { 11363 default: llvm_unreachable("Unknown unary op!"); 11364 case tok::plusplus: Opc = UO_PreInc; break; 11365 case tok::minusminus: Opc = UO_PreDec; break; 11366 case tok::amp: Opc = UO_AddrOf; break; 11367 case tok::star: Opc = UO_Deref; break; 11368 case tok::plus: Opc = UO_Plus; break; 11369 case tok::minus: Opc = UO_Minus; break; 11370 case tok::tilde: Opc = UO_Not; break; 11371 case tok::exclaim: Opc = UO_LNot; break; 11372 case tok::kw___real: Opc = UO_Real; break; 11373 case tok::kw___imag: Opc = UO_Imag; break; 11374 case tok::kw___extension__: Opc = UO_Extension; break; 11375 } 11376 return Opc; 11377 } 11378 11379 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 11380 /// This warning is only emitted for builtin assignment operations. It is also 11381 /// suppressed in the event of macro expansions. 11382 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 11383 SourceLocation OpLoc) { 11384 if (S.inTemplateInstantiation()) 11385 return; 11386 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 11387 return; 11388 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 11389 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 11390 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 11391 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 11392 if (!LHSDeclRef || !RHSDeclRef || 11393 LHSDeclRef->getLocation().isMacroID() || 11394 RHSDeclRef->getLocation().isMacroID()) 11395 return; 11396 const ValueDecl *LHSDecl = 11397 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 11398 const ValueDecl *RHSDecl = 11399 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 11400 if (LHSDecl != RHSDecl) 11401 return; 11402 if (LHSDecl->getType().isVolatileQualified()) 11403 return; 11404 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 11405 if (RefTy->getPointeeType().isVolatileQualified()) 11406 return; 11407 11408 S.Diag(OpLoc, diag::warn_self_assignment) 11409 << LHSDeclRef->getType() 11410 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 11411 } 11412 11413 /// Check if a bitwise-& is performed on an Objective-C pointer. This 11414 /// is usually indicative of introspection within the Objective-C pointer. 11415 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 11416 SourceLocation OpLoc) { 11417 if (!S.getLangOpts().ObjC1) 11418 return; 11419 11420 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 11421 const Expr *LHS = L.get(); 11422 const Expr *RHS = R.get(); 11423 11424 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 11425 ObjCPointerExpr = LHS; 11426 OtherExpr = RHS; 11427 } 11428 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 11429 ObjCPointerExpr = RHS; 11430 OtherExpr = LHS; 11431 } 11432 11433 // This warning is deliberately made very specific to reduce false 11434 // positives with logic that uses '&' for hashing. This logic mainly 11435 // looks for code trying to introspect into tagged pointers, which 11436 // code should generally never do. 11437 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 11438 unsigned Diag = diag::warn_objc_pointer_masking; 11439 // Determine if we are introspecting the result of performSelectorXXX. 11440 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 11441 // Special case messages to -performSelector and friends, which 11442 // can return non-pointer values boxed in a pointer value. 11443 // Some clients may wish to silence warnings in this subcase. 11444 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 11445 Selector S = ME->getSelector(); 11446 StringRef SelArg0 = S.getNameForSlot(0); 11447 if (SelArg0.startswith("performSelector")) 11448 Diag = diag::warn_objc_pointer_masking_performSelector; 11449 } 11450 11451 S.Diag(OpLoc, Diag) 11452 << ObjCPointerExpr->getSourceRange(); 11453 } 11454 } 11455 11456 static NamedDecl *getDeclFromExpr(Expr *E) { 11457 if (!E) 11458 return nullptr; 11459 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 11460 return DRE->getDecl(); 11461 if (auto *ME = dyn_cast<MemberExpr>(E)) 11462 return ME->getMemberDecl(); 11463 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 11464 return IRE->getDecl(); 11465 return nullptr; 11466 } 11467 11468 static std::pair<ExprResult, ExprResult> 11469 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 11470 Expr *RHSExpr) { 11471 ExprResult LHS = LHSExpr, RHS = RHSExpr; 11472 if (!S.getLangOpts().CPlusPlus) { 11473 // C cannot handle TypoExpr nodes on either side of a binop because it 11474 // doesn't handle dependent types properly, so make sure any TypoExprs have 11475 // been dealt with before checking the operands. 11476 LHS = S.CorrectDelayedTyposInExpr(LHS); 11477 RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) { 11478 if (Opc != BO_Assign) 11479 return ExprResult(E); 11480 // Avoid correcting the RHS to the same Expr as the LHS. 11481 Decl *D = getDeclFromExpr(E); 11482 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 11483 }); 11484 } 11485 return std::make_pair(LHS, RHS); 11486 } 11487 11488 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 11489 /// operator @p Opc at location @c TokLoc. This routine only supports 11490 /// built-in operations; ActOnBinOp handles overloaded operators. 11491 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 11492 BinaryOperatorKind Opc, 11493 Expr *LHSExpr, Expr *RHSExpr) { 11494 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 11495 // The syntax only allows initializer lists on the RHS of assignment, 11496 // so we don't need to worry about accepting invalid code for 11497 // non-assignment operators. 11498 // C++11 5.17p9: 11499 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 11500 // of x = {} is x = T(). 11501 InitializationKind Kind = 11502 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 11503 InitializedEntity Entity = 11504 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 11505 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 11506 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 11507 if (Init.isInvalid()) 11508 return Init; 11509 RHSExpr = Init.get(); 11510 } 11511 11512 ExprResult LHS = LHSExpr, RHS = RHSExpr; 11513 QualType ResultTy; // Result type of the binary operator. 11514 // The following two variables are used for compound assignment operators 11515 QualType CompLHSTy; // Type of LHS after promotions for computation 11516 QualType CompResultTy; // Type of computation result 11517 ExprValueKind VK = VK_RValue; 11518 ExprObjectKind OK = OK_Ordinary; 11519 11520 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 11521 if (!LHS.isUsable() || !RHS.isUsable()) 11522 return ExprError(); 11523 11524 if (getLangOpts().OpenCL) { 11525 QualType LHSTy = LHSExpr->getType(); 11526 QualType RHSTy = RHSExpr->getType(); 11527 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 11528 // the ATOMIC_VAR_INIT macro. 11529 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 11530 SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 11531 if (BO_Assign == Opc) 11532 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 11533 else 11534 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 11535 return ExprError(); 11536 } 11537 11538 // OpenCL special types - image, sampler, pipe, and blocks are to be used 11539 // only with a builtin functions and therefore should be disallowed here. 11540 if (LHSTy->isImageType() || RHSTy->isImageType() || 11541 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 11542 LHSTy->isPipeType() || RHSTy->isPipeType() || 11543 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 11544 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 11545 return ExprError(); 11546 } 11547 } 11548 11549 switch (Opc) { 11550 case BO_Assign: 11551 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 11552 if (getLangOpts().CPlusPlus && 11553 LHS.get()->getObjectKind() != OK_ObjCProperty) { 11554 VK = LHS.get()->getValueKind(); 11555 OK = LHS.get()->getObjectKind(); 11556 } 11557 if (!ResultTy.isNull()) { 11558 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 11559 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 11560 } 11561 RecordModifiableNonNullParam(*this, LHS.get()); 11562 break; 11563 case BO_PtrMemD: 11564 case BO_PtrMemI: 11565 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 11566 Opc == BO_PtrMemI); 11567 break; 11568 case BO_Mul: 11569 case BO_Div: 11570 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 11571 Opc == BO_Div); 11572 break; 11573 case BO_Rem: 11574 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 11575 break; 11576 case BO_Add: 11577 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 11578 break; 11579 case BO_Sub: 11580 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 11581 break; 11582 case BO_Shl: 11583 case BO_Shr: 11584 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 11585 break; 11586 case BO_LE: 11587 case BO_LT: 11588 case BO_GE: 11589 case BO_GT: 11590 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 11591 break; 11592 case BO_EQ: 11593 case BO_NE: 11594 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 11595 break; 11596 case BO_And: 11597 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 11598 LLVM_FALLTHROUGH; 11599 case BO_Xor: 11600 case BO_Or: 11601 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 11602 break; 11603 case BO_LAnd: 11604 case BO_LOr: 11605 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 11606 break; 11607 case BO_MulAssign: 11608 case BO_DivAssign: 11609 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 11610 Opc == BO_DivAssign); 11611 CompLHSTy = CompResultTy; 11612 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11613 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11614 break; 11615 case BO_RemAssign: 11616 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 11617 CompLHSTy = CompResultTy; 11618 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11619 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11620 break; 11621 case BO_AddAssign: 11622 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 11623 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11624 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11625 break; 11626 case BO_SubAssign: 11627 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 11628 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11629 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11630 break; 11631 case BO_ShlAssign: 11632 case BO_ShrAssign: 11633 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 11634 CompLHSTy = CompResultTy; 11635 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11636 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11637 break; 11638 case BO_AndAssign: 11639 case BO_OrAssign: // fallthrough 11640 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 11641 LLVM_FALLTHROUGH; 11642 case BO_XorAssign: 11643 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 11644 CompLHSTy = CompResultTy; 11645 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11646 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11647 break; 11648 case BO_Comma: 11649 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 11650 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 11651 VK = RHS.get()->getValueKind(); 11652 OK = RHS.get()->getObjectKind(); 11653 } 11654 break; 11655 } 11656 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 11657 return ExprError(); 11658 11659 // Check for array bounds violations for both sides of the BinaryOperator 11660 CheckArrayAccess(LHS.get()); 11661 CheckArrayAccess(RHS.get()); 11662 11663 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 11664 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 11665 &Context.Idents.get("object_setClass"), 11666 SourceLocation(), LookupOrdinaryName); 11667 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 11668 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd()); 11669 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 11670 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 11671 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 11672 FixItHint::CreateInsertion(RHSLocEnd, ")"); 11673 } 11674 else 11675 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 11676 } 11677 else if (const ObjCIvarRefExpr *OIRE = 11678 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 11679 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 11680 11681 if (CompResultTy.isNull()) 11682 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 11683 OK, OpLoc, FPFeatures); 11684 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 11685 OK_ObjCProperty) { 11686 VK = VK_LValue; 11687 OK = LHS.get()->getObjectKind(); 11688 } 11689 return new (Context) CompoundAssignOperator( 11690 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 11691 OpLoc, FPFeatures); 11692 } 11693 11694 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 11695 /// operators are mixed in a way that suggests that the programmer forgot that 11696 /// comparison operators have higher precedence. The most typical example of 11697 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 11698 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 11699 SourceLocation OpLoc, Expr *LHSExpr, 11700 Expr *RHSExpr) { 11701 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 11702 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 11703 11704 // Check that one of the sides is a comparison operator and the other isn't. 11705 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 11706 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 11707 if (isLeftComp == isRightComp) 11708 return; 11709 11710 // Bitwise operations are sometimes used as eager logical ops. 11711 // Don't diagnose this. 11712 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 11713 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 11714 if (isLeftBitwise || isRightBitwise) 11715 return; 11716 11717 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 11718 OpLoc) 11719 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 11720 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 11721 SourceRange ParensRange = isLeftComp ? 11722 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 11723 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd()); 11724 11725 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 11726 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 11727 SuggestParentheses(Self, OpLoc, 11728 Self.PDiag(diag::note_precedence_silence) << OpStr, 11729 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 11730 SuggestParentheses(Self, OpLoc, 11731 Self.PDiag(diag::note_precedence_bitwise_first) 11732 << BinaryOperator::getOpcodeStr(Opc), 11733 ParensRange); 11734 } 11735 11736 /// \brief It accepts a '&&' expr that is inside a '||' one. 11737 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 11738 /// in parentheses. 11739 static void 11740 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 11741 BinaryOperator *Bop) { 11742 assert(Bop->getOpcode() == BO_LAnd); 11743 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 11744 << Bop->getSourceRange() << OpLoc; 11745 SuggestParentheses(Self, Bop->getOperatorLoc(), 11746 Self.PDiag(diag::note_precedence_silence) 11747 << Bop->getOpcodeStr(), 11748 Bop->getSourceRange()); 11749 } 11750 11751 /// \brief Returns true if the given expression can be evaluated as a constant 11752 /// 'true'. 11753 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 11754 bool Res; 11755 return !E->isValueDependent() && 11756 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 11757 } 11758 11759 /// \brief Returns true if the given expression can be evaluated as a constant 11760 /// 'false'. 11761 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 11762 bool Res; 11763 return !E->isValueDependent() && 11764 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 11765 } 11766 11767 /// \brief Look for '&&' in the left hand of a '||' expr. 11768 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 11769 Expr *LHSExpr, Expr *RHSExpr) { 11770 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 11771 if (Bop->getOpcode() == BO_LAnd) { 11772 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 11773 if (EvaluatesAsFalse(S, RHSExpr)) 11774 return; 11775 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 11776 if (!EvaluatesAsTrue(S, Bop->getLHS())) 11777 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11778 } else if (Bop->getOpcode() == BO_LOr) { 11779 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 11780 // If it's "a || b && 1 || c" we didn't warn earlier for 11781 // "a || b && 1", but warn now. 11782 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 11783 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 11784 } 11785 } 11786 } 11787 } 11788 11789 /// \brief Look for '&&' in the right hand of a '||' expr. 11790 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 11791 Expr *LHSExpr, Expr *RHSExpr) { 11792 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 11793 if (Bop->getOpcode() == BO_LAnd) { 11794 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 11795 if (EvaluatesAsFalse(S, LHSExpr)) 11796 return; 11797 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 11798 if (!EvaluatesAsTrue(S, Bop->getRHS())) 11799 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11800 } 11801 } 11802 } 11803 11804 /// \brief Look for bitwise op in the left or right hand of a bitwise op with 11805 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 11806 /// the '&' expression in parentheses. 11807 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 11808 SourceLocation OpLoc, Expr *SubExpr) { 11809 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11810 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 11811 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 11812 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 11813 << Bop->getSourceRange() << OpLoc; 11814 SuggestParentheses(S, Bop->getOperatorLoc(), 11815 S.PDiag(diag::note_precedence_silence) 11816 << Bop->getOpcodeStr(), 11817 Bop->getSourceRange()); 11818 } 11819 } 11820 } 11821 11822 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 11823 Expr *SubExpr, StringRef Shift) { 11824 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11825 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 11826 StringRef Op = Bop->getOpcodeStr(); 11827 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 11828 << Bop->getSourceRange() << OpLoc << Shift << Op; 11829 SuggestParentheses(S, Bop->getOperatorLoc(), 11830 S.PDiag(diag::note_precedence_silence) << Op, 11831 Bop->getSourceRange()); 11832 } 11833 } 11834 } 11835 11836 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 11837 Expr *LHSExpr, Expr *RHSExpr) { 11838 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 11839 if (!OCE) 11840 return; 11841 11842 FunctionDecl *FD = OCE->getDirectCallee(); 11843 if (!FD || !FD->isOverloadedOperator()) 11844 return; 11845 11846 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 11847 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 11848 return; 11849 11850 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 11851 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 11852 << (Kind == OO_LessLess); 11853 SuggestParentheses(S, OCE->getOperatorLoc(), 11854 S.PDiag(diag::note_precedence_silence) 11855 << (Kind == OO_LessLess ? "<<" : ">>"), 11856 OCE->getSourceRange()); 11857 SuggestParentheses(S, OpLoc, 11858 S.PDiag(diag::note_evaluate_comparison_first), 11859 SourceRange(OCE->getArg(1)->getLocStart(), 11860 RHSExpr->getLocEnd())); 11861 } 11862 11863 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 11864 /// precedence. 11865 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 11866 SourceLocation OpLoc, Expr *LHSExpr, 11867 Expr *RHSExpr){ 11868 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 11869 if (BinaryOperator::isBitwiseOp(Opc)) 11870 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 11871 11872 // Diagnose "arg1 & arg2 | arg3" 11873 if ((Opc == BO_Or || Opc == BO_Xor) && 11874 !OpLoc.isMacroID()/* Don't warn in macros. */) { 11875 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 11876 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 11877 } 11878 11879 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 11880 // We don't warn for 'assert(a || b && "bad")' since this is safe. 11881 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 11882 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 11883 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 11884 } 11885 11886 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 11887 || Opc == BO_Shr) { 11888 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 11889 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 11890 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 11891 } 11892 11893 // Warn on overloaded shift operators and comparisons, such as: 11894 // cout << 5 == 4; 11895 if (BinaryOperator::isComparisonOp(Opc)) 11896 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 11897 } 11898 11899 // Binary Operators. 'Tok' is the token for the operator. 11900 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 11901 tok::TokenKind Kind, 11902 Expr *LHSExpr, Expr *RHSExpr) { 11903 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 11904 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 11905 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 11906 11907 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 11908 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 11909 11910 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 11911 } 11912 11913 /// Build an overloaded binary operator expression in the given scope. 11914 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 11915 BinaryOperatorKind Opc, 11916 Expr *LHS, Expr *RHS) { 11917 // Find all of the overloaded operators visible from this 11918 // point. We perform both an operator-name lookup from the local 11919 // scope and an argument-dependent lookup based on the types of 11920 // the arguments. 11921 UnresolvedSet<16> Functions; 11922 OverloadedOperatorKind OverOp 11923 = BinaryOperator::getOverloadedOperator(Opc); 11924 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 11925 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 11926 RHS->getType(), Functions); 11927 11928 // Build the (potentially-overloaded, potentially-dependent) 11929 // binary operation. 11930 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 11931 } 11932 11933 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 11934 BinaryOperatorKind Opc, 11935 Expr *LHSExpr, Expr *RHSExpr) { 11936 ExprResult LHS, RHS; 11937 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 11938 if (!LHS.isUsable() || !RHS.isUsable()) 11939 return ExprError(); 11940 LHSExpr = LHS.get(); 11941 RHSExpr = RHS.get(); 11942 11943 // We want to end up calling one of checkPseudoObjectAssignment 11944 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 11945 // both expressions are overloadable or either is type-dependent), 11946 // or CreateBuiltinBinOp (in any other case). We also want to get 11947 // any placeholder types out of the way. 11948 11949 // Handle pseudo-objects in the LHS. 11950 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 11951 // Assignments with a pseudo-object l-value need special analysis. 11952 if (pty->getKind() == BuiltinType::PseudoObject && 11953 BinaryOperator::isAssignmentOp(Opc)) 11954 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 11955 11956 // Don't resolve overloads if the other type is overloadable. 11957 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 11958 // We can't actually test that if we still have a placeholder, 11959 // though. Fortunately, none of the exceptions we see in that 11960 // code below are valid when the LHS is an overload set. Note 11961 // that an overload set can be dependently-typed, but it never 11962 // instantiates to having an overloadable type. 11963 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 11964 if (resolvedRHS.isInvalid()) return ExprError(); 11965 RHSExpr = resolvedRHS.get(); 11966 11967 if (RHSExpr->isTypeDependent() || 11968 RHSExpr->getType()->isOverloadableType()) 11969 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11970 } 11971 11972 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 11973 // template, diagnose the missing 'template' keyword instead of diagnosing 11974 // an invalid use of a bound member function. 11975 // 11976 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 11977 // to C++1z [over.over]/1.4, but we already checked for that case above. 11978 if (Opc == BO_LT && inTemplateInstantiation() && 11979 (pty->getKind() == BuiltinType::BoundMember || 11980 pty->getKind() == BuiltinType::Overload)) { 11981 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 11982 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 11983 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 11984 return isa<FunctionTemplateDecl>(ND); 11985 })) { 11986 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 11987 : OE->getNameLoc(), 11988 diag::err_template_kw_missing) 11989 << OE->getName().getAsString() << ""; 11990 return ExprError(); 11991 } 11992 } 11993 11994 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 11995 if (LHS.isInvalid()) return ExprError(); 11996 LHSExpr = LHS.get(); 11997 } 11998 11999 // Handle pseudo-objects in the RHS. 12000 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 12001 // An overload in the RHS can potentially be resolved by the type 12002 // being assigned to. 12003 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 12004 if (getLangOpts().CPlusPlus && 12005 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 12006 LHSExpr->getType()->isOverloadableType())) 12007 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12008 12009 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 12010 } 12011 12012 // Don't resolve overloads if the other type is overloadable. 12013 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 12014 LHSExpr->getType()->isOverloadableType()) 12015 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12016 12017 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 12018 if (!resolvedRHS.isUsable()) return ExprError(); 12019 RHSExpr = resolvedRHS.get(); 12020 } 12021 12022 if (getLangOpts().CPlusPlus) { 12023 // If either expression is type-dependent, always build an 12024 // overloaded op. 12025 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 12026 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12027 12028 // Otherwise, build an overloaded op if either expression has an 12029 // overloadable type. 12030 if (LHSExpr->getType()->isOverloadableType() || 12031 RHSExpr->getType()->isOverloadableType()) 12032 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12033 } 12034 12035 // Build a built-in binary operation. 12036 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 12037 } 12038 12039 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 12040 UnaryOperatorKind Opc, 12041 Expr *InputExpr) { 12042 ExprResult Input = InputExpr; 12043 ExprValueKind VK = VK_RValue; 12044 ExprObjectKind OK = OK_Ordinary; 12045 QualType resultType; 12046 if (getLangOpts().OpenCL) { 12047 QualType Ty = InputExpr->getType(); 12048 // The only legal unary operation for atomics is '&'. 12049 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 12050 // OpenCL special types - image, sampler, pipe, and blocks are to be used 12051 // only with a builtin functions and therefore should be disallowed here. 12052 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 12053 || Ty->isBlockPointerType())) { 12054 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12055 << InputExpr->getType() 12056 << Input.get()->getSourceRange()); 12057 } 12058 } 12059 switch (Opc) { 12060 case UO_PreInc: 12061 case UO_PreDec: 12062 case UO_PostInc: 12063 case UO_PostDec: 12064 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 12065 OpLoc, 12066 Opc == UO_PreInc || 12067 Opc == UO_PostInc, 12068 Opc == UO_PreInc || 12069 Opc == UO_PreDec); 12070 break; 12071 case UO_AddrOf: 12072 resultType = CheckAddressOfOperand(Input, OpLoc); 12073 RecordModifiableNonNullParam(*this, InputExpr); 12074 break; 12075 case UO_Deref: { 12076 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 12077 if (Input.isInvalid()) return ExprError(); 12078 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 12079 break; 12080 } 12081 case UO_Plus: 12082 case UO_Minus: 12083 Input = UsualUnaryConversions(Input.get()); 12084 if (Input.isInvalid()) return ExprError(); 12085 resultType = Input.get()->getType(); 12086 if (resultType->isDependentType()) 12087 break; 12088 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 12089 break; 12090 else if (resultType->isVectorType() && 12091 // The z vector extensions don't allow + or - with bool vectors. 12092 (!Context.getLangOpts().ZVector || 12093 resultType->getAs<VectorType>()->getVectorKind() != 12094 VectorType::AltiVecBool)) 12095 break; 12096 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 12097 Opc == UO_Plus && 12098 resultType->isPointerType()) 12099 break; 12100 12101 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12102 << resultType << Input.get()->getSourceRange()); 12103 12104 case UO_Not: // bitwise complement 12105 Input = UsualUnaryConversions(Input.get()); 12106 if (Input.isInvalid()) 12107 return ExprError(); 12108 resultType = Input.get()->getType(); 12109 if (resultType->isDependentType()) 12110 break; 12111 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 12112 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 12113 // C99 does not support '~' for complex conjugation. 12114 Diag(OpLoc, diag::ext_integer_complement_complex) 12115 << resultType << Input.get()->getSourceRange(); 12116 else if (resultType->hasIntegerRepresentation()) 12117 break; 12118 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 12119 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 12120 // on vector float types. 12121 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 12122 if (!T->isIntegerType()) 12123 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12124 << resultType << Input.get()->getSourceRange()); 12125 } else { 12126 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12127 << resultType << Input.get()->getSourceRange()); 12128 } 12129 break; 12130 12131 case UO_LNot: // logical negation 12132 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 12133 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 12134 if (Input.isInvalid()) return ExprError(); 12135 resultType = Input.get()->getType(); 12136 12137 // Though we still have to promote half FP to float... 12138 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 12139 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 12140 resultType = Context.FloatTy; 12141 } 12142 12143 if (resultType->isDependentType()) 12144 break; 12145 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 12146 // C99 6.5.3.3p1: ok, fallthrough; 12147 if (Context.getLangOpts().CPlusPlus) { 12148 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 12149 // operand contextually converted to bool. 12150 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 12151 ScalarTypeToBooleanCastKind(resultType)); 12152 } else if (Context.getLangOpts().OpenCL && 12153 Context.getLangOpts().OpenCLVersion < 120) { 12154 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 12155 // operate on scalar float types. 12156 if (!resultType->isIntegerType() && !resultType->isPointerType()) 12157 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12158 << resultType << Input.get()->getSourceRange()); 12159 } 12160 } else if (resultType->isExtVectorType()) { 12161 if (Context.getLangOpts().OpenCL && 12162 Context.getLangOpts().OpenCLVersion < 120) { 12163 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 12164 // operate on vector float types. 12165 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 12166 if (!T->isIntegerType()) 12167 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12168 << resultType << Input.get()->getSourceRange()); 12169 } 12170 // Vector logical not returns the signed variant of the operand type. 12171 resultType = GetSignedVectorType(resultType); 12172 break; 12173 } else { 12174 // FIXME: GCC's vector extension permits the usage of '!' with a vector 12175 // type in C++. We should allow that here too. 12176 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12177 << resultType << Input.get()->getSourceRange()); 12178 } 12179 12180 // LNot always has type int. C99 6.5.3.3p5. 12181 // In C++, it's bool. C++ 5.3.1p8 12182 resultType = Context.getLogicalOperationType(); 12183 break; 12184 case UO_Real: 12185 case UO_Imag: 12186 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 12187 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 12188 // complex l-values to ordinary l-values and all other values to r-values. 12189 if (Input.isInvalid()) return ExprError(); 12190 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 12191 if (Input.get()->getValueKind() != VK_RValue && 12192 Input.get()->getObjectKind() == OK_Ordinary) 12193 VK = Input.get()->getValueKind(); 12194 } else if (!getLangOpts().CPlusPlus) { 12195 // In C, a volatile scalar is read by __imag. In C++, it is not. 12196 Input = DefaultLvalueConversion(Input.get()); 12197 } 12198 break; 12199 case UO_Extension: 12200 resultType = Input.get()->getType(); 12201 VK = Input.get()->getValueKind(); 12202 OK = Input.get()->getObjectKind(); 12203 break; 12204 case UO_Coawait: 12205 // It's unnessesary to represent the pass-through operator co_await in the 12206 // AST; just return the input expression instead. 12207 assert(!Input.get()->getType()->isDependentType() && 12208 "the co_await expression must be non-dependant before " 12209 "building operator co_await"); 12210 return Input; 12211 } 12212 if (resultType.isNull() || Input.isInvalid()) 12213 return ExprError(); 12214 12215 // Check for array bounds violations in the operand of the UnaryOperator, 12216 // except for the '*' and '&' operators that have to be handled specially 12217 // by CheckArrayAccess (as there are special cases like &array[arraysize] 12218 // that are explicitly defined as valid by the standard). 12219 if (Opc != UO_AddrOf && Opc != UO_Deref) 12220 CheckArrayAccess(Input.get()); 12221 12222 return new (Context) 12223 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc); 12224 } 12225 12226 /// \brief Determine whether the given expression is a qualified member 12227 /// access expression, of a form that could be turned into a pointer to member 12228 /// with the address-of operator. 12229 static bool isQualifiedMemberAccess(Expr *E) { 12230 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12231 if (!DRE->getQualifier()) 12232 return false; 12233 12234 ValueDecl *VD = DRE->getDecl(); 12235 if (!VD->isCXXClassMember()) 12236 return false; 12237 12238 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 12239 return true; 12240 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 12241 return Method->isInstance(); 12242 12243 return false; 12244 } 12245 12246 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 12247 if (!ULE->getQualifier()) 12248 return false; 12249 12250 for (NamedDecl *D : ULE->decls()) { 12251 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 12252 if (Method->isInstance()) 12253 return true; 12254 } else { 12255 // Overload set does not contain methods. 12256 break; 12257 } 12258 } 12259 12260 return false; 12261 } 12262 12263 return false; 12264 } 12265 12266 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 12267 UnaryOperatorKind Opc, Expr *Input) { 12268 // First things first: handle placeholders so that the 12269 // overloaded-operator check considers the right type. 12270 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 12271 // Increment and decrement of pseudo-object references. 12272 if (pty->getKind() == BuiltinType::PseudoObject && 12273 UnaryOperator::isIncrementDecrementOp(Opc)) 12274 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 12275 12276 // extension is always a builtin operator. 12277 if (Opc == UO_Extension) 12278 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12279 12280 // & gets special logic for several kinds of placeholder. 12281 // The builtin code knows what to do. 12282 if (Opc == UO_AddrOf && 12283 (pty->getKind() == BuiltinType::Overload || 12284 pty->getKind() == BuiltinType::UnknownAny || 12285 pty->getKind() == BuiltinType::BoundMember)) 12286 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12287 12288 // Anything else needs to be handled now. 12289 ExprResult Result = CheckPlaceholderExpr(Input); 12290 if (Result.isInvalid()) return ExprError(); 12291 Input = Result.get(); 12292 } 12293 12294 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 12295 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 12296 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 12297 // Find all of the overloaded operators visible from this 12298 // point. We perform both an operator-name lookup from the local 12299 // scope and an argument-dependent lookup based on the types of 12300 // the arguments. 12301 UnresolvedSet<16> Functions; 12302 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 12303 if (S && OverOp != OO_None) 12304 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 12305 Functions); 12306 12307 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 12308 } 12309 12310 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12311 } 12312 12313 // Unary Operators. 'Tok' is the token for the operator. 12314 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 12315 tok::TokenKind Op, Expr *Input) { 12316 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 12317 } 12318 12319 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 12320 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 12321 LabelDecl *TheDecl) { 12322 TheDecl->markUsed(Context); 12323 // Create the AST node. The address of a label always has type 'void*'. 12324 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 12325 Context.getPointerType(Context.VoidTy)); 12326 } 12327 12328 /// Given the last statement in a statement-expression, check whether 12329 /// the result is a producing expression (like a call to an 12330 /// ns_returns_retained function) and, if so, rebuild it to hoist the 12331 /// release out of the full-expression. Otherwise, return null. 12332 /// Cannot fail. 12333 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 12334 // Should always be wrapped with one of these. 12335 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 12336 if (!cleanups) return nullptr; 12337 12338 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 12339 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 12340 return nullptr; 12341 12342 // Splice out the cast. This shouldn't modify any interesting 12343 // features of the statement. 12344 Expr *producer = cast->getSubExpr(); 12345 assert(producer->getType() == cast->getType()); 12346 assert(producer->getValueKind() == cast->getValueKind()); 12347 cleanups->setSubExpr(producer); 12348 return cleanups; 12349 } 12350 12351 void Sema::ActOnStartStmtExpr() { 12352 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 12353 } 12354 12355 void Sema::ActOnStmtExprError() { 12356 // Note that function is also called by TreeTransform when leaving a 12357 // StmtExpr scope without rebuilding anything. 12358 12359 DiscardCleanupsInEvaluationContext(); 12360 PopExpressionEvaluationContext(); 12361 } 12362 12363 ExprResult 12364 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 12365 SourceLocation RPLoc) { // "({..})" 12366 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 12367 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 12368 12369 if (hasAnyUnrecoverableErrorsInThisFunction()) 12370 DiscardCleanupsInEvaluationContext(); 12371 assert(!Cleanup.exprNeedsCleanups() && 12372 "cleanups within StmtExpr not correctly bound!"); 12373 PopExpressionEvaluationContext(); 12374 12375 // FIXME: there are a variety of strange constraints to enforce here, for 12376 // example, it is not possible to goto into a stmt expression apparently. 12377 // More semantic analysis is needed. 12378 12379 // If there are sub-stmts in the compound stmt, take the type of the last one 12380 // as the type of the stmtexpr. 12381 QualType Ty = Context.VoidTy; 12382 bool StmtExprMayBindToTemp = false; 12383 if (!Compound->body_empty()) { 12384 Stmt *LastStmt = Compound->body_back(); 12385 LabelStmt *LastLabelStmt = nullptr; 12386 // If LastStmt is a label, skip down through into the body. 12387 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 12388 LastLabelStmt = Label; 12389 LastStmt = Label->getSubStmt(); 12390 } 12391 12392 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 12393 // Do function/array conversion on the last expression, but not 12394 // lvalue-to-rvalue. However, initialize an unqualified type. 12395 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 12396 if (LastExpr.isInvalid()) 12397 return ExprError(); 12398 Ty = LastExpr.get()->getType().getUnqualifiedType(); 12399 12400 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 12401 // In ARC, if the final expression ends in a consume, splice 12402 // the consume out and bind it later. In the alternate case 12403 // (when dealing with a retainable type), the result 12404 // initialization will create a produce. In both cases the 12405 // result will be +1, and we'll need to balance that out with 12406 // a bind. 12407 if (Expr *rebuiltLastStmt 12408 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 12409 LastExpr = rebuiltLastStmt; 12410 } else { 12411 LastExpr = PerformCopyInitialization( 12412 InitializedEntity::InitializeResult(LPLoc, 12413 Ty, 12414 false), 12415 SourceLocation(), 12416 LastExpr); 12417 } 12418 12419 if (LastExpr.isInvalid()) 12420 return ExprError(); 12421 if (LastExpr.get() != nullptr) { 12422 if (!LastLabelStmt) 12423 Compound->setLastStmt(LastExpr.get()); 12424 else 12425 LastLabelStmt->setSubStmt(LastExpr.get()); 12426 StmtExprMayBindToTemp = true; 12427 } 12428 } 12429 } 12430 } 12431 12432 // FIXME: Check that expression type is complete/non-abstract; statement 12433 // expressions are not lvalues. 12434 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 12435 if (StmtExprMayBindToTemp) 12436 return MaybeBindToTemporary(ResStmtExpr); 12437 return ResStmtExpr; 12438 } 12439 12440 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 12441 TypeSourceInfo *TInfo, 12442 ArrayRef<OffsetOfComponent> Components, 12443 SourceLocation RParenLoc) { 12444 QualType ArgTy = TInfo->getType(); 12445 bool Dependent = ArgTy->isDependentType(); 12446 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 12447 12448 // We must have at least one component that refers to the type, and the first 12449 // one is known to be a field designator. Verify that the ArgTy represents 12450 // a struct/union/class. 12451 if (!Dependent && !ArgTy->isRecordType()) 12452 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 12453 << ArgTy << TypeRange); 12454 12455 // Type must be complete per C99 7.17p3 because a declaring a variable 12456 // with an incomplete type would be ill-formed. 12457 if (!Dependent 12458 && RequireCompleteType(BuiltinLoc, ArgTy, 12459 diag::err_offsetof_incomplete_type, TypeRange)) 12460 return ExprError(); 12461 12462 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 12463 // GCC extension, diagnose them. 12464 // FIXME: This diagnostic isn't actually visible because the location is in 12465 // a system header! 12466 if (Components.size() != 1) 12467 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 12468 << SourceRange(Components[1].LocStart, Components.back().LocEnd); 12469 12470 bool DidWarnAboutNonPOD = false; 12471 QualType CurrentType = ArgTy; 12472 SmallVector<OffsetOfNode, 4> Comps; 12473 SmallVector<Expr*, 4> Exprs; 12474 for (const OffsetOfComponent &OC : Components) { 12475 if (OC.isBrackets) { 12476 // Offset of an array sub-field. TODO: Should we allow vector elements? 12477 if (!CurrentType->isDependentType()) { 12478 const ArrayType *AT = Context.getAsArrayType(CurrentType); 12479 if(!AT) 12480 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 12481 << CurrentType); 12482 CurrentType = AT->getElementType(); 12483 } else 12484 CurrentType = Context.DependentTy; 12485 12486 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 12487 if (IdxRval.isInvalid()) 12488 return ExprError(); 12489 Expr *Idx = IdxRval.get(); 12490 12491 // The expression must be an integral expression. 12492 // FIXME: An integral constant expression? 12493 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 12494 !Idx->getType()->isIntegerType()) 12495 return ExprError(Diag(Idx->getLocStart(), 12496 diag::err_typecheck_subscript_not_integer) 12497 << Idx->getSourceRange()); 12498 12499 // Record this array index. 12500 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 12501 Exprs.push_back(Idx); 12502 continue; 12503 } 12504 12505 // Offset of a field. 12506 if (CurrentType->isDependentType()) { 12507 // We have the offset of a field, but we can't look into the dependent 12508 // type. Just record the identifier of the field. 12509 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 12510 CurrentType = Context.DependentTy; 12511 continue; 12512 } 12513 12514 // We need to have a complete type to look into. 12515 if (RequireCompleteType(OC.LocStart, CurrentType, 12516 diag::err_offsetof_incomplete_type)) 12517 return ExprError(); 12518 12519 // Look for the designated field. 12520 const RecordType *RC = CurrentType->getAs<RecordType>(); 12521 if (!RC) 12522 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 12523 << CurrentType); 12524 RecordDecl *RD = RC->getDecl(); 12525 12526 // C++ [lib.support.types]p5: 12527 // The macro offsetof accepts a restricted set of type arguments in this 12528 // International Standard. type shall be a POD structure or a POD union 12529 // (clause 9). 12530 // C++11 [support.types]p4: 12531 // If type is not a standard-layout class (Clause 9), the results are 12532 // undefined. 12533 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 12534 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 12535 unsigned DiagID = 12536 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 12537 : diag::ext_offsetof_non_pod_type; 12538 12539 if (!IsSafe && !DidWarnAboutNonPOD && 12540 DiagRuntimeBehavior(BuiltinLoc, nullptr, 12541 PDiag(DiagID) 12542 << SourceRange(Components[0].LocStart, OC.LocEnd) 12543 << CurrentType)) 12544 DidWarnAboutNonPOD = true; 12545 } 12546 12547 // Look for the field. 12548 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 12549 LookupQualifiedName(R, RD); 12550 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 12551 IndirectFieldDecl *IndirectMemberDecl = nullptr; 12552 if (!MemberDecl) { 12553 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 12554 MemberDecl = IndirectMemberDecl->getAnonField(); 12555 } 12556 12557 if (!MemberDecl) 12558 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 12559 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 12560 OC.LocEnd)); 12561 12562 // C99 7.17p3: 12563 // (If the specified member is a bit-field, the behavior is undefined.) 12564 // 12565 // We diagnose this as an error. 12566 if (MemberDecl->isBitField()) { 12567 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 12568 << MemberDecl->getDeclName() 12569 << SourceRange(BuiltinLoc, RParenLoc); 12570 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 12571 return ExprError(); 12572 } 12573 12574 RecordDecl *Parent = MemberDecl->getParent(); 12575 if (IndirectMemberDecl) 12576 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 12577 12578 // If the member was found in a base class, introduce OffsetOfNodes for 12579 // the base class indirections. 12580 CXXBasePaths Paths; 12581 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 12582 Paths)) { 12583 if (Paths.getDetectedVirtual()) { 12584 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 12585 << MemberDecl->getDeclName() 12586 << SourceRange(BuiltinLoc, RParenLoc); 12587 return ExprError(); 12588 } 12589 12590 CXXBasePath &Path = Paths.front(); 12591 for (const CXXBasePathElement &B : Path) 12592 Comps.push_back(OffsetOfNode(B.Base)); 12593 } 12594 12595 if (IndirectMemberDecl) { 12596 for (auto *FI : IndirectMemberDecl->chain()) { 12597 assert(isa<FieldDecl>(FI)); 12598 Comps.push_back(OffsetOfNode(OC.LocStart, 12599 cast<FieldDecl>(FI), OC.LocEnd)); 12600 } 12601 } else 12602 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 12603 12604 CurrentType = MemberDecl->getType().getNonReferenceType(); 12605 } 12606 12607 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 12608 Comps, Exprs, RParenLoc); 12609 } 12610 12611 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 12612 SourceLocation BuiltinLoc, 12613 SourceLocation TypeLoc, 12614 ParsedType ParsedArgTy, 12615 ArrayRef<OffsetOfComponent> Components, 12616 SourceLocation RParenLoc) { 12617 12618 TypeSourceInfo *ArgTInfo; 12619 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 12620 if (ArgTy.isNull()) 12621 return ExprError(); 12622 12623 if (!ArgTInfo) 12624 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 12625 12626 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 12627 } 12628 12629 12630 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 12631 Expr *CondExpr, 12632 Expr *LHSExpr, Expr *RHSExpr, 12633 SourceLocation RPLoc) { 12634 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 12635 12636 ExprValueKind VK = VK_RValue; 12637 ExprObjectKind OK = OK_Ordinary; 12638 QualType resType; 12639 bool ValueDependent = false; 12640 bool CondIsTrue = false; 12641 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 12642 resType = Context.DependentTy; 12643 ValueDependent = true; 12644 } else { 12645 // The conditional expression is required to be a constant expression. 12646 llvm::APSInt condEval(32); 12647 ExprResult CondICE 12648 = VerifyIntegerConstantExpression(CondExpr, &condEval, 12649 diag::err_typecheck_choose_expr_requires_constant, false); 12650 if (CondICE.isInvalid()) 12651 return ExprError(); 12652 CondExpr = CondICE.get(); 12653 CondIsTrue = condEval.getZExtValue(); 12654 12655 // If the condition is > zero, then the AST type is the same as the LSHExpr. 12656 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 12657 12658 resType = ActiveExpr->getType(); 12659 ValueDependent = ActiveExpr->isValueDependent(); 12660 VK = ActiveExpr->getValueKind(); 12661 OK = ActiveExpr->getObjectKind(); 12662 } 12663 12664 return new (Context) 12665 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 12666 CondIsTrue, resType->isDependentType(), ValueDependent); 12667 } 12668 12669 //===----------------------------------------------------------------------===// 12670 // Clang Extensions. 12671 //===----------------------------------------------------------------------===// 12672 12673 /// ActOnBlockStart - This callback is invoked when a block literal is started. 12674 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 12675 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 12676 12677 if (LangOpts.CPlusPlus) { 12678 Decl *ManglingContextDecl; 12679 if (MangleNumberingContext *MCtx = 12680 getCurrentMangleNumberContext(Block->getDeclContext(), 12681 ManglingContextDecl)) { 12682 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 12683 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 12684 } 12685 } 12686 12687 PushBlockScope(CurScope, Block); 12688 CurContext->addDecl(Block); 12689 if (CurScope) 12690 PushDeclContext(CurScope, Block); 12691 else 12692 CurContext = Block; 12693 12694 getCurBlock()->HasImplicitReturnType = true; 12695 12696 // Enter a new evaluation context to insulate the block from any 12697 // cleanups from the enclosing full-expression. 12698 PushExpressionEvaluationContext( 12699 ExpressionEvaluationContext::PotentiallyEvaluated); 12700 } 12701 12702 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 12703 Scope *CurScope) { 12704 assert(ParamInfo.getIdentifier() == nullptr && 12705 "block-id should have no identifier!"); 12706 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 12707 BlockScopeInfo *CurBlock = getCurBlock(); 12708 12709 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 12710 QualType T = Sig->getType(); 12711 12712 // FIXME: We should allow unexpanded parameter packs here, but that would, 12713 // in turn, make the block expression contain unexpanded parameter packs. 12714 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 12715 // Drop the parameters. 12716 FunctionProtoType::ExtProtoInfo EPI; 12717 EPI.HasTrailingReturn = false; 12718 EPI.TypeQuals |= DeclSpec::TQ_const; 12719 T = Context.getFunctionType(Context.DependentTy, None, EPI); 12720 Sig = Context.getTrivialTypeSourceInfo(T); 12721 } 12722 12723 // GetTypeForDeclarator always produces a function type for a block 12724 // literal signature. Furthermore, it is always a FunctionProtoType 12725 // unless the function was written with a typedef. 12726 assert(T->isFunctionType() && 12727 "GetTypeForDeclarator made a non-function block signature"); 12728 12729 // Look for an explicit signature in that function type. 12730 FunctionProtoTypeLoc ExplicitSignature; 12731 12732 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 12733 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) { 12734 12735 // Check whether that explicit signature was synthesized by 12736 // GetTypeForDeclarator. If so, don't save that as part of the 12737 // written signature. 12738 if (ExplicitSignature.getLocalRangeBegin() == 12739 ExplicitSignature.getLocalRangeEnd()) { 12740 // This would be much cheaper if we stored TypeLocs instead of 12741 // TypeSourceInfos. 12742 TypeLoc Result = ExplicitSignature.getReturnLoc(); 12743 unsigned Size = Result.getFullDataSize(); 12744 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 12745 Sig->getTypeLoc().initializeFullCopy(Result, Size); 12746 12747 ExplicitSignature = FunctionProtoTypeLoc(); 12748 } 12749 } 12750 12751 CurBlock->TheDecl->setSignatureAsWritten(Sig); 12752 CurBlock->FunctionType = T; 12753 12754 const FunctionType *Fn = T->getAs<FunctionType>(); 12755 QualType RetTy = Fn->getReturnType(); 12756 bool isVariadic = 12757 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 12758 12759 CurBlock->TheDecl->setIsVariadic(isVariadic); 12760 12761 // Context.DependentTy is used as a placeholder for a missing block 12762 // return type. TODO: what should we do with declarators like: 12763 // ^ * { ... } 12764 // If the answer is "apply template argument deduction".... 12765 if (RetTy != Context.DependentTy) { 12766 CurBlock->ReturnType = RetTy; 12767 CurBlock->TheDecl->setBlockMissingReturnType(false); 12768 CurBlock->HasImplicitReturnType = false; 12769 } 12770 12771 // Push block parameters from the declarator if we had them. 12772 SmallVector<ParmVarDecl*, 8> Params; 12773 if (ExplicitSignature) { 12774 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 12775 ParmVarDecl *Param = ExplicitSignature.getParam(I); 12776 if (Param->getIdentifier() == nullptr && 12777 !Param->isImplicit() && 12778 !Param->isInvalidDecl() && 12779 !getLangOpts().CPlusPlus) 12780 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 12781 Params.push_back(Param); 12782 } 12783 12784 // Fake up parameter variables if we have a typedef, like 12785 // ^ fntype { ... } 12786 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 12787 for (const auto &I : Fn->param_types()) { 12788 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 12789 CurBlock->TheDecl, ParamInfo.getLocStart(), I); 12790 Params.push_back(Param); 12791 } 12792 } 12793 12794 // Set the parameters on the block decl. 12795 if (!Params.empty()) { 12796 CurBlock->TheDecl->setParams(Params); 12797 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 12798 /*CheckParameterNames=*/false); 12799 } 12800 12801 // Finally we can process decl attributes. 12802 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 12803 12804 // Put the parameter variables in scope. 12805 for (auto AI : CurBlock->TheDecl->parameters()) { 12806 AI->setOwningFunction(CurBlock->TheDecl); 12807 12808 // If this has an identifier, add it to the scope stack. 12809 if (AI->getIdentifier()) { 12810 CheckShadow(CurBlock->TheScope, AI); 12811 12812 PushOnScopeChains(AI, CurBlock->TheScope); 12813 } 12814 } 12815 } 12816 12817 /// ActOnBlockError - If there is an error parsing a block, this callback 12818 /// is invoked to pop the information about the block from the action impl. 12819 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 12820 // Leave the expression-evaluation context. 12821 DiscardCleanupsInEvaluationContext(); 12822 PopExpressionEvaluationContext(); 12823 12824 // Pop off CurBlock, handle nested blocks. 12825 PopDeclContext(); 12826 PopFunctionScopeInfo(); 12827 } 12828 12829 /// ActOnBlockStmtExpr - This is called when the body of a block statement 12830 /// literal was successfully completed. ^(int x){...} 12831 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 12832 Stmt *Body, Scope *CurScope) { 12833 // If blocks are disabled, emit an error. 12834 if (!LangOpts.Blocks) 12835 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 12836 12837 // Leave the expression-evaluation context. 12838 if (hasAnyUnrecoverableErrorsInThisFunction()) 12839 DiscardCleanupsInEvaluationContext(); 12840 assert(!Cleanup.exprNeedsCleanups() && 12841 "cleanups within block not correctly bound!"); 12842 PopExpressionEvaluationContext(); 12843 12844 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 12845 12846 if (BSI->HasImplicitReturnType) 12847 deduceClosureReturnType(*BSI); 12848 12849 PopDeclContext(); 12850 12851 QualType RetTy = Context.VoidTy; 12852 if (!BSI->ReturnType.isNull()) 12853 RetTy = BSI->ReturnType; 12854 12855 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 12856 QualType BlockTy; 12857 12858 // Set the captured variables on the block. 12859 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 12860 SmallVector<BlockDecl::Capture, 4> Captures; 12861 for (CapturingScopeInfo::Capture &Cap : BSI->Captures) { 12862 if (Cap.isThisCapture()) 12863 continue; 12864 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 12865 Cap.isNested(), Cap.getInitExpr()); 12866 Captures.push_back(NewCap); 12867 } 12868 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 12869 12870 // If the user wrote a function type in some form, try to use that. 12871 if (!BSI->FunctionType.isNull()) { 12872 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 12873 12874 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 12875 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 12876 12877 // Turn protoless block types into nullary block types. 12878 if (isa<FunctionNoProtoType>(FTy)) { 12879 FunctionProtoType::ExtProtoInfo EPI; 12880 EPI.ExtInfo = Ext; 12881 BlockTy = Context.getFunctionType(RetTy, None, EPI); 12882 12883 // Otherwise, if we don't need to change anything about the function type, 12884 // preserve its sugar structure. 12885 } else if (FTy->getReturnType() == RetTy && 12886 (!NoReturn || FTy->getNoReturnAttr())) { 12887 BlockTy = BSI->FunctionType; 12888 12889 // Otherwise, make the minimal modifications to the function type. 12890 } else { 12891 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 12892 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 12893 EPI.TypeQuals = 0; // FIXME: silently? 12894 EPI.ExtInfo = Ext; 12895 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 12896 } 12897 12898 // If we don't have a function type, just build one from nothing. 12899 } else { 12900 FunctionProtoType::ExtProtoInfo EPI; 12901 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 12902 BlockTy = Context.getFunctionType(RetTy, None, EPI); 12903 } 12904 12905 DiagnoseUnusedParameters(BSI->TheDecl->parameters()); 12906 BlockTy = Context.getBlockPointerType(BlockTy); 12907 12908 // If needed, diagnose invalid gotos and switches in the block. 12909 if (getCurFunction()->NeedsScopeChecking() && 12910 !PP.isCodeCompletionEnabled()) 12911 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 12912 12913 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 12914 12915 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 12916 DiagnoseUnguardedAvailabilityViolations(BSI->TheDecl); 12917 12918 // Try to apply the named return value optimization. We have to check again 12919 // if we can do this, though, because blocks keep return statements around 12920 // to deduce an implicit return type. 12921 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 12922 !BSI->TheDecl->isDependentContext()) 12923 computeNRVO(Body, BSI); 12924 12925 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 12926 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 12927 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 12928 12929 // If the block isn't obviously global, i.e. it captures anything at 12930 // all, then we need to do a few things in the surrounding context: 12931 if (Result->getBlockDecl()->hasCaptures()) { 12932 // First, this expression has a new cleanup object. 12933 ExprCleanupObjects.push_back(Result->getBlockDecl()); 12934 Cleanup.setExprNeedsCleanups(true); 12935 12936 // It also gets a branch-protected scope if any of the captured 12937 // variables needs destruction. 12938 for (const auto &CI : Result->getBlockDecl()->captures()) { 12939 const VarDecl *var = CI.getVariable(); 12940 if (var->getType().isDestructedType() != QualType::DK_none) { 12941 getCurFunction()->setHasBranchProtectedScope(); 12942 break; 12943 } 12944 } 12945 } 12946 12947 return Result; 12948 } 12949 12950 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 12951 SourceLocation RPLoc) { 12952 TypeSourceInfo *TInfo; 12953 GetTypeFromParser(Ty, &TInfo); 12954 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 12955 } 12956 12957 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 12958 Expr *E, TypeSourceInfo *TInfo, 12959 SourceLocation RPLoc) { 12960 Expr *OrigExpr = E; 12961 bool IsMS = false; 12962 12963 // CUDA device code does not support varargs. 12964 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 12965 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 12966 CUDAFunctionTarget T = IdentifyCUDATarget(F); 12967 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 12968 return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device)); 12969 } 12970 } 12971 12972 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 12973 // as Microsoft ABI on an actual Microsoft platform, where 12974 // __builtin_ms_va_list and __builtin_va_list are the same.) 12975 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 12976 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 12977 QualType MSVaListType = Context.getBuiltinMSVaListType(); 12978 if (Context.hasSameType(MSVaListType, E->getType())) { 12979 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 12980 return ExprError(); 12981 IsMS = true; 12982 } 12983 } 12984 12985 // Get the va_list type 12986 QualType VaListType = Context.getBuiltinVaListType(); 12987 if (!IsMS) { 12988 if (VaListType->isArrayType()) { 12989 // Deal with implicit array decay; for example, on x86-64, 12990 // va_list is an array, but it's supposed to decay to 12991 // a pointer for va_arg. 12992 VaListType = Context.getArrayDecayedType(VaListType); 12993 // Make sure the input expression also decays appropriately. 12994 ExprResult Result = UsualUnaryConversions(E); 12995 if (Result.isInvalid()) 12996 return ExprError(); 12997 E = Result.get(); 12998 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 12999 // If va_list is a record type and we are compiling in C++ mode, 13000 // check the argument using reference binding. 13001 InitializedEntity Entity = InitializedEntity::InitializeParameter( 13002 Context, Context.getLValueReferenceType(VaListType), false); 13003 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 13004 if (Init.isInvalid()) 13005 return ExprError(); 13006 E = Init.getAs<Expr>(); 13007 } else { 13008 // Otherwise, the va_list argument must be an l-value because 13009 // it is modified by va_arg. 13010 if (!E->isTypeDependent() && 13011 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 13012 return ExprError(); 13013 } 13014 } 13015 13016 if (!IsMS && !E->isTypeDependent() && 13017 !Context.hasSameType(VaListType, E->getType())) 13018 return ExprError(Diag(E->getLocStart(), 13019 diag::err_first_argument_to_va_arg_not_of_type_va_list) 13020 << OrigExpr->getType() << E->getSourceRange()); 13021 13022 if (!TInfo->getType()->isDependentType()) { 13023 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 13024 diag::err_second_parameter_to_va_arg_incomplete, 13025 TInfo->getTypeLoc())) 13026 return ExprError(); 13027 13028 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 13029 TInfo->getType(), 13030 diag::err_second_parameter_to_va_arg_abstract, 13031 TInfo->getTypeLoc())) 13032 return ExprError(); 13033 13034 if (!TInfo->getType().isPODType(Context)) { 13035 Diag(TInfo->getTypeLoc().getBeginLoc(), 13036 TInfo->getType()->isObjCLifetimeType() 13037 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 13038 : diag::warn_second_parameter_to_va_arg_not_pod) 13039 << TInfo->getType() 13040 << TInfo->getTypeLoc().getSourceRange(); 13041 } 13042 13043 // Check for va_arg where arguments of the given type will be promoted 13044 // (i.e. this va_arg is guaranteed to have undefined behavior). 13045 QualType PromoteType; 13046 if (TInfo->getType()->isPromotableIntegerType()) { 13047 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 13048 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 13049 PromoteType = QualType(); 13050 } 13051 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 13052 PromoteType = Context.DoubleTy; 13053 if (!PromoteType.isNull()) 13054 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 13055 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 13056 << TInfo->getType() 13057 << PromoteType 13058 << TInfo->getTypeLoc().getSourceRange()); 13059 } 13060 13061 QualType T = TInfo->getType().getNonLValueExprType(Context); 13062 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 13063 } 13064 13065 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 13066 // The type of __null will be int or long, depending on the size of 13067 // pointers on the target. 13068 QualType Ty; 13069 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 13070 if (pw == Context.getTargetInfo().getIntWidth()) 13071 Ty = Context.IntTy; 13072 else if (pw == Context.getTargetInfo().getLongWidth()) 13073 Ty = Context.LongTy; 13074 else if (pw == Context.getTargetInfo().getLongLongWidth()) 13075 Ty = Context.LongLongTy; 13076 else { 13077 llvm_unreachable("I don't know size of pointer!"); 13078 } 13079 13080 return new (Context) GNUNullExpr(Ty, TokenLoc); 13081 } 13082 13083 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 13084 bool Diagnose) { 13085 if (!getLangOpts().ObjC1) 13086 return false; 13087 13088 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 13089 if (!PT) 13090 return false; 13091 13092 if (!PT->isObjCIdType()) { 13093 // Check if the destination is the 'NSString' interface. 13094 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 13095 if (!ID || !ID->getIdentifier()->isStr("NSString")) 13096 return false; 13097 } 13098 13099 // Ignore any parens, implicit casts (should only be 13100 // array-to-pointer decays), and not-so-opaque values. The last is 13101 // important for making this trigger for property assignments. 13102 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 13103 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 13104 if (OV->getSourceExpr()) 13105 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 13106 13107 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 13108 if (!SL || !SL->isAscii()) 13109 return false; 13110 if (Diagnose) { 13111 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix) 13112 << FixItHint::CreateInsertion(SL->getLocStart(), "@"); 13113 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get(); 13114 } 13115 return true; 13116 } 13117 13118 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 13119 const Expr *SrcExpr) { 13120 if (!DstType->isFunctionPointerType() || 13121 !SrcExpr->getType()->isFunctionType()) 13122 return false; 13123 13124 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 13125 if (!DRE) 13126 return false; 13127 13128 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 13129 if (!FD) 13130 return false; 13131 13132 return !S.checkAddressOfFunctionIsAvailable(FD, 13133 /*Complain=*/true, 13134 SrcExpr->getLocStart()); 13135 } 13136 13137 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 13138 SourceLocation Loc, 13139 QualType DstType, QualType SrcType, 13140 Expr *SrcExpr, AssignmentAction Action, 13141 bool *Complained) { 13142 if (Complained) 13143 *Complained = false; 13144 13145 // Decode the result (notice that AST's are still created for extensions). 13146 bool CheckInferredResultType = false; 13147 bool isInvalid = false; 13148 unsigned DiagKind = 0; 13149 FixItHint Hint; 13150 ConversionFixItGenerator ConvHints; 13151 bool MayHaveConvFixit = false; 13152 bool MayHaveFunctionDiff = false; 13153 const ObjCInterfaceDecl *IFace = nullptr; 13154 const ObjCProtocolDecl *PDecl = nullptr; 13155 13156 switch (ConvTy) { 13157 case Compatible: 13158 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 13159 return false; 13160 13161 case PointerToInt: 13162 DiagKind = diag::ext_typecheck_convert_pointer_int; 13163 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13164 MayHaveConvFixit = true; 13165 break; 13166 case IntToPointer: 13167 DiagKind = diag::ext_typecheck_convert_int_pointer; 13168 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13169 MayHaveConvFixit = true; 13170 break; 13171 case IncompatiblePointer: 13172 if (Action == AA_Passing_CFAudited) 13173 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 13174 else if (SrcType->isFunctionPointerType() && 13175 DstType->isFunctionPointerType()) 13176 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 13177 else 13178 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 13179 13180 CheckInferredResultType = DstType->isObjCObjectPointerType() && 13181 SrcType->isObjCObjectPointerType(); 13182 if (Hint.isNull() && !CheckInferredResultType) { 13183 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13184 } 13185 else if (CheckInferredResultType) { 13186 SrcType = SrcType.getUnqualifiedType(); 13187 DstType = DstType.getUnqualifiedType(); 13188 } 13189 MayHaveConvFixit = true; 13190 break; 13191 case IncompatiblePointerSign: 13192 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 13193 break; 13194 case FunctionVoidPointer: 13195 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 13196 break; 13197 case IncompatiblePointerDiscardsQualifiers: { 13198 // Perform array-to-pointer decay if necessary. 13199 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 13200 13201 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 13202 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 13203 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 13204 DiagKind = diag::err_typecheck_incompatible_address_space; 13205 break; 13206 13207 13208 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 13209 DiagKind = diag::err_typecheck_incompatible_ownership; 13210 break; 13211 } 13212 13213 llvm_unreachable("unknown error case for discarding qualifiers!"); 13214 // fallthrough 13215 } 13216 case CompatiblePointerDiscardsQualifiers: 13217 // If the qualifiers lost were because we were applying the 13218 // (deprecated) C++ conversion from a string literal to a char* 13219 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 13220 // Ideally, this check would be performed in 13221 // checkPointerTypesForAssignment. However, that would require a 13222 // bit of refactoring (so that the second argument is an 13223 // expression, rather than a type), which should be done as part 13224 // of a larger effort to fix checkPointerTypesForAssignment for 13225 // C++ semantics. 13226 if (getLangOpts().CPlusPlus && 13227 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 13228 return false; 13229 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 13230 break; 13231 case IncompatibleNestedPointerQualifiers: 13232 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 13233 break; 13234 case IntToBlockPointer: 13235 DiagKind = diag::err_int_to_block_pointer; 13236 break; 13237 case IncompatibleBlockPointer: 13238 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 13239 break; 13240 case IncompatibleObjCQualifiedId: { 13241 if (SrcType->isObjCQualifiedIdType()) { 13242 const ObjCObjectPointerType *srcOPT = 13243 SrcType->getAs<ObjCObjectPointerType>(); 13244 for (auto *srcProto : srcOPT->quals()) { 13245 PDecl = srcProto; 13246 break; 13247 } 13248 if (const ObjCInterfaceType *IFaceT = 13249 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 13250 IFace = IFaceT->getDecl(); 13251 } 13252 else if (DstType->isObjCQualifiedIdType()) { 13253 const ObjCObjectPointerType *dstOPT = 13254 DstType->getAs<ObjCObjectPointerType>(); 13255 for (auto *dstProto : dstOPT->quals()) { 13256 PDecl = dstProto; 13257 break; 13258 } 13259 if (const ObjCInterfaceType *IFaceT = 13260 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 13261 IFace = IFaceT->getDecl(); 13262 } 13263 DiagKind = diag::warn_incompatible_qualified_id; 13264 break; 13265 } 13266 case IncompatibleVectors: 13267 DiagKind = diag::warn_incompatible_vectors; 13268 break; 13269 case IncompatibleObjCWeakRef: 13270 DiagKind = diag::err_arc_weak_unavailable_assign; 13271 break; 13272 case Incompatible: 13273 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 13274 if (Complained) 13275 *Complained = true; 13276 return true; 13277 } 13278 13279 DiagKind = diag::err_typecheck_convert_incompatible; 13280 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13281 MayHaveConvFixit = true; 13282 isInvalid = true; 13283 MayHaveFunctionDiff = true; 13284 break; 13285 } 13286 13287 QualType FirstType, SecondType; 13288 switch (Action) { 13289 case AA_Assigning: 13290 case AA_Initializing: 13291 // The destination type comes first. 13292 FirstType = DstType; 13293 SecondType = SrcType; 13294 break; 13295 13296 case AA_Returning: 13297 case AA_Passing: 13298 case AA_Passing_CFAudited: 13299 case AA_Converting: 13300 case AA_Sending: 13301 case AA_Casting: 13302 // The source type comes first. 13303 FirstType = SrcType; 13304 SecondType = DstType; 13305 break; 13306 } 13307 13308 PartialDiagnostic FDiag = PDiag(DiagKind); 13309 if (Action == AA_Passing_CFAudited) 13310 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 13311 else 13312 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 13313 13314 // If we can fix the conversion, suggest the FixIts. 13315 assert(ConvHints.isNull() || Hint.isNull()); 13316 if (!ConvHints.isNull()) { 13317 for (FixItHint &H : ConvHints.Hints) 13318 FDiag << H; 13319 } else { 13320 FDiag << Hint; 13321 } 13322 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 13323 13324 if (MayHaveFunctionDiff) 13325 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 13326 13327 Diag(Loc, FDiag); 13328 if (DiagKind == diag::warn_incompatible_qualified_id && 13329 PDecl && IFace && !IFace->hasDefinition()) 13330 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 13331 << IFace->getName() << PDecl->getName(); 13332 13333 if (SecondType == Context.OverloadTy) 13334 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 13335 FirstType, /*TakingAddress=*/true); 13336 13337 if (CheckInferredResultType) 13338 EmitRelatedResultTypeNote(SrcExpr); 13339 13340 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 13341 EmitRelatedResultTypeNoteForReturn(DstType); 13342 13343 if (Complained) 13344 *Complained = true; 13345 return isInvalid; 13346 } 13347 13348 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 13349 llvm::APSInt *Result) { 13350 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 13351 public: 13352 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 13353 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 13354 } 13355 } Diagnoser; 13356 13357 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 13358 } 13359 13360 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 13361 llvm::APSInt *Result, 13362 unsigned DiagID, 13363 bool AllowFold) { 13364 class IDDiagnoser : public VerifyICEDiagnoser { 13365 unsigned DiagID; 13366 13367 public: 13368 IDDiagnoser(unsigned DiagID) 13369 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 13370 13371 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 13372 S.Diag(Loc, DiagID) << SR; 13373 } 13374 } Diagnoser(DiagID); 13375 13376 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 13377 } 13378 13379 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 13380 SourceRange SR) { 13381 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 13382 } 13383 13384 ExprResult 13385 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 13386 VerifyICEDiagnoser &Diagnoser, 13387 bool AllowFold) { 13388 SourceLocation DiagLoc = E->getLocStart(); 13389 13390 if (getLangOpts().CPlusPlus11) { 13391 // C++11 [expr.const]p5: 13392 // If an expression of literal class type is used in a context where an 13393 // integral constant expression is required, then that class type shall 13394 // have a single non-explicit conversion function to an integral or 13395 // unscoped enumeration type 13396 ExprResult Converted; 13397 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 13398 public: 13399 CXX11ConvertDiagnoser(bool Silent) 13400 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 13401 Silent, true) {} 13402 13403 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 13404 QualType T) override { 13405 return S.Diag(Loc, diag::err_ice_not_integral) << T; 13406 } 13407 13408 SemaDiagnosticBuilder diagnoseIncomplete( 13409 Sema &S, SourceLocation Loc, QualType T) override { 13410 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 13411 } 13412 13413 SemaDiagnosticBuilder diagnoseExplicitConv( 13414 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 13415 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 13416 } 13417 13418 SemaDiagnosticBuilder noteExplicitConv( 13419 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 13420 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 13421 << ConvTy->isEnumeralType() << ConvTy; 13422 } 13423 13424 SemaDiagnosticBuilder diagnoseAmbiguous( 13425 Sema &S, SourceLocation Loc, QualType T) override { 13426 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 13427 } 13428 13429 SemaDiagnosticBuilder noteAmbiguous( 13430 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 13431 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 13432 << ConvTy->isEnumeralType() << ConvTy; 13433 } 13434 13435 SemaDiagnosticBuilder diagnoseConversion( 13436 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 13437 llvm_unreachable("conversion functions are permitted"); 13438 } 13439 } ConvertDiagnoser(Diagnoser.Suppress); 13440 13441 Converted = PerformContextualImplicitConversion(DiagLoc, E, 13442 ConvertDiagnoser); 13443 if (Converted.isInvalid()) 13444 return Converted; 13445 E = Converted.get(); 13446 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 13447 return ExprError(); 13448 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 13449 // An ICE must be of integral or unscoped enumeration type. 13450 if (!Diagnoser.Suppress) 13451 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 13452 return ExprError(); 13453 } 13454 13455 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 13456 // in the non-ICE case. 13457 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 13458 if (Result) 13459 *Result = E->EvaluateKnownConstInt(Context); 13460 return E; 13461 } 13462 13463 Expr::EvalResult EvalResult; 13464 SmallVector<PartialDiagnosticAt, 8> Notes; 13465 EvalResult.Diag = &Notes; 13466 13467 // Try to evaluate the expression, and produce diagnostics explaining why it's 13468 // not a constant expression as a side-effect. 13469 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 13470 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 13471 13472 // In C++11, we can rely on diagnostics being produced for any expression 13473 // which is not a constant expression. If no diagnostics were produced, then 13474 // this is a constant expression. 13475 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 13476 if (Result) 13477 *Result = EvalResult.Val.getInt(); 13478 return E; 13479 } 13480 13481 // If our only note is the usual "invalid subexpression" note, just point 13482 // the caret at its location rather than producing an essentially 13483 // redundant note. 13484 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 13485 diag::note_invalid_subexpr_in_const_expr) { 13486 DiagLoc = Notes[0].first; 13487 Notes.clear(); 13488 } 13489 13490 if (!Folded || !AllowFold) { 13491 if (!Diagnoser.Suppress) { 13492 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 13493 for (const PartialDiagnosticAt &Note : Notes) 13494 Diag(Note.first, Note.second); 13495 } 13496 13497 return ExprError(); 13498 } 13499 13500 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 13501 for (const PartialDiagnosticAt &Note : Notes) 13502 Diag(Note.first, Note.second); 13503 13504 if (Result) 13505 *Result = EvalResult.Val.getInt(); 13506 return E; 13507 } 13508 13509 namespace { 13510 // Handle the case where we conclude a expression which we speculatively 13511 // considered to be unevaluated is actually evaluated. 13512 class TransformToPE : public TreeTransform<TransformToPE> { 13513 typedef TreeTransform<TransformToPE> BaseTransform; 13514 13515 public: 13516 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 13517 13518 // Make sure we redo semantic analysis 13519 bool AlwaysRebuild() { return true; } 13520 13521 // Make sure we handle LabelStmts correctly. 13522 // FIXME: This does the right thing, but maybe we need a more general 13523 // fix to TreeTransform? 13524 StmtResult TransformLabelStmt(LabelStmt *S) { 13525 S->getDecl()->setStmt(nullptr); 13526 return BaseTransform::TransformLabelStmt(S); 13527 } 13528 13529 // We need to special-case DeclRefExprs referring to FieldDecls which 13530 // are not part of a member pointer formation; normal TreeTransforming 13531 // doesn't catch this case because of the way we represent them in the AST. 13532 // FIXME: This is a bit ugly; is it really the best way to handle this 13533 // case? 13534 // 13535 // Error on DeclRefExprs referring to FieldDecls. 13536 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 13537 if (isa<FieldDecl>(E->getDecl()) && 13538 !SemaRef.isUnevaluatedContext()) 13539 return SemaRef.Diag(E->getLocation(), 13540 diag::err_invalid_non_static_member_use) 13541 << E->getDecl() << E->getSourceRange(); 13542 13543 return BaseTransform::TransformDeclRefExpr(E); 13544 } 13545 13546 // Exception: filter out member pointer formation 13547 ExprResult TransformUnaryOperator(UnaryOperator *E) { 13548 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 13549 return E; 13550 13551 return BaseTransform::TransformUnaryOperator(E); 13552 } 13553 13554 ExprResult TransformLambdaExpr(LambdaExpr *E) { 13555 // Lambdas never need to be transformed. 13556 return E; 13557 } 13558 }; 13559 } 13560 13561 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 13562 assert(isUnevaluatedContext() && 13563 "Should only transform unevaluated expressions"); 13564 ExprEvalContexts.back().Context = 13565 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 13566 if (isUnevaluatedContext()) 13567 return E; 13568 return TransformToPE(*this).TransformExpr(E); 13569 } 13570 13571 void 13572 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 13573 Decl *LambdaContextDecl, 13574 bool IsDecltype) { 13575 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 13576 LambdaContextDecl, IsDecltype); 13577 Cleanup.reset(); 13578 if (!MaybeODRUseExprs.empty()) 13579 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 13580 } 13581 13582 void 13583 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 13584 ReuseLambdaContextDecl_t, 13585 bool IsDecltype) { 13586 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 13587 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 13588 } 13589 13590 void Sema::PopExpressionEvaluationContext() { 13591 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 13592 unsigned NumTypos = Rec.NumTypos; 13593 13594 if (!Rec.Lambdas.empty()) { 13595 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 13596 unsigned D; 13597 if (Rec.isUnevaluated()) { 13598 // C++11 [expr.prim.lambda]p2: 13599 // A lambda-expression shall not appear in an unevaluated operand 13600 // (Clause 5). 13601 D = diag::err_lambda_unevaluated_operand; 13602 } else { 13603 // C++1y [expr.const]p2: 13604 // A conditional-expression e is a core constant expression unless the 13605 // evaluation of e, following the rules of the abstract machine, would 13606 // evaluate [...] a lambda-expression. 13607 D = diag::err_lambda_in_constant_expression; 13608 } 13609 13610 // C++1z allows lambda expressions as core constant expressions. 13611 // FIXME: In C++1z, reinstate the restrictions on lambda expressions (CWG 13612 // 1607) from appearing within template-arguments and array-bounds that 13613 // are part of function-signatures. Be mindful that P0315 (Lambdas in 13614 // unevaluated contexts) might lift some of these restrictions in a 13615 // future version. 13616 if (!Rec.isConstantEvaluated() || !getLangOpts().CPlusPlus1z) 13617 for (const auto *L : Rec.Lambdas) 13618 Diag(L->getLocStart(), D); 13619 } else { 13620 // Mark the capture expressions odr-used. This was deferred 13621 // during lambda expression creation. 13622 for (auto *Lambda : Rec.Lambdas) { 13623 for (auto *C : Lambda->capture_inits()) 13624 MarkDeclarationsReferencedInExpr(C); 13625 } 13626 } 13627 } 13628 13629 // When are coming out of an unevaluated context, clear out any 13630 // temporaries that we may have created as part of the evaluation of 13631 // the expression in that context: they aren't relevant because they 13632 // will never be constructed. 13633 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 13634 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 13635 ExprCleanupObjects.end()); 13636 Cleanup = Rec.ParentCleanup; 13637 CleanupVarDeclMarking(); 13638 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 13639 // Otherwise, merge the contexts together. 13640 } else { 13641 Cleanup.mergeFrom(Rec.ParentCleanup); 13642 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 13643 Rec.SavedMaybeODRUseExprs.end()); 13644 } 13645 13646 // Pop the current expression evaluation context off the stack. 13647 ExprEvalContexts.pop_back(); 13648 13649 if (!ExprEvalContexts.empty()) 13650 ExprEvalContexts.back().NumTypos += NumTypos; 13651 else 13652 assert(NumTypos == 0 && "There are outstanding typos after popping the " 13653 "last ExpressionEvaluationContextRecord"); 13654 } 13655 13656 void Sema::DiscardCleanupsInEvaluationContext() { 13657 ExprCleanupObjects.erase( 13658 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 13659 ExprCleanupObjects.end()); 13660 Cleanup.reset(); 13661 MaybeODRUseExprs.clear(); 13662 } 13663 13664 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 13665 if (!E->getType()->isVariablyModifiedType()) 13666 return E; 13667 return TransformToPotentiallyEvaluated(E); 13668 } 13669 13670 /// Are we within a context in which some evaluation could be performed (be it 13671 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite 13672 /// captured by C++'s idea of an "unevaluated context". 13673 static bool isEvaluatableContext(Sema &SemaRef) { 13674 switch (SemaRef.ExprEvalContexts.back().Context) { 13675 case Sema::ExpressionEvaluationContext::Unevaluated: 13676 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 13677 case Sema::ExpressionEvaluationContext::DiscardedStatement: 13678 // Expressions in this context are never evaluated. 13679 return false; 13680 13681 case Sema::ExpressionEvaluationContext::UnevaluatedList: 13682 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 13683 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 13684 // Expressions in this context could be evaluated. 13685 return true; 13686 13687 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 13688 // Referenced declarations will only be used if the construct in the 13689 // containing expression is used, at which point we'll be given another 13690 // turn to mark them. 13691 return false; 13692 } 13693 llvm_unreachable("Invalid context"); 13694 } 13695 13696 /// Are we within a context in which references to resolved functions or to 13697 /// variables result in odr-use? 13698 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) { 13699 // An expression in a template is not really an expression until it's been 13700 // instantiated, so it doesn't trigger odr-use. 13701 if (SkipDependentUses && SemaRef.CurContext->isDependentContext()) 13702 return false; 13703 13704 switch (SemaRef.ExprEvalContexts.back().Context) { 13705 case Sema::ExpressionEvaluationContext::Unevaluated: 13706 case Sema::ExpressionEvaluationContext::UnevaluatedList: 13707 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 13708 case Sema::ExpressionEvaluationContext::DiscardedStatement: 13709 return false; 13710 13711 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 13712 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 13713 return true; 13714 13715 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 13716 return false; 13717 } 13718 llvm_unreachable("Invalid context"); 13719 } 13720 13721 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 13722 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 13723 return Func->isConstexpr() && 13724 (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided())); 13725 } 13726 13727 /// \brief Mark a function referenced, and check whether it is odr-used 13728 /// (C++ [basic.def.odr]p2, C99 6.9p3) 13729 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 13730 bool MightBeOdrUse) { 13731 assert(Func && "No function?"); 13732 13733 Func->setReferenced(); 13734 13735 // C++11 [basic.def.odr]p3: 13736 // A function whose name appears as a potentially-evaluated expression is 13737 // odr-used if it is the unique lookup result or the selected member of a 13738 // set of overloaded functions [...]. 13739 // 13740 // We (incorrectly) mark overload resolution as an unevaluated context, so we 13741 // can just check that here. 13742 bool OdrUse = MightBeOdrUse && isOdrUseContext(*this); 13743 13744 // Determine whether we require a function definition to exist, per 13745 // C++11 [temp.inst]p3: 13746 // Unless a function template specialization has been explicitly 13747 // instantiated or explicitly specialized, the function template 13748 // specialization is implicitly instantiated when the specialization is 13749 // referenced in a context that requires a function definition to exist. 13750 // 13751 // That is either when this is an odr-use, or when a usage of a constexpr 13752 // function occurs within an evaluatable context. 13753 bool NeedDefinition = 13754 OdrUse || (isEvaluatableContext(*this) && 13755 isImplicitlyDefinableConstexprFunction(Func)); 13756 13757 // C++14 [temp.expl.spec]p6: 13758 // If a template [...] is explicitly specialized then that specialization 13759 // shall be declared before the first use of that specialization that would 13760 // cause an implicit instantiation to take place, in every translation unit 13761 // in which such a use occurs 13762 if (NeedDefinition && 13763 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 13764 Func->getMemberSpecializationInfo())) 13765 checkSpecializationVisibility(Loc, Func); 13766 13767 // C++14 [except.spec]p17: 13768 // An exception-specification is considered to be needed when: 13769 // - the function is odr-used or, if it appears in an unevaluated operand, 13770 // would be odr-used if the expression were potentially-evaluated; 13771 // 13772 // Note, we do this even if MightBeOdrUse is false. That indicates that the 13773 // function is a pure virtual function we're calling, and in that case the 13774 // function was selected by overload resolution and we need to resolve its 13775 // exception specification for a different reason. 13776 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 13777 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 13778 ResolveExceptionSpec(Loc, FPT); 13779 13780 // If we don't need to mark the function as used, and we don't need to 13781 // try to provide a definition, there's nothing more to do. 13782 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) && 13783 (!NeedDefinition || Func->getBody())) 13784 return; 13785 13786 // Note that this declaration has been used. 13787 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 13788 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 13789 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 13790 if (Constructor->isDefaultConstructor()) { 13791 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 13792 return; 13793 DefineImplicitDefaultConstructor(Loc, Constructor); 13794 } else if (Constructor->isCopyConstructor()) { 13795 DefineImplicitCopyConstructor(Loc, Constructor); 13796 } else if (Constructor->isMoveConstructor()) { 13797 DefineImplicitMoveConstructor(Loc, Constructor); 13798 } 13799 } else if (Constructor->getInheritedConstructor()) { 13800 DefineInheritingConstructor(Loc, Constructor); 13801 } 13802 } else if (CXXDestructorDecl *Destructor = 13803 dyn_cast<CXXDestructorDecl>(Func)) { 13804 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 13805 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 13806 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 13807 return; 13808 DefineImplicitDestructor(Loc, Destructor); 13809 } 13810 if (Destructor->isVirtual() && getLangOpts().AppleKext) 13811 MarkVTableUsed(Loc, Destructor->getParent()); 13812 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 13813 if (MethodDecl->isOverloadedOperator() && 13814 MethodDecl->getOverloadedOperator() == OO_Equal) { 13815 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 13816 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 13817 if (MethodDecl->isCopyAssignmentOperator()) 13818 DefineImplicitCopyAssignment(Loc, MethodDecl); 13819 else if (MethodDecl->isMoveAssignmentOperator()) 13820 DefineImplicitMoveAssignment(Loc, MethodDecl); 13821 } 13822 } else if (isa<CXXConversionDecl>(MethodDecl) && 13823 MethodDecl->getParent()->isLambda()) { 13824 CXXConversionDecl *Conversion = 13825 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 13826 if (Conversion->isLambdaToBlockPointerConversion()) 13827 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 13828 else 13829 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 13830 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 13831 MarkVTableUsed(Loc, MethodDecl->getParent()); 13832 } 13833 13834 // Recursive functions should be marked when used from another function. 13835 // FIXME: Is this really right? 13836 if (CurContext == Func) return; 13837 13838 // Implicit instantiation of function templates and member functions of 13839 // class templates. 13840 if (Func->isImplicitlyInstantiable()) { 13841 bool AlreadyInstantiated = false; 13842 SourceLocation PointOfInstantiation = Loc; 13843 if (FunctionTemplateSpecializationInfo *SpecInfo 13844 = Func->getTemplateSpecializationInfo()) { 13845 if (SpecInfo->getPointOfInstantiation().isInvalid()) 13846 SpecInfo->setPointOfInstantiation(Loc); 13847 else if (SpecInfo->getTemplateSpecializationKind() 13848 == TSK_ImplicitInstantiation) { 13849 AlreadyInstantiated = true; 13850 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 13851 } 13852 } else if (MemberSpecializationInfo *MSInfo 13853 = Func->getMemberSpecializationInfo()) { 13854 if (MSInfo->getPointOfInstantiation().isInvalid()) 13855 MSInfo->setPointOfInstantiation(Loc); 13856 else if (MSInfo->getTemplateSpecializationKind() 13857 == TSK_ImplicitInstantiation) { 13858 AlreadyInstantiated = true; 13859 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 13860 } 13861 } 13862 13863 if (!AlreadyInstantiated || Func->isConstexpr()) { 13864 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 13865 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 13866 CodeSynthesisContexts.size()) 13867 PendingLocalImplicitInstantiations.push_back( 13868 std::make_pair(Func, PointOfInstantiation)); 13869 else if (Func->isConstexpr()) 13870 // Do not defer instantiations of constexpr functions, to avoid the 13871 // expression evaluator needing to call back into Sema if it sees a 13872 // call to such a function. 13873 InstantiateFunctionDefinition(PointOfInstantiation, Func); 13874 else { 13875 Func->setInstantiationIsPending(true); 13876 PendingInstantiations.push_back(std::make_pair(Func, 13877 PointOfInstantiation)); 13878 // Notify the consumer that a function was implicitly instantiated. 13879 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 13880 } 13881 } 13882 } else { 13883 // Walk redefinitions, as some of them may be instantiable. 13884 for (auto i : Func->redecls()) { 13885 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 13886 MarkFunctionReferenced(Loc, i, OdrUse); 13887 } 13888 } 13889 13890 if (!OdrUse) return; 13891 13892 // Keep track of used but undefined functions. 13893 if (!Func->isDefined()) { 13894 if (mightHaveNonExternalLinkage(Func)) 13895 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 13896 else if (Func->getMostRecentDecl()->isInlined() && 13897 !LangOpts.GNUInline && 13898 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 13899 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 13900 } 13901 13902 Func->markUsed(Context); 13903 } 13904 13905 static void 13906 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 13907 ValueDecl *var, DeclContext *DC) { 13908 DeclContext *VarDC = var->getDeclContext(); 13909 13910 // If the parameter still belongs to the translation unit, then 13911 // we're actually just using one parameter in the declaration of 13912 // the next. 13913 if (isa<ParmVarDecl>(var) && 13914 isa<TranslationUnitDecl>(VarDC)) 13915 return; 13916 13917 // For C code, don't diagnose about capture if we're not actually in code 13918 // right now; it's impossible to write a non-constant expression outside of 13919 // function context, so we'll get other (more useful) diagnostics later. 13920 // 13921 // For C++, things get a bit more nasty... it would be nice to suppress this 13922 // diagnostic for certain cases like using a local variable in an array bound 13923 // for a member of a local class, but the correct predicate is not obvious. 13924 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 13925 return; 13926 13927 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 13928 unsigned ContextKind = 3; // unknown 13929 if (isa<CXXMethodDecl>(VarDC) && 13930 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 13931 ContextKind = 2; 13932 } else if (isa<FunctionDecl>(VarDC)) { 13933 ContextKind = 0; 13934 } else if (isa<BlockDecl>(VarDC)) { 13935 ContextKind = 1; 13936 } 13937 13938 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 13939 << var << ValueKind << ContextKind << VarDC; 13940 S.Diag(var->getLocation(), diag::note_entity_declared_at) 13941 << var; 13942 13943 // FIXME: Add additional diagnostic info about class etc. which prevents 13944 // capture. 13945 } 13946 13947 13948 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 13949 bool &SubCapturesAreNested, 13950 QualType &CaptureType, 13951 QualType &DeclRefType) { 13952 // Check whether we've already captured it. 13953 if (CSI->CaptureMap.count(Var)) { 13954 // If we found a capture, any subcaptures are nested. 13955 SubCapturesAreNested = true; 13956 13957 // Retrieve the capture type for this variable. 13958 CaptureType = CSI->getCapture(Var).getCaptureType(); 13959 13960 // Compute the type of an expression that refers to this variable. 13961 DeclRefType = CaptureType.getNonReferenceType(); 13962 13963 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 13964 // are mutable in the sense that user can change their value - they are 13965 // private instances of the captured declarations. 13966 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 13967 if (Cap.isCopyCapture() && 13968 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 13969 !(isa<CapturedRegionScopeInfo>(CSI) && 13970 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 13971 DeclRefType.addConst(); 13972 return true; 13973 } 13974 return false; 13975 } 13976 13977 // Only block literals, captured statements, and lambda expressions can 13978 // capture; other scopes don't work. 13979 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 13980 SourceLocation Loc, 13981 const bool Diagnose, Sema &S) { 13982 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 13983 return getLambdaAwareParentOfDeclContext(DC); 13984 else if (Var->hasLocalStorage()) { 13985 if (Diagnose) 13986 diagnoseUncapturableValueReference(S, Loc, Var, DC); 13987 } 13988 return nullptr; 13989 } 13990 13991 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 13992 // certain types of variables (unnamed, variably modified types etc.) 13993 // so check for eligibility. 13994 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 13995 SourceLocation Loc, 13996 const bool Diagnose, Sema &S) { 13997 13998 bool IsBlock = isa<BlockScopeInfo>(CSI); 13999 bool IsLambda = isa<LambdaScopeInfo>(CSI); 14000 14001 // Lambdas are not allowed to capture unnamed variables 14002 // (e.g. anonymous unions). 14003 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 14004 // assuming that's the intent. 14005 if (IsLambda && !Var->getDeclName()) { 14006 if (Diagnose) { 14007 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 14008 S.Diag(Var->getLocation(), diag::note_declared_at); 14009 } 14010 return false; 14011 } 14012 14013 // Prohibit variably-modified types in blocks; they're difficult to deal with. 14014 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 14015 if (Diagnose) { 14016 S.Diag(Loc, diag::err_ref_vm_type); 14017 S.Diag(Var->getLocation(), diag::note_previous_decl) 14018 << Var->getDeclName(); 14019 } 14020 return false; 14021 } 14022 // Prohibit structs with flexible array members too. 14023 // We cannot capture what is in the tail end of the struct. 14024 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 14025 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 14026 if (Diagnose) { 14027 if (IsBlock) 14028 S.Diag(Loc, diag::err_ref_flexarray_type); 14029 else 14030 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 14031 << Var->getDeclName(); 14032 S.Diag(Var->getLocation(), diag::note_previous_decl) 14033 << Var->getDeclName(); 14034 } 14035 return false; 14036 } 14037 } 14038 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 14039 // Lambdas and captured statements are not allowed to capture __block 14040 // variables; they don't support the expected semantics. 14041 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 14042 if (Diagnose) { 14043 S.Diag(Loc, diag::err_capture_block_variable) 14044 << Var->getDeclName() << !IsLambda; 14045 S.Diag(Var->getLocation(), diag::note_previous_decl) 14046 << Var->getDeclName(); 14047 } 14048 return false; 14049 } 14050 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 14051 if (S.getLangOpts().OpenCL && IsBlock && 14052 Var->getType()->isBlockPointerType()) { 14053 if (Diagnose) 14054 S.Diag(Loc, diag::err_opencl_block_ref_block); 14055 return false; 14056 } 14057 14058 return true; 14059 } 14060 14061 // Returns true if the capture by block was successful. 14062 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 14063 SourceLocation Loc, 14064 const bool BuildAndDiagnose, 14065 QualType &CaptureType, 14066 QualType &DeclRefType, 14067 const bool Nested, 14068 Sema &S) { 14069 Expr *CopyExpr = nullptr; 14070 bool ByRef = false; 14071 14072 // Blocks are not allowed to capture arrays. 14073 if (CaptureType->isArrayType()) { 14074 if (BuildAndDiagnose) { 14075 S.Diag(Loc, diag::err_ref_array_type); 14076 S.Diag(Var->getLocation(), diag::note_previous_decl) 14077 << Var->getDeclName(); 14078 } 14079 return false; 14080 } 14081 14082 // Forbid the block-capture of autoreleasing variables. 14083 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 14084 if (BuildAndDiagnose) { 14085 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 14086 << /*block*/ 0; 14087 S.Diag(Var->getLocation(), diag::note_previous_decl) 14088 << Var->getDeclName(); 14089 } 14090 return false; 14091 } 14092 14093 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 14094 if (const auto *PT = CaptureType->getAs<PointerType>()) { 14095 // This function finds out whether there is an AttributedType of kind 14096 // attr_objc_ownership in Ty. The existence of AttributedType of kind 14097 // attr_objc_ownership implies __autoreleasing was explicitly specified 14098 // rather than being added implicitly by the compiler. 14099 auto IsObjCOwnershipAttributedType = [](QualType Ty) { 14100 while (const auto *AttrTy = Ty->getAs<AttributedType>()) { 14101 if (AttrTy->getAttrKind() == AttributedType::attr_objc_ownership) 14102 return true; 14103 14104 // Peel off AttributedTypes that are not of kind objc_ownership. 14105 Ty = AttrTy->getModifiedType(); 14106 } 14107 14108 return false; 14109 }; 14110 14111 QualType PointeeTy = PT->getPointeeType(); 14112 14113 if (PointeeTy->getAs<ObjCObjectPointerType>() && 14114 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 14115 !IsObjCOwnershipAttributedType(PointeeTy)) { 14116 if (BuildAndDiagnose) { 14117 SourceLocation VarLoc = Var->getLocation(); 14118 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 14119 { 14120 auto AddAutoreleaseNote = 14121 S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing); 14122 // Provide a fix-it for the '__autoreleasing' keyword at the 14123 // appropriate location in the variable's type. 14124 if (const auto *TSI = Var->getTypeSourceInfo()) { 14125 PointerTypeLoc PTL = 14126 TSI->getTypeLoc().getAsAdjusted<PointerTypeLoc>(); 14127 if (PTL) { 14128 SourceLocation Loc = PTL.getPointeeLoc().getEndLoc(); 14129 Loc = Lexer::getLocForEndOfToken(Loc, 0, S.getSourceManager(), 14130 S.getLangOpts()); 14131 if (Loc.isValid()) { 14132 StringRef CharAtLoc = Lexer::getSourceText( 14133 CharSourceRange::getCharRange(Loc, Loc.getLocWithOffset(1)), 14134 S.getSourceManager(), S.getLangOpts()); 14135 AddAutoreleaseNote << FixItHint::CreateInsertion( 14136 Loc, CharAtLoc.empty() || !isWhitespace(CharAtLoc[0]) 14137 ? " __autoreleasing " 14138 : " __autoreleasing"); 14139 } 14140 } 14141 } 14142 } 14143 S.Diag(VarLoc, diag::note_declare_parameter_strong); 14144 } 14145 } 14146 } 14147 14148 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 14149 if (HasBlocksAttr || CaptureType->isReferenceType() || 14150 (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) { 14151 // Block capture by reference does not change the capture or 14152 // declaration reference types. 14153 ByRef = true; 14154 } else { 14155 // Block capture by copy introduces 'const'. 14156 CaptureType = CaptureType.getNonReferenceType().withConst(); 14157 DeclRefType = CaptureType; 14158 14159 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 14160 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 14161 // The capture logic needs the destructor, so make sure we mark it. 14162 // Usually this is unnecessary because most local variables have 14163 // their destructors marked at declaration time, but parameters are 14164 // an exception because it's technically only the call site that 14165 // actually requires the destructor. 14166 if (isa<ParmVarDecl>(Var)) 14167 S.FinalizeVarWithDestructor(Var, Record); 14168 14169 // Enter a new evaluation context to insulate the copy 14170 // full-expression. 14171 EnterExpressionEvaluationContext scope( 14172 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 14173 14174 // According to the blocks spec, the capture of a variable from 14175 // the stack requires a const copy constructor. This is not true 14176 // of the copy/move done to move a __block variable to the heap. 14177 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 14178 DeclRefType.withConst(), 14179 VK_LValue, Loc); 14180 14181 ExprResult Result 14182 = S.PerformCopyInitialization( 14183 InitializedEntity::InitializeBlock(Var->getLocation(), 14184 CaptureType, false), 14185 Loc, DeclRef); 14186 14187 // Build a full-expression copy expression if initialization 14188 // succeeded and used a non-trivial constructor. Recover from 14189 // errors by pretending that the copy isn't necessary. 14190 if (!Result.isInvalid() && 14191 !cast<CXXConstructExpr>(Result.get())->getConstructor() 14192 ->isTrivial()) { 14193 Result = S.MaybeCreateExprWithCleanups(Result); 14194 CopyExpr = Result.get(); 14195 } 14196 } 14197 } 14198 } 14199 14200 // Actually capture the variable. 14201 if (BuildAndDiagnose) 14202 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 14203 SourceLocation(), CaptureType, CopyExpr); 14204 14205 return true; 14206 14207 } 14208 14209 14210 /// \brief Capture the given variable in the captured region. 14211 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 14212 VarDecl *Var, 14213 SourceLocation Loc, 14214 const bool BuildAndDiagnose, 14215 QualType &CaptureType, 14216 QualType &DeclRefType, 14217 const bool RefersToCapturedVariable, 14218 Sema &S) { 14219 // By default, capture variables by reference. 14220 bool ByRef = true; 14221 // Using an LValue reference type is consistent with Lambdas (see below). 14222 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 14223 if (S.IsOpenMPCapturedDecl(Var)) 14224 DeclRefType = DeclRefType.getUnqualifiedType(); 14225 ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel); 14226 } 14227 14228 if (ByRef) 14229 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 14230 else 14231 CaptureType = DeclRefType; 14232 14233 Expr *CopyExpr = nullptr; 14234 if (BuildAndDiagnose) { 14235 // The current implementation assumes that all variables are captured 14236 // by references. Since there is no capture by copy, no expression 14237 // evaluation will be needed. 14238 RecordDecl *RD = RSI->TheRecordDecl; 14239 14240 FieldDecl *Field 14241 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 14242 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 14243 nullptr, false, ICIS_NoInit); 14244 Field->setImplicit(true); 14245 Field->setAccess(AS_private); 14246 RD->addDecl(Field); 14247 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) 14248 S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel); 14249 14250 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, 14251 DeclRefType, VK_LValue, Loc); 14252 Var->setReferenced(true); 14253 Var->markUsed(S.Context); 14254 } 14255 14256 // Actually capture the variable. 14257 if (BuildAndDiagnose) 14258 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 14259 SourceLocation(), CaptureType, CopyExpr); 14260 14261 14262 return true; 14263 } 14264 14265 /// \brief Create a field within the lambda class for the variable 14266 /// being captured. 14267 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, 14268 QualType FieldType, QualType DeclRefType, 14269 SourceLocation Loc, 14270 bool RefersToCapturedVariable) { 14271 CXXRecordDecl *Lambda = LSI->Lambda; 14272 14273 // Build the non-static data member. 14274 FieldDecl *Field 14275 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 14276 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 14277 nullptr, false, ICIS_NoInit); 14278 Field->setImplicit(true); 14279 Field->setAccess(AS_private); 14280 Lambda->addDecl(Field); 14281 } 14282 14283 /// \brief Capture the given variable in the lambda. 14284 static bool captureInLambda(LambdaScopeInfo *LSI, 14285 VarDecl *Var, 14286 SourceLocation Loc, 14287 const bool BuildAndDiagnose, 14288 QualType &CaptureType, 14289 QualType &DeclRefType, 14290 const bool RefersToCapturedVariable, 14291 const Sema::TryCaptureKind Kind, 14292 SourceLocation EllipsisLoc, 14293 const bool IsTopScope, 14294 Sema &S) { 14295 14296 // Determine whether we are capturing by reference or by value. 14297 bool ByRef = false; 14298 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 14299 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 14300 } else { 14301 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 14302 } 14303 14304 // Compute the type of the field that will capture this variable. 14305 if (ByRef) { 14306 // C++11 [expr.prim.lambda]p15: 14307 // An entity is captured by reference if it is implicitly or 14308 // explicitly captured but not captured by copy. It is 14309 // unspecified whether additional unnamed non-static data 14310 // members are declared in the closure type for entities 14311 // captured by reference. 14312 // 14313 // FIXME: It is not clear whether we want to build an lvalue reference 14314 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 14315 // to do the former, while EDG does the latter. Core issue 1249 will 14316 // clarify, but for now we follow GCC because it's a more permissive and 14317 // easily defensible position. 14318 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 14319 } else { 14320 // C++11 [expr.prim.lambda]p14: 14321 // For each entity captured by copy, an unnamed non-static 14322 // data member is declared in the closure type. The 14323 // declaration order of these members is unspecified. The type 14324 // of such a data member is the type of the corresponding 14325 // captured entity if the entity is not a reference to an 14326 // object, or the referenced type otherwise. [Note: If the 14327 // captured entity is a reference to a function, the 14328 // corresponding data member is also a reference to a 14329 // function. - end note ] 14330 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 14331 if (!RefType->getPointeeType()->isFunctionType()) 14332 CaptureType = RefType->getPointeeType(); 14333 } 14334 14335 // Forbid the lambda copy-capture of autoreleasing variables. 14336 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 14337 if (BuildAndDiagnose) { 14338 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 14339 S.Diag(Var->getLocation(), diag::note_previous_decl) 14340 << Var->getDeclName(); 14341 } 14342 return false; 14343 } 14344 14345 // Make sure that by-copy captures are of a complete and non-abstract type. 14346 if (BuildAndDiagnose) { 14347 if (!CaptureType->isDependentType() && 14348 S.RequireCompleteType(Loc, CaptureType, 14349 diag::err_capture_of_incomplete_type, 14350 Var->getDeclName())) 14351 return false; 14352 14353 if (S.RequireNonAbstractType(Loc, CaptureType, 14354 diag::err_capture_of_abstract_type)) 14355 return false; 14356 } 14357 } 14358 14359 // Capture this variable in the lambda. 14360 if (BuildAndDiagnose) 14361 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc, 14362 RefersToCapturedVariable); 14363 14364 // Compute the type of a reference to this captured variable. 14365 if (ByRef) 14366 DeclRefType = CaptureType.getNonReferenceType(); 14367 else { 14368 // C++ [expr.prim.lambda]p5: 14369 // The closure type for a lambda-expression has a public inline 14370 // function call operator [...]. This function call operator is 14371 // declared const (9.3.1) if and only if the lambda-expression's 14372 // parameter-declaration-clause is not followed by mutable. 14373 DeclRefType = CaptureType.getNonReferenceType(); 14374 if (!LSI->Mutable && !CaptureType->isReferenceType()) 14375 DeclRefType.addConst(); 14376 } 14377 14378 // Add the capture. 14379 if (BuildAndDiagnose) 14380 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 14381 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 14382 14383 return true; 14384 } 14385 14386 bool Sema::tryCaptureVariable( 14387 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 14388 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 14389 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 14390 // An init-capture is notionally from the context surrounding its 14391 // declaration, but its parent DC is the lambda class. 14392 DeclContext *VarDC = Var->getDeclContext(); 14393 if (Var->isInitCapture()) 14394 VarDC = VarDC->getParent(); 14395 14396 DeclContext *DC = CurContext; 14397 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 14398 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 14399 // We need to sync up the Declaration Context with the 14400 // FunctionScopeIndexToStopAt 14401 if (FunctionScopeIndexToStopAt) { 14402 unsigned FSIndex = FunctionScopes.size() - 1; 14403 while (FSIndex != MaxFunctionScopesIndex) { 14404 DC = getLambdaAwareParentOfDeclContext(DC); 14405 --FSIndex; 14406 } 14407 } 14408 14409 14410 // If the variable is declared in the current context, there is no need to 14411 // capture it. 14412 if (VarDC == DC) return true; 14413 14414 // Capture global variables if it is required to use private copy of this 14415 // variable. 14416 bool IsGlobal = !Var->hasLocalStorage(); 14417 if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var))) 14418 return true; 14419 Var = Var->getCanonicalDecl(); 14420 14421 // Walk up the stack to determine whether we can capture the variable, 14422 // performing the "simple" checks that don't depend on type. We stop when 14423 // we've either hit the declared scope of the variable or find an existing 14424 // capture of that variable. We start from the innermost capturing-entity 14425 // (the DC) and ensure that all intervening capturing-entities 14426 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 14427 // declcontext can either capture the variable or have already captured 14428 // the variable. 14429 CaptureType = Var->getType(); 14430 DeclRefType = CaptureType.getNonReferenceType(); 14431 bool Nested = false; 14432 bool Explicit = (Kind != TryCapture_Implicit); 14433 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 14434 do { 14435 // Only block literals, captured statements, and lambda expressions can 14436 // capture; other scopes don't work. 14437 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 14438 ExprLoc, 14439 BuildAndDiagnose, 14440 *this); 14441 // We need to check for the parent *first* because, if we *have* 14442 // private-captured a global variable, we need to recursively capture it in 14443 // intermediate blocks, lambdas, etc. 14444 if (!ParentDC) { 14445 if (IsGlobal) { 14446 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 14447 break; 14448 } 14449 return true; 14450 } 14451 14452 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 14453 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 14454 14455 14456 // Check whether we've already captured it. 14457 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 14458 DeclRefType)) { 14459 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 14460 break; 14461 } 14462 // If we are instantiating a generic lambda call operator body, 14463 // we do not want to capture new variables. What was captured 14464 // during either a lambdas transformation or initial parsing 14465 // should be used. 14466 if (isGenericLambdaCallOperatorSpecialization(DC)) { 14467 if (BuildAndDiagnose) { 14468 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 14469 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 14470 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 14471 Diag(Var->getLocation(), diag::note_previous_decl) 14472 << Var->getDeclName(); 14473 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); 14474 } else 14475 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 14476 } 14477 return true; 14478 } 14479 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 14480 // certain types of variables (unnamed, variably modified types etc.) 14481 // so check for eligibility. 14482 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 14483 return true; 14484 14485 // Try to capture variable-length arrays types. 14486 if (Var->getType()->isVariablyModifiedType()) { 14487 // We're going to walk down into the type and look for VLA 14488 // expressions. 14489 QualType QTy = Var->getType(); 14490 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 14491 QTy = PVD->getOriginalType(); 14492 captureVariablyModifiedType(Context, QTy, CSI); 14493 } 14494 14495 if (getLangOpts().OpenMP) { 14496 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 14497 // OpenMP private variables should not be captured in outer scope, so 14498 // just break here. Similarly, global variables that are captured in a 14499 // target region should not be captured outside the scope of the region. 14500 if (RSI->CapRegionKind == CR_OpenMP) { 14501 auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 14502 // When we detect target captures we are looking from inside the 14503 // target region, therefore we need to propagate the capture from the 14504 // enclosing region. Therefore, the capture is not initially nested. 14505 if (IsTargetCap) 14506 FunctionScopesIndex--; 14507 14508 if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) { 14509 Nested = !IsTargetCap; 14510 DeclRefType = DeclRefType.getUnqualifiedType(); 14511 CaptureType = Context.getLValueReferenceType(DeclRefType); 14512 break; 14513 } 14514 } 14515 } 14516 } 14517 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 14518 // No capture-default, and this is not an explicit capture 14519 // so cannot capture this variable. 14520 if (BuildAndDiagnose) { 14521 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 14522 Diag(Var->getLocation(), diag::note_previous_decl) 14523 << Var->getDeclName(); 14524 if (cast<LambdaScopeInfo>(CSI)->Lambda) 14525 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 14526 diag::note_lambda_decl); 14527 // FIXME: If we error out because an outer lambda can not implicitly 14528 // capture a variable that an inner lambda explicitly captures, we 14529 // should have the inner lambda do the explicit capture - because 14530 // it makes for cleaner diagnostics later. This would purely be done 14531 // so that the diagnostic does not misleadingly claim that a variable 14532 // can not be captured by a lambda implicitly even though it is captured 14533 // explicitly. Suggestion: 14534 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 14535 // at the function head 14536 // - cache the StartingDeclContext - this must be a lambda 14537 // - captureInLambda in the innermost lambda the variable. 14538 } 14539 return true; 14540 } 14541 14542 FunctionScopesIndex--; 14543 DC = ParentDC; 14544 Explicit = false; 14545 } while (!VarDC->Equals(DC)); 14546 14547 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 14548 // computing the type of the capture at each step, checking type-specific 14549 // requirements, and adding captures if requested. 14550 // If the variable had already been captured previously, we start capturing 14551 // at the lambda nested within that one. 14552 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 14553 ++I) { 14554 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 14555 14556 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 14557 if (!captureInBlock(BSI, Var, ExprLoc, 14558 BuildAndDiagnose, CaptureType, 14559 DeclRefType, Nested, *this)) 14560 return true; 14561 Nested = true; 14562 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 14563 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 14564 BuildAndDiagnose, CaptureType, 14565 DeclRefType, Nested, *this)) 14566 return true; 14567 Nested = true; 14568 } else { 14569 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 14570 if (!captureInLambda(LSI, Var, ExprLoc, 14571 BuildAndDiagnose, CaptureType, 14572 DeclRefType, Nested, Kind, EllipsisLoc, 14573 /*IsTopScope*/I == N - 1, *this)) 14574 return true; 14575 Nested = true; 14576 } 14577 } 14578 return false; 14579 } 14580 14581 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 14582 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 14583 QualType CaptureType; 14584 QualType DeclRefType; 14585 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 14586 /*BuildAndDiagnose=*/true, CaptureType, 14587 DeclRefType, nullptr); 14588 } 14589 14590 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 14591 QualType CaptureType; 14592 QualType DeclRefType; 14593 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 14594 /*BuildAndDiagnose=*/false, CaptureType, 14595 DeclRefType, nullptr); 14596 } 14597 14598 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 14599 QualType CaptureType; 14600 QualType DeclRefType; 14601 14602 // Determine whether we can capture this variable. 14603 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 14604 /*BuildAndDiagnose=*/false, CaptureType, 14605 DeclRefType, nullptr)) 14606 return QualType(); 14607 14608 return DeclRefType; 14609 } 14610 14611 14612 14613 // If either the type of the variable or the initializer is dependent, 14614 // return false. Otherwise, determine whether the variable is a constant 14615 // expression. Use this if you need to know if a variable that might or 14616 // might not be dependent is truly a constant expression. 14617 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 14618 ASTContext &Context) { 14619 14620 if (Var->getType()->isDependentType()) 14621 return false; 14622 const VarDecl *DefVD = nullptr; 14623 Var->getAnyInitializer(DefVD); 14624 if (!DefVD) 14625 return false; 14626 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 14627 Expr *Init = cast<Expr>(Eval->Value); 14628 if (Init->isValueDependent()) 14629 return false; 14630 return IsVariableAConstantExpression(Var, Context); 14631 } 14632 14633 14634 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 14635 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 14636 // an object that satisfies the requirements for appearing in a 14637 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 14638 // is immediately applied." This function handles the lvalue-to-rvalue 14639 // conversion part. 14640 MaybeODRUseExprs.erase(E->IgnoreParens()); 14641 14642 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 14643 // to a variable that is a constant expression, and if so, identify it as 14644 // a reference to a variable that does not involve an odr-use of that 14645 // variable. 14646 if (LambdaScopeInfo *LSI = getCurLambda()) { 14647 Expr *SansParensExpr = E->IgnoreParens(); 14648 VarDecl *Var = nullptr; 14649 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 14650 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 14651 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 14652 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 14653 14654 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 14655 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 14656 } 14657 } 14658 14659 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 14660 Res = CorrectDelayedTyposInExpr(Res); 14661 14662 if (!Res.isUsable()) 14663 return Res; 14664 14665 // If a constant-expression is a reference to a variable where we delay 14666 // deciding whether it is an odr-use, just assume we will apply the 14667 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 14668 // (a non-type template argument), we have special handling anyway. 14669 UpdateMarkingForLValueToRValue(Res.get()); 14670 return Res; 14671 } 14672 14673 void Sema::CleanupVarDeclMarking() { 14674 for (Expr *E : MaybeODRUseExprs) { 14675 VarDecl *Var; 14676 SourceLocation Loc; 14677 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 14678 Var = cast<VarDecl>(DRE->getDecl()); 14679 Loc = DRE->getLocation(); 14680 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 14681 Var = cast<VarDecl>(ME->getMemberDecl()); 14682 Loc = ME->getMemberLoc(); 14683 } else { 14684 llvm_unreachable("Unexpected expression"); 14685 } 14686 14687 MarkVarDeclODRUsed(Var, Loc, *this, 14688 /*MaxFunctionScopeIndex Pointer*/ nullptr); 14689 } 14690 14691 MaybeODRUseExprs.clear(); 14692 } 14693 14694 14695 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 14696 VarDecl *Var, Expr *E) { 14697 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 14698 "Invalid Expr argument to DoMarkVarDeclReferenced"); 14699 Var->setReferenced(); 14700 14701 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 14702 14703 bool OdrUseContext = isOdrUseContext(SemaRef); 14704 bool NeedDefinition = 14705 OdrUseContext || (isEvaluatableContext(SemaRef) && 14706 Var->isUsableInConstantExpressions(SemaRef.Context)); 14707 14708 VarTemplateSpecializationDecl *VarSpec = 14709 dyn_cast<VarTemplateSpecializationDecl>(Var); 14710 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 14711 "Can't instantiate a partial template specialization."); 14712 14713 // If this might be a member specialization of a static data member, check 14714 // the specialization is visible. We already did the checks for variable 14715 // template specializations when we created them. 14716 if (NeedDefinition && TSK != TSK_Undeclared && 14717 !isa<VarTemplateSpecializationDecl>(Var)) 14718 SemaRef.checkSpecializationVisibility(Loc, Var); 14719 14720 // Perform implicit instantiation of static data members, static data member 14721 // templates of class templates, and variable template specializations. Delay 14722 // instantiations of variable templates, except for those that could be used 14723 // in a constant expression. 14724 if (NeedDefinition && isTemplateInstantiation(TSK)) { 14725 bool TryInstantiating = TSK == TSK_ImplicitInstantiation; 14726 14727 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) { 14728 if (Var->getPointOfInstantiation().isInvalid()) { 14729 // This is a modification of an existing AST node. Notify listeners. 14730 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 14731 L->StaticDataMemberInstantiated(Var); 14732 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context)) 14733 // Don't bother trying to instantiate it again, unless we might need 14734 // its initializer before we get to the end of the TU. 14735 TryInstantiating = false; 14736 } 14737 14738 if (Var->getPointOfInstantiation().isInvalid()) 14739 Var->setTemplateSpecializationKind(TSK, Loc); 14740 14741 if (TryInstantiating) { 14742 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 14743 bool InstantiationDependent = false; 14744 bool IsNonDependent = 14745 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 14746 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 14747 : true; 14748 14749 // Do not instantiate specializations that are still type-dependent. 14750 if (IsNonDependent) { 14751 if (Var->isUsableInConstantExpressions(SemaRef.Context)) { 14752 // Do not defer instantiations of variables which could be used in a 14753 // constant expression. 14754 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 14755 } else { 14756 SemaRef.PendingInstantiations 14757 .push_back(std::make_pair(Var, PointOfInstantiation)); 14758 } 14759 } 14760 } 14761 } 14762 14763 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 14764 // the requirements for appearing in a constant expression (5.19) and, if 14765 // it is an object, the lvalue-to-rvalue conversion (4.1) 14766 // is immediately applied." We check the first part here, and 14767 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 14768 // Note that we use the C++11 definition everywhere because nothing in 14769 // C++03 depends on whether we get the C++03 version correct. The second 14770 // part does not apply to references, since they are not objects. 14771 if (OdrUseContext && E && 14772 IsVariableAConstantExpression(Var, SemaRef.Context)) { 14773 // A reference initialized by a constant expression can never be 14774 // odr-used, so simply ignore it. 14775 if (!Var->getType()->isReferenceType()) 14776 SemaRef.MaybeODRUseExprs.insert(E); 14777 } else if (OdrUseContext) { 14778 MarkVarDeclODRUsed(Var, Loc, SemaRef, 14779 /*MaxFunctionScopeIndex ptr*/ nullptr); 14780 } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) { 14781 // If this is a dependent context, we don't need to mark variables as 14782 // odr-used, but we may still need to track them for lambda capture. 14783 // FIXME: Do we also need to do this inside dependent typeid expressions 14784 // (which are modeled as unevaluated at this point)? 14785 const bool RefersToEnclosingScope = 14786 (SemaRef.CurContext != Var->getDeclContext() && 14787 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 14788 if (RefersToEnclosingScope) { 14789 LambdaScopeInfo *const LSI = 14790 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 14791 if (LSI && !LSI->CallOperator->Encloses(Var->getDeclContext())) { 14792 // If a variable could potentially be odr-used, defer marking it so 14793 // until we finish analyzing the full expression for any 14794 // lvalue-to-rvalue 14795 // or discarded value conversions that would obviate odr-use. 14796 // Add it to the list of potential captures that will be analyzed 14797 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 14798 // unless the variable is a reference that was initialized by a constant 14799 // expression (this will never need to be captured or odr-used). 14800 assert(E && "Capture variable should be used in an expression."); 14801 if (!Var->getType()->isReferenceType() || 14802 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 14803 LSI->addPotentialCapture(E->IgnoreParens()); 14804 } 14805 } 14806 } 14807 } 14808 14809 /// \brief Mark a variable referenced, and check whether it is odr-used 14810 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 14811 /// used directly for normal expressions referring to VarDecl. 14812 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 14813 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 14814 } 14815 14816 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 14817 Decl *D, Expr *E, bool MightBeOdrUse) { 14818 if (SemaRef.isInOpenMPDeclareTargetContext()) 14819 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 14820 14821 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 14822 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 14823 return; 14824 } 14825 14826 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 14827 14828 // If this is a call to a method via a cast, also mark the method in the 14829 // derived class used in case codegen can devirtualize the call. 14830 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 14831 if (!ME) 14832 return; 14833 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 14834 if (!MD) 14835 return; 14836 // Only attempt to devirtualize if this is truly a virtual call. 14837 bool IsVirtualCall = MD->isVirtual() && 14838 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 14839 if (!IsVirtualCall) 14840 return; 14841 14842 // If it's possible to devirtualize the call, mark the called function 14843 // referenced. 14844 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 14845 ME->getBase(), SemaRef.getLangOpts().AppleKext); 14846 if (DM) 14847 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 14848 } 14849 14850 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 14851 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 14852 // TODO: update this with DR# once a defect report is filed. 14853 // C++11 defect. The address of a pure member should not be an ODR use, even 14854 // if it's a qualified reference. 14855 bool OdrUse = true; 14856 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 14857 if (Method->isVirtual() && 14858 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 14859 OdrUse = false; 14860 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 14861 } 14862 14863 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 14864 void Sema::MarkMemberReferenced(MemberExpr *E) { 14865 // C++11 [basic.def.odr]p2: 14866 // A non-overloaded function whose name appears as a potentially-evaluated 14867 // expression or a member of a set of candidate functions, if selected by 14868 // overload resolution when referred to from a potentially-evaluated 14869 // expression, is odr-used, unless it is a pure virtual function and its 14870 // name is not explicitly qualified. 14871 bool MightBeOdrUse = true; 14872 if (E->performsVirtualDispatch(getLangOpts())) { 14873 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 14874 if (Method->isPure()) 14875 MightBeOdrUse = false; 14876 } 14877 SourceLocation Loc = E->getMemberLoc().isValid() ? 14878 E->getMemberLoc() : E->getLocStart(); 14879 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 14880 } 14881 14882 /// \brief Perform marking for a reference to an arbitrary declaration. It 14883 /// marks the declaration referenced, and performs odr-use checking for 14884 /// functions and variables. This method should not be used when building a 14885 /// normal expression which refers to a variable. 14886 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 14887 bool MightBeOdrUse) { 14888 if (MightBeOdrUse) { 14889 if (auto *VD = dyn_cast<VarDecl>(D)) { 14890 MarkVariableReferenced(Loc, VD); 14891 return; 14892 } 14893 } 14894 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 14895 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 14896 return; 14897 } 14898 D->setReferenced(); 14899 } 14900 14901 namespace { 14902 // Mark all of the declarations used by a type as referenced. 14903 // FIXME: Not fully implemented yet! We need to have a better understanding 14904 // of when we're entering a context we should not recurse into. 14905 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 14906 // TreeTransforms rebuilding the type in a new context. Rather than 14907 // duplicating the TreeTransform logic, we should consider reusing it here. 14908 // Currently that causes problems when rebuilding LambdaExprs. 14909 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 14910 Sema &S; 14911 SourceLocation Loc; 14912 14913 public: 14914 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 14915 14916 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 14917 14918 bool TraverseTemplateArgument(const TemplateArgument &Arg); 14919 }; 14920 } 14921 14922 bool MarkReferencedDecls::TraverseTemplateArgument( 14923 const TemplateArgument &Arg) { 14924 { 14925 // A non-type template argument is a constant-evaluated context. 14926 EnterExpressionEvaluationContext Evaluated( 14927 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 14928 if (Arg.getKind() == TemplateArgument::Declaration) { 14929 if (Decl *D = Arg.getAsDecl()) 14930 S.MarkAnyDeclReferenced(Loc, D, true); 14931 } else if (Arg.getKind() == TemplateArgument::Expression) { 14932 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 14933 } 14934 } 14935 14936 return Inherited::TraverseTemplateArgument(Arg); 14937 } 14938 14939 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 14940 MarkReferencedDecls Marker(*this, Loc); 14941 Marker.TraverseType(T); 14942 } 14943 14944 namespace { 14945 /// \brief Helper class that marks all of the declarations referenced by 14946 /// potentially-evaluated subexpressions as "referenced". 14947 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 14948 Sema &S; 14949 bool SkipLocalVariables; 14950 14951 public: 14952 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 14953 14954 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 14955 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 14956 14957 void VisitDeclRefExpr(DeclRefExpr *E) { 14958 // If we were asked not to visit local variables, don't. 14959 if (SkipLocalVariables) { 14960 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 14961 if (VD->hasLocalStorage()) 14962 return; 14963 } 14964 14965 S.MarkDeclRefReferenced(E); 14966 } 14967 14968 void VisitMemberExpr(MemberExpr *E) { 14969 S.MarkMemberReferenced(E); 14970 Inherited::VisitMemberExpr(E); 14971 } 14972 14973 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 14974 S.MarkFunctionReferenced(E->getLocStart(), 14975 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 14976 Visit(E->getSubExpr()); 14977 } 14978 14979 void VisitCXXNewExpr(CXXNewExpr *E) { 14980 if (E->getOperatorNew()) 14981 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 14982 if (E->getOperatorDelete()) 14983 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 14984 Inherited::VisitCXXNewExpr(E); 14985 } 14986 14987 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 14988 if (E->getOperatorDelete()) 14989 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 14990 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 14991 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 14992 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 14993 S.MarkFunctionReferenced(E->getLocStart(), 14994 S.LookupDestructor(Record)); 14995 } 14996 14997 Inherited::VisitCXXDeleteExpr(E); 14998 } 14999 15000 void VisitCXXConstructExpr(CXXConstructExpr *E) { 15001 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 15002 Inherited::VisitCXXConstructExpr(E); 15003 } 15004 15005 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 15006 Visit(E->getExpr()); 15007 } 15008 15009 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 15010 Inherited::VisitImplicitCastExpr(E); 15011 15012 if (E->getCastKind() == CK_LValueToRValue) 15013 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 15014 } 15015 }; 15016 } 15017 15018 /// \brief Mark any declarations that appear within this expression or any 15019 /// potentially-evaluated subexpressions as "referenced". 15020 /// 15021 /// \param SkipLocalVariables If true, don't mark local variables as 15022 /// 'referenced'. 15023 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 15024 bool SkipLocalVariables) { 15025 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 15026 } 15027 15028 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 15029 /// of the program being compiled. 15030 /// 15031 /// This routine emits the given diagnostic when the code currently being 15032 /// type-checked is "potentially evaluated", meaning that there is a 15033 /// possibility that the code will actually be executable. Code in sizeof() 15034 /// expressions, code used only during overload resolution, etc., are not 15035 /// potentially evaluated. This routine will suppress such diagnostics or, 15036 /// in the absolutely nutty case of potentially potentially evaluated 15037 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 15038 /// later. 15039 /// 15040 /// This routine should be used for all diagnostics that describe the run-time 15041 /// behavior of a program, such as passing a non-POD value through an ellipsis. 15042 /// Failure to do so will likely result in spurious diagnostics or failures 15043 /// during overload resolution or within sizeof/alignof/typeof/typeid. 15044 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 15045 const PartialDiagnostic &PD) { 15046 switch (ExprEvalContexts.back().Context) { 15047 case ExpressionEvaluationContext::Unevaluated: 15048 case ExpressionEvaluationContext::UnevaluatedList: 15049 case ExpressionEvaluationContext::UnevaluatedAbstract: 15050 case ExpressionEvaluationContext::DiscardedStatement: 15051 // The argument will never be evaluated, so don't complain. 15052 break; 15053 15054 case ExpressionEvaluationContext::ConstantEvaluated: 15055 // Relevant diagnostics should be produced by constant evaluation. 15056 break; 15057 15058 case ExpressionEvaluationContext::PotentiallyEvaluated: 15059 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 15060 if (Statement && getCurFunctionOrMethodDecl()) { 15061 FunctionScopes.back()->PossiblyUnreachableDiags. 15062 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 15063 } 15064 else 15065 Diag(Loc, PD); 15066 15067 return true; 15068 } 15069 15070 return false; 15071 } 15072 15073 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 15074 CallExpr *CE, FunctionDecl *FD) { 15075 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 15076 return false; 15077 15078 // If we're inside a decltype's expression, don't check for a valid return 15079 // type or construct temporaries until we know whether this is the last call. 15080 if (ExprEvalContexts.back().IsDecltype) { 15081 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 15082 return false; 15083 } 15084 15085 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 15086 FunctionDecl *FD; 15087 CallExpr *CE; 15088 15089 public: 15090 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 15091 : FD(FD), CE(CE) { } 15092 15093 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 15094 if (!FD) { 15095 S.Diag(Loc, diag::err_call_incomplete_return) 15096 << T << CE->getSourceRange(); 15097 return; 15098 } 15099 15100 S.Diag(Loc, diag::err_call_function_incomplete_return) 15101 << CE->getSourceRange() << FD->getDeclName() << T; 15102 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 15103 << FD->getDeclName(); 15104 } 15105 } Diagnoser(FD, CE); 15106 15107 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 15108 return true; 15109 15110 return false; 15111 } 15112 15113 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 15114 // will prevent this condition from triggering, which is what we want. 15115 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 15116 SourceLocation Loc; 15117 15118 unsigned diagnostic = diag::warn_condition_is_assignment; 15119 bool IsOrAssign = false; 15120 15121 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 15122 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 15123 return; 15124 15125 IsOrAssign = Op->getOpcode() == BO_OrAssign; 15126 15127 // Greylist some idioms by putting them into a warning subcategory. 15128 if (ObjCMessageExpr *ME 15129 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 15130 Selector Sel = ME->getSelector(); 15131 15132 // self = [<foo> init...] 15133 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 15134 diagnostic = diag::warn_condition_is_idiomatic_assignment; 15135 15136 // <foo> = [<bar> nextObject] 15137 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 15138 diagnostic = diag::warn_condition_is_idiomatic_assignment; 15139 } 15140 15141 Loc = Op->getOperatorLoc(); 15142 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 15143 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 15144 return; 15145 15146 IsOrAssign = Op->getOperator() == OO_PipeEqual; 15147 Loc = Op->getOperatorLoc(); 15148 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 15149 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 15150 else { 15151 // Not an assignment. 15152 return; 15153 } 15154 15155 Diag(Loc, diagnostic) << E->getSourceRange(); 15156 15157 SourceLocation Open = E->getLocStart(); 15158 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 15159 Diag(Loc, diag::note_condition_assign_silence) 15160 << FixItHint::CreateInsertion(Open, "(") 15161 << FixItHint::CreateInsertion(Close, ")"); 15162 15163 if (IsOrAssign) 15164 Diag(Loc, diag::note_condition_or_assign_to_comparison) 15165 << FixItHint::CreateReplacement(Loc, "!="); 15166 else 15167 Diag(Loc, diag::note_condition_assign_to_comparison) 15168 << FixItHint::CreateReplacement(Loc, "=="); 15169 } 15170 15171 /// \brief Redundant parentheses over an equality comparison can indicate 15172 /// that the user intended an assignment used as condition. 15173 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 15174 // Don't warn if the parens came from a macro. 15175 SourceLocation parenLoc = ParenE->getLocStart(); 15176 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 15177 return; 15178 // Don't warn for dependent expressions. 15179 if (ParenE->isTypeDependent()) 15180 return; 15181 15182 Expr *E = ParenE->IgnoreParens(); 15183 15184 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 15185 if (opE->getOpcode() == BO_EQ && 15186 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 15187 == Expr::MLV_Valid) { 15188 SourceLocation Loc = opE->getOperatorLoc(); 15189 15190 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 15191 SourceRange ParenERange = ParenE->getSourceRange(); 15192 Diag(Loc, diag::note_equality_comparison_silence) 15193 << FixItHint::CreateRemoval(ParenERange.getBegin()) 15194 << FixItHint::CreateRemoval(ParenERange.getEnd()); 15195 Diag(Loc, diag::note_equality_comparison_to_assign) 15196 << FixItHint::CreateReplacement(Loc, "="); 15197 } 15198 } 15199 15200 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 15201 bool IsConstexpr) { 15202 DiagnoseAssignmentAsCondition(E); 15203 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 15204 DiagnoseEqualityWithExtraParens(parenE); 15205 15206 ExprResult result = CheckPlaceholderExpr(E); 15207 if (result.isInvalid()) return ExprError(); 15208 E = result.get(); 15209 15210 if (!E->isTypeDependent()) { 15211 if (getLangOpts().CPlusPlus) 15212 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 15213 15214 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 15215 if (ERes.isInvalid()) 15216 return ExprError(); 15217 E = ERes.get(); 15218 15219 QualType T = E->getType(); 15220 if (!T->isScalarType()) { // C99 6.8.4.1p1 15221 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 15222 << T << E->getSourceRange(); 15223 return ExprError(); 15224 } 15225 CheckBoolLikeConversion(E, Loc); 15226 } 15227 15228 return E; 15229 } 15230 15231 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 15232 Expr *SubExpr, ConditionKind CK) { 15233 // Empty conditions are valid in for-statements. 15234 if (!SubExpr) 15235 return ConditionResult(); 15236 15237 ExprResult Cond; 15238 switch (CK) { 15239 case ConditionKind::Boolean: 15240 Cond = CheckBooleanCondition(Loc, SubExpr); 15241 break; 15242 15243 case ConditionKind::ConstexprIf: 15244 Cond = CheckBooleanCondition(Loc, SubExpr, true); 15245 break; 15246 15247 case ConditionKind::Switch: 15248 Cond = CheckSwitchCondition(Loc, SubExpr); 15249 break; 15250 } 15251 if (Cond.isInvalid()) 15252 return ConditionError(); 15253 15254 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 15255 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 15256 if (!FullExpr.get()) 15257 return ConditionError(); 15258 15259 return ConditionResult(*this, nullptr, FullExpr, 15260 CK == ConditionKind::ConstexprIf); 15261 } 15262 15263 namespace { 15264 /// A visitor for rebuilding a call to an __unknown_any expression 15265 /// to have an appropriate type. 15266 struct RebuildUnknownAnyFunction 15267 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 15268 15269 Sema &S; 15270 15271 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 15272 15273 ExprResult VisitStmt(Stmt *S) { 15274 llvm_unreachable("unexpected statement!"); 15275 } 15276 15277 ExprResult VisitExpr(Expr *E) { 15278 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 15279 << E->getSourceRange(); 15280 return ExprError(); 15281 } 15282 15283 /// Rebuild an expression which simply semantically wraps another 15284 /// expression which it shares the type and value kind of. 15285 template <class T> ExprResult rebuildSugarExpr(T *E) { 15286 ExprResult SubResult = Visit(E->getSubExpr()); 15287 if (SubResult.isInvalid()) return ExprError(); 15288 15289 Expr *SubExpr = SubResult.get(); 15290 E->setSubExpr(SubExpr); 15291 E->setType(SubExpr->getType()); 15292 E->setValueKind(SubExpr->getValueKind()); 15293 assert(E->getObjectKind() == OK_Ordinary); 15294 return E; 15295 } 15296 15297 ExprResult VisitParenExpr(ParenExpr *E) { 15298 return rebuildSugarExpr(E); 15299 } 15300 15301 ExprResult VisitUnaryExtension(UnaryOperator *E) { 15302 return rebuildSugarExpr(E); 15303 } 15304 15305 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 15306 ExprResult SubResult = Visit(E->getSubExpr()); 15307 if (SubResult.isInvalid()) return ExprError(); 15308 15309 Expr *SubExpr = SubResult.get(); 15310 E->setSubExpr(SubExpr); 15311 E->setType(S.Context.getPointerType(SubExpr->getType())); 15312 assert(E->getValueKind() == VK_RValue); 15313 assert(E->getObjectKind() == OK_Ordinary); 15314 return E; 15315 } 15316 15317 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 15318 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 15319 15320 E->setType(VD->getType()); 15321 15322 assert(E->getValueKind() == VK_RValue); 15323 if (S.getLangOpts().CPlusPlus && 15324 !(isa<CXXMethodDecl>(VD) && 15325 cast<CXXMethodDecl>(VD)->isInstance())) 15326 E->setValueKind(VK_LValue); 15327 15328 return E; 15329 } 15330 15331 ExprResult VisitMemberExpr(MemberExpr *E) { 15332 return resolveDecl(E, E->getMemberDecl()); 15333 } 15334 15335 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 15336 return resolveDecl(E, E->getDecl()); 15337 } 15338 }; 15339 } 15340 15341 /// Given a function expression of unknown-any type, try to rebuild it 15342 /// to have a function type. 15343 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 15344 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 15345 if (Result.isInvalid()) return ExprError(); 15346 return S.DefaultFunctionArrayConversion(Result.get()); 15347 } 15348 15349 namespace { 15350 /// A visitor for rebuilding an expression of type __unknown_anytype 15351 /// into one which resolves the type directly on the referring 15352 /// expression. Strict preservation of the original source 15353 /// structure is not a goal. 15354 struct RebuildUnknownAnyExpr 15355 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 15356 15357 Sema &S; 15358 15359 /// The current destination type. 15360 QualType DestType; 15361 15362 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 15363 : S(S), DestType(CastType) {} 15364 15365 ExprResult VisitStmt(Stmt *S) { 15366 llvm_unreachable("unexpected statement!"); 15367 } 15368 15369 ExprResult VisitExpr(Expr *E) { 15370 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 15371 << E->getSourceRange(); 15372 return ExprError(); 15373 } 15374 15375 ExprResult VisitCallExpr(CallExpr *E); 15376 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 15377 15378 /// Rebuild an expression which simply semantically wraps another 15379 /// expression which it shares the type and value kind of. 15380 template <class T> ExprResult rebuildSugarExpr(T *E) { 15381 ExprResult SubResult = Visit(E->getSubExpr()); 15382 if (SubResult.isInvalid()) return ExprError(); 15383 Expr *SubExpr = SubResult.get(); 15384 E->setSubExpr(SubExpr); 15385 E->setType(SubExpr->getType()); 15386 E->setValueKind(SubExpr->getValueKind()); 15387 assert(E->getObjectKind() == OK_Ordinary); 15388 return E; 15389 } 15390 15391 ExprResult VisitParenExpr(ParenExpr *E) { 15392 return rebuildSugarExpr(E); 15393 } 15394 15395 ExprResult VisitUnaryExtension(UnaryOperator *E) { 15396 return rebuildSugarExpr(E); 15397 } 15398 15399 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 15400 const PointerType *Ptr = DestType->getAs<PointerType>(); 15401 if (!Ptr) { 15402 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 15403 << E->getSourceRange(); 15404 return ExprError(); 15405 } 15406 15407 if (isa<CallExpr>(E->getSubExpr())) { 15408 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 15409 << E->getSourceRange(); 15410 return ExprError(); 15411 } 15412 15413 assert(E->getValueKind() == VK_RValue); 15414 assert(E->getObjectKind() == OK_Ordinary); 15415 E->setType(DestType); 15416 15417 // Build the sub-expression as if it were an object of the pointee type. 15418 DestType = Ptr->getPointeeType(); 15419 ExprResult SubResult = Visit(E->getSubExpr()); 15420 if (SubResult.isInvalid()) return ExprError(); 15421 E->setSubExpr(SubResult.get()); 15422 return E; 15423 } 15424 15425 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 15426 15427 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 15428 15429 ExprResult VisitMemberExpr(MemberExpr *E) { 15430 return resolveDecl(E, E->getMemberDecl()); 15431 } 15432 15433 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 15434 return resolveDecl(E, E->getDecl()); 15435 } 15436 }; 15437 } 15438 15439 /// Rebuilds a call expression which yielded __unknown_anytype. 15440 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 15441 Expr *CalleeExpr = E->getCallee(); 15442 15443 enum FnKind { 15444 FK_MemberFunction, 15445 FK_FunctionPointer, 15446 FK_BlockPointer 15447 }; 15448 15449 FnKind Kind; 15450 QualType CalleeType = CalleeExpr->getType(); 15451 if (CalleeType == S.Context.BoundMemberTy) { 15452 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 15453 Kind = FK_MemberFunction; 15454 CalleeType = Expr::findBoundMemberType(CalleeExpr); 15455 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 15456 CalleeType = Ptr->getPointeeType(); 15457 Kind = FK_FunctionPointer; 15458 } else { 15459 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 15460 Kind = FK_BlockPointer; 15461 } 15462 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 15463 15464 // Verify that this is a legal result type of a function. 15465 if (DestType->isArrayType() || DestType->isFunctionType()) { 15466 unsigned diagID = diag::err_func_returning_array_function; 15467 if (Kind == FK_BlockPointer) 15468 diagID = diag::err_block_returning_array_function; 15469 15470 S.Diag(E->getExprLoc(), diagID) 15471 << DestType->isFunctionType() << DestType; 15472 return ExprError(); 15473 } 15474 15475 // Otherwise, go ahead and set DestType as the call's result. 15476 E->setType(DestType.getNonLValueExprType(S.Context)); 15477 E->setValueKind(Expr::getValueKindForType(DestType)); 15478 assert(E->getObjectKind() == OK_Ordinary); 15479 15480 // Rebuild the function type, replacing the result type with DestType. 15481 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 15482 if (Proto) { 15483 // __unknown_anytype(...) is a special case used by the debugger when 15484 // it has no idea what a function's signature is. 15485 // 15486 // We want to build this call essentially under the K&R 15487 // unprototyped rules, but making a FunctionNoProtoType in C++ 15488 // would foul up all sorts of assumptions. However, we cannot 15489 // simply pass all arguments as variadic arguments, nor can we 15490 // portably just call the function under a non-variadic type; see 15491 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 15492 // However, it turns out that in practice it is generally safe to 15493 // call a function declared as "A foo(B,C,D);" under the prototype 15494 // "A foo(B,C,D,...);". The only known exception is with the 15495 // Windows ABI, where any variadic function is implicitly cdecl 15496 // regardless of its normal CC. Therefore we change the parameter 15497 // types to match the types of the arguments. 15498 // 15499 // This is a hack, but it is far superior to moving the 15500 // corresponding target-specific code from IR-gen to Sema/AST. 15501 15502 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 15503 SmallVector<QualType, 8> ArgTypes; 15504 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 15505 ArgTypes.reserve(E->getNumArgs()); 15506 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 15507 Expr *Arg = E->getArg(i); 15508 QualType ArgType = Arg->getType(); 15509 if (E->isLValue()) { 15510 ArgType = S.Context.getLValueReferenceType(ArgType); 15511 } else if (E->isXValue()) { 15512 ArgType = S.Context.getRValueReferenceType(ArgType); 15513 } 15514 ArgTypes.push_back(ArgType); 15515 } 15516 ParamTypes = ArgTypes; 15517 } 15518 DestType = S.Context.getFunctionType(DestType, ParamTypes, 15519 Proto->getExtProtoInfo()); 15520 } else { 15521 DestType = S.Context.getFunctionNoProtoType(DestType, 15522 FnType->getExtInfo()); 15523 } 15524 15525 // Rebuild the appropriate pointer-to-function type. 15526 switch (Kind) { 15527 case FK_MemberFunction: 15528 // Nothing to do. 15529 break; 15530 15531 case FK_FunctionPointer: 15532 DestType = S.Context.getPointerType(DestType); 15533 break; 15534 15535 case FK_BlockPointer: 15536 DestType = S.Context.getBlockPointerType(DestType); 15537 break; 15538 } 15539 15540 // Finally, we can recurse. 15541 ExprResult CalleeResult = Visit(CalleeExpr); 15542 if (!CalleeResult.isUsable()) return ExprError(); 15543 E->setCallee(CalleeResult.get()); 15544 15545 // Bind a temporary if necessary. 15546 return S.MaybeBindToTemporary(E); 15547 } 15548 15549 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 15550 // Verify that this is a legal result type of a call. 15551 if (DestType->isArrayType() || DestType->isFunctionType()) { 15552 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 15553 << DestType->isFunctionType() << DestType; 15554 return ExprError(); 15555 } 15556 15557 // Rewrite the method result type if available. 15558 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 15559 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 15560 Method->setReturnType(DestType); 15561 } 15562 15563 // Change the type of the message. 15564 E->setType(DestType.getNonReferenceType()); 15565 E->setValueKind(Expr::getValueKindForType(DestType)); 15566 15567 return S.MaybeBindToTemporary(E); 15568 } 15569 15570 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 15571 // The only case we should ever see here is a function-to-pointer decay. 15572 if (E->getCastKind() == CK_FunctionToPointerDecay) { 15573 assert(E->getValueKind() == VK_RValue); 15574 assert(E->getObjectKind() == OK_Ordinary); 15575 15576 E->setType(DestType); 15577 15578 // Rebuild the sub-expression as the pointee (function) type. 15579 DestType = DestType->castAs<PointerType>()->getPointeeType(); 15580 15581 ExprResult Result = Visit(E->getSubExpr()); 15582 if (!Result.isUsable()) return ExprError(); 15583 15584 E->setSubExpr(Result.get()); 15585 return E; 15586 } else if (E->getCastKind() == CK_LValueToRValue) { 15587 assert(E->getValueKind() == VK_RValue); 15588 assert(E->getObjectKind() == OK_Ordinary); 15589 15590 assert(isa<BlockPointerType>(E->getType())); 15591 15592 E->setType(DestType); 15593 15594 // The sub-expression has to be a lvalue reference, so rebuild it as such. 15595 DestType = S.Context.getLValueReferenceType(DestType); 15596 15597 ExprResult Result = Visit(E->getSubExpr()); 15598 if (!Result.isUsable()) return ExprError(); 15599 15600 E->setSubExpr(Result.get()); 15601 return E; 15602 } else { 15603 llvm_unreachable("Unhandled cast type!"); 15604 } 15605 } 15606 15607 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 15608 ExprValueKind ValueKind = VK_LValue; 15609 QualType Type = DestType; 15610 15611 // We know how to make this work for certain kinds of decls: 15612 15613 // - functions 15614 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 15615 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 15616 DestType = Ptr->getPointeeType(); 15617 ExprResult Result = resolveDecl(E, VD); 15618 if (Result.isInvalid()) return ExprError(); 15619 return S.ImpCastExprToType(Result.get(), Type, 15620 CK_FunctionToPointerDecay, VK_RValue); 15621 } 15622 15623 if (!Type->isFunctionType()) { 15624 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 15625 << VD << E->getSourceRange(); 15626 return ExprError(); 15627 } 15628 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 15629 // We must match the FunctionDecl's type to the hack introduced in 15630 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 15631 // type. See the lengthy commentary in that routine. 15632 QualType FDT = FD->getType(); 15633 const FunctionType *FnType = FDT->castAs<FunctionType>(); 15634 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 15635 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 15636 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 15637 SourceLocation Loc = FD->getLocation(); 15638 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(), 15639 FD->getDeclContext(), 15640 Loc, Loc, FD->getNameInfo().getName(), 15641 DestType, FD->getTypeSourceInfo(), 15642 SC_None, false/*isInlineSpecified*/, 15643 FD->hasPrototype(), 15644 false/*isConstexprSpecified*/); 15645 15646 if (FD->getQualifier()) 15647 NewFD->setQualifierInfo(FD->getQualifierLoc()); 15648 15649 SmallVector<ParmVarDecl*, 16> Params; 15650 for (const auto &AI : FT->param_types()) { 15651 ParmVarDecl *Param = 15652 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 15653 Param->setScopeInfo(0, Params.size()); 15654 Params.push_back(Param); 15655 } 15656 NewFD->setParams(Params); 15657 DRE->setDecl(NewFD); 15658 VD = DRE->getDecl(); 15659 } 15660 } 15661 15662 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 15663 if (MD->isInstance()) { 15664 ValueKind = VK_RValue; 15665 Type = S.Context.BoundMemberTy; 15666 } 15667 15668 // Function references aren't l-values in C. 15669 if (!S.getLangOpts().CPlusPlus) 15670 ValueKind = VK_RValue; 15671 15672 // - variables 15673 } else if (isa<VarDecl>(VD)) { 15674 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 15675 Type = RefTy->getPointeeType(); 15676 } else if (Type->isFunctionType()) { 15677 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 15678 << VD << E->getSourceRange(); 15679 return ExprError(); 15680 } 15681 15682 // - nothing else 15683 } else { 15684 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 15685 << VD << E->getSourceRange(); 15686 return ExprError(); 15687 } 15688 15689 // Modifying the declaration like this is friendly to IR-gen but 15690 // also really dangerous. 15691 VD->setType(DestType); 15692 E->setType(Type); 15693 E->setValueKind(ValueKind); 15694 return E; 15695 } 15696 15697 /// Check a cast of an unknown-any type. We intentionally only 15698 /// trigger this for C-style casts. 15699 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 15700 Expr *CastExpr, CastKind &CastKind, 15701 ExprValueKind &VK, CXXCastPath &Path) { 15702 // The type we're casting to must be either void or complete. 15703 if (!CastType->isVoidType() && 15704 RequireCompleteType(TypeRange.getBegin(), CastType, 15705 diag::err_typecheck_cast_to_incomplete)) 15706 return ExprError(); 15707 15708 // Rewrite the casted expression from scratch. 15709 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 15710 if (!result.isUsable()) return ExprError(); 15711 15712 CastExpr = result.get(); 15713 VK = CastExpr->getValueKind(); 15714 CastKind = CK_NoOp; 15715 15716 return CastExpr; 15717 } 15718 15719 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 15720 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 15721 } 15722 15723 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 15724 Expr *arg, QualType ¶mType) { 15725 // If the syntactic form of the argument is not an explicit cast of 15726 // any sort, just do default argument promotion. 15727 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 15728 if (!castArg) { 15729 ExprResult result = DefaultArgumentPromotion(arg); 15730 if (result.isInvalid()) return ExprError(); 15731 paramType = result.get()->getType(); 15732 return result; 15733 } 15734 15735 // Otherwise, use the type that was written in the explicit cast. 15736 assert(!arg->hasPlaceholderType()); 15737 paramType = castArg->getTypeAsWritten(); 15738 15739 // Copy-initialize a parameter of that type. 15740 InitializedEntity entity = 15741 InitializedEntity::InitializeParameter(Context, paramType, 15742 /*consumed*/ false); 15743 return PerformCopyInitialization(entity, callLoc, arg); 15744 } 15745 15746 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 15747 Expr *orig = E; 15748 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 15749 while (true) { 15750 E = E->IgnoreParenImpCasts(); 15751 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 15752 E = call->getCallee(); 15753 diagID = diag::err_uncasted_call_of_unknown_any; 15754 } else { 15755 break; 15756 } 15757 } 15758 15759 SourceLocation loc; 15760 NamedDecl *d; 15761 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 15762 loc = ref->getLocation(); 15763 d = ref->getDecl(); 15764 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 15765 loc = mem->getMemberLoc(); 15766 d = mem->getMemberDecl(); 15767 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 15768 diagID = diag::err_uncasted_call_of_unknown_any; 15769 loc = msg->getSelectorStartLoc(); 15770 d = msg->getMethodDecl(); 15771 if (!d) { 15772 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 15773 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 15774 << orig->getSourceRange(); 15775 return ExprError(); 15776 } 15777 } else { 15778 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 15779 << E->getSourceRange(); 15780 return ExprError(); 15781 } 15782 15783 S.Diag(loc, diagID) << d << orig->getSourceRange(); 15784 15785 // Never recoverable. 15786 return ExprError(); 15787 } 15788 15789 /// Check for operands with placeholder types and complain if found. 15790 /// Returns ExprError() if there was an error and no recovery was possible. 15791 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 15792 if (!getLangOpts().CPlusPlus) { 15793 // C cannot handle TypoExpr nodes on either side of a binop because it 15794 // doesn't handle dependent types properly, so make sure any TypoExprs have 15795 // been dealt with before checking the operands. 15796 ExprResult Result = CorrectDelayedTyposInExpr(E); 15797 if (!Result.isUsable()) return ExprError(); 15798 E = Result.get(); 15799 } 15800 15801 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 15802 if (!placeholderType) return E; 15803 15804 switch (placeholderType->getKind()) { 15805 15806 // Overloaded expressions. 15807 case BuiltinType::Overload: { 15808 // Try to resolve a single function template specialization. 15809 // This is obligatory. 15810 ExprResult Result = E; 15811 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 15812 return Result; 15813 15814 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 15815 // leaves Result unchanged on failure. 15816 Result = E; 15817 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) 15818 return Result; 15819 15820 // If that failed, try to recover with a call. 15821 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 15822 /*complain*/ true); 15823 return Result; 15824 } 15825 15826 // Bound member functions. 15827 case BuiltinType::BoundMember: { 15828 ExprResult result = E; 15829 const Expr *BME = E->IgnoreParens(); 15830 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 15831 // Try to give a nicer diagnostic if it is a bound member that we recognize. 15832 if (isa<CXXPseudoDestructorExpr>(BME)) { 15833 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 15834 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 15835 if (ME->getMemberNameInfo().getName().getNameKind() == 15836 DeclarationName::CXXDestructorName) 15837 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 15838 } 15839 tryToRecoverWithCall(result, PD, 15840 /*complain*/ true); 15841 return result; 15842 } 15843 15844 // ARC unbridged casts. 15845 case BuiltinType::ARCUnbridgedCast: { 15846 Expr *realCast = stripARCUnbridgedCast(E); 15847 diagnoseARCUnbridgedCast(realCast); 15848 return realCast; 15849 } 15850 15851 // Expressions of unknown type. 15852 case BuiltinType::UnknownAny: 15853 return diagnoseUnknownAnyExpr(*this, E); 15854 15855 // Pseudo-objects. 15856 case BuiltinType::PseudoObject: 15857 return checkPseudoObjectRValue(E); 15858 15859 case BuiltinType::BuiltinFn: { 15860 // Accept __noop without parens by implicitly converting it to a call expr. 15861 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 15862 if (DRE) { 15863 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 15864 if (FD->getBuiltinID() == Builtin::BI__noop) { 15865 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 15866 CK_BuiltinFnToFnPtr).get(); 15867 return new (Context) CallExpr(Context, E, None, Context.IntTy, 15868 VK_RValue, SourceLocation()); 15869 } 15870 } 15871 15872 Diag(E->getLocStart(), diag::err_builtin_fn_use); 15873 return ExprError(); 15874 } 15875 15876 // Expressions of unknown type. 15877 case BuiltinType::OMPArraySection: 15878 Diag(E->getLocStart(), diag::err_omp_array_section_use); 15879 return ExprError(); 15880 15881 // Everything else should be impossible. 15882 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 15883 case BuiltinType::Id: 15884 #include "clang/Basic/OpenCLImageTypes.def" 15885 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 15886 #define PLACEHOLDER_TYPE(Id, SingletonId) 15887 #include "clang/AST/BuiltinTypes.def" 15888 break; 15889 } 15890 15891 llvm_unreachable("invalid placeholder type!"); 15892 } 15893 15894 bool Sema::CheckCaseExpression(Expr *E) { 15895 if (E->isTypeDependent()) 15896 return true; 15897 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 15898 return E->getType()->isIntegralOrEnumerationType(); 15899 return false; 15900 } 15901 15902 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 15903 ExprResult 15904 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 15905 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 15906 "Unknown Objective-C Boolean value!"); 15907 QualType BoolT = Context.ObjCBuiltinBoolTy; 15908 if (!Context.getBOOLDecl()) { 15909 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 15910 Sema::LookupOrdinaryName); 15911 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 15912 NamedDecl *ND = Result.getFoundDecl(); 15913 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 15914 Context.setBOOLDecl(TD); 15915 } 15916 } 15917 if (Context.getBOOLDecl()) 15918 BoolT = Context.getBOOLType(); 15919 return new (Context) 15920 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 15921 } 15922 15923 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 15924 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 15925 SourceLocation RParen) { 15926 15927 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 15928 15929 auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(), 15930 [&](const AvailabilitySpec &Spec) { 15931 return Spec.getPlatform() == Platform; 15932 }); 15933 15934 VersionTuple Version; 15935 if (Spec != AvailSpecs.end()) 15936 Version = Spec->getVersion(); 15937 15938 // The use of `@available` in the enclosing function should be analyzed to 15939 // warn when it's used inappropriately (i.e. not if(@available)). 15940 if (getCurFunctionOrMethodDecl()) 15941 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 15942 else if (getCurBlock() || getCurLambda()) 15943 getCurFunction()->HasPotentialAvailabilityViolations = true; 15944 15945 return new (Context) 15946 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 15947 } 15948