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 static bool HasRedeclarationWithoutAvailabilityInCategory(const Decl *D) { 91 const auto *OMD = dyn_cast<ObjCMethodDecl>(D); 92 if (!OMD) 93 return false; 94 const ObjCInterfaceDecl *OID = OMD->getClassInterface(); 95 if (!OID) 96 return false; 97 98 for (const ObjCCategoryDecl *Cat : OID->visible_categories()) 99 if (ObjCMethodDecl *CatMeth = 100 Cat->getMethod(OMD->getSelector(), OMD->isInstanceMethod())) 101 if (!CatMeth->hasAttr<AvailabilityAttr>()) 102 return true; 103 return false; 104 } 105 106 AvailabilityResult 107 Sema::ShouldDiagnoseAvailabilityOfDecl(NamedDecl *&D, std::string *Message) { 108 AvailabilityResult Result = D->getAvailability(Message); 109 110 // For typedefs, if the typedef declaration appears available look 111 // to the underlying type to see if it is more restrictive. 112 while (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) { 113 if (Result == AR_Available) { 114 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 115 D = TT->getDecl(); 116 Result = D->getAvailability(Message); 117 continue; 118 } 119 } 120 break; 121 } 122 123 // Forward class declarations get their attributes from their definition. 124 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) { 125 if (IDecl->getDefinition()) { 126 D = IDecl->getDefinition(); 127 Result = D->getAvailability(Message); 128 } 129 } 130 131 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) 132 if (Result == AR_Available) { 133 const DeclContext *DC = ECD->getDeclContext(); 134 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC)) 135 Result = TheEnumDecl->getAvailability(Message); 136 } 137 138 if (Result == AR_NotYetIntroduced) { 139 // Don't do this for enums, they can't be redeclared. 140 if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D)) 141 return AR_Available; 142 143 bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited(); 144 // Objective-C method declarations in categories are not modelled as 145 // redeclarations, so manually look for a redeclaration in a category 146 // if necessary. 147 if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D)) 148 Warn = false; 149 // In general, D will point to the most recent redeclaration. However, 150 // for `@class A;` decls, this isn't true -- manually go through the 151 // redecl chain in that case. 152 if (Warn && isa<ObjCInterfaceDecl>(D)) 153 for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn; 154 Redecl = Redecl->getPreviousDecl()) 155 if (!Redecl->hasAttr<AvailabilityAttr>() || 156 Redecl->getAttr<AvailabilityAttr>()->isInherited()) 157 Warn = false; 158 159 return Warn ? AR_NotYetIntroduced : AR_Available; 160 } 161 162 return Result; 163 } 164 165 static void 166 DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc, 167 const ObjCInterfaceDecl *UnknownObjCClass, 168 bool ObjCPropertyAccess) { 169 std::string Message; 170 // See if this declaration is unavailable, deprecated, or partial. 171 if (AvailabilityResult Result = 172 S.ShouldDiagnoseAvailabilityOfDecl(D, &Message)) { 173 174 if (Result == AR_NotYetIntroduced && S.getCurFunctionOrMethodDecl()) { 175 S.getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 176 return; 177 } 178 179 const ObjCPropertyDecl *ObjCPDecl = nullptr; 180 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 181 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) { 182 AvailabilityResult PDeclResult = PD->getAvailability(nullptr); 183 if (PDeclResult == Result) 184 ObjCPDecl = PD; 185 } 186 } 187 188 S.EmitAvailabilityWarning(Result, D, Message, Loc, UnknownObjCClass, 189 ObjCPDecl, ObjCPropertyAccess); 190 } 191 } 192 193 /// \brief Emit a note explaining that this function is deleted. 194 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 195 assert(Decl->isDeleted()); 196 197 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 198 199 if (Method && Method->isDeleted() && Method->isDefaulted()) { 200 // If the method was explicitly defaulted, point at that declaration. 201 if (!Method->isImplicit()) 202 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 203 204 // Try to diagnose why this special member function was implicitly 205 // deleted. This might fail, if that reason no longer applies. 206 CXXSpecialMember CSM = getSpecialMember(Method); 207 if (CSM != CXXInvalid) 208 ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true); 209 210 return; 211 } 212 213 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 214 if (Ctor && Ctor->isInheritingConstructor()) 215 return NoteDeletedInheritingConstructor(Ctor); 216 217 Diag(Decl->getLocation(), diag::note_availability_specified_here) 218 << Decl << true; 219 } 220 221 /// \brief Determine whether a FunctionDecl was ever declared with an 222 /// explicit storage class. 223 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 224 for (auto I : D->redecls()) { 225 if (I->getStorageClass() != SC_None) 226 return true; 227 } 228 return false; 229 } 230 231 /// \brief Check whether we're in an extern inline function and referring to a 232 /// variable or function with internal linkage (C11 6.7.4p3). 233 /// 234 /// This is only a warning because we used to silently accept this code, but 235 /// in many cases it will not behave correctly. This is not enabled in C++ mode 236 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 237 /// and so while there may still be user mistakes, most of the time we can't 238 /// prove that there are errors. 239 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 240 const NamedDecl *D, 241 SourceLocation Loc) { 242 // This is disabled under C++; there are too many ways for this to fire in 243 // contexts where the warning is a false positive, or where it is technically 244 // correct but benign. 245 if (S.getLangOpts().CPlusPlus) 246 return; 247 248 // Check if this is an inlined function or method. 249 FunctionDecl *Current = S.getCurFunctionDecl(); 250 if (!Current) 251 return; 252 if (!Current->isInlined()) 253 return; 254 if (!Current->isExternallyVisible()) 255 return; 256 257 // Check if the decl has internal linkage. 258 if (D->getFormalLinkage() != InternalLinkage) 259 return; 260 261 // Downgrade from ExtWarn to Extension if 262 // (1) the supposedly external inline function is in the main file, 263 // and probably won't be included anywhere else. 264 // (2) the thing we're referencing is a pure function. 265 // (3) the thing we're referencing is another inline function. 266 // This last can give us false negatives, but it's better than warning on 267 // wrappers for simple C library functions. 268 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 269 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 270 if (!DowngradeWarning && UsedFn) 271 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 272 273 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 274 : diag::ext_internal_in_extern_inline) 275 << /*IsVar=*/!UsedFn << D; 276 277 S.MaybeSuggestAddingStaticToDecl(Current); 278 279 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 280 << D; 281 } 282 283 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 284 const FunctionDecl *First = Cur->getFirstDecl(); 285 286 // Suggest "static" on the function, if possible. 287 if (!hasAnyExplicitStorageClass(First)) { 288 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 289 Diag(DeclBegin, diag::note_convert_inline_to_static) 290 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 291 } 292 } 293 294 /// \brief Determine whether the use of this declaration is valid, and 295 /// emit any corresponding diagnostics. 296 /// 297 /// This routine diagnoses various problems with referencing 298 /// declarations that can occur when using a declaration. For example, 299 /// it might warn if a deprecated or unavailable declaration is being 300 /// used, or produce an error (and return true) if a C++0x deleted 301 /// function is being used. 302 /// 303 /// \returns true if there was an error (this declaration cannot be 304 /// referenced), false otherwise. 305 /// 306 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 307 const ObjCInterfaceDecl *UnknownObjCClass, 308 bool ObjCPropertyAccess) { 309 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 310 // If there were any diagnostics suppressed by template argument deduction, 311 // emit them now. 312 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 313 if (Pos != SuppressedDiagnostics.end()) { 314 for (const PartialDiagnosticAt &Suppressed : Pos->second) 315 Diag(Suppressed.first, Suppressed.second); 316 317 // Clear out the list of suppressed diagnostics, so that we don't emit 318 // them again for this specialization. However, we don't obsolete this 319 // entry from the table, because we want to avoid ever emitting these 320 // diagnostics again. 321 Pos->second.clear(); 322 } 323 324 // C++ [basic.start.main]p3: 325 // The function 'main' shall not be used within a program. 326 if (cast<FunctionDecl>(D)->isMain()) 327 Diag(Loc, diag::ext_main_used); 328 } 329 330 // See if this is an auto-typed variable whose initializer we are parsing. 331 if (ParsingInitForAutoVars.count(D)) { 332 if (isa<BindingDecl>(D)) { 333 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 334 << D->getDeclName(); 335 } else { 336 const AutoType *AT = cast<VarDecl>(D)->getType()->getContainedAutoType(); 337 338 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 339 << D->getDeclName() << (unsigned)AT->getKeyword(); 340 } 341 return true; 342 } 343 344 // See if this is a deleted function. 345 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 346 if (FD->isDeleted()) { 347 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 348 if (Ctor && Ctor->isInheritingConstructor()) 349 Diag(Loc, diag::err_deleted_inherited_ctor_use) 350 << Ctor->getParent() 351 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 352 else 353 Diag(Loc, diag::err_deleted_function_use); 354 NoteDeletedFunction(FD); 355 return true; 356 } 357 358 // If the function has a deduced return type, and we can't deduce it, 359 // then we can't use it either. 360 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 361 DeduceReturnType(FD, Loc)) 362 return true; 363 364 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 365 return true; 366 } 367 368 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 369 // Only the variables omp_in and omp_out are allowed in the combiner. 370 // Only the variables omp_priv and omp_orig are allowed in the 371 // initializer-clause. 372 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 373 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 374 isa<VarDecl>(D)) { 375 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 376 << getCurFunction()->HasOMPDeclareReductionCombiner; 377 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 378 return true; 379 } 380 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass, 381 ObjCPropertyAccess); 382 383 DiagnoseUnusedOfDecl(*this, D, Loc); 384 385 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 386 387 return false; 388 } 389 390 /// \brief Retrieve the message suffix that should be added to a 391 /// diagnostic complaining about the given function being deleted or 392 /// unavailable. 393 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 394 std::string Message; 395 if (FD->getAvailability(&Message)) 396 return ": " + Message; 397 398 return std::string(); 399 } 400 401 /// DiagnoseSentinelCalls - This routine checks whether a call or 402 /// message-send is to a declaration with the sentinel attribute, and 403 /// if so, it checks that the requirements of the sentinel are 404 /// satisfied. 405 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 406 ArrayRef<Expr *> Args) { 407 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 408 if (!attr) 409 return; 410 411 // The number of formal parameters of the declaration. 412 unsigned numFormalParams; 413 414 // The kind of declaration. This is also an index into a %select in 415 // the diagnostic. 416 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 417 418 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 419 numFormalParams = MD->param_size(); 420 calleeType = CT_Method; 421 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 422 numFormalParams = FD->param_size(); 423 calleeType = CT_Function; 424 } else if (isa<VarDecl>(D)) { 425 QualType type = cast<ValueDecl>(D)->getType(); 426 const FunctionType *fn = nullptr; 427 if (const PointerType *ptr = type->getAs<PointerType>()) { 428 fn = ptr->getPointeeType()->getAs<FunctionType>(); 429 if (!fn) return; 430 calleeType = CT_Function; 431 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 432 fn = ptr->getPointeeType()->castAs<FunctionType>(); 433 calleeType = CT_Block; 434 } else { 435 return; 436 } 437 438 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 439 numFormalParams = proto->getNumParams(); 440 } else { 441 numFormalParams = 0; 442 } 443 } else { 444 return; 445 } 446 447 // "nullPos" is the number of formal parameters at the end which 448 // effectively count as part of the variadic arguments. This is 449 // useful if you would prefer to not have *any* formal parameters, 450 // but the language forces you to have at least one. 451 unsigned nullPos = attr->getNullPos(); 452 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 453 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 454 455 // The number of arguments which should follow the sentinel. 456 unsigned numArgsAfterSentinel = attr->getSentinel(); 457 458 // If there aren't enough arguments for all the formal parameters, 459 // the sentinel, and the args after the sentinel, complain. 460 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 461 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 462 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 463 return; 464 } 465 466 // Otherwise, find the sentinel expression. 467 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 468 if (!sentinelExpr) return; 469 if (sentinelExpr->isValueDependent()) return; 470 if (Context.isSentinelNullExpr(sentinelExpr)) return; 471 472 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 473 // or 'NULL' if those are actually defined in the context. Only use 474 // 'nil' for ObjC methods, where it's much more likely that the 475 // variadic arguments form a list of object pointers. 476 SourceLocation MissingNilLoc 477 = getLocForEndOfToken(sentinelExpr->getLocEnd()); 478 std::string NullValue; 479 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 480 NullValue = "nil"; 481 else if (getLangOpts().CPlusPlus11) 482 NullValue = "nullptr"; 483 else if (PP.isMacroDefined("NULL")) 484 NullValue = "NULL"; 485 else 486 NullValue = "(void*) 0"; 487 488 if (MissingNilLoc.isInvalid()) 489 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 490 else 491 Diag(MissingNilLoc, diag::warn_missing_sentinel) 492 << int(calleeType) 493 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 494 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 495 } 496 497 SourceRange Sema::getExprRange(Expr *E) const { 498 return E ? E->getSourceRange() : SourceRange(); 499 } 500 501 //===----------------------------------------------------------------------===// 502 // Standard Promotions and Conversions 503 //===----------------------------------------------------------------------===// 504 505 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 506 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 507 // Handle any placeholder expressions which made it here. 508 if (E->getType()->isPlaceholderType()) { 509 ExprResult result = CheckPlaceholderExpr(E); 510 if (result.isInvalid()) return ExprError(); 511 E = result.get(); 512 } 513 514 QualType Ty = E->getType(); 515 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 516 517 if (Ty->isFunctionType()) { 518 // If we are here, we are not calling a function but taking 519 // its address (which is not allowed in OpenCL v1.0 s6.8.a.3). 520 if (getLangOpts().OpenCL) { 521 if (Diagnose) 522 Diag(E->getExprLoc(), diag::err_opencl_taking_function_address); 523 return ExprError(); 524 } 525 526 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 527 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 528 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 529 return ExprError(); 530 531 E = ImpCastExprToType(E, Context.getPointerType(Ty), 532 CK_FunctionToPointerDecay).get(); 533 } else if (Ty->isArrayType()) { 534 // In C90 mode, arrays only promote to pointers if the array expression is 535 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 536 // type 'array of type' is converted to an expression that has type 'pointer 537 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 538 // that has type 'array of type' ...". The relevant change is "an lvalue" 539 // (C90) to "an expression" (C99). 540 // 541 // C++ 4.2p1: 542 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 543 // T" can be converted to an rvalue of type "pointer to T". 544 // 545 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 546 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 547 CK_ArrayToPointerDecay).get(); 548 } 549 return E; 550 } 551 552 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 553 // Check to see if we are dereferencing a null pointer. If so, 554 // and if not volatile-qualified, this is undefined behavior that the 555 // optimizer will delete, so warn about it. People sometimes try to use this 556 // to get a deterministic trap and are surprised by clang's behavior. This 557 // only handles the pattern "*null", which is a very syntactic check. 558 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 559 if (UO->getOpcode() == UO_Deref && 560 UO->getSubExpr()->IgnoreParenCasts()-> 561 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 562 !UO->getType().isVolatileQualified()) { 563 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 564 S.PDiag(diag::warn_indirection_through_null) 565 << UO->getSubExpr()->getSourceRange()); 566 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 567 S.PDiag(diag::note_indirection_through_null)); 568 } 569 } 570 571 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 572 SourceLocation AssignLoc, 573 const Expr* RHS) { 574 const ObjCIvarDecl *IV = OIRE->getDecl(); 575 if (!IV) 576 return; 577 578 DeclarationName MemberName = IV->getDeclName(); 579 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 580 if (!Member || !Member->isStr("isa")) 581 return; 582 583 const Expr *Base = OIRE->getBase(); 584 QualType BaseType = Base->getType(); 585 if (OIRE->isArrow()) 586 BaseType = BaseType->getPointeeType(); 587 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 588 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 589 ObjCInterfaceDecl *ClassDeclared = nullptr; 590 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 591 if (!ClassDeclared->getSuperClass() 592 && (*ClassDeclared->ivar_begin()) == IV) { 593 if (RHS) { 594 NamedDecl *ObjectSetClass = 595 S.LookupSingleName(S.TUScope, 596 &S.Context.Idents.get("object_setClass"), 597 SourceLocation(), S.LookupOrdinaryName); 598 if (ObjectSetClass) { 599 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd()); 600 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 601 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 602 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 603 AssignLoc), ",") << 604 FixItHint::CreateInsertion(RHSLocEnd, ")"); 605 } 606 else 607 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 608 } else { 609 NamedDecl *ObjectGetClass = 610 S.LookupSingleName(S.TUScope, 611 &S.Context.Idents.get("object_getClass"), 612 SourceLocation(), S.LookupOrdinaryName); 613 if (ObjectGetClass) 614 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 615 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 616 FixItHint::CreateReplacement( 617 SourceRange(OIRE->getOpLoc(), 618 OIRE->getLocEnd()), ")"); 619 else 620 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 621 } 622 S.Diag(IV->getLocation(), diag::note_ivar_decl); 623 } 624 } 625 } 626 627 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 628 // Handle any placeholder expressions which made it here. 629 if (E->getType()->isPlaceholderType()) { 630 ExprResult result = CheckPlaceholderExpr(E); 631 if (result.isInvalid()) return ExprError(); 632 E = result.get(); 633 } 634 635 // C++ [conv.lval]p1: 636 // A glvalue of a non-function, non-array type T can be 637 // converted to a prvalue. 638 if (!E->isGLValue()) return E; 639 640 QualType T = E->getType(); 641 assert(!T.isNull() && "r-value conversion on typeless expression?"); 642 643 // We don't want to throw lvalue-to-rvalue casts on top of 644 // expressions of certain types in C++. 645 if (getLangOpts().CPlusPlus && 646 (E->getType() == Context.OverloadTy || 647 T->isDependentType() || 648 T->isRecordType())) 649 return E; 650 651 // The C standard is actually really unclear on this point, and 652 // DR106 tells us what the result should be but not why. It's 653 // generally best to say that void types just doesn't undergo 654 // lvalue-to-rvalue at all. Note that expressions of unqualified 655 // 'void' type are never l-values, but qualified void can be. 656 if (T->isVoidType()) 657 return E; 658 659 // OpenCL usually rejects direct accesses to values of 'half' type. 660 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 && 661 T->isHalfType()) { 662 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 663 << 0 << T; 664 return ExprError(); 665 } 666 667 CheckForNullPointerDereference(*this, E); 668 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 669 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 670 &Context.Idents.get("object_getClass"), 671 SourceLocation(), LookupOrdinaryName); 672 if (ObjectGetClass) 673 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 674 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 675 FixItHint::CreateReplacement( 676 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 677 else 678 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 679 } 680 else if (const ObjCIvarRefExpr *OIRE = 681 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 682 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 683 684 // C++ [conv.lval]p1: 685 // [...] If T is a non-class type, the type of the prvalue is the 686 // cv-unqualified version of T. Otherwise, the type of the 687 // rvalue is T. 688 // 689 // C99 6.3.2.1p2: 690 // If the lvalue has qualified type, the value has the unqualified 691 // version of the type of the lvalue; otherwise, the value has the 692 // type of the lvalue. 693 if (T.hasQualifiers()) 694 T = T.getUnqualifiedType(); 695 696 // Under the MS ABI, lock down the inheritance model now. 697 if (T->isMemberPointerType() && 698 Context.getTargetInfo().getCXXABI().isMicrosoft()) 699 (void)isCompleteType(E->getExprLoc(), T); 700 701 UpdateMarkingForLValueToRValue(E); 702 703 // Loading a __weak object implicitly retains the value, so we need a cleanup to 704 // balance that. 705 if (getLangOpts().ObjCAutoRefCount && 706 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 707 Cleanup.setExprNeedsCleanups(true); 708 709 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 710 nullptr, VK_RValue); 711 712 // C11 6.3.2.1p2: 713 // ... if the lvalue has atomic type, the value has the non-atomic version 714 // of the type of the lvalue ... 715 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 716 T = Atomic->getValueType().getUnqualifiedType(); 717 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 718 nullptr, VK_RValue); 719 } 720 721 return Res; 722 } 723 724 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 725 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 726 if (Res.isInvalid()) 727 return ExprError(); 728 Res = DefaultLvalueConversion(Res.get()); 729 if (Res.isInvalid()) 730 return ExprError(); 731 return Res; 732 } 733 734 /// CallExprUnaryConversions - a special case of an unary conversion 735 /// performed on a function designator of a call expression. 736 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 737 QualType Ty = E->getType(); 738 ExprResult Res = E; 739 // Only do implicit cast for a function type, but not for a pointer 740 // to function type. 741 if (Ty->isFunctionType()) { 742 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 743 CK_FunctionToPointerDecay).get(); 744 if (Res.isInvalid()) 745 return ExprError(); 746 } 747 Res = DefaultLvalueConversion(Res.get()); 748 if (Res.isInvalid()) 749 return ExprError(); 750 return Res.get(); 751 } 752 753 /// UsualUnaryConversions - Performs various conversions that are common to most 754 /// operators (C99 6.3). The conversions of array and function types are 755 /// sometimes suppressed. For example, the array->pointer conversion doesn't 756 /// apply if the array is an argument to the sizeof or address (&) operators. 757 /// In these instances, this routine should *not* be called. 758 ExprResult Sema::UsualUnaryConversions(Expr *E) { 759 // First, convert to an r-value. 760 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 761 if (Res.isInvalid()) 762 return ExprError(); 763 E = Res.get(); 764 765 QualType Ty = E->getType(); 766 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 767 768 // Half FP have to be promoted to float unless it is natively supported 769 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 770 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 771 772 // Try to perform integral promotions if the object has a theoretically 773 // promotable type. 774 if (Ty->isIntegralOrUnscopedEnumerationType()) { 775 // C99 6.3.1.1p2: 776 // 777 // The following may be used in an expression wherever an int or 778 // unsigned int may be used: 779 // - an object or expression with an integer type whose integer 780 // conversion rank is less than or equal to the rank of int 781 // and unsigned int. 782 // - A bit-field of type _Bool, int, signed int, or unsigned int. 783 // 784 // If an int can represent all values of the original type, the 785 // value is converted to an int; otherwise, it is converted to an 786 // unsigned int. These are called the integer promotions. All 787 // other types are unchanged by the integer promotions. 788 789 QualType PTy = Context.isPromotableBitField(E); 790 if (!PTy.isNull()) { 791 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 792 return E; 793 } 794 if (Ty->isPromotableIntegerType()) { 795 QualType PT = Context.getPromotedIntegerType(Ty); 796 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 797 return E; 798 } 799 } 800 return E; 801 } 802 803 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 804 /// do not have a prototype. Arguments that have type float or __fp16 805 /// are promoted to double. All other argument types are converted by 806 /// UsualUnaryConversions(). 807 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 808 QualType Ty = E->getType(); 809 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 810 811 ExprResult Res = UsualUnaryConversions(E); 812 if (Res.isInvalid()) 813 return ExprError(); 814 E = Res.get(); 815 816 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to 817 // double. 818 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 819 if (BTy && (BTy->getKind() == BuiltinType::Half || 820 BTy->getKind() == BuiltinType::Float)) 821 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 822 823 // C++ performs lvalue-to-rvalue conversion as a default argument 824 // promotion, even on class types, but note: 825 // C++11 [conv.lval]p2: 826 // When an lvalue-to-rvalue conversion occurs in an unevaluated 827 // operand or a subexpression thereof the value contained in the 828 // referenced object is not accessed. Otherwise, if the glvalue 829 // has a class type, the conversion copy-initializes a temporary 830 // of type T from the glvalue and the result of the conversion 831 // is a prvalue for the temporary. 832 // FIXME: add some way to gate this entire thing for correctness in 833 // potentially potentially evaluated contexts. 834 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 835 ExprResult Temp = PerformCopyInitialization( 836 InitializedEntity::InitializeTemporary(E->getType()), 837 E->getExprLoc(), E); 838 if (Temp.isInvalid()) 839 return ExprError(); 840 E = Temp.get(); 841 } 842 843 return E; 844 } 845 846 /// Determine the degree of POD-ness for an expression. 847 /// Incomplete types are considered POD, since this check can be performed 848 /// when we're in an unevaluated context. 849 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 850 if (Ty->isIncompleteType()) { 851 // C++11 [expr.call]p7: 852 // After these conversions, if the argument does not have arithmetic, 853 // enumeration, pointer, pointer to member, or class type, the program 854 // is ill-formed. 855 // 856 // Since we've already performed array-to-pointer and function-to-pointer 857 // decay, the only such type in C++ is cv void. This also handles 858 // initializer lists as variadic arguments. 859 if (Ty->isVoidType()) 860 return VAK_Invalid; 861 862 if (Ty->isObjCObjectType()) 863 return VAK_Invalid; 864 return VAK_Valid; 865 } 866 867 if (Ty.isCXX98PODType(Context)) 868 return VAK_Valid; 869 870 // C++11 [expr.call]p7: 871 // Passing a potentially-evaluated argument of class type (Clause 9) 872 // having a non-trivial copy constructor, a non-trivial move constructor, 873 // or a non-trivial destructor, with no corresponding parameter, 874 // is conditionally-supported with implementation-defined semantics. 875 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 876 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 877 if (!Record->hasNonTrivialCopyConstructor() && 878 !Record->hasNonTrivialMoveConstructor() && 879 !Record->hasNonTrivialDestructor()) 880 return VAK_ValidInCXX11; 881 882 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 883 return VAK_Valid; 884 885 if (Ty->isObjCObjectType()) 886 return VAK_Invalid; 887 888 if (getLangOpts().MSVCCompat) 889 return VAK_MSVCUndefined; 890 891 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 892 // permitted to reject them. We should consider doing so. 893 return VAK_Undefined; 894 } 895 896 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 897 // Don't allow one to pass an Objective-C interface to a vararg. 898 const QualType &Ty = E->getType(); 899 VarArgKind VAK = isValidVarArgType(Ty); 900 901 // Complain about passing non-POD types through varargs. 902 switch (VAK) { 903 case VAK_ValidInCXX11: 904 DiagRuntimeBehavior( 905 E->getLocStart(), nullptr, 906 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 907 << Ty << CT); 908 // Fall through. 909 case VAK_Valid: 910 if (Ty->isRecordType()) { 911 // This is unlikely to be what the user intended. If the class has a 912 // 'c_str' member function, the user probably meant to call that. 913 DiagRuntimeBehavior(E->getLocStart(), nullptr, 914 PDiag(diag::warn_pass_class_arg_to_vararg) 915 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 916 } 917 break; 918 919 case VAK_Undefined: 920 case VAK_MSVCUndefined: 921 DiagRuntimeBehavior( 922 E->getLocStart(), nullptr, 923 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 924 << getLangOpts().CPlusPlus11 << Ty << CT); 925 break; 926 927 case VAK_Invalid: 928 if (Ty->isObjCObjectType()) 929 DiagRuntimeBehavior( 930 E->getLocStart(), nullptr, 931 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 932 << Ty << CT); 933 else 934 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg) 935 << isa<InitListExpr>(E) << Ty << CT; 936 break; 937 } 938 } 939 940 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 941 /// will create a trap if the resulting type is not a POD type. 942 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 943 FunctionDecl *FDecl) { 944 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 945 // Strip the unbridged-cast placeholder expression off, if applicable. 946 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 947 (CT == VariadicMethod || 948 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 949 E = stripARCUnbridgedCast(E); 950 951 // Otherwise, do normal placeholder checking. 952 } else { 953 ExprResult ExprRes = CheckPlaceholderExpr(E); 954 if (ExprRes.isInvalid()) 955 return ExprError(); 956 E = ExprRes.get(); 957 } 958 } 959 960 ExprResult ExprRes = DefaultArgumentPromotion(E); 961 if (ExprRes.isInvalid()) 962 return ExprError(); 963 E = ExprRes.get(); 964 965 // Diagnostics regarding non-POD argument types are 966 // emitted along with format string checking in Sema::CheckFunctionCall(). 967 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 968 // Turn this into a trap. 969 CXXScopeSpec SS; 970 SourceLocation TemplateKWLoc; 971 UnqualifiedId Name; 972 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 973 E->getLocStart()); 974 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 975 Name, true, false); 976 if (TrapFn.isInvalid()) 977 return ExprError(); 978 979 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 980 E->getLocStart(), None, 981 E->getLocEnd()); 982 if (Call.isInvalid()) 983 return ExprError(); 984 985 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 986 Call.get(), E); 987 if (Comma.isInvalid()) 988 return ExprError(); 989 return Comma.get(); 990 } 991 992 if (!getLangOpts().CPlusPlus && 993 RequireCompleteType(E->getExprLoc(), E->getType(), 994 diag::err_call_incomplete_argument)) 995 return ExprError(); 996 997 return E; 998 } 999 1000 /// \brief Converts an integer to complex float type. Helper function of 1001 /// UsualArithmeticConversions() 1002 /// 1003 /// \return false if the integer expression is an integer type and is 1004 /// successfully converted to the complex type. 1005 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1006 ExprResult &ComplexExpr, 1007 QualType IntTy, 1008 QualType ComplexTy, 1009 bool SkipCast) { 1010 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1011 if (SkipCast) return false; 1012 if (IntTy->isIntegerType()) { 1013 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1014 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1015 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1016 CK_FloatingRealToComplex); 1017 } else { 1018 assert(IntTy->isComplexIntegerType()); 1019 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1020 CK_IntegralComplexToFloatingComplex); 1021 } 1022 return false; 1023 } 1024 1025 /// \brief Handle arithmetic conversion with complex types. Helper function of 1026 /// UsualArithmeticConversions() 1027 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1028 ExprResult &RHS, QualType LHSType, 1029 QualType RHSType, 1030 bool IsCompAssign) { 1031 // if we have an integer operand, the result is the complex type. 1032 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1033 /*skipCast*/false)) 1034 return LHSType; 1035 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1036 /*skipCast*/IsCompAssign)) 1037 return RHSType; 1038 1039 // This handles complex/complex, complex/float, or float/complex. 1040 // When both operands are complex, the shorter operand is converted to the 1041 // type of the longer, and that is the type of the result. This corresponds 1042 // to what is done when combining two real floating-point operands. 1043 // The fun begins when size promotion occur across type domains. 1044 // From H&S 6.3.4: When one operand is complex and the other is a real 1045 // floating-point type, the less precise type is converted, within it's 1046 // real or complex domain, to the precision of the other type. For example, 1047 // when combining a "long double" with a "double _Complex", the 1048 // "double _Complex" is promoted to "long double _Complex". 1049 1050 // Compute the rank of the two types, regardless of whether they are complex. 1051 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1052 1053 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1054 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1055 QualType LHSElementType = 1056 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1057 QualType RHSElementType = 1058 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1059 1060 QualType ResultType = S.Context.getComplexType(LHSElementType); 1061 if (Order < 0) { 1062 // Promote the precision of the LHS if not an assignment. 1063 ResultType = S.Context.getComplexType(RHSElementType); 1064 if (!IsCompAssign) { 1065 if (LHSComplexType) 1066 LHS = 1067 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1068 else 1069 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1070 } 1071 } else if (Order > 0) { 1072 // Promote the precision of the RHS. 1073 if (RHSComplexType) 1074 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1075 else 1076 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1077 } 1078 return ResultType; 1079 } 1080 1081 /// \brief Hande arithmetic conversion from integer to float. Helper function 1082 /// of UsualArithmeticConversions() 1083 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1084 ExprResult &IntExpr, 1085 QualType FloatTy, QualType IntTy, 1086 bool ConvertFloat, bool ConvertInt) { 1087 if (IntTy->isIntegerType()) { 1088 if (ConvertInt) 1089 // Convert intExpr to the lhs floating point type. 1090 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1091 CK_IntegralToFloating); 1092 return FloatTy; 1093 } 1094 1095 // Convert both sides to the appropriate complex float. 1096 assert(IntTy->isComplexIntegerType()); 1097 QualType result = S.Context.getComplexType(FloatTy); 1098 1099 // _Complex int -> _Complex float 1100 if (ConvertInt) 1101 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1102 CK_IntegralComplexToFloatingComplex); 1103 1104 // float -> _Complex float 1105 if (ConvertFloat) 1106 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1107 CK_FloatingRealToComplex); 1108 1109 return result; 1110 } 1111 1112 /// \brief Handle arithmethic conversion with floating point types. Helper 1113 /// function of UsualArithmeticConversions() 1114 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1115 ExprResult &RHS, QualType LHSType, 1116 QualType RHSType, bool IsCompAssign) { 1117 bool LHSFloat = LHSType->isRealFloatingType(); 1118 bool RHSFloat = RHSType->isRealFloatingType(); 1119 1120 // If we have two real floating types, convert the smaller operand 1121 // to the bigger result. 1122 if (LHSFloat && RHSFloat) { 1123 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1124 if (order > 0) { 1125 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1126 return LHSType; 1127 } 1128 1129 assert(order < 0 && "illegal float comparison"); 1130 if (!IsCompAssign) 1131 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1132 return RHSType; 1133 } 1134 1135 if (LHSFloat) { 1136 // Half FP has to be promoted to float unless it is natively supported 1137 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1138 LHSType = S.Context.FloatTy; 1139 1140 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1141 /*convertFloat=*/!IsCompAssign, 1142 /*convertInt=*/ true); 1143 } 1144 assert(RHSFloat); 1145 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1146 /*convertInt=*/ true, 1147 /*convertFloat=*/!IsCompAssign); 1148 } 1149 1150 /// \brief Diagnose attempts to convert between __float128 and long double if 1151 /// there is no support for such conversion. Helper function of 1152 /// UsualArithmeticConversions(). 1153 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1154 QualType RHSType) { 1155 /* No issue converting if at least one of the types is not a floating point 1156 type or the two types have the same rank. 1157 */ 1158 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1159 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1160 return false; 1161 1162 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1163 "The remaining types must be floating point types."); 1164 1165 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1166 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1167 1168 QualType LHSElemType = LHSComplex ? 1169 LHSComplex->getElementType() : LHSType; 1170 QualType RHSElemType = RHSComplex ? 1171 RHSComplex->getElementType() : RHSType; 1172 1173 // No issue if the two types have the same representation 1174 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1175 &S.Context.getFloatTypeSemantics(RHSElemType)) 1176 return false; 1177 1178 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1179 RHSElemType == S.Context.LongDoubleTy); 1180 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1181 RHSElemType == S.Context.Float128Ty); 1182 1183 /* We've handled the situation where __float128 and long double have the same 1184 representation. The only other allowable conversion is if long double is 1185 really just double. 1186 */ 1187 return Float128AndLongDouble && 1188 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) != 1189 &llvm::APFloat::IEEEdouble); 1190 } 1191 1192 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1193 1194 namespace { 1195 /// These helper callbacks are placed in an anonymous namespace to 1196 /// permit their use as function template parameters. 1197 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1198 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1199 } 1200 1201 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1202 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1203 CK_IntegralComplexCast); 1204 } 1205 } 1206 1207 /// \brief Handle integer arithmetic conversions. Helper function of 1208 /// UsualArithmeticConversions() 1209 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1210 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1211 ExprResult &RHS, QualType LHSType, 1212 QualType RHSType, bool IsCompAssign) { 1213 // The rules for this case are in C99 6.3.1.8 1214 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1215 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1216 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1217 if (LHSSigned == RHSSigned) { 1218 // Same signedness; use the higher-ranked type 1219 if (order >= 0) { 1220 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1221 return LHSType; 1222 } else if (!IsCompAssign) 1223 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1224 return RHSType; 1225 } else if (order != (LHSSigned ? 1 : -1)) { 1226 // The unsigned type has greater than or equal rank to the 1227 // signed type, so use the unsigned type 1228 if (RHSSigned) { 1229 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1230 return LHSType; 1231 } else if (!IsCompAssign) 1232 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1233 return RHSType; 1234 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1235 // The two types are different widths; if we are here, that 1236 // means the signed type is larger than the unsigned type, so 1237 // use the signed type. 1238 if (LHSSigned) { 1239 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1240 return LHSType; 1241 } else if (!IsCompAssign) 1242 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1243 return RHSType; 1244 } else { 1245 // The signed type is higher-ranked than the unsigned type, 1246 // but isn't actually any bigger (like unsigned int and long 1247 // on most 32-bit systems). Use the unsigned type corresponding 1248 // to the signed type. 1249 QualType result = 1250 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1251 RHS = (*doRHSCast)(S, RHS.get(), result); 1252 if (!IsCompAssign) 1253 LHS = (*doLHSCast)(S, LHS.get(), result); 1254 return result; 1255 } 1256 } 1257 1258 /// \brief Handle conversions with GCC complex int extension. Helper function 1259 /// of UsualArithmeticConversions() 1260 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1261 ExprResult &RHS, QualType LHSType, 1262 QualType RHSType, 1263 bool IsCompAssign) { 1264 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1265 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1266 1267 if (LHSComplexInt && RHSComplexInt) { 1268 QualType LHSEltType = LHSComplexInt->getElementType(); 1269 QualType RHSEltType = RHSComplexInt->getElementType(); 1270 QualType ScalarType = 1271 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1272 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1273 1274 return S.Context.getComplexType(ScalarType); 1275 } 1276 1277 if (LHSComplexInt) { 1278 QualType LHSEltType = LHSComplexInt->getElementType(); 1279 QualType ScalarType = 1280 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1281 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1282 QualType ComplexType = S.Context.getComplexType(ScalarType); 1283 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1284 CK_IntegralRealToComplex); 1285 1286 return ComplexType; 1287 } 1288 1289 assert(RHSComplexInt); 1290 1291 QualType RHSEltType = RHSComplexInt->getElementType(); 1292 QualType ScalarType = 1293 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1294 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1295 QualType ComplexType = S.Context.getComplexType(ScalarType); 1296 1297 if (!IsCompAssign) 1298 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1299 CK_IntegralRealToComplex); 1300 return ComplexType; 1301 } 1302 1303 /// UsualArithmeticConversions - Performs various conversions that are common to 1304 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1305 /// routine returns the first non-arithmetic type found. The client is 1306 /// responsible for emitting appropriate error diagnostics. 1307 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1308 bool IsCompAssign) { 1309 if (!IsCompAssign) { 1310 LHS = UsualUnaryConversions(LHS.get()); 1311 if (LHS.isInvalid()) 1312 return QualType(); 1313 } 1314 1315 RHS = UsualUnaryConversions(RHS.get()); 1316 if (RHS.isInvalid()) 1317 return QualType(); 1318 1319 // For conversion purposes, we ignore any qualifiers. 1320 // For example, "const float" and "float" are equivalent. 1321 QualType LHSType = 1322 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1323 QualType RHSType = 1324 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1325 1326 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1327 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1328 LHSType = AtomicLHS->getValueType(); 1329 1330 // If both types are identical, no conversion is needed. 1331 if (LHSType == RHSType) 1332 return LHSType; 1333 1334 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1335 // The caller can deal with this (e.g. pointer + int). 1336 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1337 return QualType(); 1338 1339 // Apply unary and bitfield promotions to the LHS's type. 1340 QualType LHSUnpromotedType = LHSType; 1341 if (LHSType->isPromotableIntegerType()) 1342 LHSType = Context.getPromotedIntegerType(LHSType); 1343 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1344 if (!LHSBitfieldPromoteTy.isNull()) 1345 LHSType = LHSBitfieldPromoteTy; 1346 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1347 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1348 1349 // If both types are identical, no conversion is needed. 1350 if (LHSType == RHSType) 1351 return LHSType; 1352 1353 // At this point, we have two different arithmetic types. 1354 1355 // Diagnose attempts to convert between __float128 and long double where 1356 // such conversions currently can't be handled. 1357 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1358 return QualType(); 1359 1360 // Handle complex types first (C99 6.3.1.8p1). 1361 if (LHSType->isComplexType() || RHSType->isComplexType()) 1362 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1363 IsCompAssign); 1364 1365 // Now handle "real" floating types (i.e. float, double, long double). 1366 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1367 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1368 IsCompAssign); 1369 1370 // Handle GCC complex int extension. 1371 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1372 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1373 IsCompAssign); 1374 1375 // Finally, we have two differing integer types. 1376 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1377 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1378 } 1379 1380 1381 //===----------------------------------------------------------------------===// 1382 // Semantic Analysis for various Expression Types 1383 //===----------------------------------------------------------------------===// 1384 1385 1386 ExprResult 1387 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1388 SourceLocation DefaultLoc, 1389 SourceLocation RParenLoc, 1390 Expr *ControllingExpr, 1391 ArrayRef<ParsedType> ArgTypes, 1392 ArrayRef<Expr *> ArgExprs) { 1393 unsigned NumAssocs = ArgTypes.size(); 1394 assert(NumAssocs == ArgExprs.size()); 1395 1396 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1397 for (unsigned i = 0; i < NumAssocs; ++i) { 1398 if (ArgTypes[i]) 1399 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1400 else 1401 Types[i] = nullptr; 1402 } 1403 1404 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1405 ControllingExpr, 1406 llvm::makeArrayRef(Types, NumAssocs), 1407 ArgExprs); 1408 delete [] Types; 1409 return ER; 1410 } 1411 1412 ExprResult 1413 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1414 SourceLocation DefaultLoc, 1415 SourceLocation RParenLoc, 1416 Expr *ControllingExpr, 1417 ArrayRef<TypeSourceInfo *> Types, 1418 ArrayRef<Expr *> Exprs) { 1419 unsigned NumAssocs = Types.size(); 1420 assert(NumAssocs == Exprs.size()); 1421 1422 // Decay and strip qualifiers for the controlling expression type, and handle 1423 // placeholder type replacement. See committee discussion from WG14 DR423. 1424 { 1425 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 1426 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1427 if (R.isInvalid()) 1428 return ExprError(); 1429 ControllingExpr = R.get(); 1430 } 1431 1432 // The controlling expression is an unevaluated operand, so side effects are 1433 // likely unintended. 1434 if (ActiveTemplateInstantiations.empty() && 1435 ControllingExpr->HasSideEffects(Context, false)) 1436 Diag(ControllingExpr->getExprLoc(), 1437 diag::warn_side_effects_unevaluated_context); 1438 1439 bool TypeErrorFound = false, 1440 IsResultDependent = ControllingExpr->isTypeDependent(), 1441 ContainsUnexpandedParameterPack 1442 = ControllingExpr->containsUnexpandedParameterPack(); 1443 1444 for (unsigned i = 0; i < NumAssocs; ++i) { 1445 if (Exprs[i]->containsUnexpandedParameterPack()) 1446 ContainsUnexpandedParameterPack = true; 1447 1448 if (Types[i]) { 1449 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1450 ContainsUnexpandedParameterPack = true; 1451 1452 if (Types[i]->getType()->isDependentType()) { 1453 IsResultDependent = true; 1454 } else { 1455 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1456 // complete object type other than a variably modified type." 1457 unsigned D = 0; 1458 if (Types[i]->getType()->isIncompleteType()) 1459 D = diag::err_assoc_type_incomplete; 1460 else if (!Types[i]->getType()->isObjectType()) 1461 D = diag::err_assoc_type_nonobject; 1462 else if (Types[i]->getType()->isVariablyModifiedType()) 1463 D = diag::err_assoc_type_variably_modified; 1464 1465 if (D != 0) { 1466 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1467 << Types[i]->getTypeLoc().getSourceRange() 1468 << Types[i]->getType(); 1469 TypeErrorFound = true; 1470 } 1471 1472 // C11 6.5.1.1p2 "No two generic associations in the same generic 1473 // selection shall specify compatible types." 1474 for (unsigned j = i+1; j < NumAssocs; ++j) 1475 if (Types[j] && !Types[j]->getType()->isDependentType() && 1476 Context.typesAreCompatible(Types[i]->getType(), 1477 Types[j]->getType())) { 1478 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1479 diag::err_assoc_compatible_types) 1480 << Types[j]->getTypeLoc().getSourceRange() 1481 << Types[j]->getType() 1482 << Types[i]->getType(); 1483 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1484 diag::note_compat_assoc) 1485 << Types[i]->getTypeLoc().getSourceRange() 1486 << Types[i]->getType(); 1487 TypeErrorFound = true; 1488 } 1489 } 1490 } 1491 } 1492 if (TypeErrorFound) 1493 return ExprError(); 1494 1495 // If we determined that the generic selection is result-dependent, don't 1496 // try to compute the result expression. 1497 if (IsResultDependent) 1498 return new (Context) GenericSelectionExpr( 1499 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1500 ContainsUnexpandedParameterPack); 1501 1502 SmallVector<unsigned, 1> CompatIndices; 1503 unsigned DefaultIndex = -1U; 1504 for (unsigned i = 0; i < NumAssocs; ++i) { 1505 if (!Types[i]) 1506 DefaultIndex = i; 1507 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1508 Types[i]->getType())) 1509 CompatIndices.push_back(i); 1510 } 1511 1512 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1513 // type compatible with at most one of the types named in its generic 1514 // association list." 1515 if (CompatIndices.size() > 1) { 1516 // We strip parens here because the controlling expression is typically 1517 // parenthesized in macro definitions. 1518 ControllingExpr = ControllingExpr->IgnoreParens(); 1519 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1520 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1521 << (unsigned) CompatIndices.size(); 1522 for (unsigned I : CompatIndices) { 1523 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1524 diag::note_compat_assoc) 1525 << Types[I]->getTypeLoc().getSourceRange() 1526 << Types[I]->getType(); 1527 } 1528 return ExprError(); 1529 } 1530 1531 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1532 // its controlling expression shall have type compatible with exactly one of 1533 // the types named in its generic association list." 1534 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1535 // We strip parens here because the controlling expression is typically 1536 // parenthesized in macro definitions. 1537 ControllingExpr = ControllingExpr->IgnoreParens(); 1538 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1539 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1540 return ExprError(); 1541 } 1542 1543 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1544 // type name that is compatible with the type of the controlling expression, 1545 // then the result expression of the generic selection is the expression 1546 // in that generic association. Otherwise, the result expression of the 1547 // generic selection is the expression in the default generic association." 1548 unsigned ResultIndex = 1549 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1550 1551 return new (Context) GenericSelectionExpr( 1552 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1553 ContainsUnexpandedParameterPack, ResultIndex); 1554 } 1555 1556 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1557 /// location of the token and the offset of the ud-suffix within it. 1558 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1559 unsigned Offset) { 1560 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1561 S.getLangOpts()); 1562 } 1563 1564 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1565 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1566 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1567 IdentifierInfo *UDSuffix, 1568 SourceLocation UDSuffixLoc, 1569 ArrayRef<Expr*> Args, 1570 SourceLocation LitEndLoc) { 1571 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1572 1573 QualType ArgTy[2]; 1574 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1575 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1576 if (ArgTy[ArgIdx]->isArrayType()) 1577 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1578 } 1579 1580 DeclarationName OpName = 1581 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1582 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1583 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1584 1585 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1586 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1587 /*AllowRaw*/false, /*AllowTemplate*/false, 1588 /*AllowStringTemplate*/false) == Sema::LOLR_Error) 1589 return ExprError(); 1590 1591 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1592 } 1593 1594 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1595 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1596 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1597 /// multiple tokens. However, the common case is that StringToks points to one 1598 /// string. 1599 /// 1600 ExprResult 1601 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1602 assert(!StringToks.empty() && "Must have at least one string!"); 1603 1604 StringLiteralParser Literal(StringToks, PP); 1605 if (Literal.hadError) 1606 return ExprError(); 1607 1608 SmallVector<SourceLocation, 4> StringTokLocs; 1609 for (const Token &Tok : StringToks) 1610 StringTokLocs.push_back(Tok.getLocation()); 1611 1612 QualType CharTy = Context.CharTy; 1613 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1614 if (Literal.isWide()) { 1615 CharTy = Context.getWideCharType(); 1616 Kind = StringLiteral::Wide; 1617 } else if (Literal.isUTF8()) { 1618 Kind = StringLiteral::UTF8; 1619 } else if (Literal.isUTF16()) { 1620 CharTy = Context.Char16Ty; 1621 Kind = StringLiteral::UTF16; 1622 } else if (Literal.isUTF32()) { 1623 CharTy = Context.Char32Ty; 1624 Kind = StringLiteral::UTF32; 1625 } else if (Literal.isPascal()) { 1626 CharTy = Context.UnsignedCharTy; 1627 } 1628 1629 QualType CharTyConst = CharTy; 1630 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1631 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1632 CharTyConst.addConst(); 1633 1634 // Get an array type for the string, according to C99 6.4.5. This includes 1635 // the nul terminator character as well as the string length for pascal 1636 // strings. 1637 QualType StrTy = Context.getConstantArrayType(CharTyConst, 1638 llvm::APInt(32, Literal.GetNumStringChars()+1), 1639 ArrayType::Normal, 0); 1640 1641 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 1642 if (getLangOpts().OpenCL) { 1643 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant); 1644 } 1645 1646 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1647 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1648 Kind, Literal.Pascal, StrTy, 1649 &StringTokLocs[0], 1650 StringTokLocs.size()); 1651 if (Literal.getUDSuffix().empty()) 1652 return Lit; 1653 1654 // We're building a user-defined literal. 1655 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1656 SourceLocation UDSuffixLoc = 1657 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1658 Literal.getUDSuffixOffset()); 1659 1660 // Make sure we're allowed user-defined literals here. 1661 if (!UDLScope) 1662 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1663 1664 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1665 // operator "" X (str, len) 1666 QualType SizeType = Context.getSizeType(); 1667 1668 DeclarationName OpName = 1669 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1670 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1671 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1672 1673 QualType ArgTy[] = { 1674 Context.getArrayDecayedType(StrTy), SizeType 1675 }; 1676 1677 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1678 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1679 /*AllowRaw*/false, /*AllowTemplate*/false, 1680 /*AllowStringTemplate*/true)) { 1681 1682 case LOLR_Cooked: { 1683 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1684 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1685 StringTokLocs[0]); 1686 Expr *Args[] = { Lit, LenArg }; 1687 1688 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1689 } 1690 1691 case LOLR_StringTemplate: { 1692 TemplateArgumentListInfo ExplicitArgs; 1693 1694 unsigned CharBits = Context.getIntWidth(CharTy); 1695 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1696 llvm::APSInt Value(CharBits, CharIsUnsigned); 1697 1698 TemplateArgument TypeArg(CharTy); 1699 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1700 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1701 1702 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1703 Value = Lit->getCodeUnit(I); 1704 TemplateArgument Arg(Context, Value, CharTy); 1705 TemplateArgumentLocInfo ArgInfo; 1706 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1707 } 1708 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1709 &ExplicitArgs); 1710 } 1711 case LOLR_Raw: 1712 case LOLR_Template: 1713 llvm_unreachable("unexpected literal operator lookup result"); 1714 case LOLR_Error: 1715 return ExprError(); 1716 } 1717 llvm_unreachable("unexpected literal operator lookup result"); 1718 } 1719 1720 ExprResult 1721 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1722 SourceLocation Loc, 1723 const CXXScopeSpec *SS) { 1724 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1725 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1726 } 1727 1728 /// BuildDeclRefExpr - Build an expression that references a 1729 /// declaration that does not require a closure capture. 1730 ExprResult 1731 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1732 const DeclarationNameInfo &NameInfo, 1733 const CXXScopeSpec *SS, NamedDecl *FoundD, 1734 const TemplateArgumentListInfo *TemplateArgs) { 1735 bool RefersToCapturedVariable = 1736 isa<VarDecl>(D) && 1737 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1738 1739 DeclRefExpr *E; 1740 if (isa<VarTemplateSpecializationDecl>(D)) { 1741 VarTemplateSpecializationDecl *VarSpec = 1742 cast<VarTemplateSpecializationDecl>(D); 1743 1744 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1745 : NestedNameSpecifierLoc(), 1746 VarSpec->getTemplateKeywordLoc(), D, 1747 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK, 1748 FoundD, TemplateArgs); 1749 } else { 1750 assert(!TemplateArgs && "No template arguments for non-variable" 1751 " template specialization references"); 1752 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1753 : NestedNameSpecifierLoc(), 1754 SourceLocation(), D, RefersToCapturedVariable, 1755 NameInfo, Ty, VK, FoundD); 1756 } 1757 1758 MarkDeclRefReferenced(E); 1759 1760 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1761 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && 1762 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart())) 1763 recordUseOfEvaluatedWeak(E); 1764 1765 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 1766 UnusedPrivateFields.remove(FD); 1767 // Just in case we're building an illegal pointer-to-member. 1768 if (FD->isBitField()) 1769 E->setObjectKind(OK_BitField); 1770 } 1771 1772 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1773 // designates a bit-field. 1774 if (auto *BD = dyn_cast<BindingDecl>(D)) 1775 if (auto *BE = BD->getBinding()) 1776 E->setObjectKind(BE->getObjectKind()); 1777 1778 return E; 1779 } 1780 1781 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1782 /// possibly a list of template arguments. 1783 /// 1784 /// If this produces template arguments, it is permitted to call 1785 /// DecomposeTemplateName. 1786 /// 1787 /// This actually loses a lot of source location information for 1788 /// non-standard name kinds; we should consider preserving that in 1789 /// some way. 1790 void 1791 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1792 TemplateArgumentListInfo &Buffer, 1793 DeclarationNameInfo &NameInfo, 1794 const TemplateArgumentListInfo *&TemplateArgs) { 1795 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1796 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1797 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1798 1799 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1800 Id.TemplateId->NumArgs); 1801 translateTemplateArguments(TemplateArgsPtr, Buffer); 1802 1803 TemplateName TName = Id.TemplateId->Template.get(); 1804 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1805 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1806 TemplateArgs = &Buffer; 1807 } else { 1808 NameInfo = GetNameFromUnqualifiedId(Id); 1809 TemplateArgs = nullptr; 1810 } 1811 } 1812 1813 static void emitEmptyLookupTypoDiagnostic( 1814 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1815 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1816 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1817 DeclContext *Ctx = 1818 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1819 if (!TC) { 1820 // Emit a special diagnostic for failed member lookups. 1821 // FIXME: computing the declaration context might fail here (?) 1822 if (Ctx) 1823 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1824 << SS.getRange(); 1825 else 1826 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1827 return; 1828 } 1829 1830 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1831 bool DroppedSpecifier = 1832 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1833 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1834 ? diag::note_implicit_param_decl 1835 : diag::note_previous_decl; 1836 if (!Ctx) 1837 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1838 SemaRef.PDiag(NoteID)); 1839 else 1840 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1841 << Typo << Ctx << DroppedSpecifier 1842 << SS.getRange(), 1843 SemaRef.PDiag(NoteID)); 1844 } 1845 1846 /// Diagnose an empty lookup. 1847 /// 1848 /// \return false if new lookup candidates were found 1849 bool 1850 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1851 std::unique_ptr<CorrectionCandidateCallback> CCC, 1852 TemplateArgumentListInfo *ExplicitTemplateArgs, 1853 ArrayRef<Expr *> Args, TypoExpr **Out) { 1854 DeclarationName Name = R.getLookupName(); 1855 1856 unsigned diagnostic = diag::err_undeclared_var_use; 1857 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1858 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1859 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1860 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1861 diagnostic = diag::err_undeclared_use; 1862 diagnostic_suggest = diag::err_undeclared_use_suggest; 1863 } 1864 1865 // If the original lookup was an unqualified lookup, fake an 1866 // unqualified lookup. This is useful when (for example) the 1867 // original lookup would not have found something because it was a 1868 // dependent name. 1869 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1870 while (DC) { 1871 if (isa<CXXRecordDecl>(DC)) { 1872 LookupQualifiedName(R, DC); 1873 1874 if (!R.empty()) { 1875 // Don't give errors about ambiguities in this lookup. 1876 R.suppressDiagnostics(); 1877 1878 // During a default argument instantiation the CurContext points 1879 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1880 // function parameter list, hence add an explicit check. 1881 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() && 1882 ActiveTemplateInstantiations.back().Kind == 1883 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation; 1884 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1885 bool isInstance = CurMethod && 1886 CurMethod->isInstance() && 1887 DC == CurMethod->getParent() && !isDefaultArgument; 1888 1889 // Give a code modification hint to insert 'this->'. 1890 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1891 // Actually quite difficult! 1892 if (getLangOpts().MSVCCompat) 1893 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1894 if (isInstance) { 1895 Diag(R.getNameLoc(), diagnostic) << Name 1896 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1897 CheckCXXThisCapture(R.getNameLoc()); 1898 } else { 1899 Diag(R.getNameLoc(), diagnostic) << Name; 1900 } 1901 1902 // Do we really want to note all of these? 1903 for (NamedDecl *D : R) 1904 Diag(D->getLocation(), diag::note_dependent_var_use); 1905 1906 // Return true if we are inside a default argument instantiation 1907 // and the found name refers to an instance member function, otherwise 1908 // the function calling DiagnoseEmptyLookup will try to create an 1909 // implicit member call and this is wrong for default argument. 1910 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1911 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1912 return true; 1913 } 1914 1915 // Tell the callee to try to recover. 1916 return false; 1917 } 1918 1919 R.clear(); 1920 } 1921 1922 // In Microsoft mode, if we are performing lookup from within a friend 1923 // function definition declared at class scope then we must set 1924 // DC to the lexical parent to be able to search into the parent 1925 // class. 1926 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1927 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1928 DC->getLexicalParent()->isRecord()) 1929 DC = DC->getLexicalParent(); 1930 else 1931 DC = DC->getParent(); 1932 } 1933 1934 // We didn't find anything, so try to correct for a typo. 1935 TypoCorrection Corrected; 1936 if (S && Out) { 1937 SourceLocation TypoLoc = R.getNameLoc(); 1938 assert(!ExplicitTemplateArgs && 1939 "Diagnosing an empty lookup with explicit template args!"); 1940 *Out = CorrectTypoDelayed( 1941 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC), 1942 [=](const TypoCorrection &TC) { 1943 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 1944 diagnostic, diagnostic_suggest); 1945 }, 1946 nullptr, CTK_ErrorRecovery); 1947 if (*Out) 1948 return true; 1949 } else if (S && (Corrected = 1950 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, 1951 &SS, std::move(CCC), CTK_ErrorRecovery))) { 1952 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1953 bool DroppedSpecifier = 1954 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1955 R.setLookupName(Corrected.getCorrection()); 1956 1957 bool AcceptableWithRecovery = false; 1958 bool AcceptableWithoutRecovery = false; 1959 NamedDecl *ND = Corrected.getFoundDecl(); 1960 if (ND) { 1961 if (Corrected.isOverloaded()) { 1962 OverloadCandidateSet OCS(R.getNameLoc(), 1963 OverloadCandidateSet::CSK_Normal); 1964 OverloadCandidateSet::iterator Best; 1965 for (NamedDecl *CD : Corrected) { 1966 if (FunctionTemplateDecl *FTD = 1967 dyn_cast<FunctionTemplateDecl>(CD)) 1968 AddTemplateOverloadCandidate( 1969 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1970 Args, OCS); 1971 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 1972 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1973 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1974 Args, OCS); 1975 } 1976 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1977 case OR_Success: 1978 ND = Best->FoundDecl; 1979 Corrected.setCorrectionDecl(ND); 1980 break; 1981 default: 1982 // FIXME: Arbitrarily pick the first declaration for the note. 1983 Corrected.setCorrectionDecl(ND); 1984 break; 1985 } 1986 } 1987 R.addDecl(ND); 1988 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 1989 CXXRecordDecl *Record = nullptr; 1990 if (Corrected.getCorrectionSpecifier()) { 1991 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 1992 Record = Ty->getAsCXXRecordDecl(); 1993 } 1994 if (!Record) 1995 Record = cast<CXXRecordDecl>( 1996 ND->getDeclContext()->getRedeclContext()); 1997 R.setNamingClass(Record); 1998 } 1999 2000 auto *UnderlyingND = ND->getUnderlyingDecl(); 2001 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2002 isa<FunctionTemplateDecl>(UnderlyingND); 2003 // FIXME: If we ended up with a typo for a type name or 2004 // Objective-C class name, we're in trouble because the parser 2005 // is in the wrong place to recover. Suggest the typo 2006 // correction, but don't make it a fix-it since we're not going 2007 // to recover well anyway. 2008 AcceptableWithoutRecovery = 2009 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND); 2010 } else { 2011 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2012 // because we aren't able to recover. 2013 AcceptableWithoutRecovery = true; 2014 } 2015 2016 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2017 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2018 ? diag::note_implicit_param_decl 2019 : diag::note_previous_decl; 2020 if (SS.isEmpty()) 2021 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2022 PDiag(NoteID), AcceptableWithRecovery); 2023 else 2024 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2025 << Name << computeDeclContext(SS, false) 2026 << DroppedSpecifier << SS.getRange(), 2027 PDiag(NoteID), AcceptableWithRecovery); 2028 2029 // Tell the callee whether to try to recover. 2030 return !AcceptableWithRecovery; 2031 } 2032 } 2033 R.clear(); 2034 2035 // Emit a special diagnostic for failed member lookups. 2036 // FIXME: computing the declaration context might fail here (?) 2037 if (!SS.isEmpty()) { 2038 Diag(R.getNameLoc(), diag::err_no_member) 2039 << Name << computeDeclContext(SS, false) 2040 << SS.getRange(); 2041 return true; 2042 } 2043 2044 // Give up, we can't recover. 2045 Diag(R.getNameLoc(), diagnostic) << Name; 2046 return true; 2047 } 2048 2049 /// In Microsoft mode, if we are inside a template class whose parent class has 2050 /// dependent base classes, and we can't resolve an unqualified identifier, then 2051 /// assume the identifier is a member of a dependent base class. We can only 2052 /// recover successfully in static methods, instance methods, and other contexts 2053 /// where 'this' is available. This doesn't precisely match MSVC's 2054 /// instantiation model, but it's close enough. 2055 static Expr * 2056 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2057 DeclarationNameInfo &NameInfo, 2058 SourceLocation TemplateKWLoc, 2059 const TemplateArgumentListInfo *TemplateArgs) { 2060 // Only try to recover from lookup into dependent bases in static methods or 2061 // contexts where 'this' is available. 2062 QualType ThisType = S.getCurrentThisType(); 2063 const CXXRecordDecl *RD = nullptr; 2064 if (!ThisType.isNull()) 2065 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2066 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2067 RD = MD->getParent(); 2068 if (!RD || !RD->hasAnyDependentBases()) 2069 return nullptr; 2070 2071 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2072 // is available, suggest inserting 'this->' as a fixit. 2073 SourceLocation Loc = NameInfo.getLoc(); 2074 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2075 DB << NameInfo.getName() << RD; 2076 2077 if (!ThisType.isNull()) { 2078 DB << FixItHint::CreateInsertion(Loc, "this->"); 2079 return CXXDependentScopeMemberExpr::Create( 2080 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2081 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2082 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 2083 } 2084 2085 // Synthesize a fake NNS that points to the derived class. This will 2086 // perform name lookup during template instantiation. 2087 CXXScopeSpec SS; 2088 auto *NNS = 2089 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2090 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2091 return DependentScopeDeclRefExpr::Create( 2092 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2093 TemplateArgs); 2094 } 2095 2096 ExprResult 2097 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2098 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2099 bool HasTrailingLParen, bool IsAddressOfOperand, 2100 std::unique_ptr<CorrectionCandidateCallback> CCC, 2101 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2102 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2103 "cannot be direct & operand and have a trailing lparen"); 2104 if (SS.isInvalid()) 2105 return ExprError(); 2106 2107 TemplateArgumentListInfo TemplateArgsBuffer; 2108 2109 // Decompose the UnqualifiedId into the following data. 2110 DeclarationNameInfo NameInfo; 2111 const TemplateArgumentListInfo *TemplateArgs; 2112 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2113 2114 DeclarationName Name = NameInfo.getName(); 2115 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2116 SourceLocation NameLoc = NameInfo.getLoc(); 2117 2118 // C++ [temp.dep.expr]p3: 2119 // An id-expression is type-dependent if it contains: 2120 // -- an identifier that was declared with a dependent type, 2121 // (note: handled after lookup) 2122 // -- a template-id that is dependent, 2123 // (note: handled in BuildTemplateIdExpr) 2124 // -- a conversion-function-id that specifies a dependent type, 2125 // -- a nested-name-specifier that contains a class-name that 2126 // names a dependent type. 2127 // Determine whether this is a member of an unknown specialization; 2128 // we need to handle these differently. 2129 bool DependentID = false; 2130 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2131 Name.getCXXNameType()->isDependentType()) { 2132 DependentID = true; 2133 } else if (SS.isSet()) { 2134 if (DeclContext *DC = computeDeclContext(SS, false)) { 2135 if (RequireCompleteDeclContext(SS, DC)) 2136 return ExprError(); 2137 } else { 2138 DependentID = true; 2139 } 2140 } 2141 2142 if (DependentID) 2143 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2144 IsAddressOfOperand, TemplateArgs); 2145 2146 // Perform the required lookup. 2147 LookupResult R(*this, NameInfo, 2148 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 2149 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 2150 if (TemplateArgs) { 2151 // Lookup the template name again to correctly establish the context in 2152 // which it was found. This is really unfortunate as we already did the 2153 // lookup to determine that it was a template name in the first place. If 2154 // this becomes a performance hit, we can work harder to preserve those 2155 // results until we get here but it's likely not worth it. 2156 bool MemberOfUnknownSpecialization; 2157 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2158 MemberOfUnknownSpecialization); 2159 2160 if (MemberOfUnknownSpecialization || 2161 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2162 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2163 IsAddressOfOperand, TemplateArgs); 2164 } else { 2165 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2166 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2167 2168 // If the result might be in a dependent base class, this is a dependent 2169 // id-expression. 2170 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2171 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2172 IsAddressOfOperand, TemplateArgs); 2173 2174 // If this reference is in an Objective-C method, then we need to do 2175 // some special Objective-C lookup, too. 2176 if (IvarLookupFollowUp) { 2177 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2178 if (E.isInvalid()) 2179 return ExprError(); 2180 2181 if (Expr *Ex = E.getAs<Expr>()) 2182 return Ex; 2183 } 2184 } 2185 2186 if (R.isAmbiguous()) 2187 return ExprError(); 2188 2189 // This could be an implicitly declared function reference (legal in C90, 2190 // extension in C99, forbidden in C++). 2191 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2192 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2193 if (D) R.addDecl(D); 2194 } 2195 2196 // Determine whether this name might be a candidate for 2197 // argument-dependent lookup. 2198 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2199 2200 if (R.empty() && !ADL) { 2201 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2202 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2203 TemplateKWLoc, TemplateArgs)) 2204 return E; 2205 } 2206 2207 // Don't diagnose an empty lookup for inline assembly. 2208 if (IsInlineAsmIdentifier) 2209 return ExprError(); 2210 2211 // If this name wasn't predeclared and if this is not a function 2212 // call, diagnose the problem. 2213 TypoExpr *TE = nullptr; 2214 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2215 II, SS.isValid() ? SS.getScopeRep() : nullptr); 2216 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; 2217 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2218 "Typo correction callback misconfigured"); 2219 if (CCC) { 2220 // Make sure the callback knows what the typo being diagnosed is. 2221 CCC->setTypoName(II); 2222 if (SS.isValid()) 2223 CCC->setTypoNNS(SS.getScopeRep()); 2224 } 2225 if (DiagnoseEmptyLookup(S, SS, R, 2226 CCC ? std::move(CCC) : std::move(DefaultValidator), 2227 nullptr, None, &TE)) { 2228 if (TE && KeywordReplacement) { 2229 auto &State = getTypoExprState(TE); 2230 auto BestTC = State.Consumer->getNextCorrection(); 2231 if (BestTC.isKeyword()) { 2232 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2233 if (State.DiagHandler) 2234 State.DiagHandler(BestTC); 2235 KeywordReplacement->startToken(); 2236 KeywordReplacement->setKind(II->getTokenID()); 2237 KeywordReplacement->setIdentifierInfo(II); 2238 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2239 // Clean up the state associated with the TypoExpr, since it has 2240 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2241 clearDelayedTypo(TE); 2242 // Signal that a correction to a keyword was performed by returning a 2243 // valid-but-null ExprResult. 2244 return (Expr*)nullptr; 2245 } 2246 State.Consumer->resetCorrectionStream(); 2247 } 2248 return TE ? TE : ExprError(); 2249 } 2250 2251 assert(!R.empty() && 2252 "DiagnoseEmptyLookup returned false but added no results"); 2253 2254 // If we found an Objective-C instance variable, let 2255 // LookupInObjCMethod build the appropriate expression to 2256 // reference the ivar. 2257 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2258 R.clear(); 2259 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2260 // In a hopelessly buggy code, Objective-C instance variable 2261 // lookup fails and no expression will be built to reference it. 2262 if (!E.isInvalid() && !E.get()) 2263 return ExprError(); 2264 return E; 2265 } 2266 } 2267 2268 // This is guaranteed from this point on. 2269 assert(!R.empty() || ADL); 2270 2271 // Check whether this might be a C++ implicit instance member access. 2272 // C++ [class.mfct.non-static]p3: 2273 // When an id-expression that is not part of a class member access 2274 // syntax and not used to form a pointer to member is used in the 2275 // body of a non-static member function of class X, if name lookup 2276 // resolves the name in the id-expression to a non-static non-type 2277 // member of some class C, the id-expression is transformed into a 2278 // class member access expression using (*this) as the 2279 // postfix-expression to the left of the . operator. 2280 // 2281 // But we don't actually need to do this for '&' operands if R 2282 // resolved to a function or overloaded function set, because the 2283 // expression is ill-formed if it actually works out to be a 2284 // non-static member function: 2285 // 2286 // C++ [expr.ref]p4: 2287 // Otherwise, if E1.E2 refers to a non-static member function. . . 2288 // [t]he expression can be used only as the left-hand operand of a 2289 // member function call. 2290 // 2291 // There are other safeguards against such uses, but it's important 2292 // to get this right here so that we don't end up making a 2293 // spuriously dependent expression if we're inside a dependent 2294 // instance method. 2295 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2296 bool MightBeImplicitMember; 2297 if (!IsAddressOfOperand) 2298 MightBeImplicitMember = true; 2299 else if (!SS.isEmpty()) 2300 MightBeImplicitMember = false; 2301 else if (R.isOverloadedResult()) 2302 MightBeImplicitMember = false; 2303 else if (R.isUnresolvableResult()) 2304 MightBeImplicitMember = true; 2305 else 2306 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2307 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2308 isa<MSPropertyDecl>(R.getFoundDecl()); 2309 2310 if (MightBeImplicitMember) 2311 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2312 R, TemplateArgs, S); 2313 } 2314 2315 if (TemplateArgs || TemplateKWLoc.isValid()) { 2316 2317 // In C++1y, if this is a variable template id, then check it 2318 // in BuildTemplateIdExpr(). 2319 // The single lookup result must be a variable template declaration. 2320 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId && 2321 Id.TemplateId->Kind == TNK_Var_template) { 2322 assert(R.getAsSingle<VarTemplateDecl>() && 2323 "There should only be one declaration found."); 2324 } 2325 2326 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2327 } 2328 2329 return BuildDeclarationNameExpr(SS, R, ADL); 2330 } 2331 2332 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2333 /// declaration name, generally during template instantiation. 2334 /// There's a large number of things which don't need to be done along 2335 /// this path. 2336 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2337 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2338 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2339 DeclContext *DC = computeDeclContext(SS, false); 2340 if (!DC) 2341 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2342 NameInfo, /*TemplateArgs=*/nullptr); 2343 2344 if (RequireCompleteDeclContext(SS, DC)) 2345 return ExprError(); 2346 2347 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2348 LookupQualifiedName(R, DC); 2349 2350 if (R.isAmbiguous()) 2351 return ExprError(); 2352 2353 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2354 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2355 NameInfo, /*TemplateArgs=*/nullptr); 2356 2357 if (R.empty()) { 2358 Diag(NameInfo.getLoc(), diag::err_no_member) 2359 << NameInfo.getName() << DC << SS.getRange(); 2360 return ExprError(); 2361 } 2362 2363 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2364 // Diagnose a missing typename if this resolved unambiguously to a type in 2365 // a dependent context. If we can recover with a type, downgrade this to 2366 // a warning in Microsoft compatibility mode. 2367 unsigned DiagID = diag::err_typename_missing; 2368 if (RecoveryTSI && getLangOpts().MSVCCompat) 2369 DiagID = diag::ext_typename_missing; 2370 SourceLocation Loc = SS.getBeginLoc(); 2371 auto D = Diag(Loc, DiagID); 2372 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2373 << SourceRange(Loc, NameInfo.getEndLoc()); 2374 2375 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2376 // context. 2377 if (!RecoveryTSI) 2378 return ExprError(); 2379 2380 // Only issue the fixit if we're prepared to recover. 2381 D << FixItHint::CreateInsertion(Loc, "typename "); 2382 2383 // Recover by pretending this was an elaborated type. 2384 QualType Ty = Context.getTypeDeclType(TD); 2385 TypeLocBuilder TLB; 2386 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2387 2388 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2389 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2390 QTL.setElaboratedKeywordLoc(SourceLocation()); 2391 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2392 2393 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2394 2395 return ExprEmpty(); 2396 } 2397 2398 // Defend against this resolving to an implicit member access. We usually 2399 // won't get here if this might be a legitimate a class member (we end up in 2400 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2401 // a pointer-to-member or in an unevaluated context in C++11. 2402 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2403 return BuildPossibleImplicitMemberExpr(SS, 2404 /*TemplateKWLoc=*/SourceLocation(), 2405 R, /*TemplateArgs=*/nullptr, S); 2406 2407 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2408 } 2409 2410 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2411 /// detected that we're currently inside an ObjC method. Perform some 2412 /// additional lookup. 2413 /// 2414 /// Ideally, most of this would be done by lookup, but there's 2415 /// actually quite a lot of extra work involved. 2416 /// 2417 /// Returns a null sentinel to indicate trivial success. 2418 ExprResult 2419 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2420 IdentifierInfo *II, bool AllowBuiltinCreation) { 2421 SourceLocation Loc = Lookup.getNameLoc(); 2422 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2423 2424 // Check for error condition which is already reported. 2425 if (!CurMethod) 2426 return ExprError(); 2427 2428 // There are two cases to handle here. 1) scoped lookup could have failed, 2429 // in which case we should look for an ivar. 2) scoped lookup could have 2430 // found a decl, but that decl is outside the current instance method (i.e. 2431 // a global variable). In these two cases, we do a lookup for an ivar with 2432 // this name, if the lookup sucedes, we replace it our current decl. 2433 2434 // If we're in a class method, we don't normally want to look for 2435 // ivars. But if we don't find anything else, and there's an 2436 // ivar, that's an error. 2437 bool IsClassMethod = CurMethod->isClassMethod(); 2438 2439 bool LookForIvars; 2440 if (Lookup.empty()) 2441 LookForIvars = true; 2442 else if (IsClassMethod) 2443 LookForIvars = false; 2444 else 2445 LookForIvars = (Lookup.isSingleResult() && 2446 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2447 ObjCInterfaceDecl *IFace = nullptr; 2448 if (LookForIvars) { 2449 IFace = CurMethod->getClassInterface(); 2450 ObjCInterfaceDecl *ClassDeclared; 2451 ObjCIvarDecl *IV = nullptr; 2452 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2453 // Diagnose using an ivar in a class method. 2454 if (IsClassMethod) 2455 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2456 << IV->getDeclName()); 2457 2458 // If we're referencing an invalid decl, just return this as a silent 2459 // error node. The error diagnostic was already emitted on the decl. 2460 if (IV->isInvalidDecl()) 2461 return ExprError(); 2462 2463 // Check if referencing a field with __attribute__((deprecated)). 2464 if (DiagnoseUseOfDecl(IV, Loc)) 2465 return ExprError(); 2466 2467 // Diagnose the use of an ivar outside of the declaring class. 2468 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2469 !declaresSameEntity(ClassDeclared, IFace) && 2470 !getLangOpts().DebuggerSupport) 2471 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 2472 2473 // FIXME: This should use a new expr for a direct reference, don't 2474 // turn this into Self->ivar, just return a BareIVarExpr or something. 2475 IdentifierInfo &II = Context.Idents.get("self"); 2476 UnqualifiedId SelfName; 2477 SelfName.setIdentifier(&II, SourceLocation()); 2478 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2479 CXXScopeSpec SelfScopeSpec; 2480 SourceLocation TemplateKWLoc; 2481 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2482 SelfName, false, false); 2483 if (SelfExpr.isInvalid()) 2484 return ExprError(); 2485 2486 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2487 if (SelfExpr.isInvalid()) 2488 return ExprError(); 2489 2490 MarkAnyDeclReferenced(Loc, IV, true); 2491 2492 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2493 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2494 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2495 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2496 2497 ObjCIvarRefExpr *Result = new (Context) 2498 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2499 IV->getLocation(), SelfExpr.get(), true, true); 2500 2501 if (getLangOpts().ObjCAutoRefCount) { 2502 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2503 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2504 recordUseOfEvaluatedWeak(Result); 2505 } 2506 if (CurContext->isClosure()) 2507 Diag(Loc, diag::warn_implicitly_retains_self) 2508 << FixItHint::CreateInsertion(Loc, "self->"); 2509 } 2510 2511 return Result; 2512 } 2513 } else if (CurMethod->isInstanceMethod()) { 2514 // We should warn if a local variable hides an ivar. 2515 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2516 ObjCInterfaceDecl *ClassDeclared; 2517 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2518 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2519 declaresSameEntity(IFace, ClassDeclared)) 2520 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2521 } 2522 } 2523 } else if (Lookup.isSingleResult() && 2524 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2525 // If accessing a stand-alone ivar in a class method, this is an error. 2526 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2527 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2528 << IV->getDeclName()); 2529 } 2530 2531 if (Lookup.empty() && II && AllowBuiltinCreation) { 2532 // FIXME. Consolidate this with similar code in LookupName. 2533 if (unsigned BuiltinID = II->getBuiltinID()) { 2534 if (!(getLangOpts().CPlusPlus && 2535 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2536 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2537 S, Lookup.isForRedeclaration(), 2538 Lookup.getNameLoc()); 2539 if (D) Lookup.addDecl(D); 2540 } 2541 } 2542 } 2543 // Sentinel value saying that we didn't do anything special. 2544 return ExprResult((Expr *)nullptr); 2545 } 2546 2547 /// \brief Cast a base object to a member's actual type. 2548 /// 2549 /// Logically this happens in three phases: 2550 /// 2551 /// * First we cast from the base type to the naming class. 2552 /// The naming class is the class into which we were looking 2553 /// when we found the member; it's the qualifier type if a 2554 /// qualifier was provided, and otherwise it's the base type. 2555 /// 2556 /// * Next we cast from the naming class to the declaring class. 2557 /// If the member we found was brought into a class's scope by 2558 /// a using declaration, this is that class; otherwise it's 2559 /// the class declaring the member. 2560 /// 2561 /// * Finally we cast from the declaring class to the "true" 2562 /// declaring class of the member. This conversion does not 2563 /// obey access control. 2564 ExprResult 2565 Sema::PerformObjectMemberConversion(Expr *From, 2566 NestedNameSpecifier *Qualifier, 2567 NamedDecl *FoundDecl, 2568 NamedDecl *Member) { 2569 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2570 if (!RD) 2571 return From; 2572 2573 QualType DestRecordType; 2574 QualType DestType; 2575 QualType FromRecordType; 2576 QualType FromType = From->getType(); 2577 bool PointerConversions = false; 2578 if (isa<FieldDecl>(Member)) { 2579 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2580 2581 if (FromType->getAs<PointerType>()) { 2582 DestType = Context.getPointerType(DestRecordType); 2583 FromRecordType = FromType->getPointeeType(); 2584 PointerConversions = true; 2585 } else { 2586 DestType = DestRecordType; 2587 FromRecordType = FromType; 2588 } 2589 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2590 if (Method->isStatic()) 2591 return From; 2592 2593 DestType = Method->getThisType(Context); 2594 DestRecordType = DestType->getPointeeType(); 2595 2596 if (FromType->getAs<PointerType>()) { 2597 FromRecordType = FromType->getPointeeType(); 2598 PointerConversions = true; 2599 } else { 2600 FromRecordType = FromType; 2601 DestType = DestRecordType; 2602 } 2603 } else { 2604 // No conversion necessary. 2605 return From; 2606 } 2607 2608 if (DestType->isDependentType() || FromType->isDependentType()) 2609 return From; 2610 2611 // If the unqualified types are the same, no conversion is necessary. 2612 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2613 return From; 2614 2615 SourceRange FromRange = From->getSourceRange(); 2616 SourceLocation FromLoc = FromRange.getBegin(); 2617 2618 ExprValueKind VK = From->getValueKind(); 2619 2620 // C++ [class.member.lookup]p8: 2621 // [...] Ambiguities can often be resolved by qualifying a name with its 2622 // class name. 2623 // 2624 // If the member was a qualified name and the qualified referred to a 2625 // specific base subobject type, we'll cast to that intermediate type 2626 // first and then to the object in which the member is declared. That allows 2627 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2628 // 2629 // class Base { public: int x; }; 2630 // class Derived1 : public Base { }; 2631 // class Derived2 : public Base { }; 2632 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2633 // 2634 // void VeryDerived::f() { 2635 // x = 17; // error: ambiguous base subobjects 2636 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2637 // } 2638 if (Qualifier && Qualifier->getAsType()) { 2639 QualType QType = QualType(Qualifier->getAsType(), 0); 2640 assert(QType->isRecordType() && "lookup done with non-record type"); 2641 2642 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2643 2644 // In C++98, the qualifier type doesn't actually have to be a base 2645 // type of the object type, in which case we just ignore it. 2646 // Otherwise build the appropriate casts. 2647 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2648 CXXCastPath BasePath; 2649 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2650 FromLoc, FromRange, &BasePath)) 2651 return ExprError(); 2652 2653 if (PointerConversions) 2654 QType = Context.getPointerType(QType); 2655 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2656 VK, &BasePath).get(); 2657 2658 FromType = QType; 2659 FromRecordType = QRecordType; 2660 2661 // If the qualifier type was the same as the destination type, 2662 // we're done. 2663 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2664 return From; 2665 } 2666 } 2667 2668 bool IgnoreAccess = false; 2669 2670 // If we actually found the member through a using declaration, cast 2671 // down to the using declaration's type. 2672 // 2673 // Pointer equality is fine here because only one declaration of a 2674 // class ever has member declarations. 2675 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2676 assert(isa<UsingShadowDecl>(FoundDecl)); 2677 QualType URecordType = Context.getTypeDeclType( 2678 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2679 2680 // We only need to do this if the naming-class to declaring-class 2681 // conversion is non-trivial. 2682 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2683 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2684 CXXCastPath BasePath; 2685 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2686 FromLoc, FromRange, &BasePath)) 2687 return ExprError(); 2688 2689 QualType UType = URecordType; 2690 if (PointerConversions) 2691 UType = Context.getPointerType(UType); 2692 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2693 VK, &BasePath).get(); 2694 FromType = UType; 2695 FromRecordType = URecordType; 2696 } 2697 2698 // We don't do access control for the conversion from the 2699 // declaring class to the true declaring class. 2700 IgnoreAccess = true; 2701 } 2702 2703 CXXCastPath BasePath; 2704 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2705 FromLoc, FromRange, &BasePath, 2706 IgnoreAccess)) 2707 return ExprError(); 2708 2709 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2710 VK, &BasePath); 2711 } 2712 2713 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2714 const LookupResult &R, 2715 bool HasTrailingLParen) { 2716 // Only when used directly as the postfix-expression of a call. 2717 if (!HasTrailingLParen) 2718 return false; 2719 2720 // Never if a scope specifier was provided. 2721 if (SS.isSet()) 2722 return false; 2723 2724 // Only in C++ or ObjC++. 2725 if (!getLangOpts().CPlusPlus) 2726 return false; 2727 2728 // Turn off ADL when we find certain kinds of declarations during 2729 // normal lookup: 2730 for (NamedDecl *D : R) { 2731 // C++0x [basic.lookup.argdep]p3: 2732 // -- a declaration of a class member 2733 // Since using decls preserve this property, we check this on the 2734 // original decl. 2735 if (D->isCXXClassMember()) 2736 return false; 2737 2738 // C++0x [basic.lookup.argdep]p3: 2739 // -- a block-scope function declaration that is not a 2740 // using-declaration 2741 // NOTE: we also trigger this for function templates (in fact, we 2742 // don't check the decl type at all, since all other decl types 2743 // turn off ADL anyway). 2744 if (isa<UsingShadowDecl>(D)) 2745 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2746 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2747 return false; 2748 2749 // C++0x [basic.lookup.argdep]p3: 2750 // -- a declaration that is neither a function or a function 2751 // template 2752 // And also for builtin functions. 2753 if (isa<FunctionDecl>(D)) { 2754 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2755 2756 // But also builtin functions. 2757 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2758 return false; 2759 } else if (!isa<FunctionTemplateDecl>(D)) 2760 return false; 2761 } 2762 2763 return true; 2764 } 2765 2766 2767 /// Diagnoses obvious problems with the use of the given declaration 2768 /// as an expression. This is only actually called for lookups that 2769 /// were not overloaded, and it doesn't promise that the declaration 2770 /// will in fact be used. 2771 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2772 if (isa<TypedefNameDecl>(D)) { 2773 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2774 return true; 2775 } 2776 2777 if (isa<ObjCInterfaceDecl>(D)) { 2778 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2779 return true; 2780 } 2781 2782 if (isa<NamespaceDecl>(D)) { 2783 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2784 return true; 2785 } 2786 2787 return false; 2788 } 2789 2790 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2791 LookupResult &R, bool NeedsADL, 2792 bool AcceptInvalidDecl) { 2793 // If this is a single, fully-resolved result and we don't need ADL, 2794 // just build an ordinary singleton decl ref. 2795 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2796 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2797 R.getRepresentativeDecl(), nullptr, 2798 AcceptInvalidDecl); 2799 2800 // We only need to check the declaration if there's exactly one 2801 // result, because in the overloaded case the results can only be 2802 // functions and function templates. 2803 if (R.isSingleResult() && 2804 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2805 return ExprError(); 2806 2807 // Otherwise, just build an unresolved lookup expression. Suppress 2808 // any lookup-related diagnostics; we'll hash these out later, when 2809 // we've picked a target. 2810 R.suppressDiagnostics(); 2811 2812 UnresolvedLookupExpr *ULE 2813 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2814 SS.getWithLocInContext(Context), 2815 R.getLookupNameInfo(), 2816 NeedsADL, R.isOverloadedResult(), 2817 R.begin(), R.end()); 2818 2819 return ULE; 2820 } 2821 2822 static void 2823 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 2824 ValueDecl *var, DeclContext *DC); 2825 2826 /// \brief Complete semantic analysis for a reference to the given declaration. 2827 ExprResult Sema::BuildDeclarationNameExpr( 2828 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2829 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2830 bool AcceptInvalidDecl) { 2831 assert(D && "Cannot refer to a NULL declaration"); 2832 assert(!isa<FunctionTemplateDecl>(D) && 2833 "Cannot refer unambiguously to a function template"); 2834 2835 SourceLocation Loc = NameInfo.getLoc(); 2836 if (CheckDeclInExpr(*this, Loc, D)) 2837 return ExprError(); 2838 2839 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2840 // Specifically diagnose references to class templates that are missing 2841 // a template argument list. 2842 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2843 << Template << SS.getRange(); 2844 Diag(Template->getLocation(), diag::note_template_decl_here); 2845 return ExprError(); 2846 } 2847 2848 // Make sure that we're referring to a value. 2849 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2850 if (!VD) { 2851 Diag(Loc, diag::err_ref_non_value) 2852 << D << SS.getRange(); 2853 Diag(D->getLocation(), diag::note_declared_at); 2854 return ExprError(); 2855 } 2856 2857 // Check whether this declaration can be used. Note that we suppress 2858 // this check when we're going to perform argument-dependent lookup 2859 // on this function name, because this might not be the function 2860 // that overload resolution actually selects. 2861 if (DiagnoseUseOfDecl(VD, Loc)) 2862 return ExprError(); 2863 2864 // Only create DeclRefExpr's for valid Decl's. 2865 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2866 return ExprError(); 2867 2868 // Handle members of anonymous structs and unions. If we got here, 2869 // and the reference is to a class member indirect field, then this 2870 // must be the subject of a pointer-to-member expression. 2871 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2872 if (!indirectField->isCXXClassMember()) 2873 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2874 indirectField); 2875 2876 { 2877 QualType type = VD->getType(); 2878 if (auto *FPT = type->getAs<FunctionProtoType>()) { 2879 // C++ [except.spec]p17: 2880 // An exception-specification is considered to be needed when: 2881 // - in an expression, the function is the unique lookup result or 2882 // the selected member of a set of overloaded functions. 2883 ResolveExceptionSpec(Loc, FPT); 2884 type = VD->getType(); 2885 } 2886 ExprValueKind valueKind = VK_RValue; 2887 2888 switch (D->getKind()) { 2889 // Ignore all the non-ValueDecl kinds. 2890 #define ABSTRACT_DECL(kind) 2891 #define VALUE(type, base) 2892 #define DECL(type, base) \ 2893 case Decl::type: 2894 #include "clang/AST/DeclNodes.inc" 2895 llvm_unreachable("invalid value decl kind"); 2896 2897 // These shouldn't make it here. 2898 case Decl::ObjCAtDefsField: 2899 case Decl::ObjCIvar: 2900 llvm_unreachable("forming non-member reference to ivar?"); 2901 2902 // Enum constants are always r-values and never references. 2903 // Unresolved using declarations are dependent. 2904 case Decl::EnumConstant: 2905 case Decl::UnresolvedUsingValue: 2906 case Decl::OMPDeclareReduction: 2907 valueKind = VK_RValue; 2908 break; 2909 2910 // Fields and indirect fields that got here must be for 2911 // pointer-to-member expressions; we just call them l-values for 2912 // internal consistency, because this subexpression doesn't really 2913 // exist in the high-level semantics. 2914 case Decl::Field: 2915 case Decl::IndirectField: 2916 assert(getLangOpts().CPlusPlus && 2917 "building reference to field in C?"); 2918 2919 // These can't have reference type in well-formed programs, but 2920 // for internal consistency we do this anyway. 2921 type = type.getNonReferenceType(); 2922 valueKind = VK_LValue; 2923 break; 2924 2925 // Non-type template parameters are either l-values or r-values 2926 // depending on the type. 2927 case Decl::NonTypeTemplateParm: { 2928 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2929 type = reftype->getPointeeType(); 2930 valueKind = VK_LValue; // even if the parameter is an r-value reference 2931 break; 2932 } 2933 2934 // For non-references, we need to strip qualifiers just in case 2935 // the template parameter was declared as 'const int' or whatever. 2936 valueKind = VK_RValue; 2937 type = type.getUnqualifiedType(); 2938 break; 2939 } 2940 2941 case Decl::Var: 2942 case Decl::VarTemplateSpecialization: 2943 case Decl::VarTemplatePartialSpecialization: 2944 case Decl::Decomposition: 2945 case Decl::OMPCapturedExpr: 2946 // In C, "extern void blah;" is valid and is an r-value. 2947 if (!getLangOpts().CPlusPlus && 2948 !type.hasQualifiers() && 2949 type->isVoidType()) { 2950 valueKind = VK_RValue; 2951 break; 2952 } 2953 // fallthrough 2954 2955 case Decl::ImplicitParam: 2956 case Decl::ParmVar: { 2957 // These are always l-values. 2958 valueKind = VK_LValue; 2959 type = type.getNonReferenceType(); 2960 2961 // FIXME: Does the addition of const really only apply in 2962 // potentially-evaluated contexts? Since the variable isn't actually 2963 // captured in an unevaluated context, it seems that the answer is no. 2964 if (!isUnevaluatedContext()) { 2965 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2966 if (!CapturedType.isNull()) 2967 type = CapturedType; 2968 } 2969 2970 break; 2971 } 2972 2973 case Decl::Binding: { 2974 // These are always lvalues. 2975 valueKind = VK_LValue; 2976 type = type.getNonReferenceType(); 2977 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 2978 // decides how that's supposed to work. 2979 auto *BD = cast<BindingDecl>(VD); 2980 if (BD->getDeclContext()->isFunctionOrMethod() && 2981 BD->getDeclContext() != CurContext) 2982 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 2983 break; 2984 } 2985 2986 case Decl::Function: { 2987 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2988 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2989 type = Context.BuiltinFnTy; 2990 valueKind = VK_RValue; 2991 break; 2992 } 2993 } 2994 2995 const FunctionType *fty = type->castAs<FunctionType>(); 2996 2997 // If we're referring to a function with an __unknown_anytype 2998 // result type, make the entire expression __unknown_anytype. 2999 if (fty->getReturnType() == Context.UnknownAnyTy) { 3000 type = Context.UnknownAnyTy; 3001 valueKind = VK_RValue; 3002 break; 3003 } 3004 3005 // Functions are l-values in C++. 3006 if (getLangOpts().CPlusPlus) { 3007 valueKind = VK_LValue; 3008 break; 3009 } 3010 3011 // C99 DR 316 says that, if a function type comes from a 3012 // function definition (without a prototype), that type is only 3013 // used for checking compatibility. Therefore, when referencing 3014 // the function, we pretend that we don't have the full function 3015 // type. 3016 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3017 isa<FunctionProtoType>(fty)) 3018 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3019 fty->getExtInfo()); 3020 3021 // Functions are r-values in C. 3022 valueKind = VK_RValue; 3023 break; 3024 } 3025 3026 case Decl::MSProperty: 3027 valueKind = VK_LValue; 3028 break; 3029 3030 case Decl::CXXMethod: 3031 // If we're referring to a method with an __unknown_anytype 3032 // result type, make the entire expression __unknown_anytype. 3033 // This should only be possible with a type written directly. 3034 if (const FunctionProtoType *proto 3035 = dyn_cast<FunctionProtoType>(VD->getType())) 3036 if (proto->getReturnType() == Context.UnknownAnyTy) { 3037 type = Context.UnknownAnyTy; 3038 valueKind = VK_RValue; 3039 break; 3040 } 3041 3042 // C++ methods are l-values if static, r-values if non-static. 3043 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3044 valueKind = VK_LValue; 3045 break; 3046 } 3047 // fallthrough 3048 3049 case Decl::CXXConversion: 3050 case Decl::CXXDestructor: 3051 case Decl::CXXConstructor: 3052 valueKind = VK_RValue; 3053 break; 3054 } 3055 3056 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3057 TemplateArgs); 3058 } 3059 } 3060 3061 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3062 SmallString<32> &Target) { 3063 Target.resize(CharByteWidth * (Source.size() + 1)); 3064 char *ResultPtr = &Target[0]; 3065 const llvm::UTF8 *ErrorPtr; 3066 bool success = 3067 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3068 (void)success; 3069 assert(success); 3070 Target.resize(ResultPtr - &Target[0]); 3071 } 3072 3073 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3074 PredefinedExpr::IdentType IT) { 3075 // Pick the current block, lambda, captured statement or function. 3076 Decl *currentDecl = nullptr; 3077 if (const BlockScopeInfo *BSI = getCurBlock()) 3078 currentDecl = BSI->TheDecl; 3079 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3080 currentDecl = LSI->CallOperator; 3081 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3082 currentDecl = CSI->TheCapturedDecl; 3083 else 3084 currentDecl = getCurFunctionOrMethodDecl(); 3085 3086 if (!currentDecl) { 3087 Diag(Loc, diag::ext_predef_outside_function); 3088 currentDecl = Context.getTranslationUnitDecl(); 3089 } 3090 3091 QualType ResTy; 3092 StringLiteral *SL = nullptr; 3093 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3094 ResTy = Context.DependentTy; 3095 else { 3096 // Pre-defined identifiers are of type char[x], where x is the length of 3097 // the string. 3098 auto Str = PredefinedExpr::ComputeName(IT, currentDecl); 3099 unsigned Length = Str.length(); 3100 3101 llvm::APInt LengthI(32, Length + 1); 3102 if (IT == PredefinedExpr::LFunction) { 3103 ResTy = Context.WideCharTy.withConst(); 3104 SmallString<32> RawChars; 3105 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3106 Str, RawChars); 3107 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3108 /*IndexTypeQuals*/ 0); 3109 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3110 /*Pascal*/ false, ResTy, Loc); 3111 } else { 3112 ResTy = Context.CharTy.withConst(); 3113 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3114 /*IndexTypeQuals*/ 0); 3115 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3116 /*Pascal*/ false, ResTy, Loc); 3117 } 3118 } 3119 3120 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL); 3121 } 3122 3123 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3124 PredefinedExpr::IdentType IT; 3125 3126 switch (Kind) { 3127 default: llvm_unreachable("Unknown simple primary expr!"); 3128 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3129 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 3130 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 3131 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS] 3132 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 3133 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 3134 } 3135 3136 return BuildPredefinedExpr(Loc, IT); 3137 } 3138 3139 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3140 SmallString<16> CharBuffer; 3141 bool Invalid = false; 3142 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3143 if (Invalid) 3144 return ExprError(); 3145 3146 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3147 PP, Tok.getKind()); 3148 if (Literal.hadError()) 3149 return ExprError(); 3150 3151 QualType Ty; 3152 if (Literal.isWide()) 3153 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3154 else if (Literal.isUTF16()) 3155 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3156 else if (Literal.isUTF32()) 3157 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3158 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3159 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3160 else 3161 Ty = Context.CharTy; // 'x' -> char in C++ 3162 3163 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3164 if (Literal.isWide()) 3165 Kind = CharacterLiteral::Wide; 3166 else if (Literal.isUTF16()) 3167 Kind = CharacterLiteral::UTF16; 3168 else if (Literal.isUTF32()) 3169 Kind = CharacterLiteral::UTF32; 3170 else if (Literal.isUTF8()) 3171 Kind = CharacterLiteral::UTF8; 3172 3173 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3174 Tok.getLocation()); 3175 3176 if (Literal.getUDSuffix().empty()) 3177 return Lit; 3178 3179 // We're building a user-defined literal. 3180 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3181 SourceLocation UDSuffixLoc = 3182 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3183 3184 // Make sure we're allowed user-defined literals here. 3185 if (!UDLScope) 3186 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3187 3188 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3189 // operator "" X (ch) 3190 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3191 Lit, Tok.getLocation()); 3192 } 3193 3194 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3195 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3196 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3197 Context.IntTy, Loc); 3198 } 3199 3200 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3201 QualType Ty, SourceLocation Loc) { 3202 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3203 3204 using llvm::APFloat; 3205 APFloat Val(Format); 3206 3207 APFloat::opStatus result = Literal.GetFloatValue(Val); 3208 3209 // Overflow is always an error, but underflow is only an error if 3210 // we underflowed to zero (APFloat reports denormals as underflow). 3211 if ((result & APFloat::opOverflow) || 3212 ((result & APFloat::opUnderflow) && Val.isZero())) { 3213 unsigned diagnostic; 3214 SmallString<20> buffer; 3215 if (result & APFloat::opOverflow) { 3216 diagnostic = diag::warn_float_overflow; 3217 APFloat::getLargest(Format).toString(buffer); 3218 } else { 3219 diagnostic = diag::warn_float_underflow; 3220 APFloat::getSmallest(Format).toString(buffer); 3221 } 3222 3223 S.Diag(Loc, diagnostic) 3224 << Ty 3225 << StringRef(buffer.data(), buffer.size()); 3226 } 3227 3228 bool isExact = (result == APFloat::opOK); 3229 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3230 } 3231 3232 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3233 assert(E && "Invalid expression"); 3234 3235 if (E->isValueDependent()) 3236 return false; 3237 3238 QualType QT = E->getType(); 3239 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3240 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3241 return true; 3242 } 3243 3244 llvm::APSInt ValueAPS; 3245 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3246 3247 if (R.isInvalid()) 3248 return true; 3249 3250 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3251 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3252 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3253 << ValueAPS.toString(10) << ValueIsPositive; 3254 return true; 3255 } 3256 3257 return false; 3258 } 3259 3260 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3261 // Fast path for a single digit (which is quite common). A single digit 3262 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3263 if (Tok.getLength() == 1) { 3264 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3265 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3266 } 3267 3268 SmallString<128> SpellingBuffer; 3269 // NumericLiteralParser wants to overread by one character. Add padding to 3270 // the buffer in case the token is copied to the buffer. If getSpelling() 3271 // returns a StringRef to the memory buffer, it should have a null char at 3272 // the EOF, so it is also safe. 3273 SpellingBuffer.resize(Tok.getLength() + 1); 3274 3275 // Get the spelling of the token, which eliminates trigraphs, etc. 3276 bool Invalid = false; 3277 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3278 if (Invalid) 3279 return ExprError(); 3280 3281 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3282 if (Literal.hadError) 3283 return ExprError(); 3284 3285 if (Literal.hasUDSuffix()) { 3286 // We're building a user-defined literal. 3287 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3288 SourceLocation UDSuffixLoc = 3289 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3290 3291 // Make sure we're allowed user-defined literals here. 3292 if (!UDLScope) 3293 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3294 3295 QualType CookedTy; 3296 if (Literal.isFloatingLiteral()) { 3297 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3298 // long double, the literal is treated as a call of the form 3299 // operator "" X (f L) 3300 CookedTy = Context.LongDoubleTy; 3301 } else { 3302 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3303 // unsigned long long, the literal is treated as a call of the form 3304 // operator "" X (n ULL) 3305 CookedTy = Context.UnsignedLongLongTy; 3306 } 3307 3308 DeclarationName OpName = 3309 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3310 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3311 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3312 3313 SourceLocation TokLoc = Tok.getLocation(); 3314 3315 // Perform literal operator lookup to determine if we're building a raw 3316 // literal or a cooked one. 3317 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3318 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3319 /*AllowRaw*/true, /*AllowTemplate*/true, 3320 /*AllowStringTemplate*/false)) { 3321 case LOLR_Error: 3322 return ExprError(); 3323 3324 case LOLR_Cooked: { 3325 Expr *Lit; 3326 if (Literal.isFloatingLiteral()) { 3327 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3328 } else { 3329 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3330 if (Literal.GetIntegerValue(ResultVal)) 3331 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3332 << /* Unsigned */ 1; 3333 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3334 Tok.getLocation()); 3335 } 3336 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3337 } 3338 3339 case LOLR_Raw: { 3340 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3341 // literal is treated as a call of the form 3342 // operator "" X ("n") 3343 unsigned Length = Literal.getUDSuffixOffset(); 3344 QualType StrTy = Context.getConstantArrayType( 3345 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 3346 ArrayType::Normal, 0); 3347 Expr *Lit = StringLiteral::Create( 3348 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3349 /*Pascal*/false, StrTy, &TokLoc, 1); 3350 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3351 } 3352 3353 case LOLR_Template: { 3354 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3355 // template), L is treated as a call fo the form 3356 // operator "" X <'c1', 'c2', ... 'ck'>() 3357 // where n is the source character sequence c1 c2 ... ck. 3358 TemplateArgumentListInfo ExplicitArgs; 3359 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3360 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3361 llvm::APSInt Value(CharBits, CharIsUnsigned); 3362 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3363 Value = TokSpelling[I]; 3364 TemplateArgument Arg(Context, Value, Context.CharTy); 3365 TemplateArgumentLocInfo ArgInfo; 3366 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3367 } 3368 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3369 &ExplicitArgs); 3370 } 3371 case LOLR_StringTemplate: 3372 llvm_unreachable("unexpected literal operator lookup result"); 3373 } 3374 } 3375 3376 Expr *Res; 3377 3378 if (Literal.isFloatingLiteral()) { 3379 QualType Ty; 3380 if (Literal.isHalf){ 3381 if (getOpenCLOptions().cl_khr_fp16) 3382 Ty = Context.HalfTy; 3383 else { 3384 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3385 return ExprError(); 3386 } 3387 } else if (Literal.isFloat) 3388 Ty = Context.FloatTy; 3389 else if (Literal.isLong) 3390 Ty = Context.LongDoubleTy; 3391 else if (Literal.isFloat128) 3392 Ty = Context.Float128Ty; 3393 else 3394 Ty = Context.DoubleTy; 3395 3396 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3397 3398 if (Ty == Context.DoubleTy) { 3399 if (getLangOpts().SinglePrecisionConstants) { 3400 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3401 } else if (getLangOpts().OpenCL && 3402 !((getLangOpts().OpenCLVersion >= 120) || 3403 getOpenCLOptions().cl_khr_fp64)) { 3404 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3405 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3406 } 3407 } 3408 } else if (!Literal.isIntegerLiteral()) { 3409 return ExprError(); 3410 } else { 3411 QualType Ty; 3412 3413 // 'long long' is a C99 or C++11 feature. 3414 if (!getLangOpts().C99 && Literal.isLongLong) { 3415 if (getLangOpts().CPlusPlus) 3416 Diag(Tok.getLocation(), 3417 getLangOpts().CPlusPlus11 ? 3418 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3419 else 3420 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3421 } 3422 3423 // Get the value in the widest-possible width. 3424 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3425 llvm::APInt ResultVal(MaxWidth, 0); 3426 3427 if (Literal.GetIntegerValue(ResultVal)) { 3428 // If this value didn't fit into uintmax_t, error and force to ull. 3429 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3430 << /* Unsigned */ 1; 3431 Ty = Context.UnsignedLongLongTy; 3432 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3433 "long long is not intmax_t?"); 3434 } else { 3435 // If this value fits into a ULL, try to figure out what else it fits into 3436 // according to the rules of C99 6.4.4.1p5. 3437 3438 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3439 // be an unsigned int. 3440 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3441 3442 // Check from smallest to largest, picking the smallest type we can. 3443 unsigned Width = 0; 3444 3445 // Microsoft specific integer suffixes are explicitly sized. 3446 if (Literal.MicrosoftInteger) { 3447 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3448 Width = 8; 3449 Ty = Context.CharTy; 3450 } else { 3451 Width = Literal.MicrosoftInteger; 3452 Ty = Context.getIntTypeForBitwidth(Width, 3453 /*Signed=*/!Literal.isUnsigned); 3454 } 3455 } 3456 3457 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3458 // Are int/unsigned possibilities? 3459 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3460 3461 // Does it fit in a unsigned int? 3462 if (ResultVal.isIntN(IntSize)) { 3463 // Does it fit in a signed int? 3464 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3465 Ty = Context.IntTy; 3466 else if (AllowUnsigned) 3467 Ty = Context.UnsignedIntTy; 3468 Width = IntSize; 3469 } 3470 } 3471 3472 // Are long/unsigned long possibilities? 3473 if (Ty.isNull() && !Literal.isLongLong) { 3474 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3475 3476 // Does it fit in a unsigned long? 3477 if (ResultVal.isIntN(LongSize)) { 3478 // Does it fit in a signed long? 3479 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3480 Ty = Context.LongTy; 3481 else if (AllowUnsigned) 3482 Ty = Context.UnsignedLongTy; 3483 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3484 // is compatible. 3485 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3486 const unsigned LongLongSize = 3487 Context.getTargetInfo().getLongLongWidth(); 3488 Diag(Tok.getLocation(), 3489 getLangOpts().CPlusPlus 3490 ? Literal.isLong 3491 ? diag::warn_old_implicitly_unsigned_long_cxx 3492 : /*C++98 UB*/ diag:: 3493 ext_old_implicitly_unsigned_long_cxx 3494 : diag::warn_old_implicitly_unsigned_long) 3495 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3496 : /*will be ill-formed*/ 1); 3497 Ty = Context.UnsignedLongTy; 3498 } 3499 Width = LongSize; 3500 } 3501 } 3502 3503 // Check long long if needed. 3504 if (Ty.isNull()) { 3505 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3506 3507 // Does it fit in a unsigned long long? 3508 if (ResultVal.isIntN(LongLongSize)) { 3509 // Does it fit in a signed long long? 3510 // To be compatible with MSVC, hex integer literals ending with the 3511 // LL or i64 suffix are always signed in Microsoft mode. 3512 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3513 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3514 Ty = Context.LongLongTy; 3515 else if (AllowUnsigned) 3516 Ty = Context.UnsignedLongLongTy; 3517 Width = LongLongSize; 3518 } 3519 } 3520 3521 // If we still couldn't decide a type, we probably have something that 3522 // does not fit in a signed long long, but has no U suffix. 3523 if (Ty.isNull()) { 3524 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3525 Ty = Context.UnsignedLongLongTy; 3526 Width = Context.getTargetInfo().getLongLongWidth(); 3527 } 3528 3529 if (ResultVal.getBitWidth() != Width) 3530 ResultVal = ResultVal.trunc(Width); 3531 } 3532 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3533 } 3534 3535 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3536 if (Literal.isImaginary) 3537 Res = new (Context) ImaginaryLiteral(Res, 3538 Context.getComplexType(Res->getType())); 3539 3540 return Res; 3541 } 3542 3543 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3544 assert(E && "ActOnParenExpr() missing expr"); 3545 return new (Context) ParenExpr(L, R, E); 3546 } 3547 3548 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3549 SourceLocation Loc, 3550 SourceRange ArgRange) { 3551 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3552 // scalar or vector data type argument..." 3553 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3554 // type (C99 6.2.5p18) or void. 3555 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3556 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3557 << T << ArgRange; 3558 return true; 3559 } 3560 3561 assert((T->isVoidType() || !T->isIncompleteType()) && 3562 "Scalar types should always be complete"); 3563 return false; 3564 } 3565 3566 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3567 SourceLocation Loc, 3568 SourceRange ArgRange, 3569 UnaryExprOrTypeTrait TraitKind) { 3570 // Invalid types must be hard errors for SFINAE in C++. 3571 if (S.LangOpts.CPlusPlus) 3572 return true; 3573 3574 // C99 6.5.3.4p1: 3575 if (T->isFunctionType() && 3576 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3577 // sizeof(function)/alignof(function) is allowed as an extension. 3578 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3579 << TraitKind << ArgRange; 3580 return false; 3581 } 3582 3583 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3584 // this is an error (OpenCL v1.1 s6.3.k) 3585 if (T->isVoidType()) { 3586 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3587 : diag::ext_sizeof_alignof_void_type; 3588 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3589 return false; 3590 } 3591 3592 return true; 3593 } 3594 3595 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3596 SourceLocation Loc, 3597 SourceRange ArgRange, 3598 UnaryExprOrTypeTrait TraitKind) { 3599 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3600 // runtime doesn't allow it. 3601 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3602 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3603 << T << (TraitKind == UETT_SizeOf) 3604 << ArgRange; 3605 return true; 3606 } 3607 3608 return false; 3609 } 3610 3611 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3612 /// pointer type is equal to T) and emit a warning if it is. 3613 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3614 Expr *E) { 3615 // Don't warn if the operation changed the type. 3616 if (T != E->getType()) 3617 return; 3618 3619 // Now look for array decays. 3620 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3621 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3622 return; 3623 3624 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3625 << ICE->getType() 3626 << ICE->getSubExpr()->getType(); 3627 } 3628 3629 /// \brief Check the constraints on expression operands to unary type expression 3630 /// and type traits. 3631 /// 3632 /// Completes any types necessary and validates the constraints on the operand 3633 /// expression. The logic mostly mirrors the type-based overload, but may modify 3634 /// the expression as it completes the type for that expression through template 3635 /// instantiation, etc. 3636 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3637 UnaryExprOrTypeTrait ExprKind) { 3638 QualType ExprTy = E->getType(); 3639 assert(!ExprTy->isReferenceType()); 3640 3641 if (ExprKind == UETT_VecStep) 3642 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3643 E->getSourceRange()); 3644 3645 // Whitelist some types as extensions 3646 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3647 E->getSourceRange(), ExprKind)) 3648 return false; 3649 3650 // 'alignof' applied to an expression only requires the base element type of 3651 // the expression to be complete. 'sizeof' requires the expression's type to 3652 // be complete (and will attempt to complete it if it's an array of unknown 3653 // bound). 3654 if (ExprKind == UETT_AlignOf) { 3655 if (RequireCompleteType(E->getExprLoc(), 3656 Context.getBaseElementType(E->getType()), 3657 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3658 E->getSourceRange())) 3659 return true; 3660 } else { 3661 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3662 ExprKind, E->getSourceRange())) 3663 return true; 3664 } 3665 3666 // Completing the expression's type may have changed it. 3667 ExprTy = E->getType(); 3668 assert(!ExprTy->isReferenceType()); 3669 3670 if (ExprTy->isFunctionType()) { 3671 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3672 << ExprKind << E->getSourceRange(); 3673 return true; 3674 } 3675 3676 // The operand for sizeof and alignof is in an unevaluated expression context, 3677 // so side effects could result in unintended consequences. 3678 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) && 3679 ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false)) 3680 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3681 3682 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3683 E->getSourceRange(), ExprKind)) 3684 return true; 3685 3686 if (ExprKind == UETT_SizeOf) { 3687 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3688 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3689 QualType OType = PVD->getOriginalType(); 3690 QualType Type = PVD->getType(); 3691 if (Type->isPointerType() && OType->isArrayType()) { 3692 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3693 << Type << OType; 3694 Diag(PVD->getLocation(), diag::note_declared_at); 3695 } 3696 } 3697 } 3698 3699 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3700 // decays into a pointer and returns an unintended result. This is most 3701 // likely a typo for "sizeof(array) op x". 3702 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3703 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3704 BO->getLHS()); 3705 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3706 BO->getRHS()); 3707 } 3708 } 3709 3710 return false; 3711 } 3712 3713 /// \brief Check the constraints on operands to unary expression and type 3714 /// traits. 3715 /// 3716 /// This will complete any types necessary, and validate the various constraints 3717 /// on those operands. 3718 /// 3719 /// The UsualUnaryConversions() function is *not* called by this routine. 3720 /// C99 6.3.2.1p[2-4] all state: 3721 /// Except when it is the operand of the sizeof operator ... 3722 /// 3723 /// C++ [expr.sizeof]p4 3724 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3725 /// standard conversions are not applied to the operand of sizeof. 3726 /// 3727 /// This policy is followed for all of the unary trait expressions. 3728 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3729 SourceLocation OpLoc, 3730 SourceRange ExprRange, 3731 UnaryExprOrTypeTrait ExprKind) { 3732 if (ExprType->isDependentType()) 3733 return false; 3734 3735 // C++ [expr.sizeof]p2: 3736 // When applied to a reference or a reference type, the result 3737 // is the size of the referenced type. 3738 // C++11 [expr.alignof]p3: 3739 // When alignof is applied to a reference type, the result 3740 // shall be the alignment of the referenced type. 3741 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3742 ExprType = Ref->getPointeeType(); 3743 3744 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3745 // When alignof or _Alignof is applied to an array type, the result 3746 // is the alignment of the element type. 3747 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign) 3748 ExprType = Context.getBaseElementType(ExprType); 3749 3750 if (ExprKind == UETT_VecStep) 3751 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3752 3753 // Whitelist some types as extensions 3754 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3755 ExprKind)) 3756 return false; 3757 3758 if (RequireCompleteType(OpLoc, ExprType, 3759 diag::err_sizeof_alignof_incomplete_type, 3760 ExprKind, ExprRange)) 3761 return true; 3762 3763 if (ExprType->isFunctionType()) { 3764 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3765 << ExprKind << ExprRange; 3766 return true; 3767 } 3768 3769 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3770 ExprKind)) 3771 return true; 3772 3773 return false; 3774 } 3775 3776 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3777 E = E->IgnoreParens(); 3778 3779 // Cannot know anything else if the expression is dependent. 3780 if (E->isTypeDependent()) 3781 return false; 3782 3783 if (E->getObjectKind() == OK_BitField) { 3784 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3785 << 1 << E->getSourceRange(); 3786 return true; 3787 } 3788 3789 ValueDecl *D = nullptr; 3790 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3791 D = DRE->getDecl(); 3792 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3793 D = ME->getMemberDecl(); 3794 } 3795 3796 // If it's a field, require the containing struct to have a 3797 // complete definition so that we can compute the layout. 3798 // 3799 // This can happen in C++11 onwards, either by naming the member 3800 // in a way that is not transformed into a member access expression 3801 // (in an unevaluated operand, for instance), or by naming the member 3802 // in a trailing-return-type. 3803 // 3804 // For the record, since __alignof__ on expressions is a GCC 3805 // extension, GCC seems to permit this but always gives the 3806 // nonsensical answer 0. 3807 // 3808 // We don't really need the layout here --- we could instead just 3809 // directly check for all the appropriate alignment-lowing 3810 // attributes --- but that would require duplicating a lot of 3811 // logic that just isn't worth duplicating for such a marginal 3812 // use-case. 3813 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3814 // Fast path this check, since we at least know the record has a 3815 // definition if we can find a member of it. 3816 if (!FD->getParent()->isCompleteDefinition()) { 3817 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3818 << E->getSourceRange(); 3819 return true; 3820 } 3821 3822 // Otherwise, if it's a field, and the field doesn't have 3823 // reference type, then it must have a complete type (or be a 3824 // flexible array member, which we explicitly want to 3825 // white-list anyway), which makes the following checks trivial. 3826 if (!FD->getType()->isReferenceType()) 3827 return false; 3828 } 3829 3830 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3831 } 3832 3833 bool Sema::CheckVecStepExpr(Expr *E) { 3834 E = E->IgnoreParens(); 3835 3836 // Cannot know anything else if the expression is dependent. 3837 if (E->isTypeDependent()) 3838 return false; 3839 3840 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3841 } 3842 3843 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 3844 CapturingScopeInfo *CSI) { 3845 assert(T->isVariablyModifiedType()); 3846 assert(CSI != nullptr); 3847 3848 // We're going to walk down into the type and look for VLA expressions. 3849 do { 3850 const Type *Ty = T.getTypePtr(); 3851 switch (Ty->getTypeClass()) { 3852 #define TYPE(Class, Base) 3853 #define ABSTRACT_TYPE(Class, Base) 3854 #define NON_CANONICAL_TYPE(Class, Base) 3855 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 3856 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 3857 #include "clang/AST/TypeNodes.def" 3858 T = QualType(); 3859 break; 3860 // These types are never variably-modified. 3861 case Type::Builtin: 3862 case Type::Complex: 3863 case Type::Vector: 3864 case Type::ExtVector: 3865 case Type::Record: 3866 case Type::Enum: 3867 case Type::Elaborated: 3868 case Type::TemplateSpecialization: 3869 case Type::ObjCObject: 3870 case Type::ObjCInterface: 3871 case Type::ObjCObjectPointer: 3872 case Type::ObjCTypeParam: 3873 case Type::Pipe: 3874 llvm_unreachable("type class is never variably-modified!"); 3875 case Type::Adjusted: 3876 T = cast<AdjustedType>(Ty)->getOriginalType(); 3877 break; 3878 case Type::Decayed: 3879 T = cast<DecayedType>(Ty)->getPointeeType(); 3880 break; 3881 case Type::Pointer: 3882 T = cast<PointerType>(Ty)->getPointeeType(); 3883 break; 3884 case Type::BlockPointer: 3885 T = cast<BlockPointerType>(Ty)->getPointeeType(); 3886 break; 3887 case Type::LValueReference: 3888 case Type::RValueReference: 3889 T = cast<ReferenceType>(Ty)->getPointeeType(); 3890 break; 3891 case Type::MemberPointer: 3892 T = cast<MemberPointerType>(Ty)->getPointeeType(); 3893 break; 3894 case Type::ConstantArray: 3895 case Type::IncompleteArray: 3896 // Losing element qualification here is fine. 3897 T = cast<ArrayType>(Ty)->getElementType(); 3898 break; 3899 case Type::VariableArray: { 3900 // Losing element qualification here is fine. 3901 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 3902 3903 // Unknown size indication requires no size computation. 3904 // Otherwise, evaluate and record it. 3905 if (auto Size = VAT->getSizeExpr()) { 3906 if (!CSI->isVLATypeCaptured(VAT)) { 3907 RecordDecl *CapRecord = nullptr; 3908 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 3909 CapRecord = LSI->Lambda; 3910 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 3911 CapRecord = CRSI->TheRecordDecl; 3912 } 3913 if (CapRecord) { 3914 auto ExprLoc = Size->getExprLoc(); 3915 auto SizeType = Context.getSizeType(); 3916 // Build the non-static data member. 3917 auto Field = 3918 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc, 3919 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 3920 /*BW*/ nullptr, /*Mutable*/ false, 3921 /*InitStyle*/ ICIS_NoInit); 3922 Field->setImplicit(true); 3923 Field->setAccess(AS_private); 3924 Field->setCapturedVLAType(VAT); 3925 CapRecord->addDecl(Field); 3926 3927 CSI->addVLATypeCapture(ExprLoc, SizeType); 3928 } 3929 } 3930 } 3931 T = VAT->getElementType(); 3932 break; 3933 } 3934 case Type::FunctionProto: 3935 case Type::FunctionNoProto: 3936 T = cast<FunctionType>(Ty)->getReturnType(); 3937 break; 3938 case Type::Paren: 3939 case Type::TypeOf: 3940 case Type::UnaryTransform: 3941 case Type::Attributed: 3942 case Type::SubstTemplateTypeParm: 3943 case Type::PackExpansion: 3944 // Keep walking after single level desugaring. 3945 T = T.getSingleStepDesugaredType(Context); 3946 break; 3947 case Type::Typedef: 3948 T = cast<TypedefType>(Ty)->desugar(); 3949 break; 3950 case Type::Decltype: 3951 T = cast<DecltypeType>(Ty)->desugar(); 3952 break; 3953 case Type::Auto: 3954 T = cast<AutoType>(Ty)->getDeducedType(); 3955 break; 3956 case Type::TypeOfExpr: 3957 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 3958 break; 3959 case Type::Atomic: 3960 T = cast<AtomicType>(Ty)->getValueType(); 3961 break; 3962 } 3963 } while (!T.isNull() && T->isVariablyModifiedType()); 3964 } 3965 3966 /// \brief Build a sizeof or alignof expression given a type operand. 3967 ExprResult 3968 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3969 SourceLocation OpLoc, 3970 UnaryExprOrTypeTrait ExprKind, 3971 SourceRange R) { 3972 if (!TInfo) 3973 return ExprError(); 3974 3975 QualType T = TInfo->getType(); 3976 3977 if (!T->isDependentType() && 3978 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3979 return ExprError(); 3980 3981 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 3982 if (auto *TT = T->getAs<TypedefType>()) { 3983 for (auto I = FunctionScopes.rbegin(), 3984 E = std::prev(FunctionScopes.rend()); 3985 I != E; ++I) { 3986 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 3987 if (CSI == nullptr) 3988 break; 3989 DeclContext *DC = nullptr; 3990 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 3991 DC = LSI->CallOperator; 3992 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 3993 DC = CRSI->TheCapturedDecl; 3994 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 3995 DC = BSI->TheDecl; 3996 if (DC) { 3997 if (DC->containsDecl(TT->getDecl())) 3998 break; 3999 captureVariablyModifiedType(Context, T, CSI); 4000 } 4001 } 4002 } 4003 } 4004 4005 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4006 return new (Context) UnaryExprOrTypeTraitExpr( 4007 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4008 } 4009 4010 /// \brief Build a sizeof or alignof expression given an expression 4011 /// operand. 4012 ExprResult 4013 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4014 UnaryExprOrTypeTrait ExprKind) { 4015 ExprResult PE = CheckPlaceholderExpr(E); 4016 if (PE.isInvalid()) 4017 return ExprError(); 4018 4019 E = PE.get(); 4020 4021 // Verify that the operand is valid. 4022 bool isInvalid = false; 4023 if (E->isTypeDependent()) { 4024 // Delay type-checking for type-dependent expressions. 4025 } else if (ExprKind == UETT_AlignOf) { 4026 isInvalid = CheckAlignOfExpr(*this, E); 4027 } else if (ExprKind == UETT_VecStep) { 4028 isInvalid = CheckVecStepExpr(E); 4029 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4030 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4031 isInvalid = true; 4032 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4033 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4034 isInvalid = true; 4035 } else { 4036 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4037 } 4038 4039 if (isInvalid) 4040 return ExprError(); 4041 4042 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4043 PE = TransformToPotentiallyEvaluated(E); 4044 if (PE.isInvalid()) return ExprError(); 4045 E = PE.get(); 4046 } 4047 4048 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4049 return new (Context) UnaryExprOrTypeTraitExpr( 4050 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4051 } 4052 4053 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4054 /// expr and the same for @c alignof and @c __alignof 4055 /// Note that the ArgRange is invalid if isType is false. 4056 ExprResult 4057 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4058 UnaryExprOrTypeTrait ExprKind, bool IsType, 4059 void *TyOrEx, SourceRange ArgRange) { 4060 // If error parsing type, ignore. 4061 if (!TyOrEx) return ExprError(); 4062 4063 if (IsType) { 4064 TypeSourceInfo *TInfo; 4065 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4066 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4067 } 4068 4069 Expr *ArgEx = (Expr *)TyOrEx; 4070 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4071 return Result; 4072 } 4073 4074 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4075 bool IsReal) { 4076 if (V.get()->isTypeDependent()) 4077 return S.Context.DependentTy; 4078 4079 // _Real and _Imag are only l-values for normal l-values. 4080 if (V.get()->getObjectKind() != OK_Ordinary) { 4081 V = S.DefaultLvalueConversion(V.get()); 4082 if (V.isInvalid()) 4083 return QualType(); 4084 } 4085 4086 // These operators return the element type of a complex type. 4087 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4088 return CT->getElementType(); 4089 4090 // Otherwise they pass through real integer and floating point types here. 4091 if (V.get()->getType()->isArithmeticType()) 4092 return V.get()->getType(); 4093 4094 // Test for placeholders. 4095 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4096 if (PR.isInvalid()) return QualType(); 4097 if (PR.get() != V.get()) { 4098 V = PR; 4099 return CheckRealImagOperand(S, V, Loc, IsReal); 4100 } 4101 4102 // Reject anything else. 4103 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4104 << (IsReal ? "__real" : "__imag"); 4105 return QualType(); 4106 } 4107 4108 4109 4110 ExprResult 4111 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4112 tok::TokenKind Kind, Expr *Input) { 4113 UnaryOperatorKind Opc; 4114 switch (Kind) { 4115 default: llvm_unreachable("Unknown unary op!"); 4116 case tok::plusplus: Opc = UO_PostInc; break; 4117 case tok::minusminus: Opc = UO_PostDec; break; 4118 } 4119 4120 // Since this might is a postfix expression, get rid of ParenListExprs. 4121 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4122 if (Result.isInvalid()) return ExprError(); 4123 Input = Result.get(); 4124 4125 return BuildUnaryOp(S, OpLoc, Opc, Input); 4126 } 4127 4128 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 4129 /// 4130 /// \return true on error 4131 static bool checkArithmeticOnObjCPointer(Sema &S, 4132 SourceLocation opLoc, 4133 Expr *op) { 4134 assert(op->getType()->isObjCObjectPointerType()); 4135 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4136 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4137 return false; 4138 4139 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4140 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4141 << op->getSourceRange(); 4142 return true; 4143 } 4144 4145 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4146 auto *BaseNoParens = Base->IgnoreParens(); 4147 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4148 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4149 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4150 } 4151 4152 ExprResult 4153 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4154 Expr *idx, SourceLocation rbLoc) { 4155 if (base && !base->getType().isNull() && 4156 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4157 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4158 /*Length=*/nullptr, rbLoc); 4159 4160 // Since this might be a postfix expression, get rid of ParenListExprs. 4161 if (isa<ParenListExpr>(base)) { 4162 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4163 if (result.isInvalid()) return ExprError(); 4164 base = result.get(); 4165 } 4166 4167 // Handle any non-overload placeholder types in the base and index 4168 // expressions. We can't handle overloads here because the other 4169 // operand might be an overloadable type, in which case the overload 4170 // resolution for the operator overload should get the first crack 4171 // at the overload. 4172 bool IsMSPropertySubscript = false; 4173 if (base->getType()->isNonOverloadPlaceholderType()) { 4174 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4175 if (!IsMSPropertySubscript) { 4176 ExprResult result = CheckPlaceholderExpr(base); 4177 if (result.isInvalid()) 4178 return ExprError(); 4179 base = result.get(); 4180 } 4181 } 4182 if (idx->getType()->isNonOverloadPlaceholderType()) { 4183 ExprResult result = CheckPlaceholderExpr(idx); 4184 if (result.isInvalid()) return ExprError(); 4185 idx = result.get(); 4186 } 4187 4188 // Build an unanalyzed expression if either operand is type-dependent. 4189 if (getLangOpts().CPlusPlus && 4190 (base->isTypeDependent() || idx->isTypeDependent())) { 4191 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4192 VK_LValue, OK_Ordinary, rbLoc); 4193 } 4194 4195 // MSDN, property (C++) 4196 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4197 // This attribute can also be used in the declaration of an empty array in a 4198 // class or structure definition. For example: 4199 // __declspec(property(get=GetX, put=PutX)) int x[]; 4200 // The above statement indicates that x[] can be used with one or more array 4201 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4202 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4203 if (IsMSPropertySubscript) { 4204 // Build MS property subscript expression if base is MS property reference 4205 // or MS property subscript. 4206 return new (Context) MSPropertySubscriptExpr( 4207 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4208 } 4209 4210 // Use C++ overloaded-operator rules if either operand has record 4211 // type. The spec says to do this if either type is *overloadable*, 4212 // but enum types can't declare subscript operators or conversion 4213 // operators, so there's nothing interesting for overload resolution 4214 // to do if there aren't any record types involved. 4215 // 4216 // ObjC pointers have their own subscripting logic that is not tied 4217 // to overload resolution and so should not take this path. 4218 if (getLangOpts().CPlusPlus && 4219 (base->getType()->isRecordType() || 4220 (!base->getType()->isObjCObjectPointerType() && 4221 idx->getType()->isRecordType()))) { 4222 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4223 } 4224 4225 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4226 } 4227 4228 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4229 Expr *LowerBound, 4230 SourceLocation ColonLoc, Expr *Length, 4231 SourceLocation RBLoc) { 4232 if (Base->getType()->isPlaceholderType() && 4233 !Base->getType()->isSpecificPlaceholderType( 4234 BuiltinType::OMPArraySection)) { 4235 ExprResult Result = CheckPlaceholderExpr(Base); 4236 if (Result.isInvalid()) 4237 return ExprError(); 4238 Base = Result.get(); 4239 } 4240 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4241 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4242 if (Result.isInvalid()) 4243 return ExprError(); 4244 Result = DefaultLvalueConversion(Result.get()); 4245 if (Result.isInvalid()) 4246 return ExprError(); 4247 LowerBound = Result.get(); 4248 } 4249 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4250 ExprResult Result = CheckPlaceholderExpr(Length); 4251 if (Result.isInvalid()) 4252 return ExprError(); 4253 Result = DefaultLvalueConversion(Result.get()); 4254 if (Result.isInvalid()) 4255 return ExprError(); 4256 Length = Result.get(); 4257 } 4258 4259 // Build an unanalyzed expression if either operand is type-dependent. 4260 if (Base->isTypeDependent() || 4261 (LowerBound && 4262 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4263 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4264 return new (Context) 4265 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4266 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4267 } 4268 4269 // Perform default conversions. 4270 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4271 QualType ResultTy; 4272 if (OriginalTy->isAnyPointerType()) { 4273 ResultTy = OriginalTy->getPointeeType(); 4274 } else if (OriginalTy->isArrayType()) { 4275 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4276 } else { 4277 return ExprError( 4278 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4279 << Base->getSourceRange()); 4280 } 4281 // C99 6.5.2.1p1 4282 if (LowerBound) { 4283 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4284 LowerBound); 4285 if (Res.isInvalid()) 4286 return ExprError(Diag(LowerBound->getExprLoc(), 4287 diag::err_omp_typecheck_section_not_integer) 4288 << 0 << LowerBound->getSourceRange()); 4289 LowerBound = Res.get(); 4290 4291 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4292 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4293 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4294 << 0 << LowerBound->getSourceRange(); 4295 } 4296 if (Length) { 4297 auto Res = 4298 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4299 if (Res.isInvalid()) 4300 return ExprError(Diag(Length->getExprLoc(), 4301 diag::err_omp_typecheck_section_not_integer) 4302 << 1 << Length->getSourceRange()); 4303 Length = Res.get(); 4304 4305 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4306 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4307 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4308 << 1 << Length->getSourceRange(); 4309 } 4310 4311 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4312 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4313 // type. Note that functions are not objects, and that (in C99 parlance) 4314 // incomplete types are not object types. 4315 if (ResultTy->isFunctionType()) { 4316 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4317 << ResultTy << Base->getSourceRange(); 4318 return ExprError(); 4319 } 4320 4321 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4322 diag::err_omp_section_incomplete_type, Base)) 4323 return ExprError(); 4324 4325 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4326 llvm::APSInt LowerBoundValue; 4327 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) { 4328 // OpenMP 4.5, [2.4 Array Sections] 4329 // The array section must be a subset of the original array. 4330 if (LowerBoundValue.isNegative()) { 4331 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4332 << LowerBound->getSourceRange(); 4333 return ExprError(); 4334 } 4335 } 4336 } 4337 4338 if (Length) { 4339 llvm::APSInt LengthValue; 4340 if (Length->EvaluateAsInt(LengthValue, Context)) { 4341 // OpenMP 4.5, [2.4 Array Sections] 4342 // The length must evaluate to non-negative integers. 4343 if (LengthValue.isNegative()) { 4344 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4345 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4346 << Length->getSourceRange(); 4347 return ExprError(); 4348 } 4349 } 4350 } else if (ColonLoc.isValid() && 4351 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4352 !OriginalTy->isVariableArrayType()))) { 4353 // OpenMP 4.5, [2.4 Array Sections] 4354 // When the size of the array dimension is not known, the length must be 4355 // specified explicitly. 4356 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4357 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4358 return ExprError(); 4359 } 4360 4361 if (!Base->getType()->isSpecificPlaceholderType( 4362 BuiltinType::OMPArraySection)) { 4363 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4364 if (Result.isInvalid()) 4365 return ExprError(); 4366 Base = Result.get(); 4367 } 4368 return new (Context) 4369 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4370 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4371 } 4372 4373 ExprResult 4374 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4375 Expr *Idx, SourceLocation RLoc) { 4376 Expr *LHSExp = Base; 4377 Expr *RHSExp = Idx; 4378 4379 // Perform default conversions. 4380 if (!LHSExp->getType()->getAs<VectorType>()) { 4381 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4382 if (Result.isInvalid()) 4383 return ExprError(); 4384 LHSExp = Result.get(); 4385 } 4386 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4387 if (Result.isInvalid()) 4388 return ExprError(); 4389 RHSExp = Result.get(); 4390 4391 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4392 ExprValueKind VK = VK_LValue; 4393 ExprObjectKind OK = OK_Ordinary; 4394 4395 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4396 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4397 // in the subscript position. As a result, we need to derive the array base 4398 // and index from the expression types. 4399 Expr *BaseExpr, *IndexExpr; 4400 QualType ResultType; 4401 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4402 BaseExpr = LHSExp; 4403 IndexExpr = RHSExp; 4404 ResultType = Context.DependentTy; 4405 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4406 BaseExpr = LHSExp; 4407 IndexExpr = RHSExp; 4408 ResultType = PTy->getPointeeType(); 4409 } else if (const ObjCObjectPointerType *PTy = 4410 LHSTy->getAs<ObjCObjectPointerType>()) { 4411 BaseExpr = LHSExp; 4412 IndexExpr = RHSExp; 4413 4414 // Use custom logic if this should be the pseudo-object subscript 4415 // expression. 4416 if (!LangOpts.isSubscriptPointerArithmetic()) 4417 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4418 nullptr); 4419 4420 ResultType = PTy->getPointeeType(); 4421 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4422 // Handle the uncommon case of "123[Ptr]". 4423 BaseExpr = RHSExp; 4424 IndexExpr = LHSExp; 4425 ResultType = PTy->getPointeeType(); 4426 } else if (const ObjCObjectPointerType *PTy = 4427 RHSTy->getAs<ObjCObjectPointerType>()) { 4428 // Handle the uncommon case of "123[Ptr]". 4429 BaseExpr = RHSExp; 4430 IndexExpr = LHSExp; 4431 ResultType = PTy->getPointeeType(); 4432 if (!LangOpts.isSubscriptPointerArithmetic()) { 4433 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4434 << ResultType << BaseExpr->getSourceRange(); 4435 return ExprError(); 4436 } 4437 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4438 BaseExpr = LHSExp; // vectors: V[123] 4439 IndexExpr = RHSExp; 4440 VK = LHSExp->getValueKind(); 4441 if (VK != VK_RValue) 4442 OK = OK_VectorComponent; 4443 4444 // FIXME: need to deal with const... 4445 ResultType = VTy->getElementType(); 4446 } else if (LHSTy->isArrayType()) { 4447 // If we see an array that wasn't promoted by 4448 // DefaultFunctionArrayLvalueConversion, it must be an array that 4449 // wasn't promoted because of the C90 rule that doesn't 4450 // allow promoting non-lvalue arrays. Warn, then 4451 // force the promotion here. 4452 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4453 LHSExp->getSourceRange(); 4454 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4455 CK_ArrayToPointerDecay).get(); 4456 LHSTy = LHSExp->getType(); 4457 4458 BaseExpr = LHSExp; 4459 IndexExpr = RHSExp; 4460 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4461 } else if (RHSTy->isArrayType()) { 4462 // Same as previous, except for 123[f().a] case 4463 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4464 RHSExp->getSourceRange(); 4465 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4466 CK_ArrayToPointerDecay).get(); 4467 RHSTy = RHSExp->getType(); 4468 4469 BaseExpr = RHSExp; 4470 IndexExpr = LHSExp; 4471 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4472 } else { 4473 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4474 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4475 } 4476 // C99 6.5.2.1p1 4477 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4478 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4479 << IndexExpr->getSourceRange()); 4480 4481 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4482 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4483 && !IndexExpr->isTypeDependent()) 4484 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4485 4486 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4487 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4488 // type. Note that Functions are not objects, and that (in C99 parlance) 4489 // incomplete types are not object types. 4490 if (ResultType->isFunctionType()) { 4491 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 4492 << ResultType << BaseExpr->getSourceRange(); 4493 return ExprError(); 4494 } 4495 4496 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4497 // GNU extension: subscripting on pointer to void 4498 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4499 << BaseExpr->getSourceRange(); 4500 4501 // C forbids expressions of unqualified void type from being l-values. 4502 // See IsCForbiddenLValueType. 4503 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4504 } else if (!ResultType->isDependentType() && 4505 RequireCompleteType(LLoc, ResultType, 4506 diag::err_subscript_incomplete_type, BaseExpr)) 4507 return ExprError(); 4508 4509 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4510 !ResultType.isCForbiddenLValueType()); 4511 4512 return new (Context) 4513 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4514 } 4515 4516 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4517 FunctionDecl *FD, 4518 ParmVarDecl *Param) { 4519 if (Param->hasUnparsedDefaultArg()) { 4520 Diag(CallLoc, 4521 diag::err_use_of_default_argument_to_function_declared_later) << 4522 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4523 Diag(UnparsedDefaultArgLocs[Param], 4524 diag::note_default_argument_declared_here); 4525 return ExprError(); 4526 } 4527 4528 if (Param->hasUninstantiatedDefaultArg()) { 4529 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4530 4531 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated, 4532 Param); 4533 4534 // Instantiate the expression. 4535 MultiLevelTemplateArgumentList MutiLevelArgList 4536 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4537 4538 InstantiatingTemplate Inst(*this, CallLoc, Param, 4539 MutiLevelArgList.getInnermost()); 4540 if (Inst.isInvalid()) 4541 return ExprError(); 4542 if (Inst.isAlreadyInstantiating()) { 4543 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4544 Param->setInvalidDecl(); 4545 return ExprError(); 4546 } 4547 4548 ExprResult Result; 4549 { 4550 // C++ [dcl.fct.default]p5: 4551 // The names in the [default argument] expression are bound, and 4552 // the semantic constraints are checked, at the point where the 4553 // default argument expression appears. 4554 ContextRAII SavedContext(*this, FD); 4555 LocalInstantiationScope Local(*this); 4556 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 4557 /*DirectInit*/false); 4558 } 4559 if (Result.isInvalid()) 4560 return ExprError(); 4561 4562 // Check the expression as an initializer for the parameter. 4563 InitializedEntity Entity 4564 = InitializedEntity::InitializeParameter(Context, Param); 4565 InitializationKind Kind 4566 = InitializationKind::CreateCopy(Param->getLocation(), 4567 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 4568 Expr *ResultE = Result.getAs<Expr>(); 4569 4570 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4571 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4572 if (Result.isInvalid()) 4573 return ExprError(); 4574 4575 Result = ActOnFinishFullExpr(Result.getAs<Expr>(), 4576 Param->getOuterLocStart()); 4577 if (Result.isInvalid()) 4578 return ExprError(); 4579 4580 // Remember the instantiated default argument. 4581 Param->setDefaultArg(Result.getAs<Expr>()); 4582 if (ASTMutationListener *L = getASTMutationListener()) { 4583 L->DefaultArgumentInstantiated(Param); 4584 } 4585 } 4586 4587 // If the default argument expression is not set yet, we are building it now. 4588 if (!Param->hasInit()) { 4589 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4590 Param->setInvalidDecl(); 4591 return ExprError(); 4592 } 4593 4594 // If the default expression creates temporaries, we need to 4595 // push them to the current stack of expression temporaries so they'll 4596 // be properly destroyed. 4597 // FIXME: We should really be rebuilding the default argument with new 4598 // bound temporaries; see the comment in PR5810. 4599 // We don't need to do that with block decls, though, because 4600 // blocks in default argument expression can never capture anything. 4601 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 4602 // Set the "needs cleanups" bit regardless of whether there are 4603 // any explicit objects. 4604 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 4605 4606 // Append all the objects to the cleanup list. Right now, this 4607 // should always be a no-op, because blocks in default argument 4608 // expressions should never be able to capture anything. 4609 assert(!Init->getNumObjects() && 4610 "default argument expression has capturing blocks?"); 4611 } 4612 4613 // We already type-checked the argument, so we know it works. 4614 // Just mark all of the declarations in this potentially-evaluated expression 4615 // as being "referenced". 4616 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4617 /*SkipLocalVariables=*/true); 4618 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4619 } 4620 4621 4622 Sema::VariadicCallType 4623 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4624 Expr *Fn) { 4625 if (Proto && Proto->isVariadic()) { 4626 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4627 return VariadicConstructor; 4628 else if (Fn && Fn->getType()->isBlockPointerType()) 4629 return VariadicBlock; 4630 else if (FDecl) { 4631 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4632 if (Method->isInstance()) 4633 return VariadicMethod; 4634 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4635 return VariadicMethod; 4636 return VariadicFunction; 4637 } 4638 return VariadicDoesNotApply; 4639 } 4640 4641 namespace { 4642 class FunctionCallCCC : public FunctionCallFilterCCC { 4643 public: 4644 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4645 unsigned NumArgs, MemberExpr *ME) 4646 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4647 FunctionName(FuncName) {} 4648 4649 bool ValidateCandidate(const TypoCorrection &candidate) override { 4650 if (!candidate.getCorrectionSpecifier() || 4651 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4652 return false; 4653 } 4654 4655 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4656 } 4657 4658 private: 4659 const IdentifierInfo *const FunctionName; 4660 }; 4661 } 4662 4663 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4664 FunctionDecl *FDecl, 4665 ArrayRef<Expr *> Args) { 4666 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4667 DeclarationName FuncName = FDecl->getDeclName(); 4668 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart(); 4669 4670 if (TypoCorrection Corrected = S.CorrectTypo( 4671 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4672 S.getScopeForContext(S.CurContext), nullptr, 4673 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4674 Args.size(), ME), 4675 Sema::CTK_ErrorRecovery)) { 4676 if (NamedDecl *ND = Corrected.getFoundDecl()) { 4677 if (Corrected.isOverloaded()) { 4678 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4679 OverloadCandidateSet::iterator Best; 4680 for (NamedDecl *CD : Corrected) { 4681 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 4682 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4683 OCS); 4684 } 4685 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4686 case OR_Success: 4687 ND = Best->FoundDecl; 4688 Corrected.setCorrectionDecl(ND); 4689 break; 4690 default: 4691 break; 4692 } 4693 } 4694 ND = ND->getUnderlyingDecl(); 4695 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 4696 return Corrected; 4697 } 4698 } 4699 return TypoCorrection(); 4700 } 4701 4702 /// ConvertArgumentsForCall - Converts the arguments specified in 4703 /// Args/NumArgs to the parameter types of the function FDecl with 4704 /// function prototype Proto. Call is the call expression itself, and 4705 /// Fn is the function expression. For a C++ member function, this 4706 /// routine does not attempt to convert the object argument. Returns 4707 /// true if the call is ill-formed. 4708 bool 4709 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4710 FunctionDecl *FDecl, 4711 const FunctionProtoType *Proto, 4712 ArrayRef<Expr *> Args, 4713 SourceLocation RParenLoc, 4714 bool IsExecConfig) { 4715 // Bail out early if calling a builtin with custom typechecking. 4716 if (FDecl) 4717 if (unsigned ID = FDecl->getBuiltinID()) 4718 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4719 return false; 4720 4721 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4722 // assignment, to the types of the corresponding parameter, ... 4723 unsigned NumParams = Proto->getNumParams(); 4724 bool Invalid = false; 4725 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4726 unsigned FnKind = Fn->getType()->isBlockPointerType() 4727 ? 1 /* block */ 4728 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4729 : 0 /* function */); 4730 4731 // If too few arguments are available (and we don't have default 4732 // arguments for the remaining parameters), don't make the call. 4733 if (Args.size() < NumParams) { 4734 if (Args.size() < MinArgs) { 4735 TypoCorrection TC; 4736 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4737 unsigned diag_id = 4738 MinArgs == NumParams && !Proto->isVariadic() 4739 ? diag::err_typecheck_call_too_few_args_suggest 4740 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4741 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4742 << static_cast<unsigned>(Args.size()) 4743 << TC.getCorrectionRange()); 4744 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4745 Diag(RParenLoc, 4746 MinArgs == NumParams && !Proto->isVariadic() 4747 ? diag::err_typecheck_call_too_few_args_one 4748 : diag::err_typecheck_call_too_few_args_at_least_one) 4749 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4750 else 4751 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4752 ? diag::err_typecheck_call_too_few_args 4753 : diag::err_typecheck_call_too_few_args_at_least) 4754 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4755 << Fn->getSourceRange(); 4756 4757 // Emit the location of the prototype. 4758 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4759 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4760 << FDecl; 4761 4762 return true; 4763 } 4764 Call->setNumArgs(Context, NumParams); 4765 } 4766 4767 // If too many are passed and not variadic, error on the extras and drop 4768 // them. 4769 if (Args.size() > NumParams) { 4770 if (!Proto->isVariadic()) { 4771 TypoCorrection TC; 4772 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4773 unsigned diag_id = 4774 MinArgs == NumParams && !Proto->isVariadic() 4775 ? diag::err_typecheck_call_too_many_args_suggest 4776 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4777 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4778 << static_cast<unsigned>(Args.size()) 4779 << TC.getCorrectionRange()); 4780 } else if (NumParams == 1 && FDecl && 4781 FDecl->getParamDecl(0)->getDeclName()) 4782 Diag(Args[NumParams]->getLocStart(), 4783 MinArgs == NumParams 4784 ? diag::err_typecheck_call_too_many_args_one 4785 : diag::err_typecheck_call_too_many_args_at_most_one) 4786 << FnKind << FDecl->getParamDecl(0) 4787 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4788 << SourceRange(Args[NumParams]->getLocStart(), 4789 Args.back()->getLocEnd()); 4790 else 4791 Diag(Args[NumParams]->getLocStart(), 4792 MinArgs == NumParams 4793 ? diag::err_typecheck_call_too_many_args 4794 : diag::err_typecheck_call_too_many_args_at_most) 4795 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4796 << Fn->getSourceRange() 4797 << SourceRange(Args[NumParams]->getLocStart(), 4798 Args.back()->getLocEnd()); 4799 4800 // Emit the location of the prototype. 4801 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4802 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4803 << FDecl; 4804 4805 // This deletes the extra arguments. 4806 Call->setNumArgs(Context, NumParams); 4807 return true; 4808 } 4809 } 4810 SmallVector<Expr *, 8> AllArgs; 4811 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4812 4813 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4814 Proto, 0, Args, AllArgs, CallType); 4815 if (Invalid) 4816 return true; 4817 unsigned TotalNumArgs = AllArgs.size(); 4818 for (unsigned i = 0; i < TotalNumArgs; ++i) 4819 Call->setArg(i, AllArgs[i]); 4820 4821 return false; 4822 } 4823 4824 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4825 const FunctionProtoType *Proto, 4826 unsigned FirstParam, ArrayRef<Expr *> Args, 4827 SmallVectorImpl<Expr *> &AllArgs, 4828 VariadicCallType CallType, bool AllowExplicit, 4829 bool IsListInitialization) { 4830 unsigned NumParams = Proto->getNumParams(); 4831 bool Invalid = false; 4832 size_t ArgIx = 0; 4833 // Continue to check argument types (even if we have too few/many args). 4834 for (unsigned i = FirstParam; i < NumParams; i++) { 4835 QualType ProtoArgType = Proto->getParamType(i); 4836 4837 Expr *Arg; 4838 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4839 if (ArgIx < Args.size()) { 4840 Arg = Args[ArgIx++]; 4841 4842 if (RequireCompleteType(Arg->getLocStart(), 4843 ProtoArgType, 4844 diag::err_call_incomplete_argument, Arg)) 4845 return true; 4846 4847 // Strip the unbridged-cast placeholder expression off, if applicable. 4848 bool CFAudited = false; 4849 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4850 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4851 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4852 Arg = stripARCUnbridgedCast(Arg); 4853 else if (getLangOpts().ObjCAutoRefCount && 4854 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4855 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4856 CFAudited = true; 4857 4858 InitializedEntity Entity = 4859 Param ? InitializedEntity::InitializeParameter(Context, Param, 4860 ProtoArgType) 4861 : InitializedEntity::InitializeParameter( 4862 Context, ProtoArgType, Proto->isParamConsumed(i)); 4863 4864 // Remember that parameter belongs to a CF audited API. 4865 if (CFAudited) 4866 Entity.setParameterCFAudited(); 4867 4868 ExprResult ArgE = PerformCopyInitialization( 4869 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 4870 if (ArgE.isInvalid()) 4871 return true; 4872 4873 Arg = ArgE.getAs<Expr>(); 4874 } else { 4875 assert(Param && "can't use default arguments without a known callee"); 4876 4877 ExprResult ArgExpr = 4878 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4879 if (ArgExpr.isInvalid()) 4880 return true; 4881 4882 Arg = ArgExpr.getAs<Expr>(); 4883 } 4884 4885 // Check for array bounds violations for each argument to the call. This 4886 // check only triggers warnings when the argument isn't a more complex Expr 4887 // with its own checking, such as a BinaryOperator. 4888 CheckArrayAccess(Arg); 4889 4890 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4891 CheckStaticArrayArgument(CallLoc, Param, Arg); 4892 4893 AllArgs.push_back(Arg); 4894 } 4895 4896 // If this is a variadic call, handle args passed through "...". 4897 if (CallType != VariadicDoesNotApply) { 4898 // Assume that extern "C" functions with variadic arguments that 4899 // return __unknown_anytype aren't *really* variadic. 4900 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4901 FDecl->isExternC()) { 4902 for (Expr *A : Args.slice(ArgIx)) { 4903 QualType paramType; // ignored 4904 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 4905 Invalid |= arg.isInvalid(); 4906 AllArgs.push_back(arg.get()); 4907 } 4908 4909 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4910 } else { 4911 for (Expr *A : Args.slice(ArgIx)) { 4912 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 4913 Invalid |= Arg.isInvalid(); 4914 AllArgs.push_back(Arg.get()); 4915 } 4916 } 4917 4918 // Check for array bounds violations. 4919 for (Expr *A : Args.slice(ArgIx)) 4920 CheckArrayAccess(A); 4921 } 4922 return Invalid; 4923 } 4924 4925 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4926 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4927 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4928 TL = DTL.getOriginalLoc(); 4929 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4930 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4931 << ATL.getLocalSourceRange(); 4932 } 4933 4934 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4935 /// array parameter, check that it is non-null, and that if it is formed by 4936 /// array-to-pointer decay, the underlying array is sufficiently large. 4937 /// 4938 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4939 /// array type derivation, then for each call to the function, the value of the 4940 /// corresponding actual argument shall provide access to the first element of 4941 /// an array with at least as many elements as specified by the size expression. 4942 void 4943 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4944 ParmVarDecl *Param, 4945 const Expr *ArgExpr) { 4946 // Static array parameters are not supported in C++. 4947 if (!Param || getLangOpts().CPlusPlus) 4948 return; 4949 4950 QualType OrigTy = Param->getOriginalType(); 4951 4952 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4953 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4954 return; 4955 4956 if (ArgExpr->isNullPointerConstant(Context, 4957 Expr::NPC_NeverValueDependent)) { 4958 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4959 DiagnoseCalleeStaticArrayParam(*this, Param); 4960 return; 4961 } 4962 4963 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 4964 if (!CAT) 4965 return; 4966 4967 const ConstantArrayType *ArgCAT = 4968 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 4969 if (!ArgCAT) 4970 return; 4971 4972 if (ArgCAT->getSize().ult(CAT->getSize())) { 4973 Diag(CallLoc, diag::warn_static_array_too_small) 4974 << ArgExpr->getSourceRange() 4975 << (unsigned) ArgCAT->getSize().getZExtValue() 4976 << (unsigned) CAT->getSize().getZExtValue(); 4977 DiagnoseCalleeStaticArrayParam(*this, Param); 4978 } 4979 } 4980 4981 /// Given a function expression of unknown-any type, try to rebuild it 4982 /// to have a function type. 4983 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 4984 4985 /// Is the given type a placeholder that we need to lower out 4986 /// immediately during argument processing? 4987 static bool isPlaceholderToRemoveAsArg(QualType type) { 4988 // Placeholders are never sugared. 4989 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 4990 if (!placeholder) return false; 4991 4992 switch (placeholder->getKind()) { 4993 // Ignore all the non-placeholder types. 4994 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 4995 case BuiltinType::Id: 4996 #include "clang/Basic/OpenCLImageTypes.def" 4997 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 4998 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 4999 #include "clang/AST/BuiltinTypes.def" 5000 return false; 5001 5002 // We cannot lower out overload sets; they might validly be resolved 5003 // by the call machinery. 5004 case BuiltinType::Overload: 5005 return false; 5006 5007 // Unbridged casts in ARC can be handled in some call positions and 5008 // should be left in place. 5009 case BuiltinType::ARCUnbridgedCast: 5010 return false; 5011 5012 // Pseudo-objects should be converted as soon as possible. 5013 case BuiltinType::PseudoObject: 5014 return true; 5015 5016 // The debugger mode could theoretically but currently does not try 5017 // to resolve unknown-typed arguments based on known parameter types. 5018 case BuiltinType::UnknownAny: 5019 return true; 5020 5021 // These are always invalid as call arguments and should be reported. 5022 case BuiltinType::BoundMember: 5023 case BuiltinType::BuiltinFn: 5024 case BuiltinType::OMPArraySection: 5025 return true; 5026 5027 } 5028 llvm_unreachable("bad builtin type kind"); 5029 } 5030 5031 /// Check an argument list for placeholders that we won't try to 5032 /// handle later. 5033 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5034 // Apply this processing to all the arguments at once instead of 5035 // dying at the first failure. 5036 bool hasInvalid = false; 5037 for (size_t i = 0, e = args.size(); i != e; i++) { 5038 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5039 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5040 if (result.isInvalid()) hasInvalid = true; 5041 else args[i] = result.get(); 5042 } else if (hasInvalid) { 5043 (void)S.CorrectDelayedTyposInExpr(args[i]); 5044 } 5045 } 5046 return hasInvalid; 5047 } 5048 5049 /// If a builtin function has a pointer argument with no explicit address 5050 /// space, then it should be able to accept a pointer to any address 5051 /// space as input. In order to do this, we need to replace the 5052 /// standard builtin declaration with one that uses the same address space 5053 /// as the call. 5054 /// 5055 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5056 /// it does not contain any pointer arguments without 5057 /// an address space qualifer. Otherwise the rewritten 5058 /// FunctionDecl is returned. 5059 /// TODO: Handle pointer return types. 5060 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5061 const FunctionDecl *FDecl, 5062 MultiExprArg ArgExprs) { 5063 5064 QualType DeclType = FDecl->getType(); 5065 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5066 5067 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 5068 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 5069 return nullptr; 5070 5071 bool NeedsNewDecl = false; 5072 unsigned i = 0; 5073 SmallVector<QualType, 8> OverloadParams; 5074 5075 for (QualType ParamType : FT->param_types()) { 5076 5077 // Convert array arguments to pointer to simplify type lookup. 5078 ExprResult ArgRes = 5079 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5080 if (ArgRes.isInvalid()) 5081 return nullptr; 5082 Expr *Arg = ArgRes.get(); 5083 QualType ArgType = Arg->getType(); 5084 if (!ParamType->isPointerType() || 5085 ParamType.getQualifiers().hasAddressSpace() || 5086 !ArgType->isPointerType() || 5087 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 5088 OverloadParams.push_back(ParamType); 5089 continue; 5090 } 5091 5092 NeedsNewDecl = true; 5093 unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace(); 5094 5095 QualType PointeeType = ParamType->getPointeeType(); 5096 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5097 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5098 } 5099 5100 if (!NeedsNewDecl) 5101 return nullptr; 5102 5103 FunctionProtoType::ExtProtoInfo EPI; 5104 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5105 OverloadParams, EPI); 5106 DeclContext *Parent = Context.getTranslationUnitDecl(); 5107 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5108 FDecl->getLocation(), 5109 FDecl->getLocation(), 5110 FDecl->getIdentifier(), 5111 OverloadTy, 5112 /*TInfo=*/nullptr, 5113 SC_Extern, false, 5114 /*hasPrototype=*/true); 5115 SmallVector<ParmVarDecl*, 16> Params; 5116 FT = cast<FunctionProtoType>(OverloadTy); 5117 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5118 QualType ParamType = FT->getParamType(i); 5119 ParmVarDecl *Parm = 5120 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5121 SourceLocation(), nullptr, ParamType, 5122 /*TInfo=*/nullptr, SC_None, nullptr); 5123 Parm->setScopeInfo(0, i); 5124 Params.push_back(Parm); 5125 } 5126 OverloadDecl->setParams(Params); 5127 return OverloadDecl; 5128 } 5129 5130 static bool isNumberOfArgsValidForCall(Sema &S, const FunctionDecl *Callee, 5131 std::size_t NumArgs) { 5132 if (S.TooManyArguments(Callee->getNumParams(), NumArgs, 5133 /*PartialOverloading=*/false)) 5134 return Callee->isVariadic(); 5135 return Callee->getMinRequiredArguments() <= NumArgs; 5136 } 5137 5138 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 5139 /// This provides the location of the left/right parens and a list of comma 5140 /// locations. 5141 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5142 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5143 Expr *ExecConfig, bool IsExecConfig) { 5144 // Since this might be a postfix expression, get rid of ParenListExprs. 5145 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 5146 if (Result.isInvalid()) return ExprError(); 5147 Fn = Result.get(); 5148 5149 if (checkArgsForPlaceholders(*this, ArgExprs)) 5150 return ExprError(); 5151 5152 if (getLangOpts().CPlusPlus) { 5153 // If this is a pseudo-destructor expression, build the call immediately. 5154 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5155 if (!ArgExprs.empty()) { 5156 // Pseudo-destructor calls should not have any arguments. 5157 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 5158 << FixItHint::CreateRemoval( 5159 SourceRange(ArgExprs.front()->getLocStart(), 5160 ArgExprs.back()->getLocEnd())); 5161 } 5162 5163 return new (Context) 5164 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc); 5165 } 5166 if (Fn->getType() == Context.PseudoObjectTy) { 5167 ExprResult result = CheckPlaceholderExpr(Fn); 5168 if (result.isInvalid()) return ExprError(); 5169 Fn = result.get(); 5170 } 5171 5172 // Determine whether this is a dependent call inside a C++ template, 5173 // in which case we won't do any semantic analysis now. 5174 bool Dependent = false; 5175 if (Fn->isTypeDependent()) 5176 Dependent = true; 5177 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5178 Dependent = true; 5179 5180 if (Dependent) { 5181 if (ExecConfig) { 5182 return new (Context) CUDAKernelCallExpr( 5183 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5184 Context.DependentTy, VK_RValue, RParenLoc); 5185 } else { 5186 return new (Context) CallExpr( 5187 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5188 } 5189 } 5190 5191 // Determine whether this is a call to an object (C++ [over.call.object]). 5192 if (Fn->getType()->isRecordType()) 5193 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 5194 RParenLoc); 5195 5196 if (Fn->getType() == Context.UnknownAnyTy) { 5197 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5198 if (result.isInvalid()) return ExprError(); 5199 Fn = result.get(); 5200 } 5201 5202 if (Fn->getType() == Context.BoundMemberTy) { 5203 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5204 RParenLoc); 5205 } 5206 } 5207 5208 // Check for overloaded calls. This can happen even in C due to extensions. 5209 if (Fn->getType() == Context.OverloadTy) { 5210 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5211 5212 // We aren't supposed to apply this logic for if there'Scope an '&' 5213 // involved. 5214 if (!find.HasFormOfMemberPointer) { 5215 OverloadExpr *ovl = find.Expression; 5216 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5217 return BuildOverloadedCallExpr( 5218 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 5219 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 5220 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5221 RParenLoc); 5222 } 5223 } 5224 5225 // If we're directly calling a function, get the appropriate declaration. 5226 if (Fn->getType() == Context.UnknownAnyTy) { 5227 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5228 if (result.isInvalid()) return ExprError(); 5229 Fn = result.get(); 5230 } 5231 5232 Expr *NakedFn = Fn->IgnoreParens(); 5233 5234 bool CallingNDeclIndirectly = false; 5235 NamedDecl *NDecl = nullptr; 5236 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5237 if (UnOp->getOpcode() == UO_AddrOf) { 5238 CallingNDeclIndirectly = true; 5239 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5240 } 5241 } 5242 5243 if (isa<DeclRefExpr>(NakedFn)) { 5244 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 5245 5246 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5247 if (FDecl && FDecl->getBuiltinID()) { 5248 // Rewrite the function decl for this builtin by replacing parameters 5249 // with no explicit address space with the address space of the arguments 5250 // in ArgExprs. 5251 if ((FDecl = 5252 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5253 NDecl = FDecl; 5254 Fn = DeclRefExpr::Create( 5255 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 5256 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl); 5257 } 5258 } 5259 } else if (isa<MemberExpr>(NakedFn)) 5260 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5261 5262 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5263 if (CallingNDeclIndirectly && 5264 !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 5265 Fn->getLocStart())) 5266 return ExprError(); 5267 5268 // CheckEnableIf assumes that the we're passing in a sane number of args for 5269 // FD, but that doesn't always hold true here. This is because, in some 5270 // cases, we'll emit a diag about an ill-formed function call, but then 5271 // we'll continue on as if the function call wasn't ill-formed. So, if the 5272 // number of args looks incorrect, don't do enable_if checks; we should've 5273 // already emitted an error about the bad call. 5274 if (FD->hasAttr<EnableIfAttr>() && 5275 isNumberOfArgsValidForCall(*this, FD, ArgExprs.size())) { 5276 if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) { 5277 Diag(Fn->getLocStart(), 5278 isa<CXXMethodDecl>(FD) 5279 ? diag::err_ovl_no_viable_member_function_in_call 5280 : diag::err_ovl_no_viable_function_in_call) 5281 << FD << FD->getSourceRange(); 5282 Diag(FD->getLocation(), 5283 diag::note_ovl_candidate_disabled_by_enable_if_attr) 5284 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5285 } 5286 } 5287 } 5288 5289 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5290 ExecConfig, IsExecConfig); 5291 } 5292 5293 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5294 /// 5295 /// __builtin_astype( value, dst type ) 5296 /// 5297 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5298 SourceLocation BuiltinLoc, 5299 SourceLocation RParenLoc) { 5300 ExprValueKind VK = VK_RValue; 5301 ExprObjectKind OK = OK_Ordinary; 5302 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5303 QualType SrcTy = E->getType(); 5304 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5305 return ExprError(Diag(BuiltinLoc, 5306 diag::err_invalid_astype_of_different_size) 5307 << DstTy 5308 << SrcTy 5309 << E->getSourceRange()); 5310 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5311 } 5312 5313 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5314 /// provided arguments. 5315 /// 5316 /// __builtin_convertvector( value, dst type ) 5317 /// 5318 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5319 SourceLocation BuiltinLoc, 5320 SourceLocation RParenLoc) { 5321 TypeSourceInfo *TInfo; 5322 GetTypeFromParser(ParsedDestTy, &TInfo); 5323 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5324 } 5325 5326 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5327 /// i.e. an expression not of \p OverloadTy. The expression should 5328 /// unary-convert to an expression of function-pointer or 5329 /// block-pointer type. 5330 /// 5331 /// \param NDecl the declaration being called, if available 5332 ExprResult 5333 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5334 SourceLocation LParenLoc, 5335 ArrayRef<Expr *> Args, 5336 SourceLocation RParenLoc, 5337 Expr *Config, bool IsExecConfig) { 5338 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5339 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5340 5341 // Functions with 'interrupt' attribute cannot be called directly. 5342 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5343 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5344 return ExprError(); 5345 } 5346 5347 // Promote the function operand. 5348 // We special-case function promotion here because we only allow promoting 5349 // builtin functions to function pointers in the callee of a call. 5350 ExprResult Result; 5351 if (BuiltinID && 5352 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5353 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 5354 CK_BuiltinFnToFnPtr).get(); 5355 } else { 5356 Result = CallExprUnaryConversions(Fn); 5357 } 5358 if (Result.isInvalid()) 5359 return ExprError(); 5360 Fn = Result.get(); 5361 5362 // Make the call expr early, before semantic checks. This guarantees cleanup 5363 // of arguments and function on error. 5364 CallExpr *TheCall; 5365 if (Config) 5366 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 5367 cast<CallExpr>(Config), Args, 5368 Context.BoolTy, VK_RValue, 5369 RParenLoc); 5370 else 5371 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 5372 VK_RValue, RParenLoc); 5373 5374 if (!getLangOpts().CPlusPlus) { 5375 // C cannot always handle TypoExpr nodes in builtin calls and direct 5376 // function calls as their argument checking don't necessarily handle 5377 // dependent types properly, so make sure any TypoExprs have been 5378 // dealt with. 5379 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5380 if (!Result.isUsable()) return ExprError(); 5381 TheCall = dyn_cast<CallExpr>(Result.get()); 5382 if (!TheCall) return Result; 5383 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5384 } 5385 5386 // Bail out early if calling a builtin with custom typechecking. 5387 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5388 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5389 5390 retry: 5391 const FunctionType *FuncT; 5392 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5393 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5394 // have type pointer to function". 5395 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5396 if (!FuncT) 5397 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5398 << Fn->getType() << Fn->getSourceRange()); 5399 } else if (const BlockPointerType *BPT = 5400 Fn->getType()->getAs<BlockPointerType>()) { 5401 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5402 } else { 5403 // Handle calls to expressions of unknown-any type. 5404 if (Fn->getType() == Context.UnknownAnyTy) { 5405 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5406 if (rewrite.isInvalid()) return ExprError(); 5407 Fn = rewrite.get(); 5408 TheCall->setCallee(Fn); 5409 goto retry; 5410 } 5411 5412 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5413 << Fn->getType() << Fn->getSourceRange()); 5414 } 5415 5416 if (getLangOpts().CUDA) { 5417 if (Config) { 5418 // CUDA: Kernel calls must be to global functions 5419 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5420 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5421 << FDecl->getName() << Fn->getSourceRange()); 5422 5423 // CUDA: Kernel function must have 'void' return type 5424 if (!FuncT->getReturnType()->isVoidType()) 5425 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5426 << Fn->getType() << Fn->getSourceRange()); 5427 } else { 5428 // CUDA: Calls to global functions must be configured 5429 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5430 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5431 << FDecl->getName() << Fn->getSourceRange()); 5432 } 5433 } 5434 5435 // Check for a valid return type 5436 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall, 5437 FDecl)) 5438 return ExprError(); 5439 5440 // We know the result type of the call, set it. 5441 TheCall->setType(FuncT->getCallResultType(Context)); 5442 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5443 5444 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 5445 if (Proto) { 5446 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5447 IsExecConfig)) 5448 return ExprError(); 5449 } else { 5450 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5451 5452 if (FDecl) { 5453 // Check if we have too few/too many template arguments, based 5454 // on our knowledge of the function definition. 5455 const FunctionDecl *Def = nullptr; 5456 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5457 Proto = Def->getType()->getAs<FunctionProtoType>(); 5458 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5459 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5460 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5461 } 5462 5463 // If the function we're calling isn't a function prototype, but we have 5464 // a function prototype from a prior declaratiom, use that prototype. 5465 if (!FDecl->hasPrototype()) 5466 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5467 } 5468 5469 // Promote the arguments (C99 6.5.2.2p6). 5470 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5471 Expr *Arg = Args[i]; 5472 5473 if (Proto && i < Proto->getNumParams()) { 5474 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5475 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5476 ExprResult ArgE = 5477 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5478 if (ArgE.isInvalid()) 5479 return true; 5480 5481 Arg = ArgE.getAs<Expr>(); 5482 5483 } else { 5484 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5485 5486 if (ArgE.isInvalid()) 5487 return true; 5488 5489 Arg = ArgE.getAs<Expr>(); 5490 } 5491 5492 if (RequireCompleteType(Arg->getLocStart(), 5493 Arg->getType(), 5494 diag::err_call_incomplete_argument, Arg)) 5495 return ExprError(); 5496 5497 TheCall->setArg(i, Arg); 5498 } 5499 } 5500 5501 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5502 if (!Method->isStatic()) 5503 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5504 << Fn->getSourceRange()); 5505 5506 // Check for sentinels 5507 if (NDecl) 5508 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5509 5510 // Do special checking on direct calls to functions. 5511 if (FDecl) { 5512 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5513 return ExprError(); 5514 5515 if (BuiltinID) 5516 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5517 } else if (NDecl) { 5518 if (CheckPointerCall(NDecl, TheCall, Proto)) 5519 return ExprError(); 5520 } else { 5521 if (CheckOtherCall(TheCall, Proto)) 5522 return ExprError(); 5523 } 5524 5525 return MaybeBindToTemporary(TheCall); 5526 } 5527 5528 ExprResult 5529 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5530 SourceLocation RParenLoc, Expr *InitExpr) { 5531 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5532 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 5533 5534 TypeSourceInfo *TInfo; 5535 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5536 if (!TInfo) 5537 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5538 5539 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5540 } 5541 5542 ExprResult 5543 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5544 SourceLocation RParenLoc, Expr *LiteralExpr) { 5545 QualType literalType = TInfo->getType(); 5546 5547 if (literalType->isArrayType()) { 5548 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5549 diag::err_illegal_decl_array_incomplete_type, 5550 SourceRange(LParenLoc, 5551 LiteralExpr->getSourceRange().getEnd()))) 5552 return ExprError(); 5553 if (literalType->isVariableArrayType()) 5554 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5555 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5556 } else if (!literalType->isDependentType() && 5557 RequireCompleteType(LParenLoc, literalType, 5558 diag::err_typecheck_decl_incomplete_type, 5559 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5560 return ExprError(); 5561 5562 InitializedEntity Entity 5563 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5564 InitializationKind Kind 5565 = InitializationKind::CreateCStyleCast(LParenLoc, 5566 SourceRange(LParenLoc, RParenLoc), 5567 /*InitList=*/true); 5568 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5569 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5570 &literalType); 5571 if (Result.isInvalid()) 5572 return ExprError(); 5573 LiteralExpr = Result.get(); 5574 5575 bool isFileScope = getCurFunctionOrMethodDecl() == nullptr; 5576 if (isFileScope && 5577 !LiteralExpr->isTypeDependent() && 5578 !LiteralExpr->isValueDependent() && 5579 !literalType->isDependentType()) { // 6.5.2.5p3 5580 if (CheckForConstantInitializer(LiteralExpr, literalType)) 5581 return ExprError(); 5582 } 5583 5584 // In C, compound literals are l-values for some reason. 5585 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue; 5586 5587 return MaybeBindToTemporary( 5588 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 5589 VK, LiteralExpr, isFileScope)); 5590 } 5591 5592 ExprResult 5593 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 5594 SourceLocation RBraceLoc) { 5595 // Immediately handle non-overload placeholders. Overloads can be 5596 // resolved contextually, but everything else here can't. 5597 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 5598 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 5599 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 5600 5601 // Ignore failures; dropping the entire initializer list because 5602 // of one failure would be terrible for indexing/etc. 5603 if (result.isInvalid()) continue; 5604 5605 InitArgList[I] = result.get(); 5606 } 5607 } 5608 5609 // Semantic analysis for initializers is done by ActOnDeclarator() and 5610 // CheckInitializer() - it requires knowledge of the object being intialized. 5611 5612 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 5613 RBraceLoc); 5614 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 5615 return E; 5616 } 5617 5618 /// Do an explicit extend of the given block pointer if we're in ARC. 5619 void Sema::maybeExtendBlockObject(ExprResult &E) { 5620 assert(E.get()->getType()->isBlockPointerType()); 5621 assert(E.get()->isRValue()); 5622 5623 // Only do this in an r-value context. 5624 if (!getLangOpts().ObjCAutoRefCount) return; 5625 5626 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 5627 CK_ARCExtendBlockObject, E.get(), 5628 /*base path*/ nullptr, VK_RValue); 5629 Cleanup.setExprNeedsCleanups(true); 5630 } 5631 5632 /// Prepare a conversion of the given expression to an ObjC object 5633 /// pointer type. 5634 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 5635 QualType type = E.get()->getType(); 5636 if (type->isObjCObjectPointerType()) { 5637 return CK_BitCast; 5638 } else if (type->isBlockPointerType()) { 5639 maybeExtendBlockObject(E); 5640 return CK_BlockPointerToObjCPointerCast; 5641 } else { 5642 assert(type->isPointerType()); 5643 return CK_CPointerToObjCPointerCast; 5644 } 5645 } 5646 5647 /// Prepares for a scalar cast, performing all the necessary stages 5648 /// except the final cast and returning the kind required. 5649 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 5650 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 5651 // Also, callers should have filtered out the invalid cases with 5652 // pointers. Everything else should be possible. 5653 5654 QualType SrcTy = Src.get()->getType(); 5655 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 5656 return CK_NoOp; 5657 5658 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 5659 case Type::STK_MemberPointer: 5660 llvm_unreachable("member pointer type in C"); 5661 5662 case Type::STK_CPointer: 5663 case Type::STK_BlockPointer: 5664 case Type::STK_ObjCObjectPointer: 5665 switch (DestTy->getScalarTypeKind()) { 5666 case Type::STK_CPointer: { 5667 unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace(); 5668 unsigned DestAS = DestTy->getPointeeType().getAddressSpace(); 5669 if (SrcAS != DestAS) 5670 return CK_AddressSpaceConversion; 5671 return CK_BitCast; 5672 } 5673 case Type::STK_BlockPointer: 5674 return (SrcKind == Type::STK_BlockPointer 5675 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 5676 case Type::STK_ObjCObjectPointer: 5677 if (SrcKind == Type::STK_ObjCObjectPointer) 5678 return CK_BitCast; 5679 if (SrcKind == Type::STK_CPointer) 5680 return CK_CPointerToObjCPointerCast; 5681 maybeExtendBlockObject(Src); 5682 return CK_BlockPointerToObjCPointerCast; 5683 case Type::STK_Bool: 5684 return CK_PointerToBoolean; 5685 case Type::STK_Integral: 5686 return CK_PointerToIntegral; 5687 case Type::STK_Floating: 5688 case Type::STK_FloatingComplex: 5689 case Type::STK_IntegralComplex: 5690 case Type::STK_MemberPointer: 5691 llvm_unreachable("illegal cast from pointer"); 5692 } 5693 llvm_unreachable("Should have returned before this"); 5694 5695 case Type::STK_Bool: // casting from bool is like casting from an integer 5696 case Type::STK_Integral: 5697 switch (DestTy->getScalarTypeKind()) { 5698 case Type::STK_CPointer: 5699 case Type::STK_ObjCObjectPointer: 5700 case Type::STK_BlockPointer: 5701 if (Src.get()->isNullPointerConstant(Context, 5702 Expr::NPC_ValueDependentIsNull)) 5703 return CK_NullToPointer; 5704 return CK_IntegralToPointer; 5705 case Type::STK_Bool: 5706 return CK_IntegralToBoolean; 5707 case Type::STK_Integral: 5708 return CK_IntegralCast; 5709 case Type::STK_Floating: 5710 return CK_IntegralToFloating; 5711 case Type::STK_IntegralComplex: 5712 Src = ImpCastExprToType(Src.get(), 5713 DestTy->castAs<ComplexType>()->getElementType(), 5714 CK_IntegralCast); 5715 return CK_IntegralRealToComplex; 5716 case Type::STK_FloatingComplex: 5717 Src = ImpCastExprToType(Src.get(), 5718 DestTy->castAs<ComplexType>()->getElementType(), 5719 CK_IntegralToFloating); 5720 return CK_FloatingRealToComplex; 5721 case Type::STK_MemberPointer: 5722 llvm_unreachable("member pointer type in C"); 5723 } 5724 llvm_unreachable("Should have returned before this"); 5725 5726 case Type::STK_Floating: 5727 switch (DestTy->getScalarTypeKind()) { 5728 case Type::STK_Floating: 5729 return CK_FloatingCast; 5730 case Type::STK_Bool: 5731 return CK_FloatingToBoolean; 5732 case Type::STK_Integral: 5733 return CK_FloatingToIntegral; 5734 case Type::STK_FloatingComplex: 5735 Src = ImpCastExprToType(Src.get(), 5736 DestTy->castAs<ComplexType>()->getElementType(), 5737 CK_FloatingCast); 5738 return CK_FloatingRealToComplex; 5739 case Type::STK_IntegralComplex: 5740 Src = ImpCastExprToType(Src.get(), 5741 DestTy->castAs<ComplexType>()->getElementType(), 5742 CK_FloatingToIntegral); 5743 return CK_IntegralRealToComplex; 5744 case Type::STK_CPointer: 5745 case Type::STK_ObjCObjectPointer: 5746 case Type::STK_BlockPointer: 5747 llvm_unreachable("valid float->pointer cast?"); 5748 case Type::STK_MemberPointer: 5749 llvm_unreachable("member pointer type in C"); 5750 } 5751 llvm_unreachable("Should have returned before this"); 5752 5753 case Type::STK_FloatingComplex: 5754 switch (DestTy->getScalarTypeKind()) { 5755 case Type::STK_FloatingComplex: 5756 return CK_FloatingComplexCast; 5757 case Type::STK_IntegralComplex: 5758 return CK_FloatingComplexToIntegralComplex; 5759 case Type::STK_Floating: { 5760 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5761 if (Context.hasSameType(ET, DestTy)) 5762 return CK_FloatingComplexToReal; 5763 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 5764 return CK_FloatingCast; 5765 } 5766 case Type::STK_Bool: 5767 return CK_FloatingComplexToBoolean; 5768 case Type::STK_Integral: 5769 Src = ImpCastExprToType(Src.get(), 5770 SrcTy->castAs<ComplexType>()->getElementType(), 5771 CK_FloatingComplexToReal); 5772 return CK_FloatingToIntegral; 5773 case Type::STK_CPointer: 5774 case Type::STK_ObjCObjectPointer: 5775 case Type::STK_BlockPointer: 5776 llvm_unreachable("valid complex float->pointer cast?"); 5777 case Type::STK_MemberPointer: 5778 llvm_unreachable("member pointer type in C"); 5779 } 5780 llvm_unreachable("Should have returned before this"); 5781 5782 case Type::STK_IntegralComplex: 5783 switch (DestTy->getScalarTypeKind()) { 5784 case Type::STK_FloatingComplex: 5785 return CK_IntegralComplexToFloatingComplex; 5786 case Type::STK_IntegralComplex: 5787 return CK_IntegralComplexCast; 5788 case Type::STK_Integral: { 5789 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5790 if (Context.hasSameType(ET, DestTy)) 5791 return CK_IntegralComplexToReal; 5792 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 5793 return CK_IntegralCast; 5794 } 5795 case Type::STK_Bool: 5796 return CK_IntegralComplexToBoolean; 5797 case Type::STK_Floating: 5798 Src = ImpCastExprToType(Src.get(), 5799 SrcTy->castAs<ComplexType>()->getElementType(), 5800 CK_IntegralComplexToReal); 5801 return CK_IntegralToFloating; 5802 case Type::STK_CPointer: 5803 case Type::STK_ObjCObjectPointer: 5804 case Type::STK_BlockPointer: 5805 llvm_unreachable("valid complex int->pointer cast?"); 5806 case Type::STK_MemberPointer: 5807 llvm_unreachable("member pointer type in C"); 5808 } 5809 llvm_unreachable("Should have returned before this"); 5810 } 5811 5812 llvm_unreachable("Unhandled scalar cast"); 5813 } 5814 5815 static bool breakDownVectorType(QualType type, uint64_t &len, 5816 QualType &eltType) { 5817 // Vectors are simple. 5818 if (const VectorType *vecType = type->getAs<VectorType>()) { 5819 len = vecType->getNumElements(); 5820 eltType = vecType->getElementType(); 5821 assert(eltType->isScalarType()); 5822 return true; 5823 } 5824 5825 // We allow lax conversion to and from non-vector types, but only if 5826 // they're real types (i.e. non-complex, non-pointer scalar types). 5827 if (!type->isRealType()) return false; 5828 5829 len = 1; 5830 eltType = type; 5831 return true; 5832 } 5833 5834 /// Are the two types lax-compatible vector types? That is, given 5835 /// that one of them is a vector, do they have equal storage sizes, 5836 /// where the storage size is the number of elements times the element 5837 /// size? 5838 /// 5839 /// This will also return false if either of the types is neither a 5840 /// vector nor a real type. 5841 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 5842 assert(destTy->isVectorType() || srcTy->isVectorType()); 5843 5844 // Disallow lax conversions between scalars and ExtVectors (these 5845 // conversions are allowed for other vector types because common headers 5846 // depend on them). Most scalar OP ExtVector cases are handled by the 5847 // splat path anyway, which does what we want (convert, not bitcast). 5848 // What this rules out for ExtVectors is crazy things like char4*float. 5849 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 5850 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 5851 5852 uint64_t srcLen, destLen; 5853 QualType srcEltTy, destEltTy; 5854 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 5855 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 5856 5857 // ASTContext::getTypeSize will return the size rounded up to a 5858 // power of 2, so instead of using that, we need to use the raw 5859 // element size multiplied by the element count. 5860 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 5861 uint64_t destEltSize = Context.getTypeSize(destEltTy); 5862 5863 return (srcLen * srcEltSize == destLen * destEltSize); 5864 } 5865 5866 /// Is this a legal conversion between two types, one of which is 5867 /// known to be a vector type? 5868 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 5869 assert(destTy->isVectorType() || srcTy->isVectorType()); 5870 5871 if (!Context.getLangOpts().LaxVectorConversions) 5872 return false; 5873 return areLaxCompatibleVectorTypes(srcTy, destTy); 5874 } 5875 5876 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5877 CastKind &Kind) { 5878 assert(VectorTy->isVectorType() && "Not a vector type!"); 5879 5880 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 5881 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 5882 return Diag(R.getBegin(), 5883 Ty->isVectorType() ? 5884 diag::err_invalid_conversion_between_vectors : 5885 diag::err_invalid_conversion_between_vector_and_integer) 5886 << VectorTy << Ty << R; 5887 } else 5888 return Diag(R.getBegin(), 5889 diag::err_invalid_conversion_between_vector_and_scalar) 5890 << VectorTy << Ty << R; 5891 5892 Kind = CK_BitCast; 5893 return false; 5894 } 5895 5896 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 5897 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 5898 5899 if (DestElemTy == SplattedExpr->getType()) 5900 return SplattedExpr; 5901 5902 assert(DestElemTy->isFloatingType() || 5903 DestElemTy->isIntegralOrEnumerationType()); 5904 5905 CastKind CK; 5906 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 5907 // OpenCL requires that we convert `true` boolean expressions to -1, but 5908 // only when splatting vectors. 5909 if (DestElemTy->isFloatingType()) { 5910 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 5911 // in two steps: boolean to signed integral, then to floating. 5912 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 5913 CK_BooleanToSignedIntegral); 5914 SplattedExpr = CastExprRes.get(); 5915 CK = CK_IntegralToFloating; 5916 } else { 5917 CK = CK_BooleanToSignedIntegral; 5918 } 5919 } else { 5920 ExprResult CastExprRes = SplattedExpr; 5921 CK = PrepareScalarCast(CastExprRes, DestElemTy); 5922 if (CastExprRes.isInvalid()) 5923 return ExprError(); 5924 SplattedExpr = CastExprRes.get(); 5925 } 5926 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 5927 } 5928 5929 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 5930 Expr *CastExpr, CastKind &Kind) { 5931 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 5932 5933 QualType SrcTy = CastExpr->getType(); 5934 5935 // If SrcTy is a VectorType, the total size must match to explicitly cast to 5936 // an ExtVectorType. 5937 // In OpenCL, casts between vectors of different types are not allowed. 5938 // (See OpenCL 6.2). 5939 if (SrcTy->isVectorType()) { 5940 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) 5941 || (getLangOpts().OpenCL && 5942 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 5943 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 5944 << DestTy << SrcTy << R; 5945 return ExprError(); 5946 } 5947 Kind = CK_BitCast; 5948 return CastExpr; 5949 } 5950 5951 // All non-pointer scalars can be cast to ExtVector type. The appropriate 5952 // conversion will take place first from scalar to elt type, and then 5953 // splat from elt type to vector. 5954 if (SrcTy->isPointerType()) 5955 return Diag(R.getBegin(), 5956 diag::err_invalid_conversion_between_vector_and_scalar) 5957 << DestTy << SrcTy << R; 5958 5959 Kind = CK_VectorSplat; 5960 return prepareVectorSplat(DestTy, CastExpr); 5961 } 5962 5963 ExprResult 5964 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 5965 Declarator &D, ParsedType &Ty, 5966 SourceLocation RParenLoc, Expr *CastExpr) { 5967 assert(!D.isInvalidType() && (CastExpr != nullptr) && 5968 "ActOnCastExpr(): missing type or expr"); 5969 5970 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 5971 if (D.isInvalidType()) 5972 return ExprError(); 5973 5974 if (getLangOpts().CPlusPlus) { 5975 // Check that there are no default arguments (C++ only). 5976 CheckExtraCXXDefaultArguments(D); 5977 } else { 5978 // Make sure any TypoExprs have been dealt with. 5979 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 5980 if (!Res.isUsable()) 5981 return ExprError(); 5982 CastExpr = Res.get(); 5983 } 5984 5985 checkUnusedDeclAttributes(D); 5986 5987 QualType castType = castTInfo->getType(); 5988 Ty = CreateParsedType(castType, castTInfo); 5989 5990 bool isVectorLiteral = false; 5991 5992 // Check for an altivec or OpenCL literal, 5993 // i.e. all the elements are integer constants. 5994 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 5995 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 5996 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 5997 && castType->isVectorType() && (PE || PLE)) { 5998 if (PLE && PLE->getNumExprs() == 0) { 5999 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 6000 return ExprError(); 6001 } 6002 if (PE || PLE->getNumExprs() == 1) { 6003 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 6004 if (!E->getType()->isVectorType()) 6005 isVectorLiteral = true; 6006 } 6007 else 6008 isVectorLiteral = true; 6009 } 6010 6011 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 6012 // then handle it as such. 6013 if (isVectorLiteral) 6014 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 6015 6016 // If the Expr being casted is a ParenListExpr, handle it specially. 6017 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 6018 // sequence of BinOp comma operators. 6019 if (isa<ParenListExpr>(CastExpr)) { 6020 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 6021 if (Result.isInvalid()) return ExprError(); 6022 CastExpr = Result.get(); 6023 } 6024 6025 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6026 !getSourceManager().isInSystemMacro(LParenLoc)) 6027 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6028 6029 CheckTollFreeBridgeCast(castType, CastExpr); 6030 6031 CheckObjCBridgeRelatedCast(castType, CastExpr); 6032 6033 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 6034 6035 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6036 } 6037 6038 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6039 SourceLocation RParenLoc, Expr *E, 6040 TypeSourceInfo *TInfo) { 6041 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6042 "Expected paren or paren list expression"); 6043 6044 Expr **exprs; 6045 unsigned numExprs; 6046 Expr *subExpr; 6047 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6048 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6049 LiteralLParenLoc = PE->getLParenLoc(); 6050 LiteralRParenLoc = PE->getRParenLoc(); 6051 exprs = PE->getExprs(); 6052 numExprs = PE->getNumExprs(); 6053 } else { // isa<ParenExpr> by assertion at function entrance 6054 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6055 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6056 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6057 exprs = &subExpr; 6058 numExprs = 1; 6059 } 6060 6061 QualType Ty = TInfo->getType(); 6062 assert(Ty->isVectorType() && "Expected vector type"); 6063 6064 SmallVector<Expr *, 8> initExprs; 6065 const VectorType *VTy = Ty->getAs<VectorType>(); 6066 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 6067 6068 // '(...)' form of vector initialization in AltiVec: the number of 6069 // initializers must be one or must match the size of the vector. 6070 // If a single value is specified in the initializer then it will be 6071 // replicated to all the components of the vector 6072 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6073 // The number of initializers must be one or must match the size of the 6074 // vector. If a single value is specified in the initializer then it will 6075 // be replicated to all the components of the vector 6076 if (numExprs == 1) { 6077 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6078 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6079 if (Literal.isInvalid()) 6080 return ExprError(); 6081 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6082 PrepareScalarCast(Literal, ElemTy)); 6083 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6084 } 6085 else if (numExprs < numElems) { 6086 Diag(E->getExprLoc(), 6087 diag::err_incorrect_number_of_vector_initializers); 6088 return ExprError(); 6089 } 6090 else 6091 initExprs.append(exprs, exprs + numExprs); 6092 } 6093 else { 6094 // For OpenCL, when the number of initializers is a single value, 6095 // it will be replicated to all components of the vector. 6096 if (getLangOpts().OpenCL && 6097 VTy->getVectorKind() == VectorType::GenericVector && 6098 numExprs == 1) { 6099 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6100 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6101 if (Literal.isInvalid()) 6102 return ExprError(); 6103 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6104 PrepareScalarCast(Literal, ElemTy)); 6105 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6106 } 6107 6108 initExprs.append(exprs, exprs + numExprs); 6109 } 6110 // FIXME: This means that pretty-printing the final AST will produce curly 6111 // braces instead of the original commas. 6112 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6113 initExprs, LiteralRParenLoc); 6114 initE->setType(Ty); 6115 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6116 } 6117 6118 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6119 /// the ParenListExpr into a sequence of comma binary operators. 6120 ExprResult 6121 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6122 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6123 if (!E) 6124 return OrigExpr; 6125 6126 ExprResult Result(E->getExpr(0)); 6127 6128 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6129 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6130 E->getExpr(i)); 6131 6132 if (Result.isInvalid()) return ExprError(); 6133 6134 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6135 } 6136 6137 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6138 SourceLocation R, 6139 MultiExprArg Val) { 6140 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 6141 return expr; 6142 } 6143 6144 /// \brief Emit a specialized diagnostic when one expression is a null pointer 6145 /// constant and the other is not a pointer. Returns true if a diagnostic is 6146 /// emitted. 6147 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6148 SourceLocation QuestionLoc) { 6149 Expr *NullExpr = LHSExpr; 6150 Expr *NonPointerExpr = RHSExpr; 6151 Expr::NullPointerConstantKind NullKind = 6152 NullExpr->isNullPointerConstant(Context, 6153 Expr::NPC_ValueDependentIsNotNull); 6154 6155 if (NullKind == Expr::NPCK_NotNull) { 6156 NullExpr = RHSExpr; 6157 NonPointerExpr = LHSExpr; 6158 NullKind = 6159 NullExpr->isNullPointerConstant(Context, 6160 Expr::NPC_ValueDependentIsNotNull); 6161 } 6162 6163 if (NullKind == Expr::NPCK_NotNull) 6164 return false; 6165 6166 if (NullKind == Expr::NPCK_ZeroExpression) 6167 return false; 6168 6169 if (NullKind == Expr::NPCK_ZeroLiteral) { 6170 // In this case, check to make sure that we got here from a "NULL" 6171 // string in the source code. 6172 NullExpr = NullExpr->IgnoreParenImpCasts(); 6173 SourceLocation loc = NullExpr->getExprLoc(); 6174 if (!findMacroSpelling(loc, "NULL")) 6175 return false; 6176 } 6177 6178 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6179 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6180 << NonPointerExpr->getType() << DiagType 6181 << NonPointerExpr->getSourceRange(); 6182 return true; 6183 } 6184 6185 /// \brief Return false if the condition expression is valid, true otherwise. 6186 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6187 QualType CondTy = Cond->getType(); 6188 6189 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6190 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6191 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6192 << CondTy << Cond->getSourceRange(); 6193 return true; 6194 } 6195 6196 // C99 6.5.15p2 6197 if (CondTy->isScalarType()) return false; 6198 6199 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6200 << CondTy << Cond->getSourceRange(); 6201 return true; 6202 } 6203 6204 /// \brief Handle when one or both operands are void type. 6205 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6206 ExprResult &RHS) { 6207 Expr *LHSExpr = LHS.get(); 6208 Expr *RHSExpr = RHS.get(); 6209 6210 if (!LHSExpr->getType()->isVoidType()) 6211 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6212 << RHSExpr->getSourceRange(); 6213 if (!RHSExpr->getType()->isVoidType()) 6214 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6215 << LHSExpr->getSourceRange(); 6216 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6217 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6218 return S.Context.VoidTy; 6219 } 6220 6221 /// \brief Return false if the NullExpr can be promoted to PointerTy, 6222 /// true otherwise. 6223 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6224 QualType PointerTy) { 6225 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6226 !NullExpr.get()->isNullPointerConstant(S.Context, 6227 Expr::NPC_ValueDependentIsNull)) 6228 return true; 6229 6230 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6231 return false; 6232 } 6233 6234 /// \brief Checks compatibility between two pointers and return the resulting 6235 /// type. 6236 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6237 ExprResult &RHS, 6238 SourceLocation Loc) { 6239 QualType LHSTy = LHS.get()->getType(); 6240 QualType RHSTy = RHS.get()->getType(); 6241 6242 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6243 // Two identical pointers types are always compatible. 6244 return LHSTy; 6245 } 6246 6247 QualType lhptee, rhptee; 6248 6249 // Get the pointee types. 6250 bool IsBlockPointer = false; 6251 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6252 lhptee = LHSBTy->getPointeeType(); 6253 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6254 IsBlockPointer = true; 6255 } else { 6256 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6257 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6258 } 6259 6260 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6261 // differently qualified versions of compatible types, the result type is 6262 // a pointer to an appropriately qualified version of the composite 6263 // type. 6264 6265 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6266 // clause doesn't make sense for our extensions. E.g. address space 2 should 6267 // be incompatible with address space 3: they may live on different devices or 6268 // anything. 6269 Qualifiers lhQual = lhptee.getQualifiers(); 6270 Qualifiers rhQual = rhptee.getQualifiers(); 6271 6272 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6273 lhQual.removeCVRQualifiers(); 6274 rhQual.removeCVRQualifiers(); 6275 6276 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 6277 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 6278 6279 // For OpenCL: 6280 // 1. If LHS and RHS types match exactly and: 6281 // (a) AS match => use standard C rules, no bitcast or addrspacecast 6282 // (b) AS overlap => generate addrspacecast 6283 // (c) AS don't overlap => give an error 6284 // 2. if LHS and RHS types don't match: 6285 // (a) AS match => use standard C rules, generate bitcast 6286 // (b) AS overlap => generate addrspacecast instead of bitcast 6287 // (c) AS don't overlap => give an error 6288 6289 // For OpenCL, non-null composite type is returned only for cases 1a and 1b. 6290 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 6291 6292 // OpenCL cases 1c, 2a, 2b, and 2c. 6293 if (CompositeTy.isNull()) { 6294 // In this situation, we assume void* type. No especially good 6295 // reason, but this is what gcc does, and we do have to pick 6296 // to get a consistent AST. 6297 QualType incompatTy; 6298 if (S.getLangOpts().OpenCL) { 6299 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 6300 // spaces is disallowed. 6301 unsigned ResultAddrSpace; 6302 if (lhQual.isAddressSpaceSupersetOf(rhQual)) { 6303 // Cases 2a and 2b. 6304 ResultAddrSpace = lhQual.getAddressSpace(); 6305 } else if (rhQual.isAddressSpaceSupersetOf(lhQual)) { 6306 // Cases 2a and 2b. 6307 ResultAddrSpace = rhQual.getAddressSpace(); 6308 } else { 6309 // Cases 1c and 2c. 6310 S.Diag(Loc, 6311 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 6312 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 6313 << RHS.get()->getSourceRange(); 6314 return QualType(); 6315 } 6316 6317 // Continue handling cases 2a and 2b. 6318 incompatTy = S.Context.getPointerType( 6319 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 6320 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, 6321 (lhQual.getAddressSpace() != ResultAddrSpace) 6322 ? CK_AddressSpaceConversion /* 2b */ 6323 : CK_BitCast /* 2a */); 6324 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, 6325 (rhQual.getAddressSpace() != ResultAddrSpace) 6326 ? CK_AddressSpaceConversion /* 2b */ 6327 : CK_BitCast /* 2a */); 6328 } else { 6329 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 6330 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6331 << RHS.get()->getSourceRange(); 6332 incompatTy = S.Context.getPointerType(S.Context.VoidTy); 6333 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6334 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6335 } 6336 return incompatTy; 6337 } 6338 6339 // The pointer types are compatible. 6340 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual); 6341 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 6342 if (IsBlockPointer) 6343 ResultTy = S.Context.getBlockPointerType(ResultTy); 6344 else { 6345 // Cases 1a and 1b for OpenCL. 6346 auto ResultAddrSpace = ResultTy.getQualifiers().getAddressSpace(); 6347 LHSCastKind = lhQual.getAddressSpace() == ResultAddrSpace 6348 ? CK_BitCast /* 1a */ 6349 : CK_AddressSpaceConversion /* 1b */; 6350 RHSCastKind = rhQual.getAddressSpace() == ResultAddrSpace 6351 ? CK_BitCast /* 1a */ 6352 : CK_AddressSpaceConversion /* 1b */; 6353 ResultTy = S.Context.getPointerType(ResultTy); 6354 } 6355 6356 // For case 1a of OpenCL, S.ImpCastExprToType will not insert bitcast 6357 // if the target type does not change. 6358 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 6359 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 6360 return ResultTy; 6361 } 6362 6363 /// \brief Return the resulting type when the operands are both block pointers. 6364 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 6365 ExprResult &LHS, 6366 ExprResult &RHS, 6367 SourceLocation Loc) { 6368 QualType LHSTy = LHS.get()->getType(); 6369 QualType RHSTy = RHS.get()->getType(); 6370 6371 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 6372 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 6373 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 6374 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6375 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6376 return destType; 6377 } 6378 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 6379 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6380 << RHS.get()->getSourceRange(); 6381 return QualType(); 6382 } 6383 6384 // We have 2 block pointer types. 6385 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6386 } 6387 6388 /// \brief Return the resulting type when the operands are both pointers. 6389 static QualType 6390 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 6391 ExprResult &RHS, 6392 SourceLocation Loc) { 6393 // get the pointer types 6394 QualType LHSTy = LHS.get()->getType(); 6395 QualType RHSTy = RHS.get()->getType(); 6396 6397 // get the "pointed to" types 6398 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6399 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6400 6401 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 6402 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 6403 // Figure out necessary qualifiers (C99 6.5.15p6) 6404 QualType destPointee 6405 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6406 QualType destType = S.Context.getPointerType(destPointee); 6407 // Add qualifiers if necessary. 6408 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6409 // Promote to void*. 6410 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6411 return destType; 6412 } 6413 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 6414 QualType destPointee 6415 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6416 QualType destType = S.Context.getPointerType(destPointee); 6417 // Add qualifiers if necessary. 6418 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6419 // Promote to void*. 6420 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6421 return destType; 6422 } 6423 6424 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6425 } 6426 6427 /// \brief Return false if the first expression is not an integer and the second 6428 /// expression is not a pointer, true otherwise. 6429 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 6430 Expr* PointerExpr, SourceLocation Loc, 6431 bool IsIntFirstExpr) { 6432 if (!PointerExpr->getType()->isPointerType() || 6433 !Int.get()->getType()->isIntegerType()) 6434 return false; 6435 6436 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 6437 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 6438 6439 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 6440 << Expr1->getType() << Expr2->getType() 6441 << Expr1->getSourceRange() << Expr2->getSourceRange(); 6442 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 6443 CK_IntegralToPointer); 6444 return true; 6445 } 6446 6447 /// \brief Simple conversion between integer and floating point types. 6448 /// 6449 /// Used when handling the OpenCL conditional operator where the 6450 /// condition is a vector while the other operands are scalar. 6451 /// 6452 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 6453 /// types are either integer or floating type. Between the two 6454 /// operands, the type with the higher rank is defined as the "result 6455 /// type". The other operand needs to be promoted to the same type. No 6456 /// other type promotion is allowed. We cannot use 6457 /// UsualArithmeticConversions() for this purpose, since it always 6458 /// promotes promotable types. 6459 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 6460 ExprResult &RHS, 6461 SourceLocation QuestionLoc) { 6462 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 6463 if (LHS.isInvalid()) 6464 return QualType(); 6465 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 6466 if (RHS.isInvalid()) 6467 return QualType(); 6468 6469 // For conversion purposes, we ignore any qualifiers. 6470 // For example, "const float" and "float" are equivalent. 6471 QualType LHSType = 6472 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6473 QualType RHSType = 6474 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6475 6476 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 6477 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6478 << LHSType << LHS.get()->getSourceRange(); 6479 return QualType(); 6480 } 6481 6482 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 6483 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6484 << RHSType << RHS.get()->getSourceRange(); 6485 return QualType(); 6486 } 6487 6488 // If both types are identical, no conversion is needed. 6489 if (LHSType == RHSType) 6490 return LHSType; 6491 6492 // Now handle "real" floating types (i.e. float, double, long double). 6493 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 6494 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 6495 /*IsCompAssign = */ false); 6496 6497 // Finally, we have two differing integer types. 6498 return handleIntegerConversion<doIntegralCast, doIntegralCast> 6499 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 6500 } 6501 6502 /// \brief Convert scalar operands to a vector that matches the 6503 /// condition in length. 6504 /// 6505 /// Used when handling the OpenCL conditional operator where the 6506 /// condition is a vector while the other operands are scalar. 6507 /// 6508 /// We first compute the "result type" for the scalar operands 6509 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 6510 /// into a vector of that type where the length matches the condition 6511 /// vector type. s6.11.6 requires that the element types of the result 6512 /// and the condition must have the same number of bits. 6513 static QualType 6514 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 6515 QualType CondTy, SourceLocation QuestionLoc) { 6516 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 6517 if (ResTy.isNull()) return QualType(); 6518 6519 const VectorType *CV = CondTy->getAs<VectorType>(); 6520 assert(CV); 6521 6522 // Determine the vector result type 6523 unsigned NumElements = CV->getNumElements(); 6524 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 6525 6526 // Ensure that all types have the same number of bits 6527 if (S.Context.getTypeSize(CV->getElementType()) 6528 != S.Context.getTypeSize(ResTy)) { 6529 // Since VectorTy is created internally, it does not pretty print 6530 // with an OpenCL name. Instead, we just print a description. 6531 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 6532 SmallString<64> Str; 6533 llvm::raw_svector_ostream OS(Str); 6534 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 6535 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6536 << CondTy << OS.str(); 6537 return QualType(); 6538 } 6539 6540 // Convert operands to the vector result type 6541 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 6542 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 6543 6544 return VectorTy; 6545 } 6546 6547 /// \brief Return false if this is a valid OpenCL condition vector 6548 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 6549 SourceLocation QuestionLoc) { 6550 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 6551 // integral type. 6552 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 6553 assert(CondTy); 6554 QualType EleTy = CondTy->getElementType(); 6555 if (EleTy->isIntegerType()) return false; 6556 6557 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6558 << Cond->getType() << Cond->getSourceRange(); 6559 return true; 6560 } 6561 6562 /// \brief Return false if the vector condition type and the vector 6563 /// result type are compatible. 6564 /// 6565 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 6566 /// number of elements, and their element types have the same number 6567 /// of bits. 6568 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 6569 SourceLocation QuestionLoc) { 6570 const VectorType *CV = CondTy->getAs<VectorType>(); 6571 const VectorType *RV = VecResTy->getAs<VectorType>(); 6572 assert(CV && RV); 6573 6574 if (CV->getNumElements() != RV->getNumElements()) { 6575 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 6576 << CondTy << VecResTy; 6577 return true; 6578 } 6579 6580 QualType CVE = CV->getElementType(); 6581 QualType RVE = RV->getElementType(); 6582 6583 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 6584 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6585 << CondTy << VecResTy; 6586 return true; 6587 } 6588 6589 return false; 6590 } 6591 6592 /// \brief Return the resulting type for the conditional operator in 6593 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 6594 /// s6.3.i) when the condition is a vector type. 6595 static QualType 6596 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 6597 ExprResult &LHS, ExprResult &RHS, 6598 SourceLocation QuestionLoc) { 6599 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 6600 if (Cond.isInvalid()) 6601 return QualType(); 6602 QualType CondTy = Cond.get()->getType(); 6603 6604 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 6605 return QualType(); 6606 6607 // If either operand is a vector then find the vector type of the 6608 // result as specified in OpenCL v1.1 s6.3.i. 6609 if (LHS.get()->getType()->isVectorType() || 6610 RHS.get()->getType()->isVectorType()) { 6611 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 6612 /*isCompAssign*/false, 6613 /*AllowBothBool*/true, 6614 /*AllowBoolConversions*/false); 6615 if (VecResTy.isNull()) return QualType(); 6616 // The result type must match the condition type as specified in 6617 // OpenCL v1.1 s6.11.6. 6618 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 6619 return QualType(); 6620 return VecResTy; 6621 } 6622 6623 // Both operands are scalar. 6624 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 6625 } 6626 6627 /// \brief Return true if the Expr is block type 6628 static bool checkBlockType(Sema &S, const Expr *E) { 6629 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 6630 QualType Ty = CE->getCallee()->getType(); 6631 if (Ty->isBlockPointerType()) { 6632 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 6633 return true; 6634 } 6635 } 6636 return false; 6637 } 6638 6639 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 6640 /// In that case, LHS = cond. 6641 /// C99 6.5.15 6642 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 6643 ExprResult &RHS, ExprValueKind &VK, 6644 ExprObjectKind &OK, 6645 SourceLocation QuestionLoc) { 6646 6647 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 6648 if (!LHSResult.isUsable()) return QualType(); 6649 LHS = LHSResult; 6650 6651 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 6652 if (!RHSResult.isUsable()) return QualType(); 6653 RHS = RHSResult; 6654 6655 // C++ is sufficiently different to merit its own checker. 6656 if (getLangOpts().CPlusPlus) 6657 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 6658 6659 VK = VK_RValue; 6660 OK = OK_Ordinary; 6661 6662 // The OpenCL operator with a vector condition is sufficiently 6663 // different to merit its own checker. 6664 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 6665 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 6666 6667 // First, check the condition. 6668 Cond = UsualUnaryConversions(Cond.get()); 6669 if (Cond.isInvalid()) 6670 return QualType(); 6671 if (checkCondition(*this, Cond.get(), QuestionLoc)) 6672 return QualType(); 6673 6674 // Now check the two expressions. 6675 if (LHS.get()->getType()->isVectorType() || 6676 RHS.get()->getType()->isVectorType()) 6677 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 6678 /*AllowBothBool*/true, 6679 /*AllowBoolConversions*/false); 6680 6681 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 6682 if (LHS.isInvalid() || RHS.isInvalid()) 6683 return QualType(); 6684 6685 QualType LHSTy = LHS.get()->getType(); 6686 QualType RHSTy = RHS.get()->getType(); 6687 6688 // Diagnose attempts to convert between __float128 and long double where 6689 // such conversions currently can't be handled. 6690 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 6691 Diag(QuestionLoc, 6692 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 6693 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6694 return QualType(); 6695 } 6696 6697 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 6698 // selection operator (?:). 6699 if (getLangOpts().OpenCL && 6700 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 6701 return QualType(); 6702 } 6703 6704 // If both operands have arithmetic type, do the usual arithmetic conversions 6705 // to find a common type: C99 6.5.15p3,5. 6706 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 6707 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 6708 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 6709 6710 return ResTy; 6711 } 6712 6713 // If both operands are the same structure or union type, the result is that 6714 // type. 6715 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 6716 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 6717 if (LHSRT->getDecl() == RHSRT->getDecl()) 6718 // "If both the operands have structure or union type, the result has 6719 // that type." This implies that CV qualifiers are dropped. 6720 return LHSTy.getUnqualifiedType(); 6721 // FIXME: Type of conditional expression must be complete in C mode. 6722 } 6723 6724 // C99 6.5.15p5: "If both operands have void type, the result has void type." 6725 // The following || allows only one side to be void (a GCC-ism). 6726 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 6727 return checkConditionalVoidType(*this, LHS, RHS); 6728 } 6729 6730 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 6731 // the type of the other operand." 6732 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 6733 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 6734 6735 // All objective-c pointer type analysis is done here. 6736 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 6737 QuestionLoc); 6738 if (LHS.isInvalid() || RHS.isInvalid()) 6739 return QualType(); 6740 if (!compositeType.isNull()) 6741 return compositeType; 6742 6743 6744 // Handle block pointer types. 6745 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 6746 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 6747 QuestionLoc); 6748 6749 // Check constraints for C object pointers types (C99 6.5.15p3,6). 6750 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 6751 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 6752 QuestionLoc); 6753 6754 // GCC compatibility: soften pointer/integer mismatch. Note that 6755 // null pointers have been filtered out by this point. 6756 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 6757 /*isIntFirstExpr=*/true)) 6758 return RHSTy; 6759 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 6760 /*isIntFirstExpr=*/false)) 6761 return LHSTy; 6762 6763 // Emit a better diagnostic if one of the expressions is a null pointer 6764 // constant and the other is not a pointer type. In this case, the user most 6765 // likely forgot to take the address of the other expression. 6766 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 6767 return QualType(); 6768 6769 // Otherwise, the operands are not compatible. 6770 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 6771 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6772 << RHS.get()->getSourceRange(); 6773 return QualType(); 6774 } 6775 6776 /// FindCompositeObjCPointerType - Helper method to find composite type of 6777 /// two objective-c pointer types of the two input expressions. 6778 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 6779 SourceLocation QuestionLoc) { 6780 QualType LHSTy = LHS.get()->getType(); 6781 QualType RHSTy = RHS.get()->getType(); 6782 6783 // Handle things like Class and struct objc_class*. Here we case the result 6784 // to the pseudo-builtin, because that will be implicitly cast back to the 6785 // redefinition type if an attempt is made to access its fields. 6786 if (LHSTy->isObjCClassType() && 6787 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 6788 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6789 return LHSTy; 6790 } 6791 if (RHSTy->isObjCClassType() && 6792 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 6793 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6794 return RHSTy; 6795 } 6796 // And the same for struct objc_object* / id 6797 if (LHSTy->isObjCIdType() && 6798 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 6799 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6800 return LHSTy; 6801 } 6802 if (RHSTy->isObjCIdType() && 6803 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 6804 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6805 return RHSTy; 6806 } 6807 // And the same for struct objc_selector* / SEL 6808 if (Context.isObjCSelType(LHSTy) && 6809 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 6810 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 6811 return LHSTy; 6812 } 6813 if (Context.isObjCSelType(RHSTy) && 6814 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 6815 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 6816 return RHSTy; 6817 } 6818 // Check constraints for Objective-C object pointers types. 6819 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 6820 6821 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 6822 // Two identical object pointer types are always compatible. 6823 return LHSTy; 6824 } 6825 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 6826 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 6827 QualType compositeType = LHSTy; 6828 6829 // If both operands are interfaces and either operand can be 6830 // assigned to the other, use that type as the composite 6831 // type. This allows 6832 // xxx ? (A*) a : (B*) b 6833 // where B is a subclass of A. 6834 // 6835 // Additionally, as for assignment, if either type is 'id' 6836 // allow silent coercion. Finally, if the types are 6837 // incompatible then make sure to use 'id' as the composite 6838 // type so the result is acceptable for sending messages to. 6839 6840 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 6841 // It could return the composite type. 6842 if (!(compositeType = 6843 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 6844 // Nothing more to do. 6845 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 6846 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 6847 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 6848 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 6849 } else if ((LHSTy->isObjCQualifiedIdType() || 6850 RHSTy->isObjCQualifiedIdType()) && 6851 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 6852 // Need to handle "id<xx>" explicitly. 6853 // GCC allows qualified id and any Objective-C type to devolve to 6854 // id. Currently localizing to here until clear this should be 6855 // part of ObjCQualifiedIdTypesAreCompatible. 6856 compositeType = Context.getObjCIdType(); 6857 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 6858 compositeType = Context.getObjCIdType(); 6859 } else { 6860 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 6861 << LHSTy << RHSTy 6862 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6863 QualType incompatTy = Context.getObjCIdType(); 6864 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6865 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6866 return incompatTy; 6867 } 6868 // The object pointer types are compatible. 6869 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 6870 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 6871 return compositeType; 6872 } 6873 // Check Objective-C object pointer types and 'void *' 6874 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 6875 if (getLangOpts().ObjCAutoRefCount) { 6876 // ARC forbids the implicit conversion of object pointers to 'void *', 6877 // so these types are not compatible. 6878 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6879 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6880 LHS = RHS = true; 6881 return QualType(); 6882 } 6883 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6884 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6885 QualType destPointee 6886 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6887 QualType destType = Context.getPointerType(destPointee); 6888 // Add qualifiers if necessary. 6889 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6890 // Promote to void*. 6891 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6892 return destType; 6893 } 6894 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 6895 if (getLangOpts().ObjCAutoRefCount) { 6896 // ARC forbids the implicit conversion of object pointers to 'void *', 6897 // so these types are not compatible. 6898 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6899 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6900 LHS = RHS = true; 6901 return QualType(); 6902 } 6903 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6904 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6905 QualType destPointee 6906 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6907 QualType destType = Context.getPointerType(destPointee); 6908 // Add qualifiers if necessary. 6909 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6910 // Promote to void*. 6911 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6912 return destType; 6913 } 6914 return QualType(); 6915 } 6916 6917 /// SuggestParentheses - Emit a note with a fixit hint that wraps 6918 /// ParenRange in parentheses. 6919 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 6920 const PartialDiagnostic &Note, 6921 SourceRange ParenRange) { 6922 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 6923 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 6924 EndLoc.isValid()) { 6925 Self.Diag(Loc, Note) 6926 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 6927 << FixItHint::CreateInsertion(EndLoc, ")"); 6928 } else { 6929 // We can't display the parentheses, so just show the bare note. 6930 Self.Diag(Loc, Note) << ParenRange; 6931 } 6932 } 6933 6934 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 6935 return BinaryOperator::isAdditiveOp(Opc) || 6936 BinaryOperator::isMultiplicativeOp(Opc) || 6937 BinaryOperator::isShiftOp(Opc); 6938 } 6939 6940 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 6941 /// expression, either using a built-in or overloaded operator, 6942 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 6943 /// expression. 6944 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 6945 Expr **RHSExprs) { 6946 // Don't strip parenthesis: we should not warn if E is in parenthesis. 6947 E = E->IgnoreImpCasts(); 6948 E = E->IgnoreConversionOperator(); 6949 E = E->IgnoreImpCasts(); 6950 6951 // Built-in binary operator. 6952 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 6953 if (IsArithmeticOp(OP->getOpcode())) { 6954 *Opcode = OP->getOpcode(); 6955 *RHSExprs = OP->getRHS(); 6956 return true; 6957 } 6958 } 6959 6960 // Overloaded operator. 6961 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 6962 if (Call->getNumArgs() != 2) 6963 return false; 6964 6965 // Make sure this is really a binary operator that is safe to pass into 6966 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 6967 OverloadedOperatorKind OO = Call->getOperator(); 6968 if (OO < OO_Plus || OO > OO_Arrow || 6969 OO == OO_PlusPlus || OO == OO_MinusMinus) 6970 return false; 6971 6972 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 6973 if (IsArithmeticOp(OpKind)) { 6974 *Opcode = OpKind; 6975 *RHSExprs = Call->getArg(1); 6976 return true; 6977 } 6978 } 6979 6980 return false; 6981 } 6982 6983 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 6984 /// or is a logical expression such as (x==y) which has int type, but is 6985 /// commonly interpreted as boolean. 6986 static bool ExprLooksBoolean(Expr *E) { 6987 E = E->IgnoreParenImpCasts(); 6988 6989 if (E->getType()->isBooleanType()) 6990 return true; 6991 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 6992 return OP->isComparisonOp() || OP->isLogicalOp(); 6993 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 6994 return OP->getOpcode() == UO_LNot; 6995 if (E->getType()->isPointerType()) 6996 return true; 6997 6998 return false; 6999 } 7000 7001 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 7002 /// and binary operator are mixed in a way that suggests the programmer assumed 7003 /// the conditional operator has higher precedence, for example: 7004 /// "int x = a + someBinaryCondition ? 1 : 2". 7005 static void DiagnoseConditionalPrecedence(Sema &Self, 7006 SourceLocation OpLoc, 7007 Expr *Condition, 7008 Expr *LHSExpr, 7009 Expr *RHSExpr) { 7010 BinaryOperatorKind CondOpcode; 7011 Expr *CondRHS; 7012 7013 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 7014 return; 7015 if (!ExprLooksBoolean(CondRHS)) 7016 return; 7017 7018 // The condition is an arithmetic binary expression, with a right- 7019 // hand side that looks boolean, so warn. 7020 7021 Self.Diag(OpLoc, diag::warn_precedence_conditional) 7022 << Condition->getSourceRange() 7023 << BinaryOperator::getOpcodeStr(CondOpcode); 7024 7025 SuggestParentheses(Self, OpLoc, 7026 Self.PDiag(diag::note_precedence_silence) 7027 << BinaryOperator::getOpcodeStr(CondOpcode), 7028 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 7029 7030 SuggestParentheses(Self, OpLoc, 7031 Self.PDiag(diag::note_precedence_conditional_first), 7032 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 7033 } 7034 7035 /// Compute the nullability of a conditional expression. 7036 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 7037 QualType LHSTy, QualType RHSTy, 7038 ASTContext &Ctx) { 7039 if (!ResTy->isAnyPointerType()) 7040 return ResTy; 7041 7042 auto GetNullability = [&Ctx](QualType Ty) { 7043 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 7044 if (Kind) 7045 return *Kind; 7046 return NullabilityKind::Unspecified; 7047 }; 7048 7049 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 7050 NullabilityKind MergedKind; 7051 7052 // Compute nullability of a binary conditional expression. 7053 if (IsBin) { 7054 if (LHSKind == NullabilityKind::NonNull) 7055 MergedKind = NullabilityKind::NonNull; 7056 else 7057 MergedKind = RHSKind; 7058 // Compute nullability of a normal conditional expression. 7059 } else { 7060 if (LHSKind == NullabilityKind::Nullable || 7061 RHSKind == NullabilityKind::Nullable) 7062 MergedKind = NullabilityKind::Nullable; 7063 else if (LHSKind == NullabilityKind::NonNull) 7064 MergedKind = RHSKind; 7065 else if (RHSKind == NullabilityKind::NonNull) 7066 MergedKind = LHSKind; 7067 else 7068 MergedKind = NullabilityKind::Unspecified; 7069 } 7070 7071 // Return if ResTy already has the correct nullability. 7072 if (GetNullability(ResTy) == MergedKind) 7073 return ResTy; 7074 7075 // Strip all nullability from ResTy. 7076 while (ResTy->getNullability(Ctx)) 7077 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 7078 7079 // Create a new AttributedType with the new nullability kind. 7080 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 7081 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 7082 } 7083 7084 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7085 /// in the case of a the GNU conditional expr extension. 7086 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7087 SourceLocation ColonLoc, 7088 Expr *CondExpr, Expr *LHSExpr, 7089 Expr *RHSExpr) { 7090 if (!getLangOpts().CPlusPlus) { 7091 // C cannot handle TypoExpr nodes in the condition because it 7092 // doesn't handle dependent types properly, so make sure any TypoExprs have 7093 // been dealt with before checking the operands. 7094 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7095 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7096 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7097 7098 if (!CondResult.isUsable()) 7099 return ExprError(); 7100 7101 if (LHSExpr) { 7102 if (!LHSResult.isUsable()) 7103 return ExprError(); 7104 } 7105 7106 if (!RHSResult.isUsable()) 7107 return ExprError(); 7108 7109 CondExpr = CondResult.get(); 7110 LHSExpr = LHSResult.get(); 7111 RHSExpr = RHSResult.get(); 7112 } 7113 7114 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7115 // was the condition. 7116 OpaqueValueExpr *opaqueValue = nullptr; 7117 Expr *commonExpr = nullptr; 7118 if (!LHSExpr) { 7119 commonExpr = CondExpr; 7120 // Lower out placeholder types first. This is important so that we don't 7121 // try to capture a placeholder. This happens in few cases in C++; such 7122 // as Objective-C++'s dictionary subscripting syntax. 7123 if (commonExpr->hasPlaceholderType()) { 7124 ExprResult result = CheckPlaceholderExpr(commonExpr); 7125 if (!result.isUsable()) return ExprError(); 7126 commonExpr = result.get(); 7127 } 7128 // We usually want to apply unary conversions *before* saving, except 7129 // in the special case of a C++ l-value conditional. 7130 if (!(getLangOpts().CPlusPlus 7131 && !commonExpr->isTypeDependent() 7132 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7133 && commonExpr->isGLValue() 7134 && commonExpr->isOrdinaryOrBitFieldObject() 7135 && RHSExpr->isOrdinaryOrBitFieldObject() 7136 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7137 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7138 if (commonRes.isInvalid()) 7139 return ExprError(); 7140 commonExpr = commonRes.get(); 7141 } 7142 7143 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7144 commonExpr->getType(), 7145 commonExpr->getValueKind(), 7146 commonExpr->getObjectKind(), 7147 commonExpr); 7148 LHSExpr = CondExpr = opaqueValue; 7149 } 7150 7151 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 7152 ExprValueKind VK = VK_RValue; 7153 ExprObjectKind OK = OK_Ordinary; 7154 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7155 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7156 VK, OK, QuestionLoc); 7157 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7158 RHS.isInvalid()) 7159 return ExprError(); 7160 7161 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7162 RHS.get()); 7163 7164 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 7165 7166 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 7167 Context); 7168 7169 if (!commonExpr) 7170 return new (Context) 7171 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 7172 RHS.get(), result, VK, OK); 7173 7174 return new (Context) BinaryConditionalOperator( 7175 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 7176 ColonLoc, result, VK, OK); 7177 } 7178 7179 // checkPointerTypesForAssignment - This is a very tricky routine (despite 7180 // being closely modeled after the C99 spec:-). The odd characteristic of this 7181 // routine is it effectively iqnores the qualifiers on the top level pointee. 7182 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 7183 // FIXME: add a couple examples in this comment. 7184 static Sema::AssignConvertType 7185 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 7186 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7187 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7188 7189 // get the "pointed to" type (ignoring qualifiers at the top level) 7190 const Type *lhptee, *rhptee; 7191 Qualifiers lhq, rhq; 7192 std::tie(lhptee, lhq) = 7193 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 7194 std::tie(rhptee, rhq) = 7195 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 7196 7197 Sema::AssignConvertType ConvTy = Sema::Compatible; 7198 7199 // C99 6.5.16.1p1: This following citation is common to constraints 7200 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 7201 // qualifiers of the type *pointed to* by the right; 7202 7203 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 7204 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 7205 lhq.compatiblyIncludesObjCLifetime(rhq)) { 7206 // Ignore lifetime for further calculation. 7207 lhq.removeObjCLifetime(); 7208 rhq.removeObjCLifetime(); 7209 } 7210 7211 if (!lhq.compatiblyIncludes(rhq)) { 7212 // Treat address-space mismatches as fatal. TODO: address subspaces 7213 if (!lhq.isAddressSpaceSupersetOf(rhq)) 7214 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7215 7216 // It's okay to add or remove GC or lifetime qualifiers when converting to 7217 // and from void*. 7218 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 7219 .compatiblyIncludes( 7220 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 7221 && (lhptee->isVoidType() || rhptee->isVoidType())) 7222 ; // keep old 7223 7224 // Treat lifetime mismatches as fatal. 7225 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 7226 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7227 7228 // For GCC/MS compatibility, other qualifier mismatches are treated 7229 // as still compatible in C. 7230 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7231 } 7232 7233 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 7234 // incomplete type and the other is a pointer to a qualified or unqualified 7235 // version of void... 7236 if (lhptee->isVoidType()) { 7237 if (rhptee->isIncompleteOrObjectType()) 7238 return ConvTy; 7239 7240 // As an extension, we allow cast to/from void* to function pointer. 7241 assert(rhptee->isFunctionType()); 7242 return Sema::FunctionVoidPointer; 7243 } 7244 7245 if (rhptee->isVoidType()) { 7246 if (lhptee->isIncompleteOrObjectType()) 7247 return ConvTy; 7248 7249 // As an extension, we allow cast to/from void* to function pointer. 7250 assert(lhptee->isFunctionType()); 7251 return Sema::FunctionVoidPointer; 7252 } 7253 7254 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7255 // unqualified versions of compatible types, ... 7256 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7257 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7258 // Check if the pointee types are compatible ignoring the sign. 7259 // We explicitly check for char so that we catch "char" vs 7260 // "unsigned char" on systems where "char" is unsigned. 7261 if (lhptee->isCharType()) 7262 ltrans = S.Context.UnsignedCharTy; 7263 else if (lhptee->hasSignedIntegerRepresentation()) 7264 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7265 7266 if (rhptee->isCharType()) 7267 rtrans = S.Context.UnsignedCharTy; 7268 else if (rhptee->hasSignedIntegerRepresentation()) 7269 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 7270 7271 if (ltrans == rtrans) { 7272 // Types are compatible ignoring the sign. Qualifier incompatibility 7273 // takes priority over sign incompatibility because the sign 7274 // warning can be disabled. 7275 if (ConvTy != Sema::Compatible) 7276 return ConvTy; 7277 7278 return Sema::IncompatiblePointerSign; 7279 } 7280 7281 // If we are a multi-level pointer, it's possible that our issue is simply 7282 // one of qualification - e.g. char ** -> const char ** is not allowed. If 7283 // the eventual target type is the same and the pointers have the same 7284 // level of indirection, this must be the issue. 7285 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 7286 do { 7287 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 7288 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 7289 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 7290 7291 if (lhptee == rhptee) 7292 return Sema::IncompatibleNestedPointerQualifiers; 7293 } 7294 7295 // General pointer incompatibility takes priority over qualifiers. 7296 return Sema::IncompatiblePointer; 7297 } 7298 if (!S.getLangOpts().CPlusPlus && 7299 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 7300 return Sema::IncompatiblePointer; 7301 return ConvTy; 7302 } 7303 7304 /// checkBlockPointerTypesForAssignment - This routine determines whether two 7305 /// block pointer types are compatible or whether a block and normal pointer 7306 /// are compatible. It is more restrict than comparing two function pointer 7307 // types. 7308 static Sema::AssignConvertType 7309 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 7310 QualType RHSType) { 7311 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7312 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7313 7314 QualType lhptee, rhptee; 7315 7316 // get the "pointed to" type (ignoring qualifiers at the top level) 7317 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 7318 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 7319 7320 // In C++, the types have to match exactly. 7321 if (S.getLangOpts().CPlusPlus) 7322 return Sema::IncompatibleBlockPointer; 7323 7324 Sema::AssignConvertType ConvTy = Sema::Compatible; 7325 7326 // For blocks we enforce that qualifiers are identical. 7327 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers()) 7328 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7329 7330 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 7331 return Sema::IncompatibleBlockPointer; 7332 7333 return ConvTy; 7334 } 7335 7336 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 7337 /// for assignment compatibility. 7338 static Sema::AssignConvertType 7339 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 7340 QualType RHSType) { 7341 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 7342 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 7343 7344 if (LHSType->isObjCBuiltinType()) { 7345 // Class is not compatible with ObjC object pointers. 7346 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 7347 !RHSType->isObjCQualifiedClassType()) 7348 return Sema::IncompatiblePointer; 7349 return Sema::Compatible; 7350 } 7351 if (RHSType->isObjCBuiltinType()) { 7352 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 7353 !LHSType->isObjCQualifiedClassType()) 7354 return Sema::IncompatiblePointer; 7355 return Sema::Compatible; 7356 } 7357 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7358 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7359 7360 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 7361 // make an exception for id<P> 7362 !LHSType->isObjCQualifiedIdType()) 7363 return Sema::CompatiblePointerDiscardsQualifiers; 7364 7365 if (S.Context.typesAreCompatible(LHSType, RHSType)) 7366 return Sema::Compatible; 7367 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 7368 return Sema::IncompatibleObjCQualifiedId; 7369 return Sema::IncompatiblePointer; 7370 } 7371 7372 Sema::AssignConvertType 7373 Sema::CheckAssignmentConstraints(SourceLocation Loc, 7374 QualType LHSType, QualType RHSType) { 7375 // Fake up an opaque expression. We don't actually care about what 7376 // cast operations are required, so if CheckAssignmentConstraints 7377 // adds casts to this they'll be wasted, but fortunately that doesn't 7378 // usually happen on valid code. 7379 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 7380 ExprResult RHSPtr = &RHSExpr; 7381 CastKind K = CK_Invalid; 7382 7383 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 7384 } 7385 7386 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 7387 /// has code to accommodate several GCC extensions when type checking 7388 /// pointers. Here are some objectionable examples that GCC considers warnings: 7389 /// 7390 /// int a, *pint; 7391 /// short *pshort; 7392 /// struct foo *pfoo; 7393 /// 7394 /// pint = pshort; // warning: assignment from incompatible pointer type 7395 /// a = pint; // warning: assignment makes integer from pointer without a cast 7396 /// pint = a; // warning: assignment makes pointer from integer without a cast 7397 /// pint = pfoo; // warning: assignment from incompatible pointer type 7398 /// 7399 /// As a result, the code for dealing with pointers is more complex than the 7400 /// C99 spec dictates. 7401 /// 7402 /// Sets 'Kind' for any result kind except Incompatible. 7403 Sema::AssignConvertType 7404 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 7405 CastKind &Kind, bool ConvertRHS) { 7406 QualType RHSType = RHS.get()->getType(); 7407 QualType OrigLHSType = LHSType; 7408 7409 // Get canonical types. We're not formatting these types, just comparing 7410 // them. 7411 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 7412 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 7413 7414 // Common case: no conversion required. 7415 if (LHSType == RHSType) { 7416 Kind = CK_NoOp; 7417 return Compatible; 7418 } 7419 7420 // If we have an atomic type, try a non-atomic assignment, then just add an 7421 // atomic qualification step. 7422 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 7423 Sema::AssignConvertType result = 7424 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 7425 if (result != Compatible) 7426 return result; 7427 if (Kind != CK_NoOp && ConvertRHS) 7428 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 7429 Kind = CK_NonAtomicToAtomic; 7430 return Compatible; 7431 } 7432 7433 // If the left-hand side is a reference type, then we are in a 7434 // (rare!) case where we've allowed the use of references in C, 7435 // e.g., as a parameter type in a built-in function. In this case, 7436 // just make sure that the type referenced is compatible with the 7437 // right-hand side type. The caller is responsible for adjusting 7438 // LHSType so that the resulting expression does not have reference 7439 // type. 7440 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 7441 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 7442 Kind = CK_LValueBitCast; 7443 return Compatible; 7444 } 7445 return Incompatible; 7446 } 7447 7448 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 7449 // to the same ExtVector type. 7450 if (LHSType->isExtVectorType()) { 7451 if (RHSType->isExtVectorType()) 7452 return Incompatible; 7453 if (RHSType->isArithmeticType()) { 7454 // CK_VectorSplat does T -> vector T, so first cast to the element type. 7455 if (ConvertRHS) 7456 RHS = prepareVectorSplat(LHSType, RHS.get()); 7457 Kind = CK_VectorSplat; 7458 return Compatible; 7459 } 7460 } 7461 7462 // Conversions to or from vector type. 7463 if (LHSType->isVectorType() || RHSType->isVectorType()) { 7464 if (LHSType->isVectorType() && RHSType->isVectorType()) { 7465 // Allow assignments of an AltiVec vector type to an equivalent GCC 7466 // vector type and vice versa 7467 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7468 Kind = CK_BitCast; 7469 return Compatible; 7470 } 7471 7472 // If we are allowing lax vector conversions, and LHS and RHS are both 7473 // vectors, the total size only needs to be the same. This is a bitcast; 7474 // no bits are changed but the result type is different. 7475 if (isLaxVectorConversion(RHSType, LHSType)) { 7476 Kind = CK_BitCast; 7477 return IncompatibleVectors; 7478 } 7479 } 7480 7481 // When the RHS comes from another lax conversion (e.g. binops between 7482 // scalars and vectors) the result is canonicalized as a vector. When the 7483 // LHS is also a vector, the lax is allowed by the condition above. Handle 7484 // the case where LHS is a scalar. 7485 if (LHSType->isScalarType()) { 7486 const VectorType *VecType = RHSType->getAs<VectorType>(); 7487 if (VecType && VecType->getNumElements() == 1 && 7488 isLaxVectorConversion(RHSType, LHSType)) { 7489 ExprResult *VecExpr = &RHS; 7490 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 7491 Kind = CK_BitCast; 7492 return Compatible; 7493 } 7494 } 7495 7496 return Incompatible; 7497 } 7498 7499 // Diagnose attempts to convert between __float128 and long double where 7500 // such conversions currently can't be handled. 7501 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 7502 return Incompatible; 7503 7504 // Arithmetic conversions. 7505 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 7506 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 7507 if (ConvertRHS) 7508 Kind = PrepareScalarCast(RHS, LHSType); 7509 return Compatible; 7510 } 7511 7512 // Conversions to normal pointers. 7513 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 7514 // U* -> T* 7515 if (isa<PointerType>(RHSType)) { 7516 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7517 unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 7518 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7519 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 7520 } 7521 7522 // int -> T* 7523 if (RHSType->isIntegerType()) { 7524 Kind = CK_IntegralToPointer; // FIXME: null? 7525 return IntToPointer; 7526 } 7527 7528 // C pointers are not compatible with ObjC object pointers, 7529 // with two exceptions: 7530 if (isa<ObjCObjectPointerType>(RHSType)) { 7531 // - conversions to void* 7532 if (LHSPointer->getPointeeType()->isVoidType()) { 7533 Kind = CK_BitCast; 7534 return Compatible; 7535 } 7536 7537 // - conversions from 'Class' to the redefinition type 7538 if (RHSType->isObjCClassType() && 7539 Context.hasSameType(LHSType, 7540 Context.getObjCClassRedefinitionType())) { 7541 Kind = CK_BitCast; 7542 return Compatible; 7543 } 7544 7545 Kind = CK_BitCast; 7546 return IncompatiblePointer; 7547 } 7548 7549 // U^ -> void* 7550 if (RHSType->getAs<BlockPointerType>()) { 7551 if (LHSPointer->getPointeeType()->isVoidType()) { 7552 Kind = CK_BitCast; 7553 return Compatible; 7554 } 7555 } 7556 7557 return Incompatible; 7558 } 7559 7560 // Conversions to block pointers. 7561 if (isa<BlockPointerType>(LHSType)) { 7562 // U^ -> T^ 7563 if (RHSType->isBlockPointerType()) { 7564 Kind = CK_BitCast; 7565 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 7566 } 7567 7568 // int or null -> T^ 7569 if (RHSType->isIntegerType()) { 7570 Kind = CK_IntegralToPointer; // FIXME: null 7571 return IntToBlockPointer; 7572 } 7573 7574 // id -> T^ 7575 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 7576 Kind = CK_AnyPointerToBlockPointerCast; 7577 return Compatible; 7578 } 7579 7580 // void* -> T^ 7581 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 7582 if (RHSPT->getPointeeType()->isVoidType()) { 7583 Kind = CK_AnyPointerToBlockPointerCast; 7584 return Compatible; 7585 } 7586 7587 return Incompatible; 7588 } 7589 7590 // Conversions to Objective-C pointers. 7591 if (isa<ObjCObjectPointerType>(LHSType)) { 7592 // A* -> B* 7593 if (RHSType->isObjCObjectPointerType()) { 7594 Kind = CK_BitCast; 7595 Sema::AssignConvertType result = 7596 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 7597 if (getLangOpts().ObjCAutoRefCount && 7598 result == Compatible && 7599 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 7600 result = IncompatibleObjCWeakRef; 7601 return result; 7602 } 7603 7604 // int or null -> A* 7605 if (RHSType->isIntegerType()) { 7606 Kind = CK_IntegralToPointer; // FIXME: null 7607 return IntToPointer; 7608 } 7609 7610 // In general, C pointers are not compatible with ObjC object pointers, 7611 // with two exceptions: 7612 if (isa<PointerType>(RHSType)) { 7613 Kind = CK_CPointerToObjCPointerCast; 7614 7615 // - conversions from 'void*' 7616 if (RHSType->isVoidPointerType()) { 7617 return Compatible; 7618 } 7619 7620 // - conversions to 'Class' from its redefinition type 7621 if (LHSType->isObjCClassType() && 7622 Context.hasSameType(RHSType, 7623 Context.getObjCClassRedefinitionType())) { 7624 return Compatible; 7625 } 7626 7627 return IncompatiblePointer; 7628 } 7629 7630 // Only under strict condition T^ is compatible with an Objective-C pointer. 7631 if (RHSType->isBlockPointerType() && 7632 LHSType->isBlockCompatibleObjCPointerType(Context)) { 7633 if (ConvertRHS) 7634 maybeExtendBlockObject(RHS); 7635 Kind = CK_BlockPointerToObjCPointerCast; 7636 return Compatible; 7637 } 7638 7639 return Incompatible; 7640 } 7641 7642 // Conversions from pointers that are not covered by the above. 7643 if (isa<PointerType>(RHSType)) { 7644 // T* -> _Bool 7645 if (LHSType == Context.BoolTy) { 7646 Kind = CK_PointerToBoolean; 7647 return Compatible; 7648 } 7649 7650 // T* -> int 7651 if (LHSType->isIntegerType()) { 7652 Kind = CK_PointerToIntegral; 7653 return PointerToInt; 7654 } 7655 7656 return Incompatible; 7657 } 7658 7659 // Conversions from Objective-C pointers that are not covered by the above. 7660 if (isa<ObjCObjectPointerType>(RHSType)) { 7661 // T* -> _Bool 7662 if (LHSType == Context.BoolTy) { 7663 Kind = CK_PointerToBoolean; 7664 return Compatible; 7665 } 7666 7667 // T* -> int 7668 if (LHSType->isIntegerType()) { 7669 Kind = CK_PointerToIntegral; 7670 return PointerToInt; 7671 } 7672 7673 return Incompatible; 7674 } 7675 7676 // struct A -> struct B 7677 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 7678 if (Context.typesAreCompatible(LHSType, RHSType)) { 7679 Kind = CK_NoOp; 7680 return Compatible; 7681 } 7682 } 7683 7684 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 7685 Kind = CK_IntToOCLSampler; 7686 return Compatible; 7687 } 7688 7689 return Incompatible; 7690 } 7691 7692 /// \brief Constructs a transparent union from an expression that is 7693 /// used to initialize the transparent union. 7694 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 7695 ExprResult &EResult, QualType UnionType, 7696 FieldDecl *Field) { 7697 // Build an initializer list that designates the appropriate member 7698 // of the transparent union. 7699 Expr *E = EResult.get(); 7700 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 7701 E, SourceLocation()); 7702 Initializer->setType(UnionType); 7703 Initializer->setInitializedFieldInUnion(Field); 7704 7705 // Build a compound literal constructing a value of the transparent 7706 // union type from this initializer list. 7707 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 7708 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 7709 VK_RValue, Initializer, false); 7710 } 7711 7712 Sema::AssignConvertType 7713 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 7714 ExprResult &RHS) { 7715 QualType RHSType = RHS.get()->getType(); 7716 7717 // If the ArgType is a Union type, we want to handle a potential 7718 // transparent_union GCC extension. 7719 const RecordType *UT = ArgType->getAsUnionType(); 7720 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 7721 return Incompatible; 7722 7723 // The field to initialize within the transparent union. 7724 RecordDecl *UD = UT->getDecl(); 7725 FieldDecl *InitField = nullptr; 7726 // It's compatible if the expression matches any of the fields. 7727 for (auto *it : UD->fields()) { 7728 if (it->getType()->isPointerType()) { 7729 // If the transparent union contains a pointer type, we allow: 7730 // 1) void pointer 7731 // 2) null pointer constant 7732 if (RHSType->isPointerType()) 7733 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 7734 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 7735 InitField = it; 7736 break; 7737 } 7738 7739 if (RHS.get()->isNullPointerConstant(Context, 7740 Expr::NPC_ValueDependentIsNull)) { 7741 RHS = ImpCastExprToType(RHS.get(), it->getType(), 7742 CK_NullToPointer); 7743 InitField = it; 7744 break; 7745 } 7746 } 7747 7748 CastKind Kind = CK_Invalid; 7749 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 7750 == Compatible) { 7751 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 7752 InitField = it; 7753 break; 7754 } 7755 } 7756 7757 if (!InitField) 7758 return Incompatible; 7759 7760 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 7761 return Compatible; 7762 } 7763 7764 Sema::AssignConvertType 7765 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 7766 bool Diagnose, 7767 bool DiagnoseCFAudited, 7768 bool ConvertRHS) { 7769 // We need to be able to tell the caller whether we diagnosed a problem, if 7770 // they ask us to issue diagnostics. 7771 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 7772 7773 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 7774 // we can't avoid *all* modifications at the moment, so we need some somewhere 7775 // to put the updated value. 7776 ExprResult LocalRHS = CallerRHS; 7777 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 7778 7779 if (getLangOpts().CPlusPlus) { 7780 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 7781 // C++ 5.17p3: If the left operand is not of class type, the 7782 // expression is implicitly converted (C++ 4) to the 7783 // cv-unqualified type of the left operand. 7784 QualType RHSType = RHS.get()->getType(); 7785 if (Diagnose) { 7786 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7787 AA_Assigning); 7788 } else { 7789 ImplicitConversionSequence ICS = 7790 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7791 /*SuppressUserConversions=*/false, 7792 /*AllowExplicit=*/false, 7793 /*InOverloadResolution=*/false, 7794 /*CStyle=*/false, 7795 /*AllowObjCWritebackConversion=*/false); 7796 if (ICS.isFailure()) 7797 return Incompatible; 7798 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7799 ICS, AA_Assigning); 7800 } 7801 if (RHS.isInvalid()) 7802 return Incompatible; 7803 Sema::AssignConvertType result = Compatible; 7804 if (getLangOpts().ObjCAutoRefCount && 7805 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 7806 result = IncompatibleObjCWeakRef; 7807 return result; 7808 } 7809 7810 // FIXME: Currently, we fall through and treat C++ classes like C 7811 // structures. 7812 // FIXME: We also fall through for atomics; not sure what should 7813 // happen there, though. 7814 } else if (RHS.get()->getType() == Context.OverloadTy) { 7815 // As a set of extensions to C, we support overloading on functions. These 7816 // functions need to be resolved here. 7817 DeclAccessPair DAP; 7818 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 7819 RHS.get(), LHSType, /*Complain=*/false, DAP)) 7820 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 7821 else 7822 return Incompatible; 7823 } 7824 7825 // C99 6.5.16.1p1: the left operand is a pointer and the right is 7826 // a null pointer constant. 7827 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 7828 LHSType->isBlockPointerType()) && 7829 RHS.get()->isNullPointerConstant(Context, 7830 Expr::NPC_ValueDependentIsNull)) { 7831 if (Diagnose || ConvertRHS) { 7832 CastKind Kind; 7833 CXXCastPath Path; 7834 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 7835 /*IgnoreBaseAccess=*/false, Diagnose); 7836 if (ConvertRHS) 7837 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 7838 } 7839 return Compatible; 7840 } 7841 7842 // This check seems unnatural, however it is necessary to ensure the proper 7843 // conversion of functions/arrays. If the conversion were done for all 7844 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 7845 // expressions that suppress this implicit conversion (&, sizeof). 7846 // 7847 // Suppress this for references: C++ 8.5.3p5. 7848 if (!LHSType->isReferenceType()) { 7849 // FIXME: We potentially allocate here even if ConvertRHS is false. 7850 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 7851 if (RHS.isInvalid()) 7852 return Incompatible; 7853 } 7854 7855 Expr *PRE = RHS.get()->IgnoreParenCasts(); 7856 if (Diagnose && isa<ObjCProtocolExpr>(PRE)) { 7857 ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol(); 7858 if (PDecl && !PDecl->hasDefinition()) { 7859 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName(); 7860 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl; 7861 } 7862 } 7863 7864 CastKind Kind = CK_Invalid; 7865 Sema::AssignConvertType result = 7866 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 7867 7868 // C99 6.5.16.1p2: The value of the right operand is converted to the 7869 // type of the assignment expression. 7870 // CheckAssignmentConstraints allows the left-hand side to be a reference, 7871 // so that we can use references in built-in functions even in C. 7872 // The getNonReferenceType() call makes sure that the resulting expression 7873 // does not have reference type. 7874 if (result != Incompatible && RHS.get()->getType() != LHSType) { 7875 QualType Ty = LHSType.getNonLValueExprType(Context); 7876 Expr *E = RHS.get(); 7877 7878 // Check for various Objective-C errors. If we are not reporting 7879 // diagnostics and just checking for errors, e.g., during overload 7880 // resolution, return Incompatible to indicate the failure. 7881 if (getLangOpts().ObjCAutoRefCount && 7882 CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 7883 Diagnose, DiagnoseCFAudited) != ACR_okay) { 7884 if (!Diagnose) 7885 return Incompatible; 7886 } 7887 if (getLangOpts().ObjC1 && 7888 (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType, 7889 E->getType(), E, Diagnose) || 7890 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 7891 if (!Diagnose) 7892 return Incompatible; 7893 // Replace the expression with a corrected version and continue so we 7894 // can find further errors. 7895 RHS = E; 7896 return Compatible; 7897 } 7898 7899 if (ConvertRHS) 7900 RHS = ImpCastExprToType(E, Ty, Kind); 7901 } 7902 return result; 7903 } 7904 7905 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 7906 ExprResult &RHS) { 7907 Diag(Loc, diag::err_typecheck_invalid_operands) 7908 << LHS.get()->getType() << RHS.get()->getType() 7909 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7910 return QualType(); 7911 } 7912 7913 /// Try to convert a value of non-vector type to a vector type by converting 7914 /// the type to the element type of the vector and then performing a splat. 7915 /// If the language is OpenCL, we only use conversions that promote scalar 7916 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 7917 /// for float->int. 7918 /// 7919 /// \param scalar - if non-null, actually perform the conversions 7920 /// \return true if the operation fails (but without diagnosing the failure) 7921 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 7922 QualType scalarTy, 7923 QualType vectorEltTy, 7924 QualType vectorTy) { 7925 // The conversion to apply to the scalar before splatting it, 7926 // if necessary. 7927 CastKind scalarCast = CK_Invalid; 7928 7929 if (vectorEltTy->isIntegralType(S.Context)) { 7930 if (!scalarTy->isIntegralType(S.Context)) 7931 return true; 7932 if (S.getLangOpts().OpenCL && 7933 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0) 7934 return true; 7935 scalarCast = CK_IntegralCast; 7936 } else if (vectorEltTy->isRealFloatingType()) { 7937 if (scalarTy->isRealFloatingType()) { 7938 if (S.getLangOpts().OpenCL && 7939 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) 7940 return true; 7941 scalarCast = CK_FloatingCast; 7942 } 7943 else if (scalarTy->isIntegralType(S.Context)) 7944 scalarCast = CK_IntegralToFloating; 7945 else 7946 return true; 7947 } else { 7948 return true; 7949 } 7950 7951 // Adjust scalar if desired. 7952 if (scalar) { 7953 if (scalarCast != CK_Invalid) 7954 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 7955 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 7956 } 7957 return false; 7958 } 7959 7960 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 7961 SourceLocation Loc, bool IsCompAssign, 7962 bool AllowBothBool, 7963 bool AllowBoolConversions) { 7964 if (!IsCompAssign) { 7965 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 7966 if (LHS.isInvalid()) 7967 return QualType(); 7968 } 7969 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 7970 if (RHS.isInvalid()) 7971 return QualType(); 7972 7973 // For conversion purposes, we ignore any qualifiers. 7974 // For example, "const float" and "float" are equivalent. 7975 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 7976 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 7977 7978 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 7979 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 7980 assert(LHSVecType || RHSVecType); 7981 7982 // AltiVec-style "vector bool op vector bool" combinations are allowed 7983 // for some operators but not others. 7984 if (!AllowBothBool && 7985 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 7986 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 7987 return InvalidOperands(Loc, LHS, RHS); 7988 7989 // If the vector types are identical, return. 7990 if (Context.hasSameType(LHSType, RHSType)) 7991 return LHSType; 7992 7993 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 7994 if (LHSVecType && RHSVecType && 7995 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7996 if (isa<ExtVectorType>(LHSVecType)) { 7997 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 7998 return LHSType; 7999 } 8000 8001 if (!IsCompAssign) 8002 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8003 return RHSType; 8004 } 8005 8006 // AllowBoolConversions says that bool and non-bool AltiVec vectors 8007 // can be mixed, with the result being the non-bool type. The non-bool 8008 // operand must have integer element type. 8009 if (AllowBoolConversions && LHSVecType && RHSVecType && 8010 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 8011 (Context.getTypeSize(LHSVecType->getElementType()) == 8012 Context.getTypeSize(RHSVecType->getElementType()))) { 8013 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 8014 LHSVecType->getElementType()->isIntegerType() && 8015 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 8016 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8017 return LHSType; 8018 } 8019 if (!IsCompAssign && 8020 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8021 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 8022 RHSVecType->getElementType()->isIntegerType()) { 8023 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8024 return RHSType; 8025 } 8026 } 8027 8028 // If there's an ext-vector type and a scalar, try to convert the scalar to 8029 // the vector element type and splat. 8030 // FIXME: this should also work for regular vector types as supported in GCC. 8031 if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) { 8032 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 8033 LHSVecType->getElementType(), LHSType)) 8034 return LHSType; 8035 } 8036 if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) { 8037 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 8038 LHSType, RHSVecType->getElementType(), 8039 RHSType)) 8040 return RHSType; 8041 } 8042 8043 // FIXME: The code below also handles convertion between vectors and 8044 // non-scalars, we should break this down into fine grained specific checks 8045 // and emit proper diagnostics. 8046 QualType VecType = LHSVecType ? LHSType : RHSType; 8047 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 8048 QualType OtherType = LHSVecType ? RHSType : LHSType; 8049 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 8050 if (isLaxVectorConversion(OtherType, VecType)) { 8051 // If we're allowing lax vector conversions, only the total (data) size 8052 // needs to be the same. For non compound assignment, if one of the types is 8053 // scalar, the result is always the vector type. 8054 if (!IsCompAssign) { 8055 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 8056 return VecType; 8057 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 8058 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 8059 // type. Note that this is already done by non-compound assignments in 8060 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 8061 // <1 x T> -> T. The result is also a vector type. 8062 } else if (OtherType->isExtVectorType() || 8063 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 8064 ExprResult *RHSExpr = &RHS; 8065 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 8066 return VecType; 8067 } 8068 } 8069 8070 // Okay, the expression is invalid. 8071 8072 // If there's a non-vector, non-real operand, diagnose that. 8073 if ((!RHSVecType && !RHSType->isRealType()) || 8074 (!LHSVecType && !LHSType->isRealType())) { 8075 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 8076 << LHSType << RHSType 8077 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8078 return QualType(); 8079 } 8080 8081 // OpenCL V1.1 6.2.6.p1: 8082 // If the operands are of more than one vector type, then an error shall 8083 // occur. Implicit conversions between vector types are not permitted, per 8084 // section 6.2.1. 8085 if (getLangOpts().OpenCL && 8086 RHSVecType && isa<ExtVectorType>(RHSVecType) && 8087 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 8088 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 8089 << RHSType; 8090 return QualType(); 8091 } 8092 8093 // Otherwise, use the generic diagnostic. 8094 Diag(Loc, diag::err_typecheck_vector_not_convertable) 8095 << LHSType << RHSType 8096 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8097 return QualType(); 8098 } 8099 8100 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 8101 // expression. These are mainly cases where the null pointer is used as an 8102 // integer instead of a pointer. 8103 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 8104 SourceLocation Loc, bool IsCompare) { 8105 // The canonical way to check for a GNU null is with isNullPointerConstant, 8106 // but we use a bit of a hack here for speed; this is a relatively 8107 // hot path, and isNullPointerConstant is slow. 8108 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 8109 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 8110 8111 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 8112 8113 // Avoid analyzing cases where the result will either be invalid (and 8114 // diagnosed as such) or entirely valid and not something to warn about. 8115 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 8116 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 8117 return; 8118 8119 // Comparison operations would not make sense with a null pointer no matter 8120 // what the other expression is. 8121 if (!IsCompare) { 8122 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 8123 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 8124 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 8125 return; 8126 } 8127 8128 // The rest of the operations only make sense with a null pointer 8129 // if the other expression is a pointer. 8130 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 8131 NonNullType->canDecayToPointerType()) 8132 return; 8133 8134 S.Diag(Loc, diag::warn_null_in_comparison_operation) 8135 << LHSNull /* LHS is NULL */ << NonNullType 8136 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8137 } 8138 8139 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 8140 ExprResult &RHS, 8141 SourceLocation Loc, bool IsDiv) { 8142 // Check for division/remainder by zero. 8143 llvm::APSInt RHSValue; 8144 if (!RHS.get()->isValueDependent() && 8145 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0) 8146 S.DiagRuntimeBehavior(Loc, RHS.get(), 8147 S.PDiag(diag::warn_remainder_division_by_zero) 8148 << IsDiv << RHS.get()->getSourceRange()); 8149 } 8150 8151 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 8152 SourceLocation Loc, 8153 bool IsCompAssign, bool IsDiv) { 8154 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8155 8156 if (LHS.get()->getType()->isVectorType() || 8157 RHS.get()->getType()->isVectorType()) 8158 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8159 /*AllowBothBool*/getLangOpts().AltiVec, 8160 /*AllowBoolConversions*/false); 8161 8162 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8163 if (LHS.isInvalid() || RHS.isInvalid()) 8164 return QualType(); 8165 8166 8167 if (compType.isNull() || !compType->isArithmeticType()) 8168 return InvalidOperands(Loc, LHS, RHS); 8169 if (IsDiv) 8170 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 8171 return compType; 8172 } 8173 8174 QualType Sema::CheckRemainderOperands( 8175 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 8176 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8177 8178 if (LHS.get()->getType()->isVectorType() || 8179 RHS.get()->getType()->isVectorType()) { 8180 if (LHS.get()->getType()->hasIntegerRepresentation() && 8181 RHS.get()->getType()->hasIntegerRepresentation()) 8182 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8183 /*AllowBothBool*/getLangOpts().AltiVec, 8184 /*AllowBoolConversions*/false); 8185 return InvalidOperands(Loc, LHS, RHS); 8186 } 8187 8188 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8189 if (LHS.isInvalid() || RHS.isInvalid()) 8190 return QualType(); 8191 8192 if (compType.isNull() || !compType->isIntegerType()) 8193 return InvalidOperands(Loc, LHS, RHS); 8194 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 8195 return compType; 8196 } 8197 8198 /// \brief Diagnose invalid arithmetic on two void pointers. 8199 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 8200 Expr *LHSExpr, Expr *RHSExpr) { 8201 S.Diag(Loc, S.getLangOpts().CPlusPlus 8202 ? diag::err_typecheck_pointer_arith_void_type 8203 : diag::ext_gnu_void_ptr) 8204 << 1 /* two pointers */ << LHSExpr->getSourceRange() 8205 << RHSExpr->getSourceRange(); 8206 } 8207 8208 /// \brief Diagnose invalid arithmetic on a void pointer. 8209 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 8210 Expr *Pointer) { 8211 S.Diag(Loc, S.getLangOpts().CPlusPlus 8212 ? diag::err_typecheck_pointer_arith_void_type 8213 : diag::ext_gnu_void_ptr) 8214 << 0 /* one pointer */ << Pointer->getSourceRange(); 8215 } 8216 8217 /// \brief Diagnose invalid arithmetic on two function pointers. 8218 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 8219 Expr *LHS, Expr *RHS) { 8220 assert(LHS->getType()->isAnyPointerType()); 8221 assert(RHS->getType()->isAnyPointerType()); 8222 S.Diag(Loc, S.getLangOpts().CPlusPlus 8223 ? diag::err_typecheck_pointer_arith_function_type 8224 : diag::ext_gnu_ptr_func_arith) 8225 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 8226 // We only show the second type if it differs from the first. 8227 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 8228 RHS->getType()) 8229 << RHS->getType()->getPointeeType() 8230 << LHS->getSourceRange() << RHS->getSourceRange(); 8231 } 8232 8233 /// \brief Diagnose invalid arithmetic on a function pointer. 8234 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 8235 Expr *Pointer) { 8236 assert(Pointer->getType()->isAnyPointerType()); 8237 S.Diag(Loc, S.getLangOpts().CPlusPlus 8238 ? diag::err_typecheck_pointer_arith_function_type 8239 : diag::ext_gnu_ptr_func_arith) 8240 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 8241 << 0 /* one pointer, so only one type */ 8242 << Pointer->getSourceRange(); 8243 } 8244 8245 /// \brief Emit error if Operand is incomplete pointer type 8246 /// 8247 /// \returns True if pointer has incomplete type 8248 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 8249 Expr *Operand) { 8250 QualType ResType = Operand->getType(); 8251 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8252 ResType = ResAtomicType->getValueType(); 8253 8254 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 8255 QualType PointeeTy = ResType->getPointeeType(); 8256 return S.RequireCompleteType(Loc, PointeeTy, 8257 diag::err_typecheck_arithmetic_incomplete_type, 8258 PointeeTy, Operand->getSourceRange()); 8259 } 8260 8261 /// \brief Check the validity of an arithmetic pointer operand. 8262 /// 8263 /// If the operand has pointer type, this code will check for pointer types 8264 /// which are invalid in arithmetic operations. These will be diagnosed 8265 /// appropriately, including whether or not the use is supported as an 8266 /// extension. 8267 /// 8268 /// \returns True when the operand is valid to use (even if as an extension). 8269 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 8270 Expr *Operand) { 8271 QualType ResType = Operand->getType(); 8272 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8273 ResType = ResAtomicType->getValueType(); 8274 8275 if (!ResType->isAnyPointerType()) return true; 8276 8277 QualType PointeeTy = ResType->getPointeeType(); 8278 if (PointeeTy->isVoidType()) { 8279 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 8280 return !S.getLangOpts().CPlusPlus; 8281 } 8282 if (PointeeTy->isFunctionType()) { 8283 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 8284 return !S.getLangOpts().CPlusPlus; 8285 } 8286 8287 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 8288 8289 return true; 8290 } 8291 8292 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 8293 /// operands. 8294 /// 8295 /// This routine will diagnose any invalid arithmetic on pointer operands much 8296 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 8297 /// for emitting a single diagnostic even for operations where both LHS and RHS 8298 /// are (potentially problematic) pointers. 8299 /// 8300 /// \returns True when the operand is valid to use (even if as an extension). 8301 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 8302 Expr *LHSExpr, Expr *RHSExpr) { 8303 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 8304 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 8305 if (!isLHSPointer && !isRHSPointer) return true; 8306 8307 QualType LHSPointeeTy, RHSPointeeTy; 8308 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 8309 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 8310 8311 // if both are pointers check if operation is valid wrt address spaces 8312 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 8313 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 8314 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 8315 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 8316 S.Diag(Loc, 8317 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8318 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 8319 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 8320 return false; 8321 } 8322 } 8323 8324 // Check for arithmetic on pointers to incomplete types. 8325 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 8326 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 8327 if (isLHSVoidPtr || isRHSVoidPtr) { 8328 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 8329 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 8330 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 8331 8332 return !S.getLangOpts().CPlusPlus; 8333 } 8334 8335 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 8336 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 8337 if (isLHSFuncPtr || isRHSFuncPtr) { 8338 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 8339 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 8340 RHSExpr); 8341 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 8342 8343 return !S.getLangOpts().CPlusPlus; 8344 } 8345 8346 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 8347 return false; 8348 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 8349 return false; 8350 8351 return true; 8352 } 8353 8354 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 8355 /// literal. 8356 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 8357 Expr *LHSExpr, Expr *RHSExpr) { 8358 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 8359 Expr* IndexExpr = RHSExpr; 8360 if (!StrExpr) { 8361 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 8362 IndexExpr = LHSExpr; 8363 } 8364 8365 bool IsStringPlusInt = StrExpr && 8366 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 8367 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 8368 return; 8369 8370 llvm::APSInt index; 8371 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 8372 unsigned StrLenWithNull = StrExpr->getLength() + 1; 8373 if (index.isNonNegative() && 8374 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 8375 index.isUnsigned())) 8376 return; 8377 } 8378 8379 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8380 Self.Diag(OpLoc, diag::warn_string_plus_int) 8381 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 8382 8383 // Only print a fixit for "str" + int, not for int + "str". 8384 if (IndexExpr == RHSExpr) { 8385 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8386 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8387 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8388 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8389 << FixItHint::CreateInsertion(EndLoc, "]"); 8390 } else 8391 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8392 } 8393 8394 /// \brief Emit a warning when adding a char literal to a string. 8395 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 8396 Expr *LHSExpr, Expr *RHSExpr) { 8397 const Expr *StringRefExpr = LHSExpr; 8398 const CharacterLiteral *CharExpr = 8399 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 8400 8401 if (!CharExpr) { 8402 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 8403 StringRefExpr = RHSExpr; 8404 } 8405 8406 if (!CharExpr || !StringRefExpr) 8407 return; 8408 8409 const QualType StringType = StringRefExpr->getType(); 8410 8411 // Return if not a PointerType. 8412 if (!StringType->isAnyPointerType()) 8413 return; 8414 8415 // Return if not a CharacterType. 8416 if (!StringType->getPointeeType()->isAnyCharacterType()) 8417 return; 8418 8419 ASTContext &Ctx = Self.getASTContext(); 8420 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8421 8422 const QualType CharType = CharExpr->getType(); 8423 if (!CharType->isAnyCharacterType() && 8424 CharType->isIntegerType() && 8425 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 8426 Self.Diag(OpLoc, diag::warn_string_plus_char) 8427 << DiagRange << Ctx.CharTy; 8428 } else { 8429 Self.Diag(OpLoc, diag::warn_string_plus_char) 8430 << DiagRange << CharExpr->getType(); 8431 } 8432 8433 // Only print a fixit for str + char, not for char + str. 8434 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 8435 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8436 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8437 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8438 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8439 << FixItHint::CreateInsertion(EndLoc, "]"); 8440 } else { 8441 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8442 } 8443 } 8444 8445 /// \brief Emit error when two pointers are incompatible. 8446 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 8447 Expr *LHSExpr, Expr *RHSExpr) { 8448 assert(LHSExpr->getType()->isAnyPointerType()); 8449 assert(RHSExpr->getType()->isAnyPointerType()); 8450 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 8451 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 8452 << RHSExpr->getSourceRange(); 8453 } 8454 8455 // C99 6.5.6 8456 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 8457 SourceLocation Loc, BinaryOperatorKind Opc, 8458 QualType* CompLHSTy) { 8459 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8460 8461 if (LHS.get()->getType()->isVectorType() || 8462 RHS.get()->getType()->isVectorType()) { 8463 QualType compType = CheckVectorOperands( 8464 LHS, RHS, Loc, CompLHSTy, 8465 /*AllowBothBool*/getLangOpts().AltiVec, 8466 /*AllowBoolConversions*/getLangOpts().ZVector); 8467 if (CompLHSTy) *CompLHSTy = compType; 8468 return compType; 8469 } 8470 8471 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8472 if (LHS.isInvalid() || RHS.isInvalid()) 8473 return QualType(); 8474 8475 // Diagnose "string literal" '+' int and string '+' "char literal". 8476 if (Opc == BO_Add) { 8477 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 8478 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 8479 } 8480 8481 // handle the common case first (both operands are arithmetic). 8482 if (!compType.isNull() && compType->isArithmeticType()) { 8483 if (CompLHSTy) *CompLHSTy = compType; 8484 return compType; 8485 } 8486 8487 // Type-checking. Ultimately the pointer's going to be in PExp; 8488 // note that we bias towards the LHS being the pointer. 8489 Expr *PExp = LHS.get(), *IExp = RHS.get(); 8490 8491 bool isObjCPointer; 8492 if (PExp->getType()->isPointerType()) { 8493 isObjCPointer = false; 8494 } else if (PExp->getType()->isObjCObjectPointerType()) { 8495 isObjCPointer = true; 8496 } else { 8497 std::swap(PExp, IExp); 8498 if (PExp->getType()->isPointerType()) { 8499 isObjCPointer = false; 8500 } else if (PExp->getType()->isObjCObjectPointerType()) { 8501 isObjCPointer = true; 8502 } else { 8503 return InvalidOperands(Loc, LHS, RHS); 8504 } 8505 } 8506 assert(PExp->getType()->isAnyPointerType()); 8507 8508 if (!IExp->getType()->isIntegerType()) 8509 return InvalidOperands(Loc, LHS, RHS); 8510 8511 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 8512 return QualType(); 8513 8514 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 8515 return QualType(); 8516 8517 // Check array bounds for pointer arithemtic 8518 CheckArrayAccess(PExp, IExp); 8519 8520 if (CompLHSTy) { 8521 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 8522 if (LHSTy.isNull()) { 8523 LHSTy = LHS.get()->getType(); 8524 if (LHSTy->isPromotableIntegerType()) 8525 LHSTy = Context.getPromotedIntegerType(LHSTy); 8526 } 8527 *CompLHSTy = LHSTy; 8528 } 8529 8530 return PExp->getType(); 8531 } 8532 8533 // C99 6.5.6 8534 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 8535 SourceLocation Loc, 8536 QualType* CompLHSTy) { 8537 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8538 8539 if (LHS.get()->getType()->isVectorType() || 8540 RHS.get()->getType()->isVectorType()) { 8541 QualType compType = CheckVectorOperands( 8542 LHS, RHS, Loc, CompLHSTy, 8543 /*AllowBothBool*/getLangOpts().AltiVec, 8544 /*AllowBoolConversions*/getLangOpts().ZVector); 8545 if (CompLHSTy) *CompLHSTy = compType; 8546 return compType; 8547 } 8548 8549 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8550 if (LHS.isInvalid() || RHS.isInvalid()) 8551 return QualType(); 8552 8553 // Enforce type constraints: C99 6.5.6p3. 8554 8555 // Handle the common case first (both operands are arithmetic). 8556 if (!compType.isNull() && compType->isArithmeticType()) { 8557 if (CompLHSTy) *CompLHSTy = compType; 8558 return compType; 8559 } 8560 8561 // Either ptr - int or ptr - ptr. 8562 if (LHS.get()->getType()->isAnyPointerType()) { 8563 QualType lpointee = LHS.get()->getType()->getPointeeType(); 8564 8565 // Diagnose bad cases where we step over interface counts. 8566 if (LHS.get()->getType()->isObjCObjectPointerType() && 8567 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 8568 return QualType(); 8569 8570 // The result type of a pointer-int computation is the pointer type. 8571 if (RHS.get()->getType()->isIntegerType()) { 8572 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 8573 return QualType(); 8574 8575 // Check array bounds for pointer arithemtic 8576 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 8577 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 8578 8579 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8580 return LHS.get()->getType(); 8581 } 8582 8583 // Handle pointer-pointer subtractions. 8584 if (const PointerType *RHSPTy 8585 = RHS.get()->getType()->getAs<PointerType>()) { 8586 QualType rpointee = RHSPTy->getPointeeType(); 8587 8588 if (getLangOpts().CPlusPlus) { 8589 // Pointee types must be the same: C++ [expr.add] 8590 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 8591 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8592 } 8593 } else { 8594 // Pointee types must be compatible C99 6.5.6p3 8595 if (!Context.typesAreCompatible( 8596 Context.getCanonicalType(lpointee).getUnqualifiedType(), 8597 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 8598 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8599 return QualType(); 8600 } 8601 } 8602 8603 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 8604 LHS.get(), RHS.get())) 8605 return QualType(); 8606 8607 // The pointee type may have zero size. As an extension, a structure or 8608 // union may have zero size or an array may have zero length. In this 8609 // case subtraction does not make sense. 8610 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 8611 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 8612 if (ElementSize.isZero()) { 8613 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 8614 << rpointee.getUnqualifiedType() 8615 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8616 } 8617 } 8618 8619 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8620 return Context.getPointerDiffType(); 8621 } 8622 } 8623 8624 return InvalidOperands(Loc, LHS, RHS); 8625 } 8626 8627 static bool isScopedEnumerationType(QualType T) { 8628 if (const EnumType *ET = T->getAs<EnumType>()) 8629 return ET->getDecl()->isScoped(); 8630 return false; 8631 } 8632 8633 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 8634 SourceLocation Loc, BinaryOperatorKind Opc, 8635 QualType LHSType) { 8636 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 8637 // so skip remaining warnings as we don't want to modify values within Sema. 8638 if (S.getLangOpts().OpenCL) 8639 return; 8640 8641 llvm::APSInt Right; 8642 // Check right/shifter operand 8643 if (RHS.get()->isValueDependent() || 8644 !RHS.get()->EvaluateAsInt(Right, S.Context)) 8645 return; 8646 8647 if (Right.isNegative()) { 8648 S.DiagRuntimeBehavior(Loc, RHS.get(), 8649 S.PDiag(diag::warn_shift_negative) 8650 << RHS.get()->getSourceRange()); 8651 return; 8652 } 8653 llvm::APInt LeftBits(Right.getBitWidth(), 8654 S.Context.getTypeSize(LHS.get()->getType())); 8655 if (Right.uge(LeftBits)) { 8656 S.DiagRuntimeBehavior(Loc, RHS.get(), 8657 S.PDiag(diag::warn_shift_gt_typewidth) 8658 << RHS.get()->getSourceRange()); 8659 return; 8660 } 8661 if (Opc != BO_Shl) 8662 return; 8663 8664 // When left shifting an ICE which is signed, we can check for overflow which 8665 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 8666 // integers have defined behavior modulo one more than the maximum value 8667 // representable in the result type, so never warn for those. 8668 llvm::APSInt Left; 8669 if (LHS.get()->isValueDependent() || 8670 LHSType->hasUnsignedIntegerRepresentation() || 8671 !LHS.get()->EvaluateAsInt(Left, S.Context)) 8672 return; 8673 8674 // If LHS does not have a signed type and non-negative value 8675 // then, the behavior is undefined. Warn about it. 8676 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) { 8677 S.DiagRuntimeBehavior(Loc, LHS.get(), 8678 S.PDiag(diag::warn_shift_lhs_negative) 8679 << LHS.get()->getSourceRange()); 8680 return; 8681 } 8682 8683 llvm::APInt ResultBits = 8684 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 8685 if (LeftBits.uge(ResultBits)) 8686 return; 8687 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 8688 Result = Result.shl(Right); 8689 8690 // Print the bit representation of the signed integer as an unsigned 8691 // hexadecimal number. 8692 SmallString<40> HexResult; 8693 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 8694 8695 // If we are only missing a sign bit, this is less likely to result in actual 8696 // bugs -- if the result is cast back to an unsigned type, it will have the 8697 // expected value. Thus we place this behind a different warning that can be 8698 // turned off separately if needed. 8699 if (LeftBits == ResultBits - 1) { 8700 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 8701 << HexResult << LHSType 8702 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8703 return; 8704 } 8705 8706 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 8707 << HexResult.str() << Result.getMinSignedBits() << LHSType 8708 << Left.getBitWidth() << LHS.get()->getSourceRange() 8709 << RHS.get()->getSourceRange(); 8710 } 8711 8712 /// \brief Return the resulting type when a vector is shifted 8713 /// by a scalar or vector shift amount. 8714 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 8715 SourceLocation Loc, bool IsCompAssign) { 8716 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 8717 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 8718 !LHS.get()->getType()->isVectorType()) { 8719 S.Diag(Loc, diag::err_shift_rhs_only_vector) 8720 << RHS.get()->getType() << LHS.get()->getType() 8721 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8722 return QualType(); 8723 } 8724 8725 if (!IsCompAssign) { 8726 LHS = S.UsualUnaryConversions(LHS.get()); 8727 if (LHS.isInvalid()) return QualType(); 8728 } 8729 8730 RHS = S.UsualUnaryConversions(RHS.get()); 8731 if (RHS.isInvalid()) return QualType(); 8732 8733 QualType LHSType = LHS.get()->getType(); 8734 // Note that LHS might be a scalar because the routine calls not only in 8735 // OpenCL case. 8736 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 8737 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 8738 8739 // Note that RHS might not be a vector. 8740 QualType RHSType = RHS.get()->getType(); 8741 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 8742 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 8743 8744 // The operands need to be integers. 8745 if (!LHSEleType->isIntegerType()) { 8746 S.Diag(Loc, diag::err_typecheck_expect_int) 8747 << LHS.get()->getType() << LHS.get()->getSourceRange(); 8748 return QualType(); 8749 } 8750 8751 if (!RHSEleType->isIntegerType()) { 8752 S.Diag(Loc, diag::err_typecheck_expect_int) 8753 << RHS.get()->getType() << RHS.get()->getSourceRange(); 8754 return QualType(); 8755 } 8756 8757 if (!LHSVecTy) { 8758 assert(RHSVecTy); 8759 if (IsCompAssign) 8760 return RHSType; 8761 if (LHSEleType != RHSEleType) { 8762 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 8763 LHSEleType = RHSEleType; 8764 } 8765 QualType VecTy = 8766 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 8767 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 8768 LHSType = VecTy; 8769 } else if (RHSVecTy) { 8770 // OpenCL v1.1 s6.3.j says that for vector types, the operators 8771 // are applied component-wise. So if RHS is a vector, then ensure 8772 // that the number of elements is the same as LHS... 8773 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 8774 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 8775 << LHS.get()->getType() << RHS.get()->getType() 8776 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8777 return QualType(); 8778 } 8779 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 8780 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 8781 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 8782 if (LHSBT != RHSBT && 8783 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 8784 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 8785 << LHS.get()->getType() << RHS.get()->getType() 8786 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8787 } 8788 } 8789 } else { 8790 // ...else expand RHS to match the number of elements in LHS. 8791 QualType VecTy = 8792 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 8793 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 8794 } 8795 8796 return LHSType; 8797 } 8798 8799 // C99 6.5.7 8800 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 8801 SourceLocation Loc, BinaryOperatorKind Opc, 8802 bool IsCompAssign) { 8803 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8804 8805 // Vector shifts promote their scalar inputs to vector type. 8806 if (LHS.get()->getType()->isVectorType() || 8807 RHS.get()->getType()->isVectorType()) { 8808 if (LangOpts.ZVector) { 8809 // The shift operators for the z vector extensions work basically 8810 // like general shifts, except that neither the LHS nor the RHS is 8811 // allowed to be a "vector bool". 8812 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 8813 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 8814 return InvalidOperands(Loc, LHS, RHS); 8815 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 8816 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8817 return InvalidOperands(Loc, LHS, RHS); 8818 } 8819 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 8820 } 8821 8822 // Shifts don't perform usual arithmetic conversions, they just do integer 8823 // promotions on each operand. C99 6.5.7p3 8824 8825 // For the LHS, do usual unary conversions, but then reset them away 8826 // if this is a compound assignment. 8827 ExprResult OldLHS = LHS; 8828 LHS = UsualUnaryConversions(LHS.get()); 8829 if (LHS.isInvalid()) 8830 return QualType(); 8831 QualType LHSType = LHS.get()->getType(); 8832 if (IsCompAssign) LHS = OldLHS; 8833 8834 // The RHS is simpler. 8835 RHS = UsualUnaryConversions(RHS.get()); 8836 if (RHS.isInvalid()) 8837 return QualType(); 8838 QualType RHSType = RHS.get()->getType(); 8839 8840 // C99 6.5.7p2: Each of the operands shall have integer type. 8841 if (!LHSType->hasIntegerRepresentation() || 8842 !RHSType->hasIntegerRepresentation()) 8843 return InvalidOperands(Loc, LHS, RHS); 8844 8845 // C++0x: Don't allow scoped enums. FIXME: Use something better than 8846 // hasIntegerRepresentation() above instead of this. 8847 if (isScopedEnumerationType(LHSType) || 8848 isScopedEnumerationType(RHSType)) { 8849 return InvalidOperands(Loc, LHS, RHS); 8850 } 8851 // Sanity-check shift operands 8852 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 8853 8854 // "The type of the result is that of the promoted left operand." 8855 return LHSType; 8856 } 8857 8858 static bool IsWithinTemplateSpecialization(Decl *D) { 8859 if (DeclContext *DC = D->getDeclContext()) { 8860 if (isa<ClassTemplateSpecializationDecl>(DC)) 8861 return true; 8862 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 8863 return FD->isFunctionTemplateSpecialization(); 8864 } 8865 return false; 8866 } 8867 8868 /// If two different enums are compared, raise a warning. 8869 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 8870 Expr *RHS) { 8871 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 8872 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 8873 8874 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 8875 if (!LHSEnumType) 8876 return; 8877 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 8878 if (!RHSEnumType) 8879 return; 8880 8881 // Ignore anonymous enums. 8882 if (!LHSEnumType->getDecl()->getIdentifier()) 8883 return; 8884 if (!RHSEnumType->getDecl()->getIdentifier()) 8885 return; 8886 8887 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 8888 return; 8889 8890 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 8891 << LHSStrippedType << RHSStrippedType 8892 << LHS->getSourceRange() << RHS->getSourceRange(); 8893 } 8894 8895 /// \brief Diagnose bad pointer comparisons. 8896 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 8897 ExprResult &LHS, ExprResult &RHS, 8898 bool IsError) { 8899 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 8900 : diag::ext_typecheck_comparison_of_distinct_pointers) 8901 << LHS.get()->getType() << RHS.get()->getType() 8902 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8903 } 8904 8905 /// \brief Returns false if the pointers are converted to a composite type, 8906 /// true otherwise. 8907 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 8908 ExprResult &LHS, ExprResult &RHS) { 8909 // C++ [expr.rel]p2: 8910 // [...] Pointer conversions (4.10) and qualification 8911 // conversions (4.4) are performed on pointer operands (or on 8912 // a pointer operand and a null pointer constant) to bring 8913 // them to their composite pointer type. [...] 8914 // 8915 // C++ [expr.eq]p1 uses the same notion for (in)equality 8916 // comparisons of pointers. 8917 8918 QualType LHSType = LHS.get()->getType(); 8919 QualType RHSType = RHS.get()->getType(); 8920 assert(LHSType->isPointerType() || RHSType->isPointerType() || 8921 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 8922 8923 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 8924 if (T.isNull()) { 8925 if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) && 8926 (RHSType->isPointerType() || RHSType->isMemberPointerType())) 8927 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 8928 else 8929 S.InvalidOperands(Loc, LHS, RHS); 8930 return true; 8931 } 8932 8933 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 8934 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 8935 return false; 8936 } 8937 8938 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 8939 ExprResult &LHS, 8940 ExprResult &RHS, 8941 bool IsError) { 8942 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 8943 : diag::ext_typecheck_comparison_of_fptr_to_void) 8944 << LHS.get()->getType() << RHS.get()->getType() 8945 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8946 } 8947 8948 static bool isObjCObjectLiteral(ExprResult &E) { 8949 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 8950 case Stmt::ObjCArrayLiteralClass: 8951 case Stmt::ObjCDictionaryLiteralClass: 8952 case Stmt::ObjCStringLiteralClass: 8953 case Stmt::ObjCBoxedExprClass: 8954 return true; 8955 default: 8956 // Note that ObjCBoolLiteral is NOT an object literal! 8957 return false; 8958 } 8959 } 8960 8961 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 8962 const ObjCObjectPointerType *Type = 8963 LHS->getType()->getAs<ObjCObjectPointerType>(); 8964 8965 // If this is not actually an Objective-C object, bail out. 8966 if (!Type) 8967 return false; 8968 8969 // Get the LHS object's interface type. 8970 QualType InterfaceType = Type->getPointeeType(); 8971 8972 // If the RHS isn't an Objective-C object, bail out. 8973 if (!RHS->getType()->isObjCObjectPointerType()) 8974 return false; 8975 8976 // Try to find the -isEqual: method. 8977 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 8978 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 8979 InterfaceType, 8980 /*instance=*/true); 8981 if (!Method) { 8982 if (Type->isObjCIdType()) { 8983 // For 'id', just check the global pool. 8984 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 8985 /*receiverId=*/true); 8986 } else { 8987 // Check protocols. 8988 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 8989 /*instance=*/true); 8990 } 8991 } 8992 8993 if (!Method) 8994 return false; 8995 8996 QualType T = Method->parameters()[0]->getType(); 8997 if (!T->isObjCObjectPointerType()) 8998 return false; 8999 9000 QualType R = Method->getReturnType(); 9001 if (!R->isScalarType()) 9002 return false; 9003 9004 return true; 9005 } 9006 9007 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 9008 FromE = FromE->IgnoreParenImpCasts(); 9009 switch (FromE->getStmtClass()) { 9010 default: 9011 break; 9012 case Stmt::ObjCStringLiteralClass: 9013 // "string literal" 9014 return LK_String; 9015 case Stmt::ObjCArrayLiteralClass: 9016 // "array literal" 9017 return LK_Array; 9018 case Stmt::ObjCDictionaryLiteralClass: 9019 // "dictionary literal" 9020 return LK_Dictionary; 9021 case Stmt::BlockExprClass: 9022 return LK_Block; 9023 case Stmt::ObjCBoxedExprClass: { 9024 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 9025 switch (Inner->getStmtClass()) { 9026 case Stmt::IntegerLiteralClass: 9027 case Stmt::FloatingLiteralClass: 9028 case Stmt::CharacterLiteralClass: 9029 case Stmt::ObjCBoolLiteralExprClass: 9030 case Stmt::CXXBoolLiteralExprClass: 9031 // "numeric literal" 9032 return LK_Numeric; 9033 case Stmt::ImplicitCastExprClass: { 9034 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 9035 // Boolean literals can be represented by implicit casts. 9036 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 9037 return LK_Numeric; 9038 break; 9039 } 9040 default: 9041 break; 9042 } 9043 return LK_Boxed; 9044 } 9045 } 9046 return LK_None; 9047 } 9048 9049 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 9050 ExprResult &LHS, ExprResult &RHS, 9051 BinaryOperator::Opcode Opc){ 9052 Expr *Literal; 9053 Expr *Other; 9054 if (isObjCObjectLiteral(LHS)) { 9055 Literal = LHS.get(); 9056 Other = RHS.get(); 9057 } else { 9058 Literal = RHS.get(); 9059 Other = LHS.get(); 9060 } 9061 9062 // Don't warn on comparisons against nil. 9063 Other = Other->IgnoreParenCasts(); 9064 if (Other->isNullPointerConstant(S.getASTContext(), 9065 Expr::NPC_ValueDependentIsNotNull)) 9066 return; 9067 9068 // This should be kept in sync with warn_objc_literal_comparison. 9069 // LK_String should always be after the other literals, since it has its own 9070 // warning flag. 9071 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 9072 assert(LiteralKind != Sema::LK_Block); 9073 if (LiteralKind == Sema::LK_None) { 9074 llvm_unreachable("Unknown Objective-C object literal kind"); 9075 } 9076 9077 if (LiteralKind == Sema::LK_String) 9078 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 9079 << Literal->getSourceRange(); 9080 else 9081 S.Diag(Loc, diag::warn_objc_literal_comparison) 9082 << LiteralKind << Literal->getSourceRange(); 9083 9084 if (BinaryOperator::isEqualityOp(Opc) && 9085 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 9086 SourceLocation Start = LHS.get()->getLocStart(); 9087 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd()); 9088 CharSourceRange OpRange = 9089 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 9090 9091 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 9092 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 9093 << FixItHint::CreateReplacement(OpRange, " isEqual:") 9094 << FixItHint::CreateInsertion(End, "]"); 9095 } 9096 } 9097 9098 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS, 9099 ExprResult &RHS, 9100 SourceLocation Loc, 9101 BinaryOperatorKind Opc) { 9102 // Check that left hand side is !something. 9103 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 9104 if (!UO || UO->getOpcode() != UO_LNot) return; 9105 9106 // Only check if the right hand side is non-bool arithmetic type. 9107 if (RHS.get()->isKnownToHaveBooleanValue()) return; 9108 9109 // Make sure that the something in !something is not bool. 9110 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 9111 if (SubExpr->isKnownToHaveBooleanValue()) return; 9112 9113 // Emit warning. 9114 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison) 9115 << Loc; 9116 9117 // First note suggest !(x < y) 9118 SourceLocation FirstOpen = SubExpr->getLocStart(); 9119 SourceLocation FirstClose = RHS.get()->getLocEnd(); 9120 FirstClose = S.getLocForEndOfToken(FirstClose); 9121 if (FirstClose.isInvalid()) 9122 FirstOpen = SourceLocation(); 9123 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 9124 << FixItHint::CreateInsertion(FirstOpen, "(") 9125 << FixItHint::CreateInsertion(FirstClose, ")"); 9126 9127 // Second note suggests (!x) < y 9128 SourceLocation SecondOpen = LHS.get()->getLocStart(); 9129 SourceLocation SecondClose = LHS.get()->getLocEnd(); 9130 SecondClose = S.getLocForEndOfToken(SecondClose); 9131 if (SecondClose.isInvalid()) 9132 SecondOpen = SourceLocation(); 9133 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 9134 << FixItHint::CreateInsertion(SecondOpen, "(") 9135 << FixItHint::CreateInsertion(SecondClose, ")"); 9136 } 9137 9138 // Get the decl for a simple expression: a reference to a variable, 9139 // an implicit C++ field reference, or an implicit ObjC ivar reference. 9140 static ValueDecl *getCompareDecl(Expr *E) { 9141 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E)) 9142 return DR->getDecl(); 9143 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 9144 if (Ivar->isFreeIvar()) 9145 return Ivar->getDecl(); 9146 } 9147 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) { 9148 if (Mem->isImplicitAccess()) 9149 return Mem->getMemberDecl(); 9150 } 9151 return nullptr; 9152 } 9153 9154 // C99 6.5.8, C++ [expr.rel] 9155 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 9156 SourceLocation Loc, BinaryOperatorKind Opc, 9157 bool IsRelational) { 9158 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 9159 9160 // Handle vector comparisons separately. 9161 if (LHS.get()->getType()->isVectorType() || 9162 RHS.get()->getType()->isVectorType()) 9163 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 9164 9165 QualType LHSType = LHS.get()->getType(); 9166 QualType RHSType = RHS.get()->getType(); 9167 9168 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 9169 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 9170 9171 checkEnumComparison(*this, Loc, LHS.get(), RHS.get()); 9172 diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, Opc); 9173 9174 if (!LHSType->hasFloatingRepresentation() && 9175 !(LHSType->isBlockPointerType() && IsRelational) && 9176 !LHS.get()->getLocStart().isMacroID() && 9177 !RHS.get()->getLocStart().isMacroID() && 9178 ActiveTemplateInstantiations.empty()) { 9179 // For non-floating point types, check for self-comparisons of the form 9180 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9181 // often indicate logic errors in the program. 9182 // 9183 // NOTE: Don't warn about comparison expressions resulting from macro 9184 // expansion. Also don't warn about comparisons which are only self 9185 // comparisons within a template specialization. The warnings should catch 9186 // obvious cases in the definition of the template anyways. The idea is to 9187 // warn when the typed comparison operator will always evaluate to the same 9188 // result. 9189 ValueDecl *DL = getCompareDecl(LHSStripped); 9190 ValueDecl *DR = getCompareDecl(RHSStripped); 9191 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) { 9192 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 9193 << 0 // self- 9194 << (Opc == BO_EQ 9195 || Opc == BO_LE 9196 || Opc == BO_GE)); 9197 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() && 9198 !DL->getType()->isReferenceType() && 9199 !DR->getType()->isReferenceType()) { 9200 // what is it always going to eval to? 9201 char always_evals_to; 9202 switch(Opc) { 9203 case BO_EQ: // e.g. array1 == array2 9204 always_evals_to = 0; // false 9205 break; 9206 case BO_NE: // e.g. array1 != array2 9207 always_evals_to = 1; // true 9208 break; 9209 default: 9210 // best we can say is 'a constant' 9211 always_evals_to = 2; // e.g. array1 <= array2 9212 break; 9213 } 9214 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 9215 << 1 // array 9216 << always_evals_to); 9217 } 9218 9219 if (isa<CastExpr>(LHSStripped)) 9220 LHSStripped = LHSStripped->IgnoreParenCasts(); 9221 if (isa<CastExpr>(RHSStripped)) 9222 RHSStripped = RHSStripped->IgnoreParenCasts(); 9223 9224 // Warn about comparisons against a string constant (unless the other 9225 // operand is null), the user probably wants strcmp. 9226 Expr *literalString = nullptr; 9227 Expr *literalStringStripped = nullptr; 9228 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 9229 !RHSStripped->isNullPointerConstant(Context, 9230 Expr::NPC_ValueDependentIsNull)) { 9231 literalString = LHS.get(); 9232 literalStringStripped = LHSStripped; 9233 } else if ((isa<StringLiteral>(RHSStripped) || 9234 isa<ObjCEncodeExpr>(RHSStripped)) && 9235 !LHSStripped->isNullPointerConstant(Context, 9236 Expr::NPC_ValueDependentIsNull)) { 9237 literalString = RHS.get(); 9238 literalStringStripped = RHSStripped; 9239 } 9240 9241 if (literalString) { 9242 DiagRuntimeBehavior(Loc, nullptr, 9243 PDiag(diag::warn_stringcompare) 9244 << isa<ObjCEncodeExpr>(literalStringStripped) 9245 << literalString->getSourceRange()); 9246 } 9247 } 9248 9249 // C99 6.5.8p3 / C99 6.5.9p4 9250 UsualArithmeticConversions(LHS, RHS); 9251 if (LHS.isInvalid() || RHS.isInvalid()) 9252 return QualType(); 9253 9254 LHSType = LHS.get()->getType(); 9255 RHSType = RHS.get()->getType(); 9256 9257 // The result of comparisons is 'bool' in C++, 'int' in C. 9258 QualType ResultTy = Context.getLogicalOperationType(); 9259 9260 if (IsRelational) { 9261 if (LHSType->isRealType() && RHSType->isRealType()) 9262 return ResultTy; 9263 } else { 9264 // Check for comparisons of floating point operands using != and ==. 9265 if (LHSType->hasFloatingRepresentation()) 9266 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9267 9268 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 9269 return ResultTy; 9270 } 9271 9272 const Expr::NullPointerConstantKind LHSNullKind = 9273 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9274 const Expr::NullPointerConstantKind RHSNullKind = 9275 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9276 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 9277 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 9278 9279 if (!IsRelational && LHSIsNull != RHSIsNull) { 9280 bool IsEquality = Opc == BO_EQ; 9281 if (RHSIsNull) 9282 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 9283 RHS.get()->getSourceRange()); 9284 else 9285 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 9286 LHS.get()->getSourceRange()); 9287 } 9288 9289 if ((LHSType->isIntegerType() && !LHSIsNull) || 9290 (RHSType->isIntegerType() && !RHSIsNull)) { 9291 // Skip normal pointer conversion checks in this case; we have better 9292 // diagnostics for this below. 9293 } else if (getLangOpts().CPlusPlus) { 9294 // Equality comparison of a function pointer to a void pointer is invalid, 9295 // but we allow it as an extension. 9296 // FIXME: If we really want to allow this, should it be part of composite 9297 // pointer type computation so it works in conditionals too? 9298 if (!IsRelational && 9299 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 9300 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 9301 // This is a gcc extension compatibility comparison. 9302 // In a SFINAE context, we treat this as a hard error to maintain 9303 // conformance with the C++ standard. 9304 diagnoseFunctionPointerToVoidComparison( 9305 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 9306 9307 if (isSFINAEContext()) 9308 return QualType(); 9309 9310 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9311 return ResultTy; 9312 } 9313 9314 // C++ [expr.eq]p2: 9315 // If at least one operand is a pointer [...] bring them to their 9316 // composite pointer type. 9317 // C++ [expr.rel]p2: 9318 // If both operands are pointers, [...] bring them to their composite 9319 // pointer type. 9320 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 9321 (IsRelational ? 2 : 1)) { 9322 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9323 return QualType(); 9324 else 9325 return ResultTy; 9326 } 9327 } else if (LHSType->isPointerType() && 9328 RHSType->isPointerType()) { // C99 6.5.8p2 9329 // All of the following pointer-related warnings are GCC extensions, except 9330 // when handling null pointer constants. 9331 QualType LCanPointeeTy = 9332 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9333 QualType RCanPointeeTy = 9334 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9335 9336 // C99 6.5.9p2 and C99 6.5.8p2 9337 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 9338 RCanPointeeTy.getUnqualifiedType())) { 9339 // Valid unless a relational comparison of function pointers 9340 if (IsRelational && LCanPointeeTy->isFunctionType()) { 9341 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 9342 << LHSType << RHSType << LHS.get()->getSourceRange() 9343 << RHS.get()->getSourceRange(); 9344 } 9345 } else if (!IsRelational && 9346 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 9347 // Valid unless comparison between non-null pointer and function pointer 9348 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 9349 && !LHSIsNull && !RHSIsNull) 9350 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 9351 /*isError*/false); 9352 } else { 9353 // Invalid 9354 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 9355 } 9356 if (LCanPointeeTy != RCanPointeeTy) { 9357 // Treat NULL constant as a special case in OpenCL. 9358 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 9359 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 9360 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 9361 Diag(Loc, 9362 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 9363 << LHSType << RHSType << 0 /* comparison */ 9364 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9365 } 9366 } 9367 unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace(); 9368 unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace(); 9369 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 9370 : CK_BitCast; 9371 if (LHSIsNull && !RHSIsNull) 9372 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 9373 else 9374 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 9375 } 9376 return ResultTy; 9377 } 9378 9379 if (getLangOpts().CPlusPlus) { 9380 // C++ [expr.eq]p4: 9381 // Two operands of type std::nullptr_t or one operand of type 9382 // std::nullptr_t and the other a null pointer constant compare equal. 9383 if (!IsRelational && LHSIsNull && RHSIsNull) { 9384 if (LHSType->isNullPtrType()) { 9385 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9386 return ResultTy; 9387 } 9388 if (RHSType->isNullPtrType()) { 9389 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9390 return ResultTy; 9391 } 9392 } 9393 9394 // Comparison of Objective-C pointers and block pointers against nullptr_t. 9395 // These aren't covered by the composite pointer type rules. 9396 if (!IsRelational && RHSType->isNullPtrType() && 9397 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 9398 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9399 return ResultTy; 9400 } 9401 if (!IsRelational && LHSType->isNullPtrType() && 9402 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 9403 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9404 return ResultTy; 9405 } 9406 9407 if (IsRelational && 9408 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 9409 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 9410 // HACK: Relational comparison of nullptr_t against a pointer type is 9411 // invalid per DR583, but we allow it within std::less<> and friends, 9412 // since otherwise common uses of it break. 9413 // FIXME: Consider removing this hack once LWG fixes std::less<> and 9414 // friends to have std::nullptr_t overload candidates. 9415 DeclContext *DC = CurContext; 9416 if (isa<FunctionDecl>(DC)) 9417 DC = DC->getParent(); 9418 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 9419 if (CTSD->isInStdNamespace() && 9420 llvm::StringSwitch<bool>(CTSD->getName()) 9421 .Cases("less", "less_equal", "greater", "greater_equal", true) 9422 .Default(false)) { 9423 if (RHSType->isNullPtrType()) 9424 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9425 else 9426 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9427 return ResultTy; 9428 } 9429 } 9430 } 9431 9432 // C++ [expr.eq]p2: 9433 // If at least one operand is a pointer to member, [...] bring them to 9434 // their composite pointer type. 9435 if (!IsRelational && 9436 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 9437 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9438 return QualType(); 9439 else 9440 return ResultTy; 9441 } 9442 9443 // Handle scoped enumeration types specifically, since they don't promote 9444 // to integers. 9445 if (LHS.get()->getType()->isEnumeralType() && 9446 Context.hasSameUnqualifiedType(LHS.get()->getType(), 9447 RHS.get()->getType())) 9448 return ResultTy; 9449 } 9450 9451 // Handle block pointer types. 9452 if (!IsRelational && LHSType->isBlockPointerType() && 9453 RHSType->isBlockPointerType()) { 9454 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 9455 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 9456 9457 if (!LHSIsNull && !RHSIsNull && 9458 !Context.typesAreCompatible(lpointee, rpointee)) { 9459 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9460 << LHSType << RHSType << LHS.get()->getSourceRange() 9461 << RHS.get()->getSourceRange(); 9462 } 9463 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9464 return ResultTy; 9465 } 9466 9467 // Allow block pointers to be compared with null pointer constants. 9468 if (!IsRelational 9469 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 9470 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 9471 if (!LHSIsNull && !RHSIsNull) { 9472 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 9473 ->getPointeeType()->isVoidType()) 9474 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 9475 ->getPointeeType()->isVoidType()))) 9476 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9477 << LHSType << RHSType << LHS.get()->getSourceRange() 9478 << RHS.get()->getSourceRange(); 9479 } 9480 if (LHSIsNull && !RHSIsNull) 9481 LHS = ImpCastExprToType(LHS.get(), RHSType, 9482 RHSType->isPointerType() ? CK_BitCast 9483 : CK_AnyPointerToBlockPointerCast); 9484 else 9485 RHS = ImpCastExprToType(RHS.get(), LHSType, 9486 LHSType->isPointerType() ? CK_BitCast 9487 : CK_AnyPointerToBlockPointerCast); 9488 return ResultTy; 9489 } 9490 9491 if (LHSType->isObjCObjectPointerType() || 9492 RHSType->isObjCObjectPointerType()) { 9493 const PointerType *LPT = LHSType->getAs<PointerType>(); 9494 const PointerType *RPT = RHSType->getAs<PointerType>(); 9495 if (LPT || RPT) { 9496 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 9497 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 9498 9499 if (!LPtrToVoid && !RPtrToVoid && 9500 !Context.typesAreCompatible(LHSType, RHSType)) { 9501 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9502 /*isError*/false); 9503 } 9504 if (LHSIsNull && !RHSIsNull) { 9505 Expr *E = LHS.get(); 9506 if (getLangOpts().ObjCAutoRefCount) 9507 CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion); 9508 LHS = ImpCastExprToType(E, RHSType, 9509 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9510 } 9511 else { 9512 Expr *E = RHS.get(); 9513 if (getLangOpts().ObjCAutoRefCount) 9514 CheckObjCARCConversion(SourceRange(), LHSType, E, 9515 CCK_ImplicitConversion, /*Diagnose=*/true, 9516 /*DiagnoseCFAudited=*/false, Opc); 9517 RHS = ImpCastExprToType(E, LHSType, 9518 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9519 } 9520 return ResultTy; 9521 } 9522 if (LHSType->isObjCObjectPointerType() && 9523 RHSType->isObjCObjectPointerType()) { 9524 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 9525 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9526 /*isError*/false); 9527 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 9528 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 9529 9530 if (LHSIsNull && !RHSIsNull) 9531 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9532 else 9533 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9534 return ResultTy; 9535 } 9536 } 9537 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 9538 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 9539 unsigned DiagID = 0; 9540 bool isError = false; 9541 if (LangOpts.DebuggerSupport) { 9542 // Under a debugger, allow the comparison of pointers to integers, 9543 // since users tend to want to compare addresses. 9544 } else if ((LHSIsNull && LHSType->isIntegerType()) || 9545 (RHSIsNull && RHSType->isIntegerType())) { 9546 if (IsRelational) { 9547 isError = getLangOpts().CPlusPlus; 9548 DiagID = 9549 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 9550 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 9551 } 9552 } else if (getLangOpts().CPlusPlus) { 9553 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 9554 isError = true; 9555 } else if (IsRelational) 9556 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 9557 else 9558 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 9559 9560 if (DiagID) { 9561 Diag(Loc, DiagID) 9562 << LHSType << RHSType << LHS.get()->getSourceRange() 9563 << RHS.get()->getSourceRange(); 9564 if (isError) 9565 return QualType(); 9566 } 9567 9568 if (LHSType->isIntegerType()) 9569 LHS = ImpCastExprToType(LHS.get(), RHSType, 9570 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 9571 else 9572 RHS = ImpCastExprToType(RHS.get(), LHSType, 9573 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 9574 return ResultTy; 9575 } 9576 9577 // Handle block pointers. 9578 if (!IsRelational && RHSIsNull 9579 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 9580 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9581 return ResultTy; 9582 } 9583 if (!IsRelational && LHSIsNull 9584 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 9585 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9586 return ResultTy; 9587 } 9588 9589 return InvalidOperands(Loc, LHS, RHS); 9590 } 9591 9592 9593 // Return a signed type that is of identical size and number of elements. 9594 // For floating point vectors, return an integer type of identical size 9595 // and number of elements. 9596 QualType Sema::GetSignedVectorType(QualType V) { 9597 const VectorType *VTy = V->getAs<VectorType>(); 9598 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 9599 if (TypeSize == Context.getTypeSize(Context.CharTy)) 9600 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 9601 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 9602 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 9603 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 9604 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 9605 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 9606 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 9607 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 9608 "Unhandled vector element size in vector compare"); 9609 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 9610 } 9611 9612 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 9613 /// operates on extended vector types. Instead of producing an IntTy result, 9614 /// like a scalar comparison, a vector comparison produces a vector of integer 9615 /// types. 9616 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 9617 SourceLocation Loc, 9618 bool IsRelational) { 9619 // Check to make sure we're operating on vectors of the same type and width, 9620 // Allowing one side to be a scalar of element type. 9621 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 9622 /*AllowBothBool*/true, 9623 /*AllowBoolConversions*/getLangOpts().ZVector); 9624 if (vType.isNull()) 9625 return vType; 9626 9627 QualType LHSType = LHS.get()->getType(); 9628 9629 // If AltiVec, the comparison results in a numeric type, i.e. 9630 // bool for C++, int for C 9631 if (getLangOpts().AltiVec && 9632 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 9633 return Context.getLogicalOperationType(); 9634 9635 // For non-floating point types, check for self-comparisons of the form 9636 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9637 // often indicate logic errors in the program. 9638 if (!LHSType->hasFloatingRepresentation() && 9639 ActiveTemplateInstantiations.empty()) { 9640 if (DeclRefExpr* DRL 9641 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 9642 if (DeclRefExpr* DRR 9643 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 9644 if (DRL->getDecl() == DRR->getDecl()) 9645 DiagRuntimeBehavior(Loc, nullptr, 9646 PDiag(diag::warn_comparison_always) 9647 << 0 // self- 9648 << 2 // "a constant" 9649 ); 9650 } 9651 9652 // Check for comparisons of floating point operands using != and ==. 9653 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 9654 assert (RHS.get()->getType()->hasFloatingRepresentation()); 9655 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9656 } 9657 9658 // Return a signed type for the vector. 9659 return GetSignedVectorType(vType); 9660 } 9661 9662 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 9663 SourceLocation Loc) { 9664 // Ensure that either both operands are of the same vector type, or 9665 // one operand is of a vector type and the other is of its element type. 9666 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 9667 /*AllowBothBool*/true, 9668 /*AllowBoolConversions*/false); 9669 if (vType.isNull()) 9670 return InvalidOperands(Loc, LHS, RHS); 9671 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 9672 vType->hasFloatingRepresentation()) 9673 return InvalidOperands(Loc, LHS, RHS); 9674 9675 return GetSignedVectorType(LHS.get()->getType()); 9676 } 9677 9678 inline QualType Sema::CheckBitwiseOperands( 9679 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 9680 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9681 9682 if (LHS.get()->getType()->isVectorType() || 9683 RHS.get()->getType()->isVectorType()) { 9684 if (LHS.get()->getType()->hasIntegerRepresentation() && 9685 RHS.get()->getType()->hasIntegerRepresentation()) 9686 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9687 /*AllowBothBool*/true, 9688 /*AllowBoolConversions*/getLangOpts().ZVector); 9689 return InvalidOperands(Loc, LHS, RHS); 9690 } 9691 9692 ExprResult LHSResult = LHS, RHSResult = RHS; 9693 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 9694 IsCompAssign); 9695 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 9696 return QualType(); 9697 LHS = LHSResult.get(); 9698 RHS = RHSResult.get(); 9699 9700 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 9701 return compType; 9702 return InvalidOperands(Loc, LHS, RHS); 9703 } 9704 9705 // C99 6.5.[13,14] 9706 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 9707 SourceLocation Loc, 9708 BinaryOperatorKind Opc) { 9709 // Check vector operands differently. 9710 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 9711 return CheckVectorLogicalOperands(LHS, RHS, Loc); 9712 9713 // Diagnose cases where the user write a logical and/or but probably meant a 9714 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 9715 // is a constant. 9716 if (LHS.get()->getType()->isIntegerType() && 9717 !LHS.get()->getType()->isBooleanType() && 9718 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 9719 // Don't warn in macros or template instantiations. 9720 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) { 9721 // If the RHS can be constant folded, and if it constant folds to something 9722 // that isn't 0 or 1 (which indicate a potential logical operation that 9723 // happened to fold to true/false) then warn. 9724 // Parens on the RHS are ignored. 9725 llvm::APSInt Result; 9726 if (RHS.get()->EvaluateAsInt(Result, Context)) 9727 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 9728 !RHS.get()->getExprLoc().isMacroID()) || 9729 (Result != 0 && Result != 1)) { 9730 Diag(Loc, diag::warn_logical_instead_of_bitwise) 9731 << RHS.get()->getSourceRange() 9732 << (Opc == BO_LAnd ? "&&" : "||"); 9733 // Suggest replacing the logical operator with the bitwise version 9734 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 9735 << (Opc == BO_LAnd ? "&" : "|") 9736 << FixItHint::CreateReplacement(SourceRange( 9737 Loc, getLocForEndOfToken(Loc)), 9738 Opc == BO_LAnd ? "&" : "|"); 9739 if (Opc == BO_LAnd) 9740 // Suggest replacing "Foo() && kNonZero" with "Foo()" 9741 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 9742 << FixItHint::CreateRemoval( 9743 SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()), 9744 RHS.get()->getLocEnd())); 9745 } 9746 } 9747 9748 if (!Context.getLangOpts().CPlusPlus) { 9749 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 9750 // not operate on the built-in scalar and vector float types. 9751 if (Context.getLangOpts().OpenCL && 9752 Context.getLangOpts().OpenCLVersion < 120) { 9753 if (LHS.get()->getType()->isFloatingType() || 9754 RHS.get()->getType()->isFloatingType()) 9755 return InvalidOperands(Loc, LHS, RHS); 9756 } 9757 9758 LHS = UsualUnaryConversions(LHS.get()); 9759 if (LHS.isInvalid()) 9760 return QualType(); 9761 9762 RHS = UsualUnaryConversions(RHS.get()); 9763 if (RHS.isInvalid()) 9764 return QualType(); 9765 9766 if (!LHS.get()->getType()->isScalarType() || 9767 !RHS.get()->getType()->isScalarType()) 9768 return InvalidOperands(Loc, LHS, RHS); 9769 9770 return Context.IntTy; 9771 } 9772 9773 // The following is safe because we only use this method for 9774 // non-overloadable operands. 9775 9776 // C++ [expr.log.and]p1 9777 // C++ [expr.log.or]p1 9778 // The operands are both contextually converted to type bool. 9779 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 9780 if (LHSRes.isInvalid()) 9781 return InvalidOperands(Loc, LHS, RHS); 9782 LHS = LHSRes; 9783 9784 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 9785 if (RHSRes.isInvalid()) 9786 return InvalidOperands(Loc, LHS, RHS); 9787 RHS = RHSRes; 9788 9789 // C++ [expr.log.and]p2 9790 // C++ [expr.log.or]p2 9791 // The result is a bool. 9792 return Context.BoolTy; 9793 } 9794 9795 static bool IsReadonlyMessage(Expr *E, Sema &S) { 9796 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 9797 if (!ME) return false; 9798 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 9799 ObjCMessageExpr *Base = 9800 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts()); 9801 if (!Base) return false; 9802 return Base->getMethodDecl() != nullptr; 9803 } 9804 9805 /// Is the given expression (which must be 'const') a reference to a 9806 /// variable which was originally non-const, but which has become 9807 /// 'const' due to being captured within a block? 9808 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 9809 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 9810 assert(E->isLValue() && E->getType().isConstQualified()); 9811 E = E->IgnoreParens(); 9812 9813 // Must be a reference to a declaration from an enclosing scope. 9814 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 9815 if (!DRE) return NCCK_None; 9816 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 9817 9818 // The declaration must be a variable which is not declared 'const'. 9819 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 9820 if (!var) return NCCK_None; 9821 if (var->getType().isConstQualified()) return NCCK_None; 9822 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 9823 9824 // Decide whether the first capture was for a block or a lambda. 9825 DeclContext *DC = S.CurContext, *Prev = nullptr; 9826 // Decide whether the first capture was for a block or a lambda. 9827 while (DC) { 9828 // For init-capture, it is possible that the variable belongs to the 9829 // template pattern of the current context. 9830 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 9831 if (var->isInitCapture() && 9832 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 9833 break; 9834 if (DC == var->getDeclContext()) 9835 break; 9836 Prev = DC; 9837 DC = DC->getParent(); 9838 } 9839 // Unless we have an init-capture, we've gone one step too far. 9840 if (!var->isInitCapture()) 9841 DC = Prev; 9842 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 9843 } 9844 9845 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 9846 Ty = Ty.getNonReferenceType(); 9847 if (IsDereference && Ty->isPointerType()) 9848 Ty = Ty->getPointeeType(); 9849 return !Ty.isConstQualified(); 9850 } 9851 9852 /// Emit the "read-only variable not assignable" error and print notes to give 9853 /// more information about why the variable is not assignable, such as pointing 9854 /// to the declaration of a const variable, showing that a method is const, or 9855 /// that the function is returning a const reference. 9856 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 9857 SourceLocation Loc) { 9858 // Update err_typecheck_assign_const and note_typecheck_assign_const 9859 // when this enum is changed. 9860 enum { 9861 ConstFunction, 9862 ConstVariable, 9863 ConstMember, 9864 ConstMethod, 9865 ConstUnknown, // Keep as last element 9866 }; 9867 9868 SourceRange ExprRange = E->getSourceRange(); 9869 9870 // Only emit one error on the first const found. All other consts will emit 9871 // a note to the error. 9872 bool DiagnosticEmitted = false; 9873 9874 // Track if the current expression is the result of a derefence, and if the 9875 // next checked expression is the result of a derefence. 9876 bool IsDereference = false; 9877 bool NextIsDereference = false; 9878 9879 // Loop to process MemberExpr chains. 9880 while (true) { 9881 IsDereference = NextIsDereference; 9882 NextIsDereference = false; 9883 9884 E = E->IgnoreParenImpCasts(); 9885 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 9886 NextIsDereference = ME->isArrow(); 9887 const ValueDecl *VD = ME->getMemberDecl(); 9888 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 9889 // Mutable fields can be modified even if the class is const. 9890 if (Field->isMutable()) { 9891 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 9892 break; 9893 } 9894 9895 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 9896 if (!DiagnosticEmitted) { 9897 S.Diag(Loc, diag::err_typecheck_assign_const) 9898 << ExprRange << ConstMember << false /*static*/ << Field 9899 << Field->getType(); 9900 DiagnosticEmitted = true; 9901 } 9902 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9903 << ConstMember << false /*static*/ << Field << Field->getType() 9904 << Field->getSourceRange(); 9905 } 9906 E = ME->getBase(); 9907 continue; 9908 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 9909 if (VDecl->getType().isConstQualified()) { 9910 if (!DiagnosticEmitted) { 9911 S.Diag(Loc, diag::err_typecheck_assign_const) 9912 << ExprRange << ConstMember << true /*static*/ << VDecl 9913 << VDecl->getType(); 9914 DiagnosticEmitted = true; 9915 } 9916 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9917 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 9918 << VDecl->getSourceRange(); 9919 } 9920 // Static fields do not inherit constness from parents. 9921 break; 9922 } 9923 break; 9924 } // End MemberExpr 9925 break; 9926 } 9927 9928 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9929 // Function calls 9930 const FunctionDecl *FD = CE->getDirectCallee(); 9931 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 9932 if (!DiagnosticEmitted) { 9933 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 9934 << ConstFunction << FD; 9935 DiagnosticEmitted = true; 9936 } 9937 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 9938 diag::note_typecheck_assign_const) 9939 << ConstFunction << FD << FD->getReturnType() 9940 << FD->getReturnTypeSourceRange(); 9941 } 9942 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9943 // Point to variable declaration. 9944 if (const ValueDecl *VD = DRE->getDecl()) { 9945 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 9946 if (!DiagnosticEmitted) { 9947 S.Diag(Loc, diag::err_typecheck_assign_const) 9948 << ExprRange << ConstVariable << VD << VD->getType(); 9949 DiagnosticEmitted = true; 9950 } 9951 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9952 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 9953 } 9954 } 9955 } else if (isa<CXXThisExpr>(E)) { 9956 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 9957 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 9958 if (MD->isConst()) { 9959 if (!DiagnosticEmitted) { 9960 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 9961 << ConstMethod << MD; 9962 DiagnosticEmitted = true; 9963 } 9964 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 9965 << ConstMethod << MD << MD->getSourceRange(); 9966 } 9967 } 9968 } 9969 } 9970 9971 if (DiagnosticEmitted) 9972 return; 9973 9974 // Can't determine a more specific message, so display the generic error. 9975 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 9976 } 9977 9978 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 9979 /// emit an error and return true. If so, return false. 9980 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 9981 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 9982 9983 S.CheckShadowingDeclModification(E, Loc); 9984 9985 SourceLocation OrigLoc = Loc; 9986 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 9987 &Loc); 9988 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 9989 IsLV = Expr::MLV_InvalidMessageExpression; 9990 if (IsLV == Expr::MLV_Valid) 9991 return false; 9992 9993 unsigned DiagID = 0; 9994 bool NeedType = false; 9995 switch (IsLV) { // C99 6.5.16p2 9996 case Expr::MLV_ConstQualified: 9997 // Use a specialized diagnostic when we're assigning to an object 9998 // from an enclosing function or block. 9999 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 10000 if (NCCK == NCCK_Block) 10001 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 10002 else 10003 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 10004 break; 10005 } 10006 10007 // In ARC, use some specialized diagnostics for occasions where we 10008 // infer 'const'. These are always pseudo-strong variables. 10009 if (S.getLangOpts().ObjCAutoRefCount) { 10010 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 10011 if (declRef && isa<VarDecl>(declRef->getDecl())) { 10012 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 10013 10014 // Use the normal diagnostic if it's pseudo-__strong but the 10015 // user actually wrote 'const'. 10016 if (var->isARCPseudoStrong() && 10017 (!var->getTypeSourceInfo() || 10018 !var->getTypeSourceInfo()->getType().isConstQualified())) { 10019 // There are two pseudo-strong cases: 10020 // - self 10021 ObjCMethodDecl *method = S.getCurMethodDecl(); 10022 if (method && var == method->getSelfDecl()) 10023 DiagID = method->isClassMethod() 10024 ? diag::err_typecheck_arc_assign_self_class_method 10025 : diag::err_typecheck_arc_assign_self; 10026 10027 // - fast enumeration variables 10028 else 10029 DiagID = diag::err_typecheck_arr_assign_enumeration; 10030 10031 SourceRange Assign; 10032 if (Loc != OrigLoc) 10033 Assign = SourceRange(OrigLoc, OrigLoc); 10034 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10035 // We need to preserve the AST regardless, so migration tool 10036 // can do its job. 10037 return false; 10038 } 10039 } 10040 } 10041 10042 // If none of the special cases above are triggered, then this is a 10043 // simple const assignment. 10044 if (DiagID == 0) { 10045 DiagnoseConstAssignment(S, E, Loc); 10046 return true; 10047 } 10048 10049 break; 10050 case Expr::MLV_ConstAddrSpace: 10051 DiagnoseConstAssignment(S, E, Loc); 10052 return true; 10053 case Expr::MLV_ArrayType: 10054 case Expr::MLV_ArrayTemporary: 10055 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 10056 NeedType = true; 10057 break; 10058 case Expr::MLV_NotObjectType: 10059 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 10060 NeedType = true; 10061 break; 10062 case Expr::MLV_LValueCast: 10063 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 10064 break; 10065 case Expr::MLV_Valid: 10066 llvm_unreachable("did not take early return for MLV_Valid"); 10067 case Expr::MLV_InvalidExpression: 10068 case Expr::MLV_MemberFunction: 10069 case Expr::MLV_ClassTemporary: 10070 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 10071 break; 10072 case Expr::MLV_IncompleteType: 10073 case Expr::MLV_IncompleteVoidType: 10074 return S.RequireCompleteType(Loc, E->getType(), 10075 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 10076 case Expr::MLV_DuplicateVectorComponents: 10077 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 10078 break; 10079 case Expr::MLV_NoSetterProperty: 10080 llvm_unreachable("readonly properties should be processed differently"); 10081 case Expr::MLV_InvalidMessageExpression: 10082 DiagID = diag::error_readonly_message_assignment; 10083 break; 10084 case Expr::MLV_SubObjCPropertySetting: 10085 DiagID = diag::error_no_subobject_property_setting; 10086 break; 10087 } 10088 10089 SourceRange Assign; 10090 if (Loc != OrigLoc) 10091 Assign = SourceRange(OrigLoc, OrigLoc); 10092 if (NeedType) 10093 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 10094 else 10095 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10096 return true; 10097 } 10098 10099 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 10100 SourceLocation Loc, 10101 Sema &Sema) { 10102 // C / C++ fields 10103 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 10104 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 10105 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 10106 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 10107 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 10108 } 10109 10110 // Objective-C instance variables 10111 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 10112 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 10113 if (OL && OR && OL->getDecl() == OR->getDecl()) { 10114 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 10115 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 10116 if (RL && RR && RL->getDecl() == RR->getDecl()) 10117 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 10118 } 10119 } 10120 10121 // C99 6.5.16.1 10122 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 10123 SourceLocation Loc, 10124 QualType CompoundType) { 10125 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 10126 10127 // Verify that LHS is a modifiable lvalue, and emit error if not. 10128 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 10129 return QualType(); 10130 10131 QualType LHSType = LHSExpr->getType(); 10132 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 10133 CompoundType; 10134 // OpenCL v1.2 s6.1.1.1 p2: 10135 // The half data type can only be used to declare a pointer to a buffer that 10136 // contains half values 10137 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 && 10138 LHSType->isHalfType()) { 10139 Diag(Loc, diag::err_opencl_half_load_store) << 1 10140 << LHSType.getUnqualifiedType(); 10141 return QualType(); 10142 } 10143 10144 AssignConvertType ConvTy; 10145 if (CompoundType.isNull()) { 10146 Expr *RHSCheck = RHS.get(); 10147 10148 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 10149 10150 QualType LHSTy(LHSType); 10151 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 10152 if (RHS.isInvalid()) 10153 return QualType(); 10154 // Special case of NSObject attributes on c-style pointer types. 10155 if (ConvTy == IncompatiblePointer && 10156 ((Context.isObjCNSObjectType(LHSType) && 10157 RHSType->isObjCObjectPointerType()) || 10158 (Context.isObjCNSObjectType(RHSType) && 10159 LHSType->isObjCObjectPointerType()))) 10160 ConvTy = Compatible; 10161 10162 if (ConvTy == Compatible && 10163 LHSType->isObjCObjectType()) 10164 Diag(Loc, diag::err_objc_object_assignment) 10165 << LHSType; 10166 10167 // If the RHS is a unary plus or minus, check to see if they = and + are 10168 // right next to each other. If so, the user may have typo'd "x =+ 4" 10169 // instead of "x += 4". 10170 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 10171 RHSCheck = ICE->getSubExpr(); 10172 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 10173 if ((UO->getOpcode() == UO_Plus || 10174 UO->getOpcode() == UO_Minus) && 10175 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 10176 // Only if the two operators are exactly adjacent. 10177 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 10178 // And there is a space or other character before the subexpr of the 10179 // unary +/-. We don't want to warn on "x=-1". 10180 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 10181 UO->getSubExpr()->getLocStart().isFileID()) { 10182 Diag(Loc, diag::warn_not_compound_assign) 10183 << (UO->getOpcode() == UO_Plus ? "+" : "-") 10184 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 10185 } 10186 } 10187 10188 if (ConvTy == Compatible) { 10189 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 10190 // Warn about retain cycles where a block captures the LHS, but 10191 // not if the LHS is a simple variable into which the block is 10192 // being stored...unless that variable can be captured by reference! 10193 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 10194 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 10195 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 10196 checkRetainCycles(LHSExpr, RHS.get()); 10197 10198 // It is safe to assign a weak reference into a strong variable. 10199 // Although this code can still have problems: 10200 // id x = self.weakProp; 10201 // id y = self.weakProp; 10202 // we do not warn to warn spuriously when 'x' and 'y' are on separate 10203 // paths through the function. This should be revisited if 10204 // -Wrepeated-use-of-weak is made flow-sensitive. 10205 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 10206 RHS.get()->getLocStart())) 10207 getCurFunction()->markSafeWeakUse(RHS.get()); 10208 10209 } else if (getLangOpts().ObjCAutoRefCount) { 10210 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 10211 } 10212 } 10213 } else { 10214 // Compound assignment "x += y" 10215 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 10216 } 10217 10218 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 10219 RHS.get(), AA_Assigning)) 10220 return QualType(); 10221 10222 CheckForNullPointerDereference(*this, LHSExpr); 10223 10224 // C99 6.5.16p3: The type of an assignment expression is the type of the 10225 // left operand unless the left operand has qualified type, in which case 10226 // it is the unqualified version of the type of the left operand. 10227 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 10228 // is converted to the type of the assignment expression (above). 10229 // C++ 5.17p1: the type of the assignment expression is that of its left 10230 // operand. 10231 return (getLangOpts().CPlusPlus 10232 ? LHSType : LHSType.getUnqualifiedType()); 10233 } 10234 10235 // Only ignore explicit casts to void. 10236 static bool IgnoreCommaOperand(const Expr *E) { 10237 E = E->IgnoreParens(); 10238 10239 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 10240 if (CE->getCastKind() == CK_ToVoid) { 10241 return true; 10242 } 10243 } 10244 10245 return false; 10246 } 10247 10248 // Look for instances where it is likely the comma operator is confused with 10249 // another operator. There is a whitelist of acceptable expressions for the 10250 // left hand side of the comma operator, otherwise emit a warning. 10251 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 10252 // No warnings in macros 10253 if (Loc.isMacroID()) 10254 return; 10255 10256 // Don't warn in template instantiations. 10257 if (!ActiveTemplateInstantiations.empty()) 10258 return; 10259 10260 // Scope isn't fine-grained enough to whitelist the specific cases, so 10261 // instead, skip more than needed, then call back into here with the 10262 // CommaVisitor in SemaStmt.cpp. 10263 // The whitelisted locations are the initialization and increment portions 10264 // of a for loop. The additional checks are on the condition of 10265 // if statements, do/while loops, and for loops. 10266 const unsigned ForIncrementFlags = 10267 Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope; 10268 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 10269 const unsigned ScopeFlags = getCurScope()->getFlags(); 10270 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 10271 (ScopeFlags & ForInitFlags) == ForInitFlags) 10272 return; 10273 10274 // If there are multiple comma operators used together, get the RHS of the 10275 // of the comma operator as the LHS. 10276 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 10277 if (BO->getOpcode() != BO_Comma) 10278 break; 10279 LHS = BO->getRHS(); 10280 } 10281 10282 // Only allow some expressions on LHS to not warn. 10283 if (IgnoreCommaOperand(LHS)) 10284 return; 10285 10286 Diag(Loc, diag::warn_comma_operator); 10287 Diag(LHS->getLocStart(), diag::note_cast_to_void) 10288 << LHS->getSourceRange() 10289 << FixItHint::CreateInsertion(LHS->getLocStart(), 10290 LangOpts.CPlusPlus ? "static_cast<void>(" 10291 : "(void)(") 10292 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()), 10293 ")"); 10294 } 10295 10296 // C99 6.5.17 10297 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 10298 SourceLocation Loc) { 10299 LHS = S.CheckPlaceholderExpr(LHS.get()); 10300 RHS = S.CheckPlaceholderExpr(RHS.get()); 10301 if (LHS.isInvalid() || RHS.isInvalid()) 10302 return QualType(); 10303 10304 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 10305 // operands, but not unary promotions. 10306 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 10307 10308 // So we treat the LHS as a ignored value, and in C++ we allow the 10309 // containing site to determine what should be done with the RHS. 10310 LHS = S.IgnoredValueConversions(LHS.get()); 10311 if (LHS.isInvalid()) 10312 return QualType(); 10313 10314 S.DiagnoseUnusedExprResult(LHS.get()); 10315 10316 if (!S.getLangOpts().CPlusPlus) { 10317 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 10318 if (RHS.isInvalid()) 10319 return QualType(); 10320 if (!RHS.get()->getType()->isVoidType()) 10321 S.RequireCompleteType(Loc, RHS.get()->getType(), 10322 diag::err_incomplete_type); 10323 } 10324 10325 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 10326 S.DiagnoseCommaOperator(LHS.get(), Loc); 10327 10328 return RHS.get()->getType(); 10329 } 10330 10331 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 10332 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 10333 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 10334 ExprValueKind &VK, 10335 ExprObjectKind &OK, 10336 SourceLocation OpLoc, 10337 bool IsInc, bool IsPrefix) { 10338 if (Op->isTypeDependent()) 10339 return S.Context.DependentTy; 10340 10341 QualType ResType = Op->getType(); 10342 // Atomic types can be used for increment / decrement where the non-atomic 10343 // versions can, so ignore the _Atomic() specifier for the purpose of 10344 // checking. 10345 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10346 ResType = ResAtomicType->getValueType(); 10347 10348 assert(!ResType.isNull() && "no type for increment/decrement expression"); 10349 10350 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 10351 // Decrement of bool is not allowed. 10352 if (!IsInc) { 10353 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 10354 return QualType(); 10355 } 10356 // Increment of bool sets it to true, but is deprecated. 10357 S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool 10358 : diag::warn_increment_bool) 10359 << Op->getSourceRange(); 10360 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 10361 // Error on enum increments and decrements in C++ mode 10362 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 10363 return QualType(); 10364 } else if (ResType->isRealType()) { 10365 // OK! 10366 } else if (ResType->isPointerType()) { 10367 // C99 6.5.2.4p2, 6.5.6p2 10368 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 10369 return QualType(); 10370 } else if (ResType->isObjCObjectPointerType()) { 10371 // On modern runtimes, ObjC pointer arithmetic is forbidden. 10372 // Otherwise, we just need a complete type. 10373 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 10374 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 10375 return QualType(); 10376 } else if (ResType->isAnyComplexType()) { 10377 // C99 does not support ++/-- on complex types, we allow as an extension. 10378 S.Diag(OpLoc, diag::ext_integer_increment_complex) 10379 << ResType << Op->getSourceRange(); 10380 } else if (ResType->isPlaceholderType()) { 10381 ExprResult PR = S.CheckPlaceholderExpr(Op); 10382 if (PR.isInvalid()) return QualType(); 10383 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 10384 IsInc, IsPrefix); 10385 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 10386 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 10387 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 10388 (ResType->getAs<VectorType>()->getVectorKind() != 10389 VectorType::AltiVecBool)) { 10390 // The z vector extensions allow ++ and -- for non-bool vectors. 10391 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 10392 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 10393 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 10394 } else { 10395 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 10396 << ResType << int(IsInc) << Op->getSourceRange(); 10397 return QualType(); 10398 } 10399 // At this point, we know we have a real, complex or pointer type. 10400 // Now make sure the operand is a modifiable lvalue. 10401 if (CheckForModifiableLvalue(Op, OpLoc, S)) 10402 return QualType(); 10403 // In C++, a prefix increment is the same type as the operand. Otherwise 10404 // (in C or with postfix), the increment is the unqualified type of the 10405 // operand. 10406 if (IsPrefix && S.getLangOpts().CPlusPlus) { 10407 VK = VK_LValue; 10408 OK = Op->getObjectKind(); 10409 return ResType; 10410 } else { 10411 VK = VK_RValue; 10412 return ResType.getUnqualifiedType(); 10413 } 10414 } 10415 10416 10417 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 10418 /// This routine allows us to typecheck complex/recursive expressions 10419 /// where the declaration is needed for type checking. We only need to 10420 /// handle cases when the expression references a function designator 10421 /// or is an lvalue. Here are some examples: 10422 /// - &(x) => x 10423 /// - &*****f => f for f a function designator. 10424 /// - &s.xx => s 10425 /// - &s.zz[1].yy -> s, if zz is an array 10426 /// - *(x + 1) -> x, if x is an array 10427 /// - &"123"[2] -> 0 10428 /// - & __real__ x -> x 10429 static ValueDecl *getPrimaryDecl(Expr *E) { 10430 switch (E->getStmtClass()) { 10431 case Stmt::DeclRefExprClass: 10432 return cast<DeclRefExpr>(E)->getDecl(); 10433 case Stmt::MemberExprClass: 10434 // If this is an arrow operator, the address is an offset from 10435 // the base's value, so the object the base refers to is 10436 // irrelevant. 10437 if (cast<MemberExpr>(E)->isArrow()) 10438 return nullptr; 10439 // Otherwise, the expression refers to a part of the base 10440 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 10441 case Stmt::ArraySubscriptExprClass: { 10442 // FIXME: This code shouldn't be necessary! We should catch the implicit 10443 // promotion of register arrays earlier. 10444 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 10445 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 10446 if (ICE->getSubExpr()->getType()->isArrayType()) 10447 return getPrimaryDecl(ICE->getSubExpr()); 10448 } 10449 return nullptr; 10450 } 10451 case Stmt::UnaryOperatorClass: { 10452 UnaryOperator *UO = cast<UnaryOperator>(E); 10453 10454 switch(UO->getOpcode()) { 10455 case UO_Real: 10456 case UO_Imag: 10457 case UO_Extension: 10458 return getPrimaryDecl(UO->getSubExpr()); 10459 default: 10460 return nullptr; 10461 } 10462 } 10463 case Stmt::ParenExprClass: 10464 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 10465 case Stmt::ImplicitCastExprClass: 10466 // If the result of an implicit cast is an l-value, we care about 10467 // the sub-expression; otherwise, the result here doesn't matter. 10468 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 10469 default: 10470 return nullptr; 10471 } 10472 } 10473 10474 namespace { 10475 enum { 10476 AO_Bit_Field = 0, 10477 AO_Vector_Element = 1, 10478 AO_Property_Expansion = 2, 10479 AO_Register_Variable = 3, 10480 AO_No_Error = 4 10481 }; 10482 } 10483 /// \brief Diagnose invalid operand for address of operations. 10484 /// 10485 /// \param Type The type of operand which cannot have its address taken. 10486 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 10487 Expr *E, unsigned Type) { 10488 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 10489 } 10490 10491 /// CheckAddressOfOperand - The operand of & must be either a function 10492 /// designator or an lvalue designating an object. If it is an lvalue, the 10493 /// object cannot be declared with storage class register or be a bit field. 10494 /// Note: The usual conversions are *not* applied to the operand of the & 10495 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 10496 /// In C++, the operand might be an overloaded function name, in which case 10497 /// we allow the '&' but retain the overloaded-function type. 10498 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 10499 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 10500 if (PTy->getKind() == BuiltinType::Overload) { 10501 Expr *E = OrigOp.get()->IgnoreParens(); 10502 if (!isa<OverloadExpr>(E)) { 10503 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 10504 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 10505 << OrigOp.get()->getSourceRange(); 10506 return QualType(); 10507 } 10508 10509 OverloadExpr *Ovl = cast<OverloadExpr>(E); 10510 if (isa<UnresolvedMemberExpr>(Ovl)) 10511 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 10512 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10513 << OrigOp.get()->getSourceRange(); 10514 return QualType(); 10515 } 10516 10517 return Context.OverloadTy; 10518 } 10519 10520 if (PTy->getKind() == BuiltinType::UnknownAny) 10521 return Context.UnknownAnyTy; 10522 10523 if (PTy->getKind() == BuiltinType::BoundMember) { 10524 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10525 << OrigOp.get()->getSourceRange(); 10526 return QualType(); 10527 } 10528 10529 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 10530 if (OrigOp.isInvalid()) return QualType(); 10531 } 10532 10533 if (OrigOp.get()->isTypeDependent()) 10534 return Context.DependentTy; 10535 10536 assert(!OrigOp.get()->getType()->isPlaceholderType()); 10537 10538 // Make sure to ignore parentheses in subsequent checks 10539 Expr *op = OrigOp.get()->IgnoreParens(); 10540 10541 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 10542 if (LangOpts.OpenCL && op->getType()->isFunctionType()) { 10543 Diag(op->getExprLoc(), diag::err_opencl_taking_function_address); 10544 return QualType(); 10545 } 10546 10547 if (getLangOpts().C99) { 10548 // Implement C99-only parts of addressof rules. 10549 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 10550 if (uOp->getOpcode() == UO_Deref) 10551 // Per C99 6.5.3.2, the address of a deref always returns a valid result 10552 // (assuming the deref expression is valid). 10553 return uOp->getSubExpr()->getType(); 10554 } 10555 // Technically, there should be a check for array subscript 10556 // expressions here, but the result of one is always an lvalue anyway. 10557 } 10558 ValueDecl *dcl = getPrimaryDecl(op); 10559 10560 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 10561 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 10562 op->getLocStart())) 10563 return QualType(); 10564 10565 Expr::LValueClassification lval = op->ClassifyLValue(Context); 10566 unsigned AddressOfError = AO_No_Error; 10567 10568 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 10569 bool sfinae = (bool)isSFINAEContext(); 10570 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 10571 : diag::ext_typecheck_addrof_temporary) 10572 << op->getType() << op->getSourceRange(); 10573 if (sfinae) 10574 return QualType(); 10575 // Materialize the temporary as an lvalue so that we can take its address. 10576 OrigOp = op = 10577 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 10578 } else if (isa<ObjCSelectorExpr>(op)) { 10579 return Context.getPointerType(op->getType()); 10580 } else if (lval == Expr::LV_MemberFunction) { 10581 // If it's an instance method, make a member pointer. 10582 // The expression must have exactly the form &A::foo. 10583 10584 // If the underlying expression isn't a decl ref, give up. 10585 if (!isa<DeclRefExpr>(op)) { 10586 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10587 << OrigOp.get()->getSourceRange(); 10588 return QualType(); 10589 } 10590 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 10591 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 10592 10593 // The id-expression was parenthesized. 10594 if (OrigOp.get() != DRE) { 10595 Diag(OpLoc, diag::err_parens_pointer_member_function) 10596 << OrigOp.get()->getSourceRange(); 10597 10598 // The method was named without a qualifier. 10599 } else if (!DRE->getQualifier()) { 10600 if (MD->getParent()->getName().empty()) 10601 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 10602 << op->getSourceRange(); 10603 else { 10604 SmallString<32> Str; 10605 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 10606 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 10607 << op->getSourceRange() 10608 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 10609 } 10610 } 10611 10612 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 10613 if (isa<CXXDestructorDecl>(MD)) 10614 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 10615 10616 QualType MPTy = Context.getMemberPointerType( 10617 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 10618 // Under the MS ABI, lock down the inheritance model now. 10619 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 10620 (void)isCompleteType(OpLoc, MPTy); 10621 return MPTy; 10622 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 10623 // C99 6.5.3.2p1 10624 // The operand must be either an l-value or a function designator 10625 if (!op->getType()->isFunctionType()) { 10626 // Use a special diagnostic for loads from property references. 10627 if (isa<PseudoObjectExpr>(op)) { 10628 AddressOfError = AO_Property_Expansion; 10629 } else { 10630 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 10631 << op->getType() << op->getSourceRange(); 10632 return QualType(); 10633 } 10634 } 10635 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 10636 // The operand cannot be a bit-field 10637 AddressOfError = AO_Bit_Field; 10638 } else if (op->getObjectKind() == OK_VectorComponent) { 10639 // The operand cannot be an element of a vector 10640 AddressOfError = AO_Vector_Element; 10641 } else if (dcl) { // C99 6.5.3.2p1 10642 // We have an lvalue with a decl. Make sure the decl is not declared 10643 // with the register storage-class specifier. 10644 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 10645 // in C++ it is not error to take address of a register 10646 // variable (c++03 7.1.1P3) 10647 if (vd->getStorageClass() == SC_Register && 10648 !getLangOpts().CPlusPlus) { 10649 AddressOfError = AO_Register_Variable; 10650 } 10651 } else if (isa<MSPropertyDecl>(dcl)) { 10652 AddressOfError = AO_Property_Expansion; 10653 } else if (isa<FunctionTemplateDecl>(dcl)) { 10654 return Context.OverloadTy; 10655 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 10656 // Okay: we can take the address of a field. 10657 // Could be a pointer to member, though, if there is an explicit 10658 // scope qualifier for the class. 10659 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 10660 DeclContext *Ctx = dcl->getDeclContext(); 10661 if (Ctx && Ctx->isRecord()) { 10662 if (dcl->getType()->isReferenceType()) { 10663 Diag(OpLoc, 10664 diag::err_cannot_form_pointer_to_member_of_reference_type) 10665 << dcl->getDeclName() << dcl->getType(); 10666 return QualType(); 10667 } 10668 10669 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 10670 Ctx = Ctx->getParent(); 10671 10672 QualType MPTy = Context.getMemberPointerType( 10673 op->getType(), 10674 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 10675 // Under the MS ABI, lock down the inheritance model now. 10676 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 10677 (void)isCompleteType(OpLoc, MPTy); 10678 return MPTy; 10679 } 10680 } 10681 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 10682 !isa<BindingDecl>(dcl)) 10683 llvm_unreachable("Unknown/unexpected decl type"); 10684 } 10685 10686 if (AddressOfError != AO_No_Error) { 10687 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 10688 return QualType(); 10689 } 10690 10691 if (lval == Expr::LV_IncompleteVoidType) { 10692 // Taking the address of a void variable is technically illegal, but we 10693 // allow it in cases which are otherwise valid. 10694 // Example: "extern void x; void* y = &x;". 10695 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 10696 } 10697 10698 // If the operand has type "type", the result has type "pointer to type". 10699 if (op->getType()->isObjCObjectType()) 10700 return Context.getObjCObjectPointerType(op->getType()); 10701 10702 CheckAddressOfPackedMember(op); 10703 10704 return Context.getPointerType(op->getType()); 10705 } 10706 10707 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 10708 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 10709 if (!DRE) 10710 return; 10711 const Decl *D = DRE->getDecl(); 10712 if (!D) 10713 return; 10714 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 10715 if (!Param) 10716 return; 10717 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 10718 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 10719 return; 10720 if (FunctionScopeInfo *FD = S.getCurFunction()) 10721 if (!FD->ModifiedNonNullParams.count(Param)) 10722 FD->ModifiedNonNullParams.insert(Param); 10723 } 10724 10725 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 10726 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 10727 SourceLocation OpLoc) { 10728 if (Op->isTypeDependent()) 10729 return S.Context.DependentTy; 10730 10731 ExprResult ConvResult = S.UsualUnaryConversions(Op); 10732 if (ConvResult.isInvalid()) 10733 return QualType(); 10734 Op = ConvResult.get(); 10735 QualType OpTy = Op->getType(); 10736 QualType Result; 10737 10738 if (isa<CXXReinterpretCastExpr>(Op)) { 10739 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 10740 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 10741 Op->getSourceRange()); 10742 } 10743 10744 if (const PointerType *PT = OpTy->getAs<PointerType>()) 10745 { 10746 Result = PT->getPointeeType(); 10747 } 10748 else if (const ObjCObjectPointerType *OPT = 10749 OpTy->getAs<ObjCObjectPointerType>()) 10750 Result = OPT->getPointeeType(); 10751 else { 10752 ExprResult PR = S.CheckPlaceholderExpr(Op); 10753 if (PR.isInvalid()) return QualType(); 10754 if (PR.get() != Op) 10755 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 10756 } 10757 10758 if (Result.isNull()) { 10759 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 10760 << OpTy << Op->getSourceRange(); 10761 return QualType(); 10762 } 10763 10764 // Note that per both C89 and C99, indirection is always legal, even if Result 10765 // is an incomplete type or void. It would be possible to warn about 10766 // dereferencing a void pointer, but it's completely well-defined, and such a 10767 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 10768 // for pointers to 'void' but is fine for any other pointer type: 10769 // 10770 // C++ [expr.unary.op]p1: 10771 // [...] the expression to which [the unary * operator] is applied shall 10772 // be a pointer to an object type, or a pointer to a function type 10773 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 10774 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 10775 << OpTy << Op->getSourceRange(); 10776 10777 // Dereferences are usually l-values... 10778 VK = VK_LValue; 10779 10780 // ...except that certain expressions are never l-values in C. 10781 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 10782 VK = VK_RValue; 10783 10784 return Result; 10785 } 10786 10787 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 10788 BinaryOperatorKind Opc; 10789 switch (Kind) { 10790 default: llvm_unreachable("Unknown binop!"); 10791 case tok::periodstar: Opc = BO_PtrMemD; break; 10792 case tok::arrowstar: Opc = BO_PtrMemI; break; 10793 case tok::star: Opc = BO_Mul; break; 10794 case tok::slash: Opc = BO_Div; break; 10795 case tok::percent: Opc = BO_Rem; break; 10796 case tok::plus: Opc = BO_Add; break; 10797 case tok::minus: Opc = BO_Sub; break; 10798 case tok::lessless: Opc = BO_Shl; break; 10799 case tok::greatergreater: Opc = BO_Shr; break; 10800 case tok::lessequal: Opc = BO_LE; break; 10801 case tok::less: Opc = BO_LT; break; 10802 case tok::greaterequal: Opc = BO_GE; break; 10803 case tok::greater: Opc = BO_GT; break; 10804 case tok::exclaimequal: Opc = BO_NE; break; 10805 case tok::equalequal: Opc = BO_EQ; break; 10806 case tok::amp: Opc = BO_And; break; 10807 case tok::caret: Opc = BO_Xor; break; 10808 case tok::pipe: Opc = BO_Or; break; 10809 case tok::ampamp: Opc = BO_LAnd; break; 10810 case tok::pipepipe: Opc = BO_LOr; break; 10811 case tok::equal: Opc = BO_Assign; break; 10812 case tok::starequal: Opc = BO_MulAssign; break; 10813 case tok::slashequal: Opc = BO_DivAssign; break; 10814 case tok::percentequal: Opc = BO_RemAssign; break; 10815 case tok::plusequal: Opc = BO_AddAssign; break; 10816 case tok::minusequal: Opc = BO_SubAssign; break; 10817 case tok::lesslessequal: Opc = BO_ShlAssign; break; 10818 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 10819 case tok::ampequal: Opc = BO_AndAssign; break; 10820 case tok::caretequal: Opc = BO_XorAssign; break; 10821 case tok::pipeequal: Opc = BO_OrAssign; break; 10822 case tok::comma: Opc = BO_Comma; break; 10823 } 10824 return Opc; 10825 } 10826 10827 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 10828 tok::TokenKind Kind) { 10829 UnaryOperatorKind Opc; 10830 switch (Kind) { 10831 default: llvm_unreachable("Unknown unary op!"); 10832 case tok::plusplus: Opc = UO_PreInc; break; 10833 case tok::minusminus: Opc = UO_PreDec; break; 10834 case tok::amp: Opc = UO_AddrOf; break; 10835 case tok::star: Opc = UO_Deref; break; 10836 case tok::plus: Opc = UO_Plus; break; 10837 case tok::minus: Opc = UO_Minus; break; 10838 case tok::tilde: Opc = UO_Not; break; 10839 case tok::exclaim: Opc = UO_LNot; break; 10840 case tok::kw___real: Opc = UO_Real; break; 10841 case tok::kw___imag: Opc = UO_Imag; break; 10842 case tok::kw___extension__: Opc = UO_Extension; break; 10843 } 10844 return Opc; 10845 } 10846 10847 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 10848 /// This warning is only emitted for builtin assignment operations. It is also 10849 /// suppressed in the event of macro expansions. 10850 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 10851 SourceLocation OpLoc) { 10852 if (!S.ActiveTemplateInstantiations.empty()) 10853 return; 10854 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 10855 return; 10856 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 10857 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 10858 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 10859 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 10860 if (!LHSDeclRef || !RHSDeclRef || 10861 LHSDeclRef->getLocation().isMacroID() || 10862 RHSDeclRef->getLocation().isMacroID()) 10863 return; 10864 const ValueDecl *LHSDecl = 10865 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 10866 const ValueDecl *RHSDecl = 10867 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 10868 if (LHSDecl != RHSDecl) 10869 return; 10870 if (LHSDecl->getType().isVolatileQualified()) 10871 return; 10872 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 10873 if (RefTy->getPointeeType().isVolatileQualified()) 10874 return; 10875 10876 S.Diag(OpLoc, diag::warn_self_assignment) 10877 << LHSDeclRef->getType() 10878 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10879 } 10880 10881 /// Check if a bitwise-& is performed on an Objective-C pointer. This 10882 /// is usually indicative of introspection within the Objective-C pointer. 10883 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 10884 SourceLocation OpLoc) { 10885 if (!S.getLangOpts().ObjC1) 10886 return; 10887 10888 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 10889 const Expr *LHS = L.get(); 10890 const Expr *RHS = R.get(); 10891 10892 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 10893 ObjCPointerExpr = LHS; 10894 OtherExpr = RHS; 10895 } 10896 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 10897 ObjCPointerExpr = RHS; 10898 OtherExpr = LHS; 10899 } 10900 10901 // This warning is deliberately made very specific to reduce false 10902 // positives with logic that uses '&' for hashing. This logic mainly 10903 // looks for code trying to introspect into tagged pointers, which 10904 // code should generally never do. 10905 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 10906 unsigned Diag = diag::warn_objc_pointer_masking; 10907 // Determine if we are introspecting the result of performSelectorXXX. 10908 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 10909 // Special case messages to -performSelector and friends, which 10910 // can return non-pointer values boxed in a pointer value. 10911 // Some clients may wish to silence warnings in this subcase. 10912 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 10913 Selector S = ME->getSelector(); 10914 StringRef SelArg0 = S.getNameForSlot(0); 10915 if (SelArg0.startswith("performSelector")) 10916 Diag = diag::warn_objc_pointer_masking_performSelector; 10917 } 10918 10919 S.Diag(OpLoc, Diag) 10920 << ObjCPointerExpr->getSourceRange(); 10921 } 10922 } 10923 10924 static NamedDecl *getDeclFromExpr(Expr *E) { 10925 if (!E) 10926 return nullptr; 10927 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 10928 return DRE->getDecl(); 10929 if (auto *ME = dyn_cast<MemberExpr>(E)) 10930 return ME->getMemberDecl(); 10931 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 10932 return IRE->getDecl(); 10933 return nullptr; 10934 } 10935 10936 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 10937 /// operator @p Opc at location @c TokLoc. This routine only supports 10938 /// built-in operations; ActOnBinOp handles overloaded operators. 10939 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 10940 BinaryOperatorKind Opc, 10941 Expr *LHSExpr, Expr *RHSExpr) { 10942 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 10943 // The syntax only allows initializer lists on the RHS of assignment, 10944 // so we don't need to worry about accepting invalid code for 10945 // non-assignment operators. 10946 // C++11 5.17p9: 10947 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 10948 // of x = {} is x = T(). 10949 InitializationKind Kind = 10950 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 10951 InitializedEntity Entity = 10952 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 10953 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 10954 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 10955 if (Init.isInvalid()) 10956 return Init; 10957 RHSExpr = Init.get(); 10958 } 10959 10960 ExprResult LHS = LHSExpr, RHS = RHSExpr; 10961 QualType ResultTy; // Result type of the binary operator. 10962 // The following two variables are used for compound assignment operators 10963 QualType CompLHSTy; // Type of LHS after promotions for computation 10964 QualType CompResultTy; // Type of computation result 10965 ExprValueKind VK = VK_RValue; 10966 ExprObjectKind OK = OK_Ordinary; 10967 10968 if (!getLangOpts().CPlusPlus) { 10969 // C cannot handle TypoExpr nodes on either side of a binop because it 10970 // doesn't handle dependent types properly, so make sure any TypoExprs have 10971 // been dealt with before checking the operands. 10972 LHS = CorrectDelayedTyposInExpr(LHSExpr); 10973 RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) { 10974 if (Opc != BO_Assign) 10975 return ExprResult(E); 10976 // Avoid correcting the RHS to the same Expr as the LHS. 10977 Decl *D = getDeclFromExpr(E); 10978 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 10979 }); 10980 if (!LHS.isUsable() || !RHS.isUsable()) 10981 return ExprError(); 10982 } 10983 10984 if (getLangOpts().OpenCL) { 10985 QualType LHSTy = LHSExpr->getType(); 10986 QualType RHSTy = RHSExpr->getType(); 10987 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 10988 // the ATOMIC_VAR_INIT macro. 10989 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 10990 SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 10991 if (BO_Assign == Opc) 10992 Diag(OpLoc, diag::err_atomic_init_constant) << SR; 10993 else 10994 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 10995 return ExprError(); 10996 } 10997 10998 // OpenCL special types - image, sampler, pipe, and blocks are to be used 10999 // only with a builtin functions and therefore should be disallowed here. 11000 if (LHSTy->isImageType() || RHSTy->isImageType() || 11001 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 11002 LHSTy->isPipeType() || RHSTy->isPipeType() || 11003 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 11004 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 11005 return ExprError(); 11006 } 11007 } 11008 11009 switch (Opc) { 11010 case BO_Assign: 11011 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 11012 if (getLangOpts().CPlusPlus && 11013 LHS.get()->getObjectKind() != OK_ObjCProperty) { 11014 VK = LHS.get()->getValueKind(); 11015 OK = LHS.get()->getObjectKind(); 11016 } 11017 if (!ResultTy.isNull()) { 11018 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 11019 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 11020 } 11021 RecordModifiableNonNullParam(*this, LHS.get()); 11022 break; 11023 case BO_PtrMemD: 11024 case BO_PtrMemI: 11025 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 11026 Opc == BO_PtrMemI); 11027 break; 11028 case BO_Mul: 11029 case BO_Div: 11030 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 11031 Opc == BO_Div); 11032 break; 11033 case BO_Rem: 11034 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 11035 break; 11036 case BO_Add: 11037 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 11038 break; 11039 case BO_Sub: 11040 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 11041 break; 11042 case BO_Shl: 11043 case BO_Shr: 11044 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 11045 break; 11046 case BO_LE: 11047 case BO_LT: 11048 case BO_GE: 11049 case BO_GT: 11050 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 11051 break; 11052 case BO_EQ: 11053 case BO_NE: 11054 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 11055 break; 11056 case BO_And: 11057 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 11058 case BO_Xor: 11059 case BO_Or: 11060 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc); 11061 break; 11062 case BO_LAnd: 11063 case BO_LOr: 11064 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 11065 break; 11066 case BO_MulAssign: 11067 case BO_DivAssign: 11068 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 11069 Opc == BO_DivAssign); 11070 CompLHSTy = CompResultTy; 11071 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11072 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11073 break; 11074 case BO_RemAssign: 11075 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 11076 CompLHSTy = CompResultTy; 11077 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11078 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11079 break; 11080 case BO_AddAssign: 11081 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 11082 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11083 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11084 break; 11085 case BO_SubAssign: 11086 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 11087 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11088 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11089 break; 11090 case BO_ShlAssign: 11091 case BO_ShrAssign: 11092 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 11093 CompLHSTy = CompResultTy; 11094 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11095 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11096 break; 11097 case BO_AndAssign: 11098 case BO_OrAssign: // fallthrough 11099 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 11100 case BO_XorAssign: 11101 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true); 11102 CompLHSTy = CompResultTy; 11103 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11104 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11105 break; 11106 case BO_Comma: 11107 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 11108 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 11109 VK = RHS.get()->getValueKind(); 11110 OK = RHS.get()->getObjectKind(); 11111 } 11112 break; 11113 } 11114 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 11115 return ExprError(); 11116 11117 // Check for array bounds violations for both sides of the BinaryOperator 11118 CheckArrayAccess(LHS.get()); 11119 CheckArrayAccess(RHS.get()); 11120 11121 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 11122 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 11123 &Context.Idents.get("object_setClass"), 11124 SourceLocation(), LookupOrdinaryName); 11125 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 11126 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd()); 11127 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 11128 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 11129 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 11130 FixItHint::CreateInsertion(RHSLocEnd, ")"); 11131 } 11132 else 11133 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 11134 } 11135 else if (const ObjCIvarRefExpr *OIRE = 11136 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 11137 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 11138 11139 if (CompResultTy.isNull()) 11140 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 11141 OK, OpLoc, FPFeatures.fp_contract); 11142 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 11143 OK_ObjCProperty) { 11144 VK = VK_LValue; 11145 OK = LHS.get()->getObjectKind(); 11146 } 11147 return new (Context) CompoundAssignOperator( 11148 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 11149 OpLoc, FPFeatures.fp_contract); 11150 } 11151 11152 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 11153 /// operators are mixed in a way that suggests that the programmer forgot that 11154 /// comparison operators have higher precedence. The most typical example of 11155 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 11156 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 11157 SourceLocation OpLoc, Expr *LHSExpr, 11158 Expr *RHSExpr) { 11159 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 11160 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 11161 11162 // Check that one of the sides is a comparison operator and the other isn't. 11163 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 11164 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 11165 if (isLeftComp == isRightComp) 11166 return; 11167 11168 // Bitwise operations are sometimes used as eager logical ops. 11169 // Don't diagnose this. 11170 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 11171 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 11172 if (isLeftBitwise || isRightBitwise) 11173 return; 11174 11175 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 11176 OpLoc) 11177 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 11178 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 11179 SourceRange ParensRange = isLeftComp ? 11180 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 11181 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd()); 11182 11183 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 11184 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 11185 SuggestParentheses(Self, OpLoc, 11186 Self.PDiag(diag::note_precedence_silence) << OpStr, 11187 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 11188 SuggestParentheses(Self, OpLoc, 11189 Self.PDiag(diag::note_precedence_bitwise_first) 11190 << BinaryOperator::getOpcodeStr(Opc), 11191 ParensRange); 11192 } 11193 11194 /// \brief It accepts a '&&' expr that is inside a '||' one. 11195 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 11196 /// in parentheses. 11197 static void 11198 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 11199 BinaryOperator *Bop) { 11200 assert(Bop->getOpcode() == BO_LAnd); 11201 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 11202 << Bop->getSourceRange() << OpLoc; 11203 SuggestParentheses(Self, Bop->getOperatorLoc(), 11204 Self.PDiag(diag::note_precedence_silence) 11205 << Bop->getOpcodeStr(), 11206 Bop->getSourceRange()); 11207 } 11208 11209 /// \brief Returns true if the given expression can be evaluated as a constant 11210 /// 'true'. 11211 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 11212 bool Res; 11213 return !E->isValueDependent() && 11214 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 11215 } 11216 11217 /// \brief Returns true if the given expression can be evaluated as a constant 11218 /// 'false'. 11219 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 11220 bool Res; 11221 return !E->isValueDependent() && 11222 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 11223 } 11224 11225 /// \brief Look for '&&' in the left hand of a '||' expr. 11226 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 11227 Expr *LHSExpr, Expr *RHSExpr) { 11228 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 11229 if (Bop->getOpcode() == BO_LAnd) { 11230 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 11231 if (EvaluatesAsFalse(S, RHSExpr)) 11232 return; 11233 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 11234 if (!EvaluatesAsTrue(S, Bop->getLHS())) 11235 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11236 } else if (Bop->getOpcode() == BO_LOr) { 11237 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 11238 // If it's "a || b && 1 || c" we didn't warn earlier for 11239 // "a || b && 1", but warn now. 11240 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 11241 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 11242 } 11243 } 11244 } 11245 } 11246 11247 /// \brief Look for '&&' in the right hand of a '||' expr. 11248 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 11249 Expr *LHSExpr, Expr *RHSExpr) { 11250 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 11251 if (Bop->getOpcode() == BO_LAnd) { 11252 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 11253 if (EvaluatesAsFalse(S, LHSExpr)) 11254 return; 11255 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 11256 if (!EvaluatesAsTrue(S, Bop->getRHS())) 11257 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11258 } 11259 } 11260 } 11261 11262 /// \brief Look for bitwise op in the left or right hand of a bitwise op with 11263 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 11264 /// the '&' expression in parentheses. 11265 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 11266 SourceLocation OpLoc, Expr *SubExpr) { 11267 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11268 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 11269 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 11270 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 11271 << Bop->getSourceRange() << OpLoc; 11272 SuggestParentheses(S, Bop->getOperatorLoc(), 11273 S.PDiag(diag::note_precedence_silence) 11274 << Bop->getOpcodeStr(), 11275 Bop->getSourceRange()); 11276 } 11277 } 11278 } 11279 11280 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 11281 Expr *SubExpr, StringRef Shift) { 11282 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11283 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 11284 StringRef Op = Bop->getOpcodeStr(); 11285 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 11286 << Bop->getSourceRange() << OpLoc << Shift << Op; 11287 SuggestParentheses(S, Bop->getOperatorLoc(), 11288 S.PDiag(diag::note_precedence_silence) << Op, 11289 Bop->getSourceRange()); 11290 } 11291 } 11292 } 11293 11294 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 11295 Expr *LHSExpr, Expr *RHSExpr) { 11296 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 11297 if (!OCE) 11298 return; 11299 11300 FunctionDecl *FD = OCE->getDirectCallee(); 11301 if (!FD || !FD->isOverloadedOperator()) 11302 return; 11303 11304 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 11305 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 11306 return; 11307 11308 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 11309 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 11310 << (Kind == OO_LessLess); 11311 SuggestParentheses(S, OCE->getOperatorLoc(), 11312 S.PDiag(diag::note_precedence_silence) 11313 << (Kind == OO_LessLess ? "<<" : ">>"), 11314 OCE->getSourceRange()); 11315 SuggestParentheses(S, OpLoc, 11316 S.PDiag(diag::note_evaluate_comparison_first), 11317 SourceRange(OCE->getArg(1)->getLocStart(), 11318 RHSExpr->getLocEnd())); 11319 } 11320 11321 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 11322 /// precedence. 11323 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 11324 SourceLocation OpLoc, Expr *LHSExpr, 11325 Expr *RHSExpr){ 11326 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 11327 if (BinaryOperator::isBitwiseOp(Opc)) 11328 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 11329 11330 // Diagnose "arg1 & arg2 | arg3" 11331 if ((Opc == BO_Or || Opc == BO_Xor) && 11332 !OpLoc.isMacroID()/* Don't warn in macros. */) { 11333 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 11334 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 11335 } 11336 11337 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 11338 // We don't warn for 'assert(a || b && "bad")' since this is safe. 11339 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 11340 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 11341 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 11342 } 11343 11344 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 11345 || Opc == BO_Shr) { 11346 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 11347 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 11348 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 11349 } 11350 11351 // Warn on overloaded shift operators and comparisons, such as: 11352 // cout << 5 == 4; 11353 if (BinaryOperator::isComparisonOp(Opc)) 11354 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 11355 } 11356 11357 // Binary Operators. 'Tok' is the token for the operator. 11358 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 11359 tok::TokenKind Kind, 11360 Expr *LHSExpr, Expr *RHSExpr) { 11361 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 11362 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 11363 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 11364 11365 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 11366 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 11367 11368 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 11369 } 11370 11371 /// Build an overloaded binary operator expression in the given scope. 11372 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 11373 BinaryOperatorKind Opc, 11374 Expr *LHS, Expr *RHS) { 11375 // Find all of the overloaded operators visible from this 11376 // point. We perform both an operator-name lookup from the local 11377 // scope and an argument-dependent lookup based on the types of 11378 // the arguments. 11379 UnresolvedSet<16> Functions; 11380 OverloadedOperatorKind OverOp 11381 = BinaryOperator::getOverloadedOperator(Opc); 11382 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 11383 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 11384 RHS->getType(), Functions); 11385 11386 // Build the (potentially-overloaded, potentially-dependent) 11387 // binary operation. 11388 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 11389 } 11390 11391 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 11392 BinaryOperatorKind Opc, 11393 Expr *LHSExpr, Expr *RHSExpr) { 11394 // We want to end up calling one of checkPseudoObjectAssignment 11395 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 11396 // both expressions are overloadable or either is type-dependent), 11397 // or CreateBuiltinBinOp (in any other case). We also want to get 11398 // any placeholder types out of the way. 11399 11400 // Handle pseudo-objects in the LHS. 11401 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 11402 // Assignments with a pseudo-object l-value need special analysis. 11403 if (pty->getKind() == BuiltinType::PseudoObject && 11404 BinaryOperator::isAssignmentOp(Opc)) 11405 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 11406 11407 // Don't resolve overloads if the other type is overloadable. 11408 if (pty->getKind() == BuiltinType::Overload) { 11409 // We can't actually test that if we still have a placeholder, 11410 // though. Fortunately, none of the exceptions we see in that 11411 // code below are valid when the LHS is an overload set. Note 11412 // that an overload set can be dependently-typed, but it never 11413 // instantiates to having an overloadable type. 11414 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 11415 if (resolvedRHS.isInvalid()) return ExprError(); 11416 RHSExpr = resolvedRHS.get(); 11417 11418 if (RHSExpr->isTypeDependent() || 11419 RHSExpr->getType()->isOverloadableType()) 11420 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11421 } 11422 11423 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 11424 if (LHS.isInvalid()) return ExprError(); 11425 LHSExpr = LHS.get(); 11426 } 11427 11428 // Handle pseudo-objects in the RHS. 11429 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 11430 // An overload in the RHS can potentially be resolved by the type 11431 // being assigned to. 11432 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 11433 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 11434 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11435 11436 if (LHSExpr->getType()->isOverloadableType()) 11437 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11438 11439 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 11440 } 11441 11442 // Don't resolve overloads if the other type is overloadable. 11443 if (pty->getKind() == BuiltinType::Overload && 11444 LHSExpr->getType()->isOverloadableType()) 11445 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11446 11447 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 11448 if (!resolvedRHS.isUsable()) return ExprError(); 11449 RHSExpr = resolvedRHS.get(); 11450 } 11451 11452 if (getLangOpts().CPlusPlus) { 11453 // If either expression is type-dependent, always build an 11454 // overloaded op. 11455 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 11456 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11457 11458 // Otherwise, build an overloaded op if either expression has an 11459 // overloadable type. 11460 if (LHSExpr->getType()->isOverloadableType() || 11461 RHSExpr->getType()->isOverloadableType()) 11462 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11463 } 11464 11465 // Build a built-in binary operation. 11466 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 11467 } 11468 11469 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 11470 UnaryOperatorKind Opc, 11471 Expr *InputExpr) { 11472 ExprResult Input = InputExpr; 11473 ExprValueKind VK = VK_RValue; 11474 ExprObjectKind OK = OK_Ordinary; 11475 QualType resultType; 11476 if (getLangOpts().OpenCL) { 11477 QualType Ty = InputExpr->getType(); 11478 // The only legal unary operation for atomics is '&'. 11479 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 11480 // OpenCL special types - image, sampler, pipe, and blocks are to be used 11481 // only with a builtin functions and therefore should be disallowed here. 11482 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 11483 || Ty->isBlockPointerType())) { 11484 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11485 << InputExpr->getType() 11486 << Input.get()->getSourceRange()); 11487 } 11488 } 11489 switch (Opc) { 11490 case UO_PreInc: 11491 case UO_PreDec: 11492 case UO_PostInc: 11493 case UO_PostDec: 11494 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 11495 OpLoc, 11496 Opc == UO_PreInc || 11497 Opc == UO_PostInc, 11498 Opc == UO_PreInc || 11499 Opc == UO_PreDec); 11500 break; 11501 case UO_AddrOf: 11502 resultType = CheckAddressOfOperand(Input, OpLoc); 11503 RecordModifiableNonNullParam(*this, InputExpr); 11504 break; 11505 case UO_Deref: { 11506 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 11507 if (Input.isInvalid()) return ExprError(); 11508 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 11509 break; 11510 } 11511 case UO_Plus: 11512 case UO_Minus: 11513 Input = UsualUnaryConversions(Input.get()); 11514 if (Input.isInvalid()) return ExprError(); 11515 resultType = Input.get()->getType(); 11516 if (resultType->isDependentType()) 11517 break; 11518 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 11519 break; 11520 else if (resultType->isVectorType() && 11521 // The z vector extensions don't allow + or - with bool vectors. 11522 (!Context.getLangOpts().ZVector || 11523 resultType->getAs<VectorType>()->getVectorKind() != 11524 VectorType::AltiVecBool)) 11525 break; 11526 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 11527 Opc == UO_Plus && 11528 resultType->isPointerType()) 11529 break; 11530 11531 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11532 << resultType << Input.get()->getSourceRange()); 11533 11534 case UO_Not: // bitwise complement 11535 Input = UsualUnaryConversions(Input.get()); 11536 if (Input.isInvalid()) 11537 return ExprError(); 11538 resultType = Input.get()->getType(); 11539 if (resultType->isDependentType()) 11540 break; 11541 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 11542 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 11543 // C99 does not support '~' for complex conjugation. 11544 Diag(OpLoc, diag::ext_integer_complement_complex) 11545 << resultType << Input.get()->getSourceRange(); 11546 else if (resultType->hasIntegerRepresentation()) 11547 break; 11548 else if (resultType->isExtVectorType()) { 11549 if (Context.getLangOpts().OpenCL) { 11550 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 11551 // on vector float types. 11552 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 11553 if (!T->isIntegerType()) 11554 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11555 << resultType << Input.get()->getSourceRange()); 11556 } 11557 break; 11558 } else { 11559 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11560 << resultType << Input.get()->getSourceRange()); 11561 } 11562 break; 11563 11564 case UO_LNot: // logical negation 11565 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 11566 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 11567 if (Input.isInvalid()) return ExprError(); 11568 resultType = Input.get()->getType(); 11569 11570 // Though we still have to promote half FP to float... 11571 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 11572 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 11573 resultType = Context.FloatTy; 11574 } 11575 11576 if (resultType->isDependentType()) 11577 break; 11578 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 11579 // C99 6.5.3.3p1: ok, fallthrough; 11580 if (Context.getLangOpts().CPlusPlus) { 11581 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 11582 // operand contextually converted to bool. 11583 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 11584 ScalarTypeToBooleanCastKind(resultType)); 11585 } else if (Context.getLangOpts().OpenCL && 11586 Context.getLangOpts().OpenCLVersion < 120) { 11587 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 11588 // operate on scalar float types. 11589 if (!resultType->isIntegerType()) 11590 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11591 << resultType << Input.get()->getSourceRange()); 11592 } 11593 } else if (resultType->isExtVectorType()) { 11594 if (Context.getLangOpts().OpenCL && 11595 Context.getLangOpts().OpenCLVersion < 120) { 11596 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 11597 // operate on vector float types. 11598 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 11599 if (!T->isIntegerType()) 11600 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11601 << resultType << Input.get()->getSourceRange()); 11602 } 11603 // Vector logical not returns the signed variant of the operand type. 11604 resultType = GetSignedVectorType(resultType); 11605 break; 11606 } else { 11607 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11608 << resultType << Input.get()->getSourceRange()); 11609 } 11610 11611 // LNot always has type int. C99 6.5.3.3p5. 11612 // In C++, it's bool. C++ 5.3.1p8 11613 resultType = Context.getLogicalOperationType(); 11614 break; 11615 case UO_Real: 11616 case UO_Imag: 11617 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 11618 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 11619 // complex l-values to ordinary l-values and all other values to r-values. 11620 if (Input.isInvalid()) return ExprError(); 11621 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 11622 if (Input.get()->getValueKind() != VK_RValue && 11623 Input.get()->getObjectKind() == OK_Ordinary) 11624 VK = Input.get()->getValueKind(); 11625 } else if (!getLangOpts().CPlusPlus) { 11626 // In C, a volatile scalar is read by __imag. In C++, it is not. 11627 Input = DefaultLvalueConversion(Input.get()); 11628 } 11629 break; 11630 case UO_Extension: 11631 case UO_Coawait: 11632 resultType = Input.get()->getType(); 11633 VK = Input.get()->getValueKind(); 11634 OK = Input.get()->getObjectKind(); 11635 break; 11636 } 11637 if (resultType.isNull() || Input.isInvalid()) 11638 return ExprError(); 11639 11640 // Check for array bounds violations in the operand of the UnaryOperator, 11641 // except for the '*' and '&' operators that have to be handled specially 11642 // by CheckArrayAccess (as there are special cases like &array[arraysize] 11643 // that are explicitly defined as valid by the standard). 11644 if (Opc != UO_AddrOf && Opc != UO_Deref) 11645 CheckArrayAccess(Input.get()); 11646 11647 return new (Context) 11648 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc); 11649 } 11650 11651 /// \brief Determine whether the given expression is a qualified member 11652 /// access expression, of a form that could be turned into a pointer to member 11653 /// with the address-of operator. 11654 static bool isQualifiedMemberAccess(Expr *E) { 11655 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11656 if (!DRE->getQualifier()) 11657 return false; 11658 11659 ValueDecl *VD = DRE->getDecl(); 11660 if (!VD->isCXXClassMember()) 11661 return false; 11662 11663 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 11664 return true; 11665 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 11666 return Method->isInstance(); 11667 11668 return false; 11669 } 11670 11671 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 11672 if (!ULE->getQualifier()) 11673 return false; 11674 11675 for (NamedDecl *D : ULE->decls()) { 11676 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 11677 if (Method->isInstance()) 11678 return true; 11679 } else { 11680 // Overload set does not contain methods. 11681 break; 11682 } 11683 } 11684 11685 return false; 11686 } 11687 11688 return false; 11689 } 11690 11691 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 11692 UnaryOperatorKind Opc, Expr *Input) { 11693 // First things first: handle placeholders so that the 11694 // overloaded-operator check considers the right type. 11695 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 11696 // Increment and decrement of pseudo-object references. 11697 if (pty->getKind() == BuiltinType::PseudoObject && 11698 UnaryOperator::isIncrementDecrementOp(Opc)) 11699 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 11700 11701 // extension is always a builtin operator. 11702 if (Opc == UO_Extension) 11703 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11704 11705 // & gets special logic for several kinds of placeholder. 11706 // The builtin code knows what to do. 11707 if (Opc == UO_AddrOf && 11708 (pty->getKind() == BuiltinType::Overload || 11709 pty->getKind() == BuiltinType::UnknownAny || 11710 pty->getKind() == BuiltinType::BoundMember)) 11711 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11712 11713 // Anything else needs to be handled now. 11714 ExprResult Result = CheckPlaceholderExpr(Input); 11715 if (Result.isInvalid()) return ExprError(); 11716 Input = Result.get(); 11717 } 11718 11719 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 11720 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 11721 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 11722 // Find all of the overloaded operators visible from this 11723 // point. We perform both an operator-name lookup from the local 11724 // scope and an argument-dependent lookup based on the types of 11725 // the arguments. 11726 UnresolvedSet<16> Functions; 11727 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 11728 if (S && OverOp != OO_None) 11729 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 11730 Functions); 11731 11732 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 11733 } 11734 11735 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11736 } 11737 11738 // Unary Operators. 'Tok' is the token for the operator. 11739 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 11740 tok::TokenKind Op, Expr *Input) { 11741 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 11742 } 11743 11744 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 11745 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 11746 LabelDecl *TheDecl) { 11747 TheDecl->markUsed(Context); 11748 // Create the AST node. The address of a label always has type 'void*'. 11749 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 11750 Context.getPointerType(Context.VoidTy)); 11751 } 11752 11753 /// Given the last statement in a statement-expression, check whether 11754 /// the result is a producing expression (like a call to an 11755 /// ns_returns_retained function) and, if so, rebuild it to hoist the 11756 /// release out of the full-expression. Otherwise, return null. 11757 /// Cannot fail. 11758 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 11759 // Should always be wrapped with one of these. 11760 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 11761 if (!cleanups) return nullptr; 11762 11763 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 11764 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 11765 return nullptr; 11766 11767 // Splice out the cast. This shouldn't modify any interesting 11768 // features of the statement. 11769 Expr *producer = cast->getSubExpr(); 11770 assert(producer->getType() == cast->getType()); 11771 assert(producer->getValueKind() == cast->getValueKind()); 11772 cleanups->setSubExpr(producer); 11773 return cleanups; 11774 } 11775 11776 void Sema::ActOnStartStmtExpr() { 11777 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 11778 } 11779 11780 void Sema::ActOnStmtExprError() { 11781 // Note that function is also called by TreeTransform when leaving a 11782 // StmtExpr scope without rebuilding anything. 11783 11784 DiscardCleanupsInEvaluationContext(); 11785 PopExpressionEvaluationContext(); 11786 } 11787 11788 ExprResult 11789 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 11790 SourceLocation RPLoc) { // "({..})" 11791 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 11792 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 11793 11794 if (hasAnyUnrecoverableErrorsInThisFunction()) 11795 DiscardCleanupsInEvaluationContext(); 11796 assert(!Cleanup.exprNeedsCleanups() && 11797 "cleanups within StmtExpr not correctly bound!"); 11798 PopExpressionEvaluationContext(); 11799 11800 // FIXME: there are a variety of strange constraints to enforce here, for 11801 // example, it is not possible to goto into a stmt expression apparently. 11802 // More semantic analysis is needed. 11803 11804 // If there are sub-stmts in the compound stmt, take the type of the last one 11805 // as the type of the stmtexpr. 11806 QualType Ty = Context.VoidTy; 11807 bool StmtExprMayBindToTemp = false; 11808 if (!Compound->body_empty()) { 11809 Stmt *LastStmt = Compound->body_back(); 11810 LabelStmt *LastLabelStmt = nullptr; 11811 // If LastStmt is a label, skip down through into the body. 11812 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 11813 LastLabelStmt = Label; 11814 LastStmt = Label->getSubStmt(); 11815 } 11816 11817 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 11818 // Do function/array conversion on the last expression, but not 11819 // lvalue-to-rvalue. However, initialize an unqualified type. 11820 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 11821 if (LastExpr.isInvalid()) 11822 return ExprError(); 11823 Ty = LastExpr.get()->getType().getUnqualifiedType(); 11824 11825 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 11826 // In ARC, if the final expression ends in a consume, splice 11827 // the consume out and bind it later. In the alternate case 11828 // (when dealing with a retainable type), the result 11829 // initialization will create a produce. In both cases the 11830 // result will be +1, and we'll need to balance that out with 11831 // a bind. 11832 if (Expr *rebuiltLastStmt 11833 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 11834 LastExpr = rebuiltLastStmt; 11835 } else { 11836 LastExpr = PerformCopyInitialization( 11837 InitializedEntity::InitializeResult(LPLoc, 11838 Ty, 11839 false), 11840 SourceLocation(), 11841 LastExpr); 11842 } 11843 11844 if (LastExpr.isInvalid()) 11845 return ExprError(); 11846 if (LastExpr.get() != nullptr) { 11847 if (!LastLabelStmt) 11848 Compound->setLastStmt(LastExpr.get()); 11849 else 11850 LastLabelStmt->setSubStmt(LastExpr.get()); 11851 StmtExprMayBindToTemp = true; 11852 } 11853 } 11854 } 11855 } 11856 11857 // FIXME: Check that expression type is complete/non-abstract; statement 11858 // expressions are not lvalues. 11859 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 11860 if (StmtExprMayBindToTemp) 11861 return MaybeBindToTemporary(ResStmtExpr); 11862 return ResStmtExpr; 11863 } 11864 11865 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 11866 TypeSourceInfo *TInfo, 11867 ArrayRef<OffsetOfComponent> Components, 11868 SourceLocation RParenLoc) { 11869 QualType ArgTy = TInfo->getType(); 11870 bool Dependent = ArgTy->isDependentType(); 11871 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 11872 11873 // We must have at least one component that refers to the type, and the first 11874 // one is known to be a field designator. Verify that the ArgTy represents 11875 // a struct/union/class. 11876 if (!Dependent && !ArgTy->isRecordType()) 11877 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 11878 << ArgTy << TypeRange); 11879 11880 // Type must be complete per C99 7.17p3 because a declaring a variable 11881 // with an incomplete type would be ill-formed. 11882 if (!Dependent 11883 && RequireCompleteType(BuiltinLoc, ArgTy, 11884 diag::err_offsetof_incomplete_type, TypeRange)) 11885 return ExprError(); 11886 11887 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 11888 // GCC extension, diagnose them. 11889 // FIXME: This diagnostic isn't actually visible because the location is in 11890 // a system header! 11891 if (Components.size() != 1) 11892 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 11893 << SourceRange(Components[1].LocStart, Components.back().LocEnd); 11894 11895 bool DidWarnAboutNonPOD = false; 11896 QualType CurrentType = ArgTy; 11897 SmallVector<OffsetOfNode, 4> Comps; 11898 SmallVector<Expr*, 4> Exprs; 11899 for (const OffsetOfComponent &OC : Components) { 11900 if (OC.isBrackets) { 11901 // Offset of an array sub-field. TODO: Should we allow vector elements? 11902 if (!CurrentType->isDependentType()) { 11903 const ArrayType *AT = Context.getAsArrayType(CurrentType); 11904 if(!AT) 11905 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 11906 << CurrentType); 11907 CurrentType = AT->getElementType(); 11908 } else 11909 CurrentType = Context.DependentTy; 11910 11911 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 11912 if (IdxRval.isInvalid()) 11913 return ExprError(); 11914 Expr *Idx = IdxRval.get(); 11915 11916 // The expression must be an integral expression. 11917 // FIXME: An integral constant expression? 11918 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 11919 !Idx->getType()->isIntegerType()) 11920 return ExprError(Diag(Idx->getLocStart(), 11921 diag::err_typecheck_subscript_not_integer) 11922 << Idx->getSourceRange()); 11923 11924 // Record this array index. 11925 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 11926 Exprs.push_back(Idx); 11927 continue; 11928 } 11929 11930 // Offset of a field. 11931 if (CurrentType->isDependentType()) { 11932 // We have the offset of a field, but we can't look into the dependent 11933 // type. Just record the identifier of the field. 11934 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 11935 CurrentType = Context.DependentTy; 11936 continue; 11937 } 11938 11939 // We need to have a complete type to look into. 11940 if (RequireCompleteType(OC.LocStart, CurrentType, 11941 diag::err_offsetof_incomplete_type)) 11942 return ExprError(); 11943 11944 // Look for the designated field. 11945 const RecordType *RC = CurrentType->getAs<RecordType>(); 11946 if (!RC) 11947 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 11948 << CurrentType); 11949 RecordDecl *RD = RC->getDecl(); 11950 11951 // C++ [lib.support.types]p5: 11952 // The macro offsetof accepts a restricted set of type arguments in this 11953 // International Standard. type shall be a POD structure or a POD union 11954 // (clause 9). 11955 // C++11 [support.types]p4: 11956 // If type is not a standard-layout class (Clause 9), the results are 11957 // undefined. 11958 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 11959 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 11960 unsigned DiagID = 11961 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 11962 : diag::ext_offsetof_non_pod_type; 11963 11964 if (!IsSafe && !DidWarnAboutNonPOD && 11965 DiagRuntimeBehavior(BuiltinLoc, nullptr, 11966 PDiag(DiagID) 11967 << SourceRange(Components[0].LocStart, OC.LocEnd) 11968 << CurrentType)) 11969 DidWarnAboutNonPOD = true; 11970 } 11971 11972 // Look for the field. 11973 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 11974 LookupQualifiedName(R, RD); 11975 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 11976 IndirectFieldDecl *IndirectMemberDecl = nullptr; 11977 if (!MemberDecl) { 11978 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 11979 MemberDecl = IndirectMemberDecl->getAnonField(); 11980 } 11981 11982 if (!MemberDecl) 11983 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 11984 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 11985 OC.LocEnd)); 11986 11987 // C99 7.17p3: 11988 // (If the specified member is a bit-field, the behavior is undefined.) 11989 // 11990 // We diagnose this as an error. 11991 if (MemberDecl->isBitField()) { 11992 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 11993 << MemberDecl->getDeclName() 11994 << SourceRange(BuiltinLoc, RParenLoc); 11995 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 11996 return ExprError(); 11997 } 11998 11999 RecordDecl *Parent = MemberDecl->getParent(); 12000 if (IndirectMemberDecl) 12001 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 12002 12003 // If the member was found in a base class, introduce OffsetOfNodes for 12004 // the base class indirections. 12005 CXXBasePaths Paths; 12006 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 12007 Paths)) { 12008 if (Paths.getDetectedVirtual()) { 12009 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 12010 << MemberDecl->getDeclName() 12011 << SourceRange(BuiltinLoc, RParenLoc); 12012 return ExprError(); 12013 } 12014 12015 CXXBasePath &Path = Paths.front(); 12016 for (const CXXBasePathElement &B : Path) 12017 Comps.push_back(OffsetOfNode(B.Base)); 12018 } 12019 12020 if (IndirectMemberDecl) { 12021 for (auto *FI : IndirectMemberDecl->chain()) { 12022 assert(isa<FieldDecl>(FI)); 12023 Comps.push_back(OffsetOfNode(OC.LocStart, 12024 cast<FieldDecl>(FI), OC.LocEnd)); 12025 } 12026 } else 12027 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 12028 12029 CurrentType = MemberDecl->getType().getNonReferenceType(); 12030 } 12031 12032 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 12033 Comps, Exprs, RParenLoc); 12034 } 12035 12036 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 12037 SourceLocation BuiltinLoc, 12038 SourceLocation TypeLoc, 12039 ParsedType ParsedArgTy, 12040 ArrayRef<OffsetOfComponent> Components, 12041 SourceLocation RParenLoc) { 12042 12043 TypeSourceInfo *ArgTInfo; 12044 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 12045 if (ArgTy.isNull()) 12046 return ExprError(); 12047 12048 if (!ArgTInfo) 12049 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 12050 12051 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 12052 } 12053 12054 12055 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 12056 Expr *CondExpr, 12057 Expr *LHSExpr, Expr *RHSExpr, 12058 SourceLocation RPLoc) { 12059 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 12060 12061 ExprValueKind VK = VK_RValue; 12062 ExprObjectKind OK = OK_Ordinary; 12063 QualType resType; 12064 bool ValueDependent = false; 12065 bool CondIsTrue = false; 12066 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 12067 resType = Context.DependentTy; 12068 ValueDependent = true; 12069 } else { 12070 // The conditional expression is required to be a constant expression. 12071 llvm::APSInt condEval(32); 12072 ExprResult CondICE 12073 = VerifyIntegerConstantExpression(CondExpr, &condEval, 12074 diag::err_typecheck_choose_expr_requires_constant, false); 12075 if (CondICE.isInvalid()) 12076 return ExprError(); 12077 CondExpr = CondICE.get(); 12078 CondIsTrue = condEval.getZExtValue(); 12079 12080 // If the condition is > zero, then the AST type is the same as the LSHExpr. 12081 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 12082 12083 resType = ActiveExpr->getType(); 12084 ValueDependent = ActiveExpr->isValueDependent(); 12085 VK = ActiveExpr->getValueKind(); 12086 OK = ActiveExpr->getObjectKind(); 12087 } 12088 12089 return new (Context) 12090 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 12091 CondIsTrue, resType->isDependentType(), ValueDependent); 12092 } 12093 12094 //===----------------------------------------------------------------------===// 12095 // Clang Extensions. 12096 //===----------------------------------------------------------------------===// 12097 12098 /// ActOnBlockStart - This callback is invoked when a block literal is started. 12099 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 12100 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 12101 12102 if (LangOpts.CPlusPlus) { 12103 Decl *ManglingContextDecl; 12104 if (MangleNumberingContext *MCtx = 12105 getCurrentMangleNumberContext(Block->getDeclContext(), 12106 ManglingContextDecl)) { 12107 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 12108 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 12109 } 12110 } 12111 12112 PushBlockScope(CurScope, Block); 12113 CurContext->addDecl(Block); 12114 if (CurScope) 12115 PushDeclContext(CurScope, Block); 12116 else 12117 CurContext = Block; 12118 12119 getCurBlock()->HasImplicitReturnType = true; 12120 12121 // Enter a new evaluation context to insulate the block from any 12122 // cleanups from the enclosing full-expression. 12123 PushExpressionEvaluationContext(PotentiallyEvaluated); 12124 } 12125 12126 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 12127 Scope *CurScope) { 12128 assert(ParamInfo.getIdentifier() == nullptr && 12129 "block-id should have no identifier!"); 12130 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 12131 BlockScopeInfo *CurBlock = getCurBlock(); 12132 12133 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 12134 QualType T = Sig->getType(); 12135 12136 // FIXME: We should allow unexpanded parameter packs here, but that would, 12137 // in turn, make the block expression contain unexpanded parameter packs. 12138 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 12139 // Drop the parameters. 12140 FunctionProtoType::ExtProtoInfo EPI; 12141 EPI.HasTrailingReturn = false; 12142 EPI.TypeQuals |= DeclSpec::TQ_const; 12143 T = Context.getFunctionType(Context.DependentTy, None, EPI); 12144 Sig = Context.getTrivialTypeSourceInfo(T); 12145 } 12146 12147 // GetTypeForDeclarator always produces a function type for a block 12148 // literal signature. Furthermore, it is always a FunctionProtoType 12149 // unless the function was written with a typedef. 12150 assert(T->isFunctionType() && 12151 "GetTypeForDeclarator made a non-function block signature"); 12152 12153 // Look for an explicit signature in that function type. 12154 FunctionProtoTypeLoc ExplicitSignature; 12155 12156 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 12157 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) { 12158 12159 // Check whether that explicit signature was synthesized by 12160 // GetTypeForDeclarator. If so, don't save that as part of the 12161 // written signature. 12162 if (ExplicitSignature.getLocalRangeBegin() == 12163 ExplicitSignature.getLocalRangeEnd()) { 12164 // This would be much cheaper if we stored TypeLocs instead of 12165 // TypeSourceInfos. 12166 TypeLoc Result = ExplicitSignature.getReturnLoc(); 12167 unsigned Size = Result.getFullDataSize(); 12168 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 12169 Sig->getTypeLoc().initializeFullCopy(Result, Size); 12170 12171 ExplicitSignature = FunctionProtoTypeLoc(); 12172 } 12173 } 12174 12175 CurBlock->TheDecl->setSignatureAsWritten(Sig); 12176 CurBlock->FunctionType = T; 12177 12178 const FunctionType *Fn = T->getAs<FunctionType>(); 12179 QualType RetTy = Fn->getReturnType(); 12180 bool isVariadic = 12181 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 12182 12183 CurBlock->TheDecl->setIsVariadic(isVariadic); 12184 12185 // Context.DependentTy is used as a placeholder for a missing block 12186 // return type. TODO: what should we do with declarators like: 12187 // ^ * { ... } 12188 // If the answer is "apply template argument deduction".... 12189 if (RetTy != Context.DependentTy) { 12190 CurBlock->ReturnType = RetTy; 12191 CurBlock->TheDecl->setBlockMissingReturnType(false); 12192 CurBlock->HasImplicitReturnType = false; 12193 } 12194 12195 // Push block parameters from the declarator if we had them. 12196 SmallVector<ParmVarDecl*, 8> Params; 12197 if (ExplicitSignature) { 12198 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 12199 ParmVarDecl *Param = ExplicitSignature.getParam(I); 12200 if (Param->getIdentifier() == nullptr && 12201 !Param->isImplicit() && 12202 !Param->isInvalidDecl() && 12203 !getLangOpts().CPlusPlus) 12204 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 12205 Params.push_back(Param); 12206 } 12207 12208 // Fake up parameter variables if we have a typedef, like 12209 // ^ fntype { ... } 12210 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 12211 for (const auto &I : Fn->param_types()) { 12212 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 12213 CurBlock->TheDecl, ParamInfo.getLocStart(), I); 12214 Params.push_back(Param); 12215 } 12216 } 12217 12218 // Set the parameters on the block decl. 12219 if (!Params.empty()) { 12220 CurBlock->TheDecl->setParams(Params); 12221 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 12222 /*CheckParameterNames=*/false); 12223 } 12224 12225 // Finally we can process decl attributes. 12226 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 12227 12228 // Put the parameter variables in scope. 12229 for (auto AI : CurBlock->TheDecl->parameters()) { 12230 AI->setOwningFunction(CurBlock->TheDecl); 12231 12232 // If this has an identifier, add it to the scope stack. 12233 if (AI->getIdentifier()) { 12234 CheckShadow(CurBlock->TheScope, AI); 12235 12236 PushOnScopeChains(AI, CurBlock->TheScope); 12237 } 12238 } 12239 } 12240 12241 /// ActOnBlockError - If there is an error parsing a block, this callback 12242 /// is invoked to pop the information about the block from the action impl. 12243 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 12244 // Leave the expression-evaluation context. 12245 DiscardCleanupsInEvaluationContext(); 12246 PopExpressionEvaluationContext(); 12247 12248 // Pop off CurBlock, handle nested blocks. 12249 PopDeclContext(); 12250 PopFunctionScopeInfo(); 12251 } 12252 12253 /// ActOnBlockStmtExpr - This is called when the body of a block statement 12254 /// literal was successfully completed. ^(int x){...} 12255 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 12256 Stmt *Body, Scope *CurScope) { 12257 // If blocks are disabled, emit an error. 12258 if (!LangOpts.Blocks) 12259 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 12260 12261 // Leave the expression-evaluation context. 12262 if (hasAnyUnrecoverableErrorsInThisFunction()) 12263 DiscardCleanupsInEvaluationContext(); 12264 assert(!Cleanup.exprNeedsCleanups() && 12265 "cleanups within block not correctly bound!"); 12266 PopExpressionEvaluationContext(); 12267 12268 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 12269 12270 if (BSI->HasImplicitReturnType) 12271 deduceClosureReturnType(*BSI); 12272 12273 PopDeclContext(); 12274 12275 QualType RetTy = Context.VoidTy; 12276 if (!BSI->ReturnType.isNull()) 12277 RetTy = BSI->ReturnType; 12278 12279 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 12280 QualType BlockTy; 12281 12282 // Set the captured variables on the block. 12283 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 12284 SmallVector<BlockDecl::Capture, 4> Captures; 12285 for (CapturingScopeInfo::Capture &Cap : BSI->Captures) { 12286 if (Cap.isThisCapture()) 12287 continue; 12288 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 12289 Cap.isNested(), Cap.getInitExpr()); 12290 Captures.push_back(NewCap); 12291 } 12292 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 12293 12294 // If the user wrote a function type in some form, try to use that. 12295 if (!BSI->FunctionType.isNull()) { 12296 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 12297 12298 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 12299 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 12300 12301 // Turn protoless block types into nullary block types. 12302 if (isa<FunctionNoProtoType>(FTy)) { 12303 FunctionProtoType::ExtProtoInfo EPI; 12304 EPI.ExtInfo = Ext; 12305 BlockTy = Context.getFunctionType(RetTy, None, EPI); 12306 12307 // Otherwise, if we don't need to change anything about the function type, 12308 // preserve its sugar structure. 12309 } else if (FTy->getReturnType() == RetTy && 12310 (!NoReturn || FTy->getNoReturnAttr())) { 12311 BlockTy = BSI->FunctionType; 12312 12313 // Otherwise, make the minimal modifications to the function type. 12314 } else { 12315 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 12316 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 12317 EPI.TypeQuals = 0; // FIXME: silently? 12318 EPI.ExtInfo = Ext; 12319 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 12320 } 12321 12322 // If we don't have a function type, just build one from nothing. 12323 } else { 12324 FunctionProtoType::ExtProtoInfo EPI; 12325 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 12326 BlockTy = Context.getFunctionType(RetTy, None, EPI); 12327 } 12328 12329 DiagnoseUnusedParameters(BSI->TheDecl->parameters()); 12330 BlockTy = Context.getBlockPointerType(BlockTy); 12331 12332 // If needed, diagnose invalid gotos and switches in the block. 12333 if (getCurFunction()->NeedsScopeChecking() && 12334 !PP.isCodeCompletionEnabled()) 12335 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 12336 12337 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 12338 12339 // Try to apply the named return value optimization. We have to check again 12340 // if we can do this, though, because blocks keep return statements around 12341 // to deduce an implicit return type. 12342 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 12343 !BSI->TheDecl->isDependentContext()) 12344 computeNRVO(Body, BSI); 12345 12346 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 12347 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 12348 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 12349 12350 // If the block isn't obviously global, i.e. it captures anything at 12351 // all, then we need to do a few things in the surrounding context: 12352 if (Result->getBlockDecl()->hasCaptures()) { 12353 // First, this expression has a new cleanup object. 12354 ExprCleanupObjects.push_back(Result->getBlockDecl()); 12355 Cleanup.setExprNeedsCleanups(true); 12356 12357 // It also gets a branch-protected scope if any of the captured 12358 // variables needs destruction. 12359 for (const auto &CI : Result->getBlockDecl()->captures()) { 12360 const VarDecl *var = CI.getVariable(); 12361 if (var->getType().isDestructedType() != QualType::DK_none) { 12362 getCurFunction()->setHasBranchProtectedScope(); 12363 break; 12364 } 12365 } 12366 } 12367 12368 return Result; 12369 } 12370 12371 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 12372 SourceLocation RPLoc) { 12373 TypeSourceInfo *TInfo; 12374 GetTypeFromParser(Ty, &TInfo); 12375 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 12376 } 12377 12378 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 12379 Expr *E, TypeSourceInfo *TInfo, 12380 SourceLocation RPLoc) { 12381 Expr *OrigExpr = E; 12382 bool IsMS = false; 12383 12384 // CUDA device code does not support varargs. 12385 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 12386 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 12387 CUDAFunctionTarget T = IdentifyCUDATarget(F); 12388 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 12389 return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device)); 12390 } 12391 } 12392 12393 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 12394 // as Microsoft ABI on an actual Microsoft platform, where 12395 // __builtin_ms_va_list and __builtin_va_list are the same.) 12396 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 12397 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 12398 QualType MSVaListType = Context.getBuiltinMSVaListType(); 12399 if (Context.hasSameType(MSVaListType, E->getType())) { 12400 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 12401 return ExprError(); 12402 IsMS = true; 12403 } 12404 } 12405 12406 // Get the va_list type 12407 QualType VaListType = Context.getBuiltinVaListType(); 12408 if (!IsMS) { 12409 if (VaListType->isArrayType()) { 12410 // Deal with implicit array decay; for example, on x86-64, 12411 // va_list is an array, but it's supposed to decay to 12412 // a pointer for va_arg. 12413 VaListType = Context.getArrayDecayedType(VaListType); 12414 // Make sure the input expression also decays appropriately. 12415 ExprResult Result = UsualUnaryConversions(E); 12416 if (Result.isInvalid()) 12417 return ExprError(); 12418 E = Result.get(); 12419 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 12420 // If va_list is a record type and we are compiling in C++ mode, 12421 // check the argument using reference binding. 12422 InitializedEntity Entity = InitializedEntity::InitializeParameter( 12423 Context, Context.getLValueReferenceType(VaListType), false); 12424 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 12425 if (Init.isInvalid()) 12426 return ExprError(); 12427 E = Init.getAs<Expr>(); 12428 } else { 12429 // Otherwise, the va_list argument must be an l-value because 12430 // it is modified by va_arg. 12431 if (!E->isTypeDependent() && 12432 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 12433 return ExprError(); 12434 } 12435 } 12436 12437 if (!IsMS && !E->isTypeDependent() && 12438 !Context.hasSameType(VaListType, E->getType())) 12439 return ExprError(Diag(E->getLocStart(), 12440 diag::err_first_argument_to_va_arg_not_of_type_va_list) 12441 << OrigExpr->getType() << E->getSourceRange()); 12442 12443 if (!TInfo->getType()->isDependentType()) { 12444 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 12445 diag::err_second_parameter_to_va_arg_incomplete, 12446 TInfo->getTypeLoc())) 12447 return ExprError(); 12448 12449 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 12450 TInfo->getType(), 12451 diag::err_second_parameter_to_va_arg_abstract, 12452 TInfo->getTypeLoc())) 12453 return ExprError(); 12454 12455 if (!TInfo->getType().isPODType(Context)) { 12456 Diag(TInfo->getTypeLoc().getBeginLoc(), 12457 TInfo->getType()->isObjCLifetimeType() 12458 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 12459 : diag::warn_second_parameter_to_va_arg_not_pod) 12460 << TInfo->getType() 12461 << TInfo->getTypeLoc().getSourceRange(); 12462 } 12463 12464 // Check for va_arg where arguments of the given type will be promoted 12465 // (i.e. this va_arg is guaranteed to have undefined behavior). 12466 QualType PromoteType; 12467 if (TInfo->getType()->isPromotableIntegerType()) { 12468 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 12469 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 12470 PromoteType = QualType(); 12471 } 12472 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 12473 PromoteType = Context.DoubleTy; 12474 if (!PromoteType.isNull()) 12475 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 12476 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 12477 << TInfo->getType() 12478 << PromoteType 12479 << TInfo->getTypeLoc().getSourceRange()); 12480 } 12481 12482 QualType T = TInfo->getType().getNonLValueExprType(Context); 12483 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 12484 } 12485 12486 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 12487 // The type of __null will be int or long, depending on the size of 12488 // pointers on the target. 12489 QualType Ty; 12490 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 12491 if (pw == Context.getTargetInfo().getIntWidth()) 12492 Ty = Context.IntTy; 12493 else if (pw == Context.getTargetInfo().getLongWidth()) 12494 Ty = Context.LongTy; 12495 else if (pw == Context.getTargetInfo().getLongLongWidth()) 12496 Ty = Context.LongLongTy; 12497 else { 12498 llvm_unreachable("I don't know size of pointer!"); 12499 } 12500 12501 return new (Context) GNUNullExpr(Ty, TokenLoc); 12502 } 12503 12504 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 12505 bool Diagnose) { 12506 if (!getLangOpts().ObjC1) 12507 return false; 12508 12509 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 12510 if (!PT) 12511 return false; 12512 12513 if (!PT->isObjCIdType()) { 12514 // Check if the destination is the 'NSString' interface. 12515 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 12516 if (!ID || !ID->getIdentifier()->isStr("NSString")) 12517 return false; 12518 } 12519 12520 // Ignore any parens, implicit casts (should only be 12521 // array-to-pointer decays), and not-so-opaque values. The last is 12522 // important for making this trigger for property assignments. 12523 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 12524 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 12525 if (OV->getSourceExpr()) 12526 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 12527 12528 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 12529 if (!SL || !SL->isAscii()) 12530 return false; 12531 if (Diagnose) { 12532 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix) 12533 << FixItHint::CreateInsertion(SL->getLocStart(), "@"); 12534 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get(); 12535 } 12536 return true; 12537 } 12538 12539 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 12540 const Expr *SrcExpr) { 12541 if (!DstType->isFunctionPointerType() || 12542 !SrcExpr->getType()->isFunctionType()) 12543 return false; 12544 12545 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 12546 if (!DRE) 12547 return false; 12548 12549 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 12550 if (!FD) 12551 return false; 12552 12553 return !S.checkAddressOfFunctionIsAvailable(FD, 12554 /*Complain=*/true, 12555 SrcExpr->getLocStart()); 12556 } 12557 12558 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 12559 SourceLocation Loc, 12560 QualType DstType, QualType SrcType, 12561 Expr *SrcExpr, AssignmentAction Action, 12562 bool *Complained) { 12563 if (Complained) 12564 *Complained = false; 12565 12566 // Decode the result (notice that AST's are still created for extensions). 12567 bool CheckInferredResultType = false; 12568 bool isInvalid = false; 12569 unsigned DiagKind = 0; 12570 FixItHint Hint; 12571 ConversionFixItGenerator ConvHints; 12572 bool MayHaveConvFixit = false; 12573 bool MayHaveFunctionDiff = false; 12574 const ObjCInterfaceDecl *IFace = nullptr; 12575 const ObjCProtocolDecl *PDecl = nullptr; 12576 12577 switch (ConvTy) { 12578 case Compatible: 12579 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 12580 return false; 12581 12582 case PointerToInt: 12583 DiagKind = diag::ext_typecheck_convert_pointer_int; 12584 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12585 MayHaveConvFixit = true; 12586 break; 12587 case IntToPointer: 12588 DiagKind = diag::ext_typecheck_convert_int_pointer; 12589 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12590 MayHaveConvFixit = true; 12591 break; 12592 case IncompatiblePointer: 12593 if (Action == AA_Passing_CFAudited) 12594 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 12595 else if (SrcType->isFunctionPointerType() && 12596 DstType->isFunctionPointerType()) 12597 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 12598 else 12599 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 12600 12601 CheckInferredResultType = DstType->isObjCObjectPointerType() && 12602 SrcType->isObjCObjectPointerType(); 12603 if (Hint.isNull() && !CheckInferredResultType) { 12604 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12605 } 12606 else if (CheckInferredResultType) { 12607 SrcType = SrcType.getUnqualifiedType(); 12608 DstType = DstType.getUnqualifiedType(); 12609 } 12610 MayHaveConvFixit = true; 12611 break; 12612 case IncompatiblePointerSign: 12613 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 12614 break; 12615 case FunctionVoidPointer: 12616 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 12617 break; 12618 case IncompatiblePointerDiscardsQualifiers: { 12619 // Perform array-to-pointer decay if necessary. 12620 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 12621 12622 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 12623 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 12624 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 12625 DiagKind = diag::err_typecheck_incompatible_address_space; 12626 break; 12627 12628 12629 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 12630 DiagKind = diag::err_typecheck_incompatible_ownership; 12631 break; 12632 } 12633 12634 llvm_unreachable("unknown error case for discarding qualifiers!"); 12635 // fallthrough 12636 } 12637 case CompatiblePointerDiscardsQualifiers: 12638 // If the qualifiers lost were because we were applying the 12639 // (deprecated) C++ conversion from a string literal to a char* 12640 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 12641 // Ideally, this check would be performed in 12642 // checkPointerTypesForAssignment. However, that would require a 12643 // bit of refactoring (so that the second argument is an 12644 // expression, rather than a type), which should be done as part 12645 // of a larger effort to fix checkPointerTypesForAssignment for 12646 // C++ semantics. 12647 if (getLangOpts().CPlusPlus && 12648 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 12649 return false; 12650 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 12651 break; 12652 case IncompatibleNestedPointerQualifiers: 12653 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 12654 break; 12655 case IntToBlockPointer: 12656 DiagKind = diag::err_int_to_block_pointer; 12657 break; 12658 case IncompatibleBlockPointer: 12659 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 12660 break; 12661 case IncompatibleObjCQualifiedId: { 12662 if (SrcType->isObjCQualifiedIdType()) { 12663 const ObjCObjectPointerType *srcOPT = 12664 SrcType->getAs<ObjCObjectPointerType>(); 12665 for (auto *srcProto : srcOPT->quals()) { 12666 PDecl = srcProto; 12667 break; 12668 } 12669 if (const ObjCInterfaceType *IFaceT = 12670 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 12671 IFace = IFaceT->getDecl(); 12672 } 12673 else if (DstType->isObjCQualifiedIdType()) { 12674 const ObjCObjectPointerType *dstOPT = 12675 DstType->getAs<ObjCObjectPointerType>(); 12676 for (auto *dstProto : dstOPT->quals()) { 12677 PDecl = dstProto; 12678 break; 12679 } 12680 if (const ObjCInterfaceType *IFaceT = 12681 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 12682 IFace = IFaceT->getDecl(); 12683 } 12684 DiagKind = diag::warn_incompatible_qualified_id; 12685 break; 12686 } 12687 case IncompatibleVectors: 12688 DiagKind = diag::warn_incompatible_vectors; 12689 break; 12690 case IncompatibleObjCWeakRef: 12691 DiagKind = diag::err_arc_weak_unavailable_assign; 12692 break; 12693 case Incompatible: 12694 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 12695 if (Complained) 12696 *Complained = true; 12697 return true; 12698 } 12699 12700 DiagKind = diag::err_typecheck_convert_incompatible; 12701 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12702 MayHaveConvFixit = true; 12703 isInvalid = true; 12704 MayHaveFunctionDiff = true; 12705 break; 12706 } 12707 12708 QualType FirstType, SecondType; 12709 switch (Action) { 12710 case AA_Assigning: 12711 case AA_Initializing: 12712 // The destination type comes first. 12713 FirstType = DstType; 12714 SecondType = SrcType; 12715 break; 12716 12717 case AA_Returning: 12718 case AA_Passing: 12719 case AA_Passing_CFAudited: 12720 case AA_Converting: 12721 case AA_Sending: 12722 case AA_Casting: 12723 // The source type comes first. 12724 FirstType = SrcType; 12725 SecondType = DstType; 12726 break; 12727 } 12728 12729 PartialDiagnostic FDiag = PDiag(DiagKind); 12730 if (Action == AA_Passing_CFAudited) 12731 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 12732 else 12733 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 12734 12735 // If we can fix the conversion, suggest the FixIts. 12736 assert(ConvHints.isNull() || Hint.isNull()); 12737 if (!ConvHints.isNull()) { 12738 for (FixItHint &H : ConvHints.Hints) 12739 FDiag << H; 12740 } else { 12741 FDiag << Hint; 12742 } 12743 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 12744 12745 if (MayHaveFunctionDiff) 12746 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 12747 12748 Diag(Loc, FDiag); 12749 if (DiagKind == diag::warn_incompatible_qualified_id && 12750 PDecl && IFace && !IFace->hasDefinition()) 12751 Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id) 12752 << IFace->getName() << PDecl->getName(); 12753 12754 if (SecondType == Context.OverloadTy) 12755 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 12756 FirstType, /*TakingAddress=*/true); 12757 12758 if (CheckInferredResultType) 12759 EmitRelatedResultTypeNote(SrcExpr); 12760 12761 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 12762 EmitRelatedResultTypeNoteForReturn(DstType); 12763 12764 if (Complained) 12765 *Complained = true; 12766 return isInvalid; 12767 } 12768 12769 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12770 llvm::APSInt *Result) { 12771 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 12772 public: 12773 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12774 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 12775 } 12776 } Diagnoser; 12777 12778 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 12779 } 12780 12781 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12782 llvm::APSInt *Result, 12783 unsigned DiagID, 12784 bool AllowFold) { 12785 class IDDiagnoser : public VerifyICEDiagnoser { 12786 unsigned DiagID; 12787 12788 public: 12789 IDDiagnoser(unsigned DiagID) 12790 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 12791 12792 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12793 S.Diag(Loc, DiagID) << SR; 12794 } 12795 } Diagnoser(DiagID); 12796 12797 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 12798 } 12799 12800 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 12801 SourceRange SR) { 12802 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 12803 } 12804 12805 ExprResult 12806 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 12807 VerifyICEDiagnoser &Diagnoser, 12808 bool AllowFold) { 12809 SourceLocation DiagLoc = E->getLocStart(); 12810 12811 if (getLangOpts().CPlusPlus11) { 12812 // C++11 [expr.const]p5: 12813 // If an expression of literal class type is used in a context where an 12814 // integral constant expression is required, then that class type shall 12815 // have a single non-explicit conversion function to an integral or 12816 // unscoped enumeration type 12817 ExprResult Converted; 12818 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 12819 public: 12820 CXX11ConvertDiagnoser(bool Silent) 12821 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 12822 Silent, true) {} 12823 12824 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 12825 QualType T) override { 12826 return S.Diag(Loc, diag::err_ice_not_integral) << T; 12827 } 12828 12829 SemaDiagnosticBuilder diagnoseIncomplete( 12830 Sema &S, SourceLocation Loc, QualType T) override { 12831 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 12832 } 12833 12834 SemaDiagnosticBuilder diagnoseExplicitConv( 12835 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12836 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 12837 } 12838 12839 SemaDiagnosticBuilder noteExplicitConv( 12840 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12841 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12842 << ConvTy->isEnumeralType() << ConvTy; 12843 } 12844 12845 SemaDiagnosticBuilder diagnoseAmbiguous( 12846 Sema &S, SourceLocation Loc, QualType T) override { 12847 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 12848 } 12849 12850 SemaDiagnosticBuilder noteAmbiguous( 12851 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12852 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12853 << ConvTy->isEnumeralType() << ConvTy; 12854 } 12855 12856 SemaDiagnosticBuilder diagnoseConversion( 12857 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12858 llvm_unreachable("conversion functions are permitted"); 12859 } 12860 } ConvertDiagnoser(Diagnoser.Suppress); 12861 12862 Converted = PerformContextualImplicitConversion(DiagLoc, E, 12863 ConvertDiagnoser); 12864 if (Converted.isInvalid()) 12865 return Converted; 12866 E = Converted.get(); 12867 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 12868 return ExprError(); 12869 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 12870 // An ICE must be of integral or unscoped enumeration type. 12871 if (!Diagnoser.Suppress) 12872 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 12873 return ExprError(); 12874 } 12875 12876 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 12877 // in the non-ICE case. 12878 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 12879 if (Result) 12880 *Result = E->EvaluateKnownConstInt(Context); 12881 return E; 12882 } 12883 12884 Expr::EvalResult EvalResult; 12885 SmallVector<PartialDiagnosticAt, 8> Notes; 12886 EvalResult.Diag = &Notes; 12887 12888 // Try to evaluate the expression, and produce diagnostics explaining why it's 12889 // not a constant expression as a side-effect. 12890 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 12891 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 12892 12893 // In C++11, we can rely on diagnostics being produced for any expression 12894 // which is not a constant expression. If no diagnostics were produced, then 12895 // this is a constant expression. 12896 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 12897 if (Result) 12898 *Result = EvalResult.Val.getInt(); 12899 return E; 12900 } 12901 12902 // If our only note is the usual "invalid subexpression" note, just point 12903 // the caret at its location rather than producing an essentially 12904 // redundant note. 12905 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 12906 diag::note_invalid_subexpr_in_const_expr) { 12907 DiagLoc = Notes[0].first; 12908 Notes.clear(); 12909 } 12910 12911 if (!Folded || !AllowFold) { 12912 if (!Diagnoser.Suppress) { 12913 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 12914 for (const PartialDiagnosticAt &Note : Notes) 12915 Diag(Note.first, Note.second); 12916 } 12917 12918 return ExprError(); 12919 } 12920 12921 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 12922 for (const PartialDiagnosticAt &Note : Notes) 12923 Diag(Note.first, Note.second); 12924 12925 if (Result) 12926 *Result = EvalResult.Val.getInt(); 12927 return E; 12928 } 12929 12930 namespace { 12931 // Handle the case where we conclude a expression which we speculatively 12932 // considered to be unevaluated is actually evaluated. 12933 class TransformToPE : public TreeTransform<TransformToPE> { 12934 typedef TreeTransform<TransformToPE> BaseTransform; 12935 12936 public: 12937 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 12938 12939 // Make sure we redo semantic analysis 12940 bool AlwaysRebuild() { return true; } 12941 12942 // Make sure we handle LabelStmts correctly. 12943 // FIXME: This does the right thing, but maybe we need a more general 12944 // fix to TreeTransform? 12945 StmtResult TransformLabelStmt(LabelStmt *S) { 12946 S->getDecl()->setStmt(nullptr); 12947 return BaseTransform::TransformLabelStmt(S); 12948 } 12949 12950 // We need to special-case DeclRefExprs referring to FieldDecls which 12951 // are not part of a member pointer formation; normal TreeTransforming 12952 // doesn't catch this case because of the way we represent them in the AST. 12953 // FIXME: This is a bit ugly; is it really the best way to handle this 12954 // case? 12955 // 12956 // Error on DeclRefExprs referring to FieldDecls. 12957 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 12958 if (isa<FieldDecl>(E->getDecl()) && 12959 !SemaRef.isUnevaluatedContext()) 12960 return SemaRef.Diag(E->getLocation(), 12961 diag::err_invalid_non_static_member_use) 12962 << E->getDecl() << E->getSourceRange(); 12963 12964 return BaseTransform::TransformDeclRefExpr(E); 12965 } 12966 12967 // Exception: filter out member pointer formation 12968 ExprResult TransformUnaryOperator(UnaryOperator *E) { 12969 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 12970 return E; 12971 12972 return BaseTransform::TransformUnaryOperator(E); 12973 } 12974 12975 ExprResult TransformLambdaExpr(LambdaExpr *E) { 12976 // Lambdas never need to be transformed. 12977 return E; 12978 } 12979 }; 12980 } 12981 12982 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 12983 assert(isUnevaluatedContext() && 12984 "Should only transform unevaluated expressions"); 12985 ExprEvalContexts.back().Context = 12986 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 12987 if (isUnevaluatedContext()) 12988 return E; 12989 return TransformToPE(*this).TransformExpr(E); 12990 } 12991 12992 void 12993 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 12994 Decl *LambdaContextDecl, 12995 bool IsDecltype) { 12996 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 12997 LambdaContextDecl, IsDecltype); 12998 Cleanup.reset(); 12999 if (!MaybeODRUseExprs.empty()) 13000 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 13001 } 13002 13003 void 13004 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 13005 ReuseLambdaContextDecl_t, 13006 bool IsDecltype) { 13007 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 13008 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 13009 } 13010 13011 void Sema::PopExpressionEvaluationContext() { 13012 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 13013 unsigned NumTypos = Rec.NumTypos; 13014 13015 if (!Rec.Lambdas.empty()) { 13016 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 13017 unsigned D; 13018 if (Rec.isUnevaluated()) { 13019 // C++11 [expr.prim.lambda]p2: 13020 // A lambda-expression shall not appear in an unevaluated operand 13021 // (Clause 5). 13022 D = diag::err_lambda_unevaluated_operand; 13023 } else { 13024 // C++1y [expr.const]p2: 13025 // A conditional-expression e is a core constant expression unless the 13026 // evaluation of e, following the rules of the abstract machine, would 13027 // evaluate [...] a lambda-expression. 13028 D = diag::err_lambda_in_constant_expression; 13029 } 13030 for (const auto *L : Rec.Lambdas) 13031 Diag(L->getLocStart(), D); 13032 } else { 13033 // Mark the capture expressions odr-used. This was deferred 13034 // during lambda expression creation. 13035 for (auto *Lambda : Rec.Lambdas) { 13036 for (auto *C : Lambda->capture_inits()) 13037 MarkDeclarationsReferencedInExpr(C); 13038 } 13039 } 13040 } 13041 13042 // When are coming out of an unevaluated context, clear out any 13043 // temporaries that we may have created as part of the evaluation of 13044 // the expression in that context: they aren't relevant because they 13045 // will never be constructed. 13046 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 13047 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 13048 ExprCleanupObjects.end()); 13049 Cleanup = Rec.ParentCleanup; 13050 CleanupVarDeclMarking(); 13051 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 13052 // Otherwise, merge the contexts together. 13053 } else { 13054 Cleanup.mergeFrom(Rec.ParentCleanup); 13055 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 13056 Rec.SavedMaybeODRUseExprs.end()); 13057 } 13058 13059 // Pop the current expression evaluation context off the stack. 13060 ExprEvalContexts.pop_back(); 13061 13062 if (!ExprEvalContexts.empty()) 13063 ExprEvalContexts.back().NumTypos += NumTypos; 13064 else 13065 assert(NumTypos == 0 && "There are outstanding typos after popping the " 13066 "last ExpressionEvaluationContextRecord"); 13067 } 13068 13069 void Sema::DiscardCleanupsInEvaluationContext() { 13070 ExprCleanupObjects.erase( 13071 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 13072 ExprCleanupObjects.end()); 13073 Cleanup.reset(); 13074 MaybeODRUseExprs.clear(); 13075 } 13076 13077 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 13078 if (!E->getType()->isVariablyModifiedType()) 13079 return E; 13080 return TransformToPotentiallyEvaluated(E); 13081 } 13082 13083 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) { 13084 // Do not mark anything as "used" within a dependent context; wait for 13085 // an instantiation. 13086 if (SemaRef.CurContext->isDependentContext()) 13087 return false; 13088 13089 switch (SemaRef.ExprEvalContexts.back().Context) { 13090 case Sema::Unevaluated: 13091 case Sema::UnevaluatedAbstract: 13092 // We are in an expression that is not potentially evaluated; do nothing. 13093 // (Depending on how you read the standard, we actually do need to do 13094 // something here for null pointer constants, but the standard's 13095 // definition of a null pointer constant is completely crazy.) 13096 return false; 13097 13098 case Sema::DiscardedStatement: 13099 // These are technically a potentially evaluated but they have the effect 13100 // of suppressing use marking. 13101 return false; 13102 13103 case Sema::ConstantEvaluated: 13104 case Sema::PotentiallyEvaluated: 13105 // We are in a potentially evaluated expression (or a constant-expression 13106 // in C++03); we need to do implicit template instantiation, implicitly 13107 // define class members, and mark most declarations as used. 13108 return true; 13109 13110 case Sema::PotentiallyEvaluatedIfUsed: 13111 // Referenced declarations will only be used if the construct in the 13112 // containing expression is used. 13113 return false; 13114 } 13115 llvm_unreachable("Invalid context"); 13116 } 13117 13118 /// \brief Mark a function referenced, and check whether it is odr-used 13119 /// (C++ [basic.def.odr]p2, C99 6.9p3) 13120 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 13121 bool MightBeOdrUse) { 13122 assert(Func && "No function?"); 13123 13124 Func->setReferenced(); 13125 13126 // C++11 [basic.def.odr]p3: 13127 // A function whose name appears as a potentially-evaluated expression is 13128 // odr-used if it is the unique lookup result or the selected member of a 13129 // set of overloaded functions [...]. 13130 // 13131 // We (incorrectly) mark overload resolution as an unevaluated context, so we 13132 // can just check that here. 13133 bool OdrUse = MightBeOdrUse && IsPotentiallyEvaluatedContext(*this); 13134 13135 // Determine whether we require a function definition to exist, per 13136 // C++11 [temp.inst]p3: 13137 // Unless a function template specialization has been explicitly 13138 // instantiated or explicitly specialized, the function template 13139 // specialization is implicitly instantiated when the specialization is 13140 // referenced in a context that requires a function definition to exist. 13141 // 13142 // We consider constexpr function templates to be referenced in a context 13143 // that requires a definition to exist whenever they are referenced. 13144 // 13145 // FIXME: This instantiates constexpr functions too frequently. If this is 13146 // really an unevaluated context (and we're not just in the definition of a 13147 // function template or overload resolution or other cases which we 13148 // incorrectly consider to be unevaluated contexts), and we're not in a 13149 // subexpression which we actually need to evaluate (for instance, a 13150 // template argument, array bound or an expression in a braced-init-list), 13151 // we are not permitted to instantiate this constexpr function definition. 13152 // 13153 // FIXME: This also implicitly defines special members too frequently. They 13154 // are only supposed to be implicitly defined if they are odr-used, but they 13155 // are not odr-used from constant expressions in unevaluated contexts. 13156 // However, they cannot be referenced if they are deleted, and they are 13157 // deleted whenever the implicit definition of the special member would 13158 // fail (with very few exceptions). 13159 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 13160 bool NeedDefinition = 13161 OdrUse || (Func->isConstexpr() && (Func->isImplicitlyInstantiable() || 13162 (MD && !MD->isUserProvided()))); 13163 13164 // C++14 [temp.expl.spec]p6: 13165 // If a template [...] is explicitly specialized then that specialization 13166 // shall be declared before the first use of that specialization that would 13167 // cause an implicit instantiation to take place, in every translation unit 13168 // in which such a use occurs 13169 if (NeedDefinition && 13170 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 13171 Func->getMemberSpecializationInfo())) 13172 checkSpecializationVisibility(Loc, Func); 13173 13174 // C++14 [except.spec]p17: 13175 // An exception-specification is considered to be needed when: 13176 // - the function is odr-used or, if it appears in an unevaluated operand, 13177 // would be odr-used if the expression were potentially-evaluated; 13178 // 13179 // Note, we do this even if MightBeOdrUse is false. That indicates that the 13180 // function is a pure virtual function we're calling, and in that case the 13181 // function was selected by overload resolution and we need to resolve its 13182 // exception specification for a different reason. 13183 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 13184 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 13185 ResolveExceptionSpec(Loc, FPT); 13186 13187 // If we don't need to mark the function as used, and we don't need to 13188 // try to provide a definition, there's nothing more to do. 13189 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) && 13190 (!NeedDefinition || Func->getBody())) 13191 return; 13192 13193 // Note that this declaration has been used. 13194 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 13195 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 13196 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 13197 if (Constructor->isDefaultConstructor()) { 13198 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 13199 return; 13200 DefineImplicitDefaultConstructor(Loc, Constructor); 13201 } else if (Constructor->isCopyConstructor()) { 13202 DefineImplicitCopyConstructor(Loc, Constructor); 13203 } else if (Constructor->isMoveConstructor()) { 13204 DefineImplicitMoveConstructor(Loc, Constructor); 13205 } 13206 } else if (Constructor->getInheritedConstructor()) { 13207 DefineInheritingConstructor(Loc, Constructor); 13208 } 13209 } else if (CXXDestructorDecl *Destructor = 13210 dyn_cast<CXXDestructorDecl>(Func)) { 13211 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 13212 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 13213 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 13214 return; 13215 DefineImplicitDestructor(Loc, Destructor); 13216 } 13217 if (Destructor->isVirtual() && getLangOpts().AppleKext) 13218 MarkVTableUsed(Loc, Destructor->getParent()); 13219 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 13220 if (MethodDecl->isOverloadedOperator() && 13221 MethodDecl->getOverloadedOperator() == OO_Equal) { 13222 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 13223 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 13224 if (MethodDecl->isCopyAssignmentOperator()) 13225 DefineImplicitCopyAssignment(Loc, MethodDecl); 13226 else if (MethodDecl->isMoveAssignmentOperator()) 13227 DefineImplicitMoveAssignment(Loc, MethodDecl); 13228 } 13229 } else if (isa<CXXConversionDecl>(MethodDecl) && 13230 MethodDecl->getParent()->isLambda()) { 13231 CXXConversionDecl *Conversion = 13232 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 13233 if (Conversion->isLambdaToBlockPointerConversion()) 13234 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 13235 else 13236 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 13237 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 13238 MarkVTableUsed(Loc, MethodDecl->getParent()); 13239 } 13240 13241 // Recursive functions should be marked when used from another function. 13242 // FIXME: Is this really right? 13243 if (CurContext == Func) return; 13244 13245 // Implicit instantiation of function templates and member functions of 13246 // class templates. 13247 if (Func->isImplicitlyInstantiable()) { 13248 bool AlreadyInstantiated = false; 13249 SourceLocation PointOfInstantiation = Loc; 13250 if (FunctionTemplateSpecializationInfo *SpecInfo 13251 = Func->getTemplateSpecializationInfo()) { 13252 if (SpecInfo->getPointOfInstantiation().isInvalid()) 13253 SpecInfo->setPointOfInstantiation(Loc); 13254 else if (SpecInfo->getTemplateSpecializationKind() 13255 == TSK_ImplicitInstantiation) { 13256 AlreadyInstantiated = true; 13257 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 13258 } 13259 } else if (MemberSpecializationInfo *MSInfo 13260 = Func->getMemberSpecializationInfo()) { 13261 if (MSInfo->getPointOfInstantiation().isInvalid()) 13262 MSInfo->setPointOfInstantiation(Loc); 13263 else if (MSInfo->getTemplateSpecializationKind() 13264 == TSK_ImplicitInstantiation) { 13265 AlreadyInstantiated = true; 13266 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 13267 } 13268 } 13269 13270 if (!AlreadyInstantiated || Func->isConstexpr()) { 13271 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 13272 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 13273 ActiveTemplateInstantiations.size()) 13274 PendingLocalImplicitInstantiations.push_back( 13275 std::make_pair(Func, PointOfInstantiation)); 13276 else if (Func->isConstexpr()) 13277 // Do not defer instantiations of constexpr functions, to avoid the 13278 // expression evaluator needing to call back into Sema if it sees a 13279 // call to such a function. 13280 InstantiateFunctionDefinition(PointOfInstantiation, Func); 13281 else { 13282 PendingInstantiations.push_back(std::make_pair(Func, 13283 PointOfInstantiation)); 13284 // Notify the consumer that a function was implicitly instantiated. 13285 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 13286 } 13287 } 13288 } else { 13289 // Walk redefinitions, as some of them may be instantiable. 13290 for (auto i : Func->redecls()) { 13291 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 13292 MarkFunctionReferenced(Loc, i, OdrUse); 13293 } 13294 } 13295 13296 if (!OdrUse) return; 13297 13298 // Keep track of used but undefined functions. 13299 if (!Func->isDefined()) { 13300 if (mightHaveNonExternalLinkage(Func)) 13301 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 13302 else if (Func->getMostRecentDecl()->isInlined() && 13303 !LangOpts.GNUInline && 13304 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 13305 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 13306 } 13307 13308 Func->markUsed(Context); 13309 } 13310 13311 static void 13312 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 13313 ValueDecl *var, DeclContext *DC) { 13314 DeclContext *VarDC = var->getDeclContext(); 13315 13316 // If the parameter still belongs to the translation unit, then 13317 // we're actually just using one parameter in the declaration of 13318 // the next. 13319 if (isa<ParmVarDecl>(var) && 13320 isa<TranslationUnitDecl>(VarDC)) 13321 return; 13322 13323 // For C code, don't diagnose about capture if we're not actually in code 13324 // right now; it's impossible to write a non-constant expression outside of 13325 // function context, so we'll get other (more useful) diagnostics later. 13326 // 13327 // For C++, things get a bit more nasty... it would be nice to suppress this 13328 // diagnostic for certain cases like using a local variable in an array bound 13329 // for a member of a local class, but the correct predicate is not obvious. 13330 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 13331 return; 13332 13333 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 13334 unsigned ContextKind = 3; // unknown 13335 if (isa<CXXMethodDecl>(VarDC) && 13336 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 13337 ContextKind = 2; 13338 } else if (isa<FunctionDecl>(VarDC)) { 13339 ContextKind = 0; 13340 } else if (isa<BlockDecl>(VarDC)) { 13341 ContextKind = 1; 13342 } 13343 13344 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 13345 << var << ValueKind << ContextKind << VarDC; 13346 S.Diag(var->getLocation(), diag::note_entity_declared_at) 13347 << var; 13348 13349 // FIXME: Add additional diagnostic info about class etc. which prevents 13350 // capture. 13351 } 13352 13353 13354 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 13355 bool &SubCapturesAreNested, 13356 QualType &CaptureType, 13357 QualType &DeclRefType) { 13358 // Check whether we've already captured it. 13359 if (CSI->CaptureMap.count(Var)) { 13360 // If we found a capture, any subcaptures are nested. 13361 SubCapturesAreNested = true; 13362 13363 // Retrieve the capture type for this variable. 13364 CaptureType = CSI->getCapture(Var).getCaptureType(); 13365 13366 // Compute the type of an expression that refers to this variable. 13367 DeclRefType = CaptureType.getNonReferenceType(); 13368 13369 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 13370 // are mutable in the sense that user can change their value - they are 13371 // private instances of the captured declarations. 13372 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 13373 if (Cap.isCopyCapture() && 13374 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 13375 !(isa<CapturedRegionScopeInfo>(CSI) && 13376 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 13377 DeclRefType.addConst(); 13378 return true; 13379 } 13380 return false; 13381 } 13382 13383 // Only block literals, captured statements, and lambda expressions can 13384 // capture; other scopes don't work. 13385 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 13386 SourceLocation Loc, 13387 const bool Diagnose, Sema &S) { 13388 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 13389 return getLambdaAwareParentOfDeclContext(DC); 13390 else if (Var->hasLocalStorage()) { 13391 if (Diagnose) 13392 diagnoseUncapturableValueReference(S, Loc, Var, DC); 13393 } 13394 return nullptr; 13395 } 13396 13397 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 13398 // certain types of variables (unnamed, variably modified types etc.) 13399 // so check for eligibility. 13400 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 13401 SourceLocation Loc, 13402 const bool Diagnose, Sema &S) { 13403 13404 bool IsBlock = isa<BlockScopeInfo>(CSI); 13405 bool IsLambda = isa<LambdaScopeInfo>(CSI); 13406 13407 // Lambdas are not allowed to capture unnamed variables 13408 // (e.g. anonymous unions). 13409 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 13410 // assuming that's the intent. 13411 if (IsLambda && !Var->getDeclName()) { 13412 if (Diagnose) { 13413 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 13414 S.Diag(Var->getLocation(), diag::note_declared_at); 13415 } 13416 return false; 13417 } 13418 13419 // Prohibit variably-modified types in blocks; they're difficult to deal with. 13420 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 13421 if (Diagnose) { 13422 S.Diag(Loc, diag::err_ref_vm_type); 13423 S.Diag(Var->getLocation(), diag::note_previous_decl) 13424 << Var->getDeclName(); 13425 } 13426 return false; 13427 } 13428 // Prohibit structs with flexible array members too. 13429 // We cannot capture what is in the tail end of the struct. 13430 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 13431 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 13432 if (Diagnose) { 13433 if (IsBlock) 13434 S.Diag(Loc, diag::err_ref_flexarray_type); 13435 else 13436 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 13437 << Var->getDeclName(); 13438 S.Diag(Var->getLocation(), diag::note_previous_decl) 13439 << Var->getDeclName(); 13440 } 13441 return false; 13442 } 13443 } 13444 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 13445 // Lambdas and captured statements are not allowed to capture __block 13446 // variables; they don't support the expected semantics. 13447 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 13448 if (Diagnose) { 13449 S.Diag(Loc, diag::err_capture_block_variable) 13450 << Var->getDeclName() << !IsLambda; 13451 S.Diag(Var->getLocation(), diag::note_previous_decl) 13452 << Var->getDeclName(); 13453 } 13454 return false; 13455 } 13456 13457 return true; 13458 } 13459 13460 // Returns true if the capture by block was successful. 13461 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 13462 SourceLocation Loc, 13463 const bool BuildAndDiagnose, 13464 QualType &CaptureType, 13465 QualType &DeclRefType, 13466 const bool Nested, 13467 Sema &S) { 13468 Expr *CopyExpr = nullptr; 13469 bool ByRef = false; 13470 13471 // Blocks are not allowed to capture arrays. 13472 if (CaptureType->isArrayType()) { 13473 if (BuildAndDiagnose) { 13474 S.Diag(Loc, diag::err_ref_array_type); 13475 S.Diag(Var->getLocation(), diag::note_previous_decl) 13476 << Var->getDeclName(); 13477 } 13478 return false; 13479 } 13480 13481 // Forbid the block-capture of autoreleasing variables. 13482 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 13483 if (BuildAndDiagnose) { 13484 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 13485 << /*block*/ 0; 13486 S.Diag(Var->getLocation(), diag::note_previous_decl) 13487 << Var->getDeclName(); 13488 } 13489 return false; 13490 } 13491 13492 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 13493 if (auto *PT = dyn_cast<PointerType>(CaptureType)) { 13494 QualType PointeeTy = PT->getPointeeType(); 13495 if (isa<ObjCObjectPointerType>(PointeeTy.getCanonicalType()) && 13496 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 13497 !isa<AttributedType>(PointeeTy)) { 13498 if (BuildAndDiagnose) { 13499 SourceLocation VarLoc = Var->getLocation(); 13500 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 13501 S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing) << 13502 FixItHint::CreateInsertion(VarLoc, "__autoreleasing"); 13503 S.Diag(VarLoc, diag::note_declare_parameter_strong); 13504 } 13505 } 13506 } 13507 13508 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 13509 if (HasBlocksAttr || CaptureType->isReferenceType() || 13510 (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) { 13511 // Block capture by reference does not change the capture or 13512 // declaration reference types. 13513 ByRef = true; 13514 } else { 13515 // Block capture by copy introduces 'const'. 13516 CaptureType = CaptureType.getNonReferenceType().withConst(); 13517 DeclRefType = CaptureType; 13518 13519 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 13520 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 13521 // The capture logic needs the destructor, so make sure we mark it. 13522 // Usually this is unnecessary because most local variables have 13523 // their destructors marked at declaration time, but parameters are 13524 // an exception because it's technically only the call site that 13525 // actually requires the destructor. 13526 if (isa<ParmVarDecl>(Var)) 13527 S.FinalizeVarWithDestructor(Var, Record); 13528 13529 // Enter a new evaluation context to insulate the copy 13530 // full-expression. 13531 EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated); 13532 13533 // According to the blocks spec, the capture of a variable from 13534 // the stack requires a const copy constructor. This is not true 13535 // of the copy/move done to move a __block variable to the heap. 13536 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 13537 DeclRefType.withConst(), 13538 VK_LValue, Loc); 13539 13540 ExprResult Result 13541 = S.PerformCopyInitialization( 13542 InitializedEntity::InitializeBlock(Var->getLocation(), 13543 CaptureType, false), 13544 Loc, DeclRef); 13545 13546 // Build a full-expression copy expression if initialization 13547 // succeeded and used a non-trivial constructor. Recover from 13548 // errors by pretending that the copy isn't necessary. 13549 if (!Result.isInvalid() && 13550 !cast<CXXConstructExpr>(Result.get())->getConstructor() 13551 ->isTrivial()) { 13552 Result = S.MaybeCreateExprWithCleanups(Result); 13553 CopyExpr = Result.get(); 13554 } 13555 } 13556 } 13557 } 13558 13559 // Actually capture the variable. 13560 if (BuildAndDiagnose) 13561 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 13562 SourceLocation(), CaptureType, CopyExpr); 13563 13564 return true; 13565 13566 } 13567 13568 13569 /// \brief Capture the given variable in the captured region. 13570 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 13571 VarDecl *Var, 13572 SourceLocation Loc, 13573 const bool BuildAndDiagnose, 13574 QualType &CaptureType, 13575 QualType &DeclRefType, 13576 const bool RefersToCapturedVariable, 13577 Sema &S) { 13578 // By default, capture variables by reference. 13579 bool ByRef = true; 13580 // Using an LValue reference type is consistent with Lambdas (see below). 13581 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 13582 if (S.IsOpenMPCapturedDecl(Var)) 13583 DeclRefType = DeclRefType.getUnqualifiedType(); 13584 ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel); 13585 } 13586 13587 if (ByRef) 13588 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 13589 else 13590 CaptureType = DeclRefType; 13591 13592 Expr *CopyExpr = nullptr; 13593 if (BuildAndDiagnose) { 13594 // The current implementation assumes that all variables are captured 13595 // by references. Since there is no capture by copy, no expression 13596 // evaluation will be needed. 13597 RecordDecl *RD = RSI->TheRecordDecl; 13598 13599 FieldDecl *Field 13600 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 13601 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 13602 nullptr, false, ICIS_NoInit); 13603 Field->setImplicit(true); 13604 Field->setAccess(AS_private); 13605 RD->addDecl(Field); 13606 13607 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, 13608 DeclRefType, VK_LValue, Loc); 13609 Var->setReferenced(true); 13610 Var->markUsed(S.Context); 13611 } 13612 13613 // Actually capture the variable. 13614 if (BuildAndDiagnose) 13615 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 13616 SourceLocation(), CaptureType, CopyExpr); 13617 13618 13619 return true; 13620 } 13621 13622 /// \brief Create a field within the lambda class for the variable 13623 /// being captured. 13624 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, 13625 QualType FieldType, QualType DeclRefType, 13626 SourceLocation Loc, 13627 bool RefersToCapturedVariable) { 13628 CXXRecordDecl *Lambda = LSI->Lambda; 13629 13630 // Build the non-static data member. 13631 FieldDecl *Field 13632 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 13633 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 13634 nullptr, false, ICIS_NoInit); 13635 Field->setImplicit(true); 13636 Field->setAccess(AS_private); 13637 Lambda->addDecl(Field); 13638 } 13639 13640 /// \brief Capture the given variable in the lambda. 13641 static bool captureInLambda(LambdaScopeInfo *LSI, 13642 VarDecl *Var, 13643 SourceLocation Loc, 13644 const bool BuildAndDiagnose, 13645 QualType &CaptureType, 13646 QualType &DeclRefType, 13647 const bool RefersToCapturedVariable, 13648 const Sema::TryCaptureKind Kind, 13649 SourceLocation EllipsisLoc, 13650 const bool IsTopScope, 13651 Sema &S) { 13652 13653 // Determine whether we are capturing by reference or by value. 13654 bool ByRef = false; 13655 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 13656 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 13657 } else { 13658 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 13659 } 13660 13661 // Compute the type of the field that will capture this variable. 13662 if (ByRef) { 13663 // C++11 [expr.prim.lambda]p15: 13664 // An entity is captured by reference if it is implicitly or 13665 // explicitly captured but not captured by copy. It is 13666 // unspecified whether additional unnamed non-static data 13667 // members are declared in the closure type for entities 13668 // captured by reference. 13669 // 13670 // FIXME: It is not clear whether we want to build an lvalue reference 13671 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 13672 // to do the former, while EDG does the latter. Core issue 1249 will 13673 // clarify, but for now we follow GCC because it's a more permissive and 13674 // easily defensible position. 13675 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 13676 } else { 13677 // C++11 [expr.prim.lambda]p14: 13678 // For each entity captured by copy, an unnamed non-static 13679 // data member is declared in the closure type. The 13680 // declaration order of these members is unspecified. The type 13681 // of such a data member is the type of the corresponding 13682 // captured entity if the entity is not a reference to an 13683 // object, or the referenced type otherwise. [Note: If the 13684 // captured entity is a reference to a function, the 13685 // corresponding data member is also a reference to a 13686 // function. - end note ] 13687 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 13688 if (!RefType->getPointeeType()->isFunctionType()) 13689 CaptureType = RefType->getPointeeType(); 13690 } 13691 13692 // Forbid the lambda copy-capture of autoreleasing variables. 13693 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 13694 if (BuildAndDiagnose) { 13695 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 13696 S.Diag(Var->getLocation(), diag::note_previous_decl) 13697 << Var->getDeclName(); 13698 } 13699 return false; 13700 } 13701 13702 // Make sure that by-copy captures are of a complete and non-abstract type. 13703 if (BuildAndDiagnose) { 13704 if (!CaptureType->isDependentType() && 13705 S.RequireCompleteType(Loc, CaptureType, 13706 diag::err_capture_of_incomplete_type, 13707 Var->getDeclName())) 13708 return false; 13709 13710 if (S.RequireNonAbstractType(Loc, CaptureType, 13711 diag::err_capture_of_abstract_type)) 13712 return false; 13713 } 13714 } 13715 13716 // Capture this variable in the lambda. 13717 if (BuildAndDiagnose) 13718 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc, 13719 RefersToCapturedVariable); 13720 13721 // Compute the type of a reference to this captured variable. 13722 if (ByRef) 13723 DeclRefType = CaptureType.getNonReferenceType(); 13724 else { 13725 // C++ [expr.prim.lambda]p5: 13726 // The closure type for a lambda-expression has a public inline 13727 // function call operator [...]. This function call operator is 13728 // declared const (9.3.1) if and only if the lambda-expression's 13729 // parameter-declaration-clause is not followed by mutable. 13730 DeclRefType = CaptureType.getNonReferenceType(); 13731 if (!LSI->Mutable && !CaptureType->isReferenceType()) 13732 DeclRefType.addConst(); 13733 } 13734 13735 // Add the capture. 13736 if (BuildAndDiagnose) 13737 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 13738 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 13739 13740 return true; 13741 } 13742 13743 bool Sema::tryCaptureVariable( 13744 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 13745 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 13746 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 13747 // An init-capture is notionally from the context surrounding its 13748 // declaration, but its parent DC is the lambda class. 13749 DeclContext *VarDC = Var->getDeclContext(); 13750 if (Var->isInitCapture()) 13751 VarDC = VarDC->getParent(); 13752 13753 DeclContext *DC = CurContext; 13754 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 13755 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 13756 // We need to sync up the Declaration Context with the 13757 // FunctionScopeIndexToStopAt 13758 if (FunctionScopeIndexToStopAt) { 13759 unsigned FSIndex = FunctionScopes.size() - 1; 13760 while (FSIndex != MaxFunctionScopesIndex) { 13761 DC = getLambdaAwareParentOfDeclContext(DC); 13762 --FSIndex; 13763 } 13764 } 13765 13766 13767 // If the variable is declared in the current context, there is no need to 13768 // capture it. 13769 if (VarDC == DC) return true; 13770 13771 // Capture global variables if it is required to use private copy of this 13772 // variable. 13773 bool IsGlobal = !Var->hasLocalStorage(); 13774 if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var))) 13775 return true; 13776 13777 // Walk up the stack to determine whether we can capture the variable, 13778 // performing the "simple" checks that don't depend on type. We stop when 13779 // we've either hit the declared scope of the variable or find an existing 13780 // capture of that variable. We start from the innermost capturing-entity 13781 // (the DC) and ensure that all intervening capturing-entities 13782 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 13783 // declcontext can either capture the variable or have already captured 13784 // the variable. 13785 CaptureType = Var->getType(); 13786 DeclRefType = CaptureType.getNonReferenceType(); 13787 bool Nested = false; 13788 bool Explicit = (Kind != TryCapture_Implicit); 13789 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 13790 do { 13791 // Only block literals, captured statements, and lambda expressions can 13792 // capture; other scopes don't work. 13793 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 13794 ExprLoc, 13795 BuildAndDiagnose, 13796 *this); 13797 // We need to check for the parent *first* because, if we *have* 13798 // private-captured a global variable, we need to recursively capture it in 13799 // intermediate blocks, lambdas, etc. 13800 if (!ParentDC) { 13801 if (IsGlobal) { 13802 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 13803 break; 13804 } 13805 return true; 13806 } 13807 13808 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 13809 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 13810 13811 13812 // Check whether we've already captured it. 13813 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 13814 DeclRefType)) 13815 break; 13816 // If we are instantiating a generic lambda call operator body, 13817 // we do not want to capture new variables. What was captured 13818 // during either a lambdas transformation or initial parsing 13819 // should be used. 13820 if (isGenericLambdaCallOperatorSpecialization(DC)) { 13821 if (BuildAndDiagnose) { 13822 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 13823 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 13824 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 13825 Diag(Var->getLocation(), diag::note_previous_decl) 13826 << Var->getDeclName(); 13827 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); 13828 } else 13829 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 13830 } 13831 return true; 13832 } 13833 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 13834 // certain types of variables (unnamed, variably modified types etc.) 13835 // so check for eligibility. 13836 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 13837 return true; 13838 13839 // Try to capture variable-length arrays types. 13840 if (Var->getType()->isVariablyModifiedType()) { 13841 // We're going to walk down into the type and look for VLA 13842 // expressions. 13843 QualType QTy = Var->getType(); 13844 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 13845 QTy = PVD->getOriginalType(); 13846 captureVariablyModifiedType(Context, QTy, CSI); 13847 } 13848 13849 if (getLangOpts().OpenMP) { 13850 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13851 // OpenMP private variables should not be captured in outer scope, so 13852 // just break here. Similarly, global variables that are captured in a 13853 // target region should not be captured outside the scope of the region. 13854 if (RSI->CapRegionKind == CR_OpenMP) { 13855 auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 13856 // When we detect target captures we are looking from inside the 13857 // target region, therefore we need to propagate the capture from the 13858 // enclosing region. Therefore, the capture is not initially nested. 13859 if (IsTargetCap) 13860 FunctionScopesIndex--; 13861 13862 if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) { 13863 Nested = !IsTargetCap; 13864 DeclRefType = DeclRefType.getUnqualifiedType(); 13865 CaptureType = Context.getLValueReferenceType(DeclRefType); 13866 break; 13867 } 13868 } 13869 } 13870 } 13871 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 13872 // No capture-default, and this is not an explicit capture 13873 // so cannot capture this variable. 13874 if (BuildAndDiagnose) { 13875 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 13876 Diag(Var->getLocation(), diag::note_previous_decl) 13877 << Var->getDeclName(); 13878 if (cast<LambdaScopeInfo>(CSI)->Lambda) 13879 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 13880 diag::note_lambda_decl); 13881 // FIXME: If we error out because an outer lambda can not implicitly 13882 // capture a variable that an inner lambda explicitly captures, we 13883 // should have the inner lambda do the explicit capture - because 13884 // it makes for cleaner diagnostics later. This would purely be done 13885 // so that the diagnostic does not misleadingly claim that a variable 13886 // can not be captured by a lambda implicitly even though it is captured 13887 // explicitly. Suggestion: 13888 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 13889 // at the function head 13890 // - cache the StartingDeclContext - this must be a lambda 13891 // - captureInLambda in the innermost lambda the variable. 13892 } 13893 return true; 13894 } 13895 13896 FunctionScopesIndex--; 13897 DC = ParentDC; 13898 Explicit = false; 13899 } while (!VarDC->Equals(DC)); 13900 13901 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 13902 // computing the type of the capture at each step, checking type-specific 13903 // requirements, and adding captures if requested. 13904 // If the variable had already been captured previously, we start capturing 13905 // at the lambda nested within that one. 13906 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 13907 ++I) { 13908 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 13909 13910 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 13911 if (!captureInBlock(BSI, Var, ExprLoc, 13912 BuildAndDiagnose, CaptureType, 13913 DeclRefType, Nested, *this)) 13914 return true; 13915 Nested = true; 13916 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13917 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 13918 BuildAndDiagnose, CaptureType, 13919 DeclRefType, Nested, *this)) 13920 return true; 13921 Nested = true; 13922 } else { 13923 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 13924 if (!captureInLambda(LSI, Var, ExprLoc, 13925 BuildAndDiagnose, CaptureType, 13926 DeclRefType, Nested, Kind, EllipsisLoc, 13927 /*IsTopScope*/I == N - 1, *this)) 13928 return true; 13929 Nested = true; 13930 } 13931 } 13932 return false; 13933 } 13934 13935 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 13936 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 13937 QualType CaptureType; 13938 QualType DeclRefType; 13939 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 13940 /*BuildAndDiagnose=*/true, CaptureType, 13941 DeclRefType, nullptr); 13942 } 13943 13944 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 13945 QualType CaptureType; 13946 QualType DeclRefType; 13947 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 13948 /*BuildAndDiagnose=*/false, CaptureType, 13949 DeclRefType, nullptr); 13950 } 13951 13952 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 13953 QualType CaptureType; 13954 QualType DeclRefType; 13955 13956 // Determine whether we can capture this variable. 13957 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 13958 /*BuildAndDiagnose=*/false, CaptureType, 13959 DeclRefType, nullptr)) 13960 return QualType(); 13961 13962 return DeclRefType; 13963 } 13964 13965 13966 13967 // If either the type of the variable or the initializer is dependent, 13968 // return false. Otherwise, determine whether the variable is a constant 13969 // expression. Use this if you need to know if a variable that might or 13970 // might not be dependent is truly a constant expression. 13971 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 13972 ASTContext &Context) { 13973 13974 if (Var->getType()->isDependentType()) 13975 return false; 13976 const VarDecl *DefVD = nullptr; 13977 Var->getAnyInitializer(DefVD); 13978 if (!DefVD) 13979 return false; 13980 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 13981 Expr *Init = cast<Expr>(Eval->Value); 13982 if (Init->isValueDependent()) 13983 return false; 13984 return IsVariableAConstantExpression(Var, Context); 13985 } 13986 13987 13988 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 13989 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 13990 // an object that satisfies the requirements for appearing in a 13991 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 13992 // is immediately applied." This function handles the lvalue-to-rvalue 13993 // conversion part. 13994 MaybeODRUseExprs.erase(E->IgnoreParens()); 13995 13996 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 13997 // to a variable that is a constant expression, and if so, identify it as 13998 // a reference to a variable that does not involve an odr-use of that 13999 // variable. 14000 if (LambdaScopeInfo *LSI = getCurLambda()) { 14001 Expr *SansParensExpr = E->IgnoreParens(); 14002 VarDecl *Var = nullptr; 14003 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 14004 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 14005 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 14006 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 14007 14008 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 14009 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 14010 } 14011 } 14012 14013 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 14014 Res = CorrectDelayedTyposInExpr(Res); 14015 14016 if (!Res.isUsable()) 14017 return Res; 14018 14019 // If a constant-expression is a reference to a variable where we delay 14020 // deciding whether it is an odr-use, just assume we will apply the 14021 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 14022 // (a non-type template argument), we have special handling anyway. 14023 UpdateMarkingForLValueToRValue(Res.get()); 14024 return Res; 14025 } 14026 14027 void Sema::CleanupVarDeclMarking() { 14028 for (Expr *E : MaybeODRUseExprs) { 14029 VarDecl *Var; 14030 SourceLocation Loc; 14031 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 14032 Var = cast<VarDecl>(DRE->getDecl()); 14033 Loc = DRE->getLocation(); 14034 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 14035 Var = cast<VarDecl>(ME->getMemberDecl()); 14036 Loc = ME->getMemberLoc(); 14037 } else { 14038 llvm_unreachable("Unexpected expression"); 14039 } 14040 14041 MarkVarDeclODRUsed(Var, Loc, *this, 14042 /*MaxFunctionScopeIndex Pointer*/ nullptr); 14043 } 14044 14045 MaybeODRUseExprs.clear(); 14046 } 14047 14048 14049 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 14050 VarDecl *Var, Expr *E) { 14051 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 14052 "Invalid Expr argument to DoMarkVarDeclReferenced"); 14053 Var->setReferenced(); 14054 14055 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 14056 bool MarkODRUsed = true; 14057 14058 // If the context is not potentially evaluated, this is not an odr-use and 14059 // does not trigger instantiation. 14060 if (!IsPotentiallyEvaluatedContext(SemaRef)) { 14061 if (SemaRef.isUnevaluatedContext()) 14062 return; 14063 14064 // If we don't yet know whether this context is going to end up being an 14065 // evaluated context, and we're referencing a variable from an enclosing 14066 // scope, add a potential capture. 14067 // 14068 // FIXME: Is this necessary? These contexts are only used for default 14069 // arguments, where local variables can't be used. 14070 const bool RefersToEnclosingScope = 14071 (SemaRef.CurContext != Var->getDeclContext() && 14072 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 14073 if (RefersToEnclosingScope) { 14074 if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) { 14075 // If a variable could potentially be odr-used, defer marking it so 14076 // until we finish analyzing the full expression for any 14077 // lvalue-to-rvalue 14078 // or discarded value conversions that would obviate odr-use. 14079 // Add it to the list of potential captures that will be analyzed 14080 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 14081 // unless the variable is a reference that was initialized by a constant 14082 // expression (this will never need to be captured or odr-used). 14083 assert(E && "Capture variable should be used in an expression."); 14084 if (!Var->getType()->isReferenceType() || 14085 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 14086 LSI->addPotentialCapture(E->IgnoreParens()); 14087 } 14088 } 14089 14090 if (!isTemplateInstantiation(TSK)) 14091 return; 14092 14093 // Instantiate, but do not mark as odr-used, variable templates. 14094 MarkODRUsed = false; 14095 } 14096 14097 VarTemplateSpecializationDecl *VarSpec = 14098 dyn_cast<VarTemplateSpecializationDecl>(Var); 14099 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 14100 "Can't instantiate a partial template specialization."); 14101 14102 // If this might be a member specialization of a static data member, check 14103 // the specialization is visible. We already did the checks for variable 14104 // template specializations when we created them. 14105 if (TSK != TSK_Undeclared && !isa<VarTemplateSpecializationDecl>(Var)) 14106 SemaRef.checkSpecializationVisibility(Loc, Var); 14107 14108 // Perform implicit instantiation of static data members, static data member 14109 // templates of class templates, and variable template specializations. Delay 14110 // instantiations of variable templates, except for those that could be used 14111 // in a constant expression. 14112 if (isTemplateInstantiation(TSK)) { 14113 bool TryInstantiating = TSK == TSK_ImplicitInstantiation; 14114 14115 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) { 14116 if (Var->getPointOfInstantiation().isInvalid()) { 14117 // This is a modification of an existing AST node. Notify listeners. 14118 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 14119 L->StaticDataMemberInstantiated(Var); 14120 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context)) 14121 // Don't bother trying to instantiate it again, unless we might need 14122 // its initializer before we get to the end of the TU. 14123 TryInstantiating = false; 14124 } 14125 14126 if (Var->getPointOfInstantiation().isInvalid()) 14127 Var->setTemplateSpecializationKind(TSK, Loc); 14128 14129 if (TryInstantiating) { 14130 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 14131 bool InstantiationDependent = false; 14132 bool IsNonDependent = 14133 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 14134 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 14135 : true; 14136 14137 // Do not instantiate specializations that are still type-dependent. 14138 if (IsNonDependent) { 14139 if (Var->isUsableInConstantExpressions(SemaRef.Context)) { 14140 // Do not defer instantiations of variables which could be used in a 14141 // constant expression. 14142 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 14143 } else { 14144 SemaRef.PendingInstantiations 14145 .push_back(std::make_pair(Var, PointOfInstantiation)); 14146 } 14147 } 14148 } 14149 } 14150 14151 if (!MarkODRUsed) 14152 return; 14153 14154 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 14155 // the requirements for appearing in a constant expression (5.19) and, if 14156 // it is an object, the lvalue-to-rvalue conversion (4.1) 14157 // is immediately applied." We check the first part here, and 14158 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 14159 // Note that we use the C++11 definition everywhere because nothing in 14160 // C++03 depends on whether we get the C++03 version correct. The second 14161 // part does not apply to references, since they are not objects. 14162 if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) { 14163 // A reference initialized by a constant expression can never be 14164 // odr-used, so simply ignore it. 14165 if (!Var->getType()->isReferenceType()) 14166 SemaRef.MaybeODRUseExprs.insert(E); 14167 } else 14168 MarkVarDeclODRUsed(Var, Loc, SemaRef, 14169 /*MaxFunctionScopeIndex ptr*/ nullptr); 14170 } 14171 14172 /// \brief Mark a variable referenced, and check whether it is odr-used 14173 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 14174 /// used directly for normal expressions referring to VarDecl. 14175 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 14176 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 14177 } 14178 14179 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 14180 Decl *D, Expr *E, bool MightBeOdrUse) { 14181 if (SemaRef.isInOpenMPDeclareTargetContext()) 14182 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 14183 14184 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 14185 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 14186 return; 14187 } 14188 14189 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 14190 14191 // If this is a call to a method via a cast, also mark the method in the 14192 // derived class used in case codegen can devirtualize the call. 14193 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 14194 if (!ME) 14195 return; 14196 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 14197 if (!MD) 14198 return; 14199 // Only attempt to devirtualize if this is truly a virtual call. 14200 bool IsVirtualCall = MD->isVirtual() && 14201 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 14202 if (!IsVirtualCall) 14203 return; 14204 const Expr *Base = ME->getBase(); 14205 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType(); 14206 if (!MostDerivedClassDecl) 14207 return; 14208 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl); 14209 if (!DM || DM->isPure()) 14210 return; 14211 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 14212 } 14213 14214 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 14215 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) { 14216 // TODO: update this with DR# once a defect report is filed. 14217 // C++11 defect. The address of a pure member should not be an ODR use, even 14218 // if it's a qualified reference. 14219 bool OdrUse = true; 14220 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 14221 if (Method->isVirtual()) 14222 OdrUse = false; 14223 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 14224 } 14225 14226 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 14227 void Sema::MarkMemberReferenced(MemberExpr *E) { 14228 // C++11 [basic.def.odr]p2: 14229 // A non-overloaded function whose name appears as a potentially-evaluated 14230 // expression or a member of a set of candidate functions, if selected by 14231 // overload resolution when referred to from a potentially-evaluated 14232 // expression, is odr-used, unless it is a pure virtual function and its 14233 // name is not explicitly qualified. 14234 bool MightBeOdrUse = true; 14235 if (E->performsVirtualDispatch(getLangOpts())) { 14236 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 14237 if (Method->isPure()) 14238 MightBeOdrUse = false; 14239 } 14240 SourceLocation Loc = E->getMemberLoc().isValid() ? 14241 E->getMemberLoc() : E->getLocStart(); 14242 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 14243 } 14244 14245 /// \brief Perform marking for a reference to an arbitrary declaration. It 14246 /// marks the declaration referenced, and performs odr-use checking for 14247 /// functions and variables. This method should not be used when building a 14248 /// normal expression which refers to a variable. 14249 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 14250 bool MightBeOdrUse) { 14251 if (MightBeOdrUse) { 14252 if (auto *VD = dyn_cast<VarDecl>(D)) { 14253 MarkVariableReferenced(Loc, VD); 14254 return; 14255 } 14256 } 14257 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 14258 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 14259 return; 14260 } 14261 D->setReferenced(); 14262 } 14263 14264 namespace { 14265 // Mark all of the declarations referenced 14266 // FIXME: Not fully implemented yet! We need to have a better understanding 14267 // of when we're entering 14268 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 14269 Sema &S; 14270 SourceLocation Loc; 14271 14272 public: 14273 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 14274 14275 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 14276 14277 bool TraverseTemplateArgument(const TemplateArgument &Arg); 14278 bool TraverseRecordType(RecordType *T); 14279 }; 14280 } 14281 14282 bool MarkReferencedDecls::TraverseTemplateArgument( 14283 const TemplateArgument &Arg) { 14284 if (Arg.getKind() == TemplateArgument::Declaration) { 14285 if (Decl *D = Arg.getAsDecl()) 14286 S.MarkAnyDeclReferenced(Loc, D, true); 14287 } 14288 14289 return Inherited::TraverseTemplateArgument(Arg); 14290 } 14291 14292 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) { 14293 if (ClassTemplateSpecializationDecl *Spec 14294 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) { 14295 const TemplateArgumentList &Args = Spec->getTemplateArgs(); 14296 return TraverseTemplateArguments(Args.data(), Args.size()); 14297 } 14298 14299 return true; 14300 } 14301 14302 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 14303 MarkReferencedDecls Marker(*this, Loc); 14304 Marker.TraverseType(Context.getCanonicalType(T)); 14305 } 14306 14307 namespace { 14308 /// \brief Helper class that marks all of the declarations referenced by 14309 /// potentially-evaluated subexpressions as "referenced". 14310 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 14311 Sema &S; 14312 bool SkipLocalVariables; 14313 14314 public: 14315 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 14316 14317 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 14318 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 14319 14320 void VisitDeclRefExpr(DeclRefExpr *E) { 14321 // If we were asked not to visit local variables, don't. 14322 if (SkipLocalVariables) { 14323 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 14324 if (VD->hasLocalStorage()) 14325 return; 14326 } 14327 14328 S.MarkDeclRefReferenced(E); 14329 } 14330 14331 void VisitMemberExpr(MemberExpr *E) { 14332 S.MarkMemberReferenced(E); 14333 Inherited::VisitMemberExpr(E); 14334 } 14335 14336 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 14337 S.MarkFunctionReferenced(E->getLocStart(), 14338 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 14339 Visit(E->getSubExpr()); 14340 } 14341 14342 void VisitCXXNewExpr(CXXNewExpr *E) { 14343 if (E->getOperatorNew()) 14344 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 14345 if (E->getOperatorDelete()) 14346 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 14347 Inherited::VisitCXXNewExpr(E); 14348 } 14349 14350 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 14351 if (E->getOperatorDelete()) 14352 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 14353 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 14354 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 14355 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 14356 S.MarkFunctionReferenced(E->getLocStart(), 14357 S.LookupDestructor(Record)); 14358 } 14359 14360 Inherited::VisitCXXDeleteExpr(E); 14361 } 14362 14363 void VisitCXXConstructExpr(CXXConstructExpr *E) { 14364 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 14365 Inherited::VisitCXXConstructExpr(E); 14366 } 14367 14368 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 14369 Visit(E->getExpr()); 14370 } 14371 14372 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 14373 Inherited::VisitImplicitCastExpr(E); 14374 14375 if (E->getCastKind() == CK_LValueToRValue) 14376 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 14377 } 14378 }; 14379 } 14380 14381 /// \brief Mark any declarations that appear within this expression or any 14382 /// potentially-evaluated subexpressions as "referenced". 14383 /// 14384 /// \param SkipLocalVariables If true, don't mark local variables as 14385 /// 'referenced'. 14386 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 14387 bool SkipLocalVariables) { 14388 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 14389 } 14390 14391 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 14392 /// of the program being compiled. 14393 /// 14394 /// This routine emits the given diagnostic when the code currently being 14395 /// type-checked is "potentially evaluated", meaning that there is a 14396 /// possibility that the code will actually be executable. Code in sizeof() 14397 /// expressions, code used only during overload resolution, etc., are not 14398 /// potentially evaluated. This routine will suppress such diagnostics or, 14399 /// in the absolutely nutty case of potentially potentially evaluated 14400 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 14401 /// later. 14402 /// 14403 /// This routine should be used for all diagnostics that describe the run-time 14404 /// behavior of a program, such as passing a non-POD value through an ellipsis. 14405 /// Failure to do so will likely result in spurious diagnostics or failures 14406 /// during overload resolution or within sizeof/alignof/typeof/typeid. 14407 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 14408 const PartialDiagnostic &PD) { 14409 switch (ExprEvalContexts.back().Context) { 14410 case Unevaluated: 14411 case UnevaluatedAbstract: 14412 case DiscardedStatement: 14413 // The argument will never be evaluated, so don't complain. 14414 break; 14415 14416 case ConstantEvaluated: 14417 // Relevant diagnostics should be produced by constant evaluation. 14418 break; 14419 14420 case PotentiallyEvaluated: 14421 case PotentiallyEvaluatedIfUsed: 14422 if (Statement && getCurFunctionOrMethodDecl()) { 14423 FunctionScopes.back()->PossiblyUnreachableDiags. 14424 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 14425 } 14426 else 14427 Diag(Loc, PD); 14428 14429 return true; 14430 } 14431 14432 return false; 14433 } 14434 14435 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 14436 CallExpr *CE, FunctionDecl *FD) { 14437 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 14438 return false; 14439 14440 // If we're inside a decltype's expression, don't check for a valid return 14441 // type or construct temporaries until we know whether this is the last call. 14442 if (ExprEvalContexts.back().IsDecltype) { 14443 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 14444 return false; 14445 } 14446 14447 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 14448 FunctionDecl *FD; 14449 CallExpr *CE; 14450 14451 public: 14452 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 14453 : FD(FD), CE(CE) { } 14454 14455 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 14456 if (!FD) { 14457 S.Diag(Loc, diag::err_call_incomplete_return) 14458 << T << CE->getSourceRange(); 14459 return; 14460 } 14461 14462 S.Diag(Loc, diag::err_call_function_incomplete_return) 14463 << CE->getSourceRange() << FD->getDeclName() << T; 14464 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 14465 << FD->getDeclName(); 14466 } 14467 } Diagnoser(FD, CE); 14468 14469 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 14470 return true; 14471 14472 return false; 14473 } 14474 14475 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 14476 // will prevent this condition from triggering, which is what we want. 14477 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 14478 SourceLocation Loc; 14479 14480 unsigned diagnostic = diag::warn_condition_is_assignment; 14481 bool IsOrAssign = false; 14482 14483 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 14484 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 14485 return; 14486 14487 IsOrAssign = Op->getOpcode() == BO_OrAssign; 14488 14489 // Greylist some idioms by putting them into a warning subcategory. 14490 if (ObjCMessageExpr *ME 14491 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 14492 Selector Sel = ME->getSelector(); 14493 14494 // self = [<foo> init...] 14495 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 14496 diagnostic = diag::warn_condition_is_idiomatic_assignment; 14497 14498 // <foo> = [<bar> nextObject] 14499 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 14500 diagnostic = diag::warn_condition_is_idiomatic_assignment; 14501 } 14502 14503 Loc = Op->getOperatorLoc(); 14504 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 14505 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 14506 return; 14507 14508 IsOrAssign = Op->getOperator() == OO_PipeEqual; 14509 Loc = Op->getOperatorLoc(); 14510 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 14511 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 14512 else { 14513 // Not an assignment. 14514 return; 14515 } 14516 14517 Diag(Loc, diagnostic) << E->getSourceRange(); 14518 14519 SourceLocation Open = E->getLocStart(); 14520 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 14521 Diag(Loc, diag::note_condition_assign_silence) 14522 << FixItHint::CreateInsertion(Open, "(") 14523 << FixItHint::CreateInsertion(Close, ")"); 14524 14525 if (IsOrAssign) 14526 Diag(Loc, diag::note_condition_or_assign_to_comparison) 14527 << FixItHint::CreateReplacement(Loc, "!="); 14528 else 14529 Diag(Loc, diag::note_condition_assign_to_comparison) 14530 << FixItHint::CreateReplacement(Loc, "=="); 14531 } 14532 14533 /// \brief Redundant parentheses over an equality comparison can indicate 14534 /// that the user intended an assignment used as condition. 14535 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 14536 // Don't warn if the parens came from a macro. 14537 SourceLocation parenLoc = ParenE->getLocStart(); 14538 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 14539 return; 14540 // Don't warn for dependent expressions. 14541 if (ParenE->isTypeDependent()) 14542 return; 14543 14544 Expr *E = ParenE->IgnoreParens(); 14545 14546 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 14547 if (opE->getOpcode() == BO_EQ && 14548 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 14549 == Expr::MLV_Valid) { 14550 SourceLocation Loc = opE->getOperatorLoc(); 14551 14552 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 14553 SourceRange ParenERange = ParenE->getSourceRange(); 14554 Diag(Loc, diag::note_equality_comparison_silence) 14555 << FixItHint::CreateRemoval(ParenERange.getBegin()) 14556 << FixItHint::CreateRemoval(ParenERange.getEnd()); 14557 Diag(Loc, diag::note_equality_comparison_to_assign) 14558 << FixItHint::CreateReplacement(Loc, "="); 14559 } 14560 } 14561 14562 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 14563 bool IsConstexpr) { 14564 DiagnoseAssignmentAsCondition(E); 14565 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 14566 DiagnoseEqualityWithExtraParens(parenE); 14567 14568 ExprResult result = CheckPlaceholderExpr(E); 14569 if (result.isInvalid()) return ExprError(); 14570 E = result.get(); 14571 14572 if (!E->isTypeDependent()) { 14573 if (getLangOpts().CPlusPlus) 14574 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 14575 14576 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 14577 if (ERes.isInvalid()) 14578 return ExprError(); 14579 E = ERes.get(); 14580 14581 QualType T = E->getType(); 14582 if (!T->isScalarType()) { // C99 6.8.4.1p1 14583 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 14584 << T << E->getSourceRange(); 14585 return ExprError(); 14586 } 14587 CheckBoolLikeConversion(E, Loc); 14588 } 14589 14590 return E; 14591 } 14592 14593 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 14594 Expr *SubExpr, ConditionKind CK) { 14595 // Empty conditions are valid in for-statements. 14596 if (!SubExpr) 14597 return ConditionResult(); 14598 14599 ExprResult Cond; 14600 switch (CK) { 14601 case ConditionKind::Boolean: 14602 Cond = CheckBooleanCondition(Loc, SubExpr); 14603 break; 14604 14605 case ConditionKind::ConstexprIf: 14606 Cond = CheckBooleanCondition(Loc, SubExpr, true); 14607 break; 14608 14609 case ConditionKind::Switch: 14610 Cond = CheckSwitchCondition(Loc, SubExpr); 14611 break; 14612 } 14613 if (Cond.isInvalid()) 14614 return ConditionError(); 14615 14616 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 14617 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 14618 if (!FullExpr.get()) 14619 return ConditionError(); 14620 14621 return ConditionResult(*this, nullptr, FullExpr, 14622 CK == ConditionKind::ConstexprIf); 14623 } 14624 14625 namespace { 14626 /// A visitor for rebuilding a call to an __unknown_any expression 14627 /// to have an appropriate type. 14628 struct RebuildUnknownAnyFunction 14629 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 14630 14631 Sema &S; 14632 14633 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 14634 14635 ExprResult VisitStmt(Stmt *S) { 14636 llvm_unreachable("unexpected statement!"); 14637 } 14638 14639 ExprResult VisitExpr(Expr *E) { 14640 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 14641 << E->getSourceRange(); 14642 return ExprError(); 14643 } 14644 14645 /// Rebuild an expression which simply semantically wraps another 14646 /// expression which it shares the type and value kind of. 14647 template <class T> ExprResult rebuildSugarExpr(T *E) { 14648 ExprResult SubResult = Visit(E->getSubExpr()); 14649 if (SubResult.isInvalid()) return ExprError(); 14650 14651 Expr *SubExpr = SubResult.get(); 14652 E->setSubExpr(SubExpr); 14653 E->setType(SubExpr->getType()); 14654 E->setValueKind(SubExpr->getValueKind()); 14655 assert(E->getObjectKind() == OK_Ordinary); 14656 return E; 14657 } 14658 14659 ExprResult VisitParenExpr(ParenExpr *E) { 14660 return rebuildSugarExpr(E); 14661 } 14662 14663 ExprResult VisitUnaryExtension(UnaryOperator *E) { 14664 return rebuildSugarExpr(E); 14665 } 14666 14667 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 14668 ExprResult SubResult = Visit(E->getSubExpr()); 14669 if (SubResult.isInvalid()) return ExprError(); 14670 14671 Expr *SubExpr = SubResult.get(); 14672 E->setSubExpr(SubExpr); 14673 E->setType(S.Context.getPointerType(SubExpr->getType())); 14674 assert(E->getValueKind() == VK_RValue); 14675 assert(E->getObjectKind() == OK_Ordinary); 14676 return E; 14677 } 14678 14679 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 14680 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 14681 14682 E->setType(VD->getType()); 14683 14684 assert(E->getValueKind() == VK_RValue); 14685 if (S.getLangOpts().CPlusPlus && 14686 !(isa<CXXMethodDecl>(VD) && 14687 cast<CXXMethodDecl>(VD)->isInstance())) 14688 E->setValueKind(VK_LValue); 14689 14690 return E; 14691 } 14692 14693 ExprResult VisitMemberExpr(MemberExpr *E) { 14694 return resolveDecl(E, E->getMemberDecl()); 14695 } 14696 14697 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 14698 return resolveDecl(E, E->getDecl()); 14699 } 14700 }; 14701 } 14702 14703 /// Given a function expression of unknown-any type, try to rebuild it 14704 /// to have a function type. 14705 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 14706 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 14707 if (Result.isInvalid()) return ExprError(); 14708 return S.DefaultFunctionArrayConversion(Result.get()); 14709 } 14710 14711 namespace { 14712 /// A visitor for rebuilding an expression of type __unknown_anytype 14713 /// into one which resolves the type directly on the referring 14714 /// expression. Strict preservation of the original source 14715 /// structure is not a goal. 14716 struct RebuildUnknownAnyExpr 14717 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 14718 14719 Sema &S; 14720 14721 /// The current destination type. 14722 QualType DestType; 14723 14724 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 14725 : S(S), DestType(CastType) {} 14726 14727 ExprResult VisitStmt(Stmt *S) { 14728 llvm_unreachable("unexpected statement!"); 14729 } 14730 14731 ExprResult VisitExpr(Expr *E) { 14732 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 14733 << E->getSourceRange(); 14734 return ExprError(); 14735 } 14736 14737 ExprResult VisitCallExpr(CallExpr *E); 14738 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 14739 14740 /// Rebuild an expression which simply semantically wraps another 14741 /// expression which it shares the type and value kind of. 14742 template <class T> ExprResult rebuildSugarExpr(T *E) { 14743 ExprResult SubResult = Visit(E->getSubExpr()); 14744 if (SubResult.isInvalid()) return ExprError(); 14745 Expr *SubExpr = SubResult.get(); 14746 E->setSubExpr(SubExpr); 14747 E->setType(SubExpr->getType()); 14748 E->setValueKind(SubExpr->getValueKind()); 14749 assert(E->getObjectKind() == OK_Ordinary); 14750 return E; 14751 } 14752 14753 ExprResult VisitParenExpr(ParenExpr *E) { 14754 return rebuildSugarExpr(E); 14755 } 14756 14757 ExprResult VisitUnaryExtension(UnaryOperator *E) { 14758 return rebuildSugarExpr(E); 14759 } 14760 14761 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 14762 const PointerType *Ptr = DestType->getAs<PointerType>(); 14763 if (!Ptr) { 14764 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 14765 << E->getSourceRange(); 14766 return ExprError(); 14767 } 14768 assert(E->getValueKind() == VK_RValue); 14769 assert(E->getObjectKind() == OK_Ordinary); 14770 E->setType(DestType); 14771 14772 // Build the sub-expression as if it were an object of the pointee type. 14773 DestType = Ptr->getPointeeType(); 14774 ExprResult SubResult = Visit(E->getSubExpr()); 14775 if (SubResult.isInvalid()) return ExprError(); 14776 E->setSubExpr(SubResult.get()); 14777 return E; 14778 } 14779 14780 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 14781 14782 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 14783 14784 ExprResult VisitMemberExpr(MemberExpr *E) { 14785 return resolveDecl(E, E->getMemberDecl()); 14786 } 14787 14788 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 14789 return resolveDecl(E, E->getDecl()); 14790 } 14791 }; 14792 } 14793 14794 /// Rebuilds a call expression which yielded __unknown_anytype. 14795 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 14796 Expr *CalleeExpr = E->getCallee(); 14797 14798 enum FnKind { 14799 FK_MemberFunction, 14800 FK_FunctionPointer, 14801 FK_BlockPointer 14802 }; 14803 14804 FnKind Kind; 14805 QualType CalleeType = CalleeExpr->getType(); 14806 if (CalleeType == S.Context.BoundMemberTy) { 14807 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 14808 Kind = FK_MemberFunction; 14809 CalleeType = Expr::findBoundMemberType(CalleeExpr); 14810 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 14811 CalleeType = Ptr->getPointeeType(); 14812 Kind = FK_FunctionPointer; 14813 } else { 14814 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 14815 Kind = FK_BlockPointer; 14816 } 14817 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 14818 14819 // Verify that this is a legal result type of a function. 14820 if (DestType->isArrayType() || DestType->isFunctionType()) { 14821 unsigned diagID = diag::err_func_returning_array_function; 14822 if (Kind == FK_BlockPointer) 14823 diagID = diag::err_block_returning_array_function; 14824 14825 S.Diag(E->getExprLoc(), diagID) 14826 << DestType->isFunctionType() << DestType; 14827 return ExprError(); 14828 } 14829 14830 // Otherwise, go ahead and set DestType as the call's result. 14831 E->setType(DestType.getNonLValueExprType(S.Context)); 14832 E->setValueKind(Expr::getValueKindForType(DestType)); 14833 assert(E->getObjectKind() == OK_Ordinary); 14834 14835 // Rebuild the function type, replacing the result type with DestType. 14836 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 14837 if (Proto) { 14838 // __unknown_anytype(...) is a special case used by the debugger when 14839 // it has no idea what a function's signature is. 14840 // 14841 // We want to build this call essentially under the K&R 14842 // unprototyped rules, but making a FunctionNoProtoType in C++ 14843 // would foul up all sorts of assumptions. However, we cannot 14844 // simply pass all arguments as variadic arguments, nor can we 14845 // portably just call the function under a non-variadic type; see 14846 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 14847 // However, it turns out that in practice it is generally safe to 14848 // call a function declared as "A foo(B,C,D);" under the prototype 14849 // "A foo(B,C,D,...);". The only known exception is with the 14850 // Windows ABI, where any variadic function is implicitly cdecl 14851 // regardless of its normal CC. Therefore we change the parameter 14852 // types to match the types of the arguments. 14853 // 14854 // This is a hack, but it is far superior to moving the 14855 // corresponding target-specific code from IR-gen to Sema/AST. 14856 14857 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 14858 SmallVector<QualType, 8> ArgTypes; 14859 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 14860 ArgTypes.reserve(E->getNumArgs()); 14861 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 14862 Expr *Arg = E->getArg(i); 14863 QualType ArgType = Arg->getType(); 14864 if (E->isLValue()) { 14865 ArgType = S.Context.getLValueReferenceType(ArgType); 14866 } else if (E->isXValue()) { 14867 ArgType = S.Context.getRValueReferenceType(ArgType); 14868 } 14869 ArgTypes.push_back(ArgType); 14870 } 14871 ParamTypes = ArgTypes; 14872 } 14873 DestType = S.Context.getFunctionType(DestType, ParamTypes, 14874 Proto->getExtProtoInfo()); 14875 } else { 14876 DestType = S.Context.getFunctionNoProtoType(DestType, 14877 FnType->getExtInfo()); 14878 } 14879 14880 // Rebuild the appropriate pointer-to-function type. 14881 switch (Kind) { 14882 case FK_MemberFunction: 14883 // Nothing to do. 14884 break; 14885 14886 case FK_FunctionPointer: 14887 DestType = S.Context.getPointerType(DestType); 14888 break; 14889 14890 case FK_BlockPointer: 14891 DestType = S.Context.getBlockPointerType(DestType); 14892 break; 14893 } 14894 14895 // Finally, we can recurse. 14896 ExprResult CalleeResult = Visit(CalleeExpr); 14897 if (!CalleeResult.isUsable()) return ExprError(); 14898 E->setCallee(CalleeResult.get()); 14899 14900 // Bind a temporary if necessary. 14901 return S.MaybeBindToTemporary(E); 14902 } 14903 14904 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 14905 // Verify that this is a legal result type of a call. 14906 if (DestType->isArrayType() || DestType->isFunctionType()) { 14907 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 14908 << DestType->isFunctionType() << DestType; 14909 return ExprError(); 14910 } 14911 14912 // Rewrite the method result type if available. 14913 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 14914 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 14915 Method->setReturnType(DestType); 14916 } 14917 14918 // Change the type of the message. 14919 E->setType(DestType.getNonReferenceType()); 14920 E->setValueKind(Expr::getValueKindForType(DestType)); 14921 14922 return S.MaybeBindToTemporary(E); 14923 } 14924 14925 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 14926 // The only case we should ever see here is a function-to-pointer decay. 14927 if (E->getCastKind() == CK_FunctionToPointerDecay) { 14928 assert(E->getValueKind() == VK_RValue); 14929 assert(E->getObjectKind() == OK_Ordinary); 14930 14931 E->setType(DestType); 14932 14933 // Rebuild the sub-expression as the pointee (function) type. 14934 DestType = DestType->castAs<PointerType>()->getPointeeType(); 14935 14936 ExprResult Result = Visit(E->getSubExpr()); 14937 if (!Result.isUsable()) return ExprError(); 14938 14939 E->setSubExpr(Result.get()); 14940 return E; 14941 } else if (E->getCastKind() == CK_LValueToRValue) { 14942 assert(E->getValueKind() == VK_RValue); 14943 assert(E->getObjectKind() == OK_Ordinary); 14944 14945 assert(isa<BlockPointerType>(E->getType())); 14946 14947 E->setType(DestType); 14948 14949 // The sub-expression has to be a lvalue reference, so rebuild it as such. 14950 DestType = S.Context.getLValueReferenceType(DestType); 14951 14952 ExprResult Result = Visit(E->getSubExpr()); 14953 if (!Result.isUsable()) return ExprError(); 14954 14955 E->setSubExpr(Result.get()); 14956 return E; 14957 } else { 14958 llvm_unreachable("Unhandled cast type!"); 14959 } 14960 } 14961 14962 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 14963 ExprValueKind ValueKind = VK_LValue; 14964 QualType Type = DestType; 14965 14966 // We know how to make this work for certain kinds of decls: 14967 14968 // - functions 14969 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 14970 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 14971 DestType = Ptr->getPointeeType(); 14972 ExprResult Result = resolveDecl(E, VD); 14973 if (Result.isInvalid()) return ExprError(); 14974 return S.ImpCastExprToType(Result.get(), Type, 14975 CK_FunctionToPointerDecay, VK_RValue); 14976 } 14977 14978 if (!Type->isFunctionType()) { 14979 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 14980 << VD << E->getSourceRange(); 14981 return ExprError(); 14982 } 14983 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 14984 // We must match the FunctionDecl's type to the hack introduced in 14985 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 14986 // type. See the lengthy commentary in that routine. 14987 QualType FDT = FD->getType(); 14988 const FunctionType *FnType = FDT->castAs<FunctionType>(); 14989 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 14990 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 14991 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 14992 SourceLocation Loc = FD->getLocation(); 14993 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(), 14994 FD->getDeclContext(), 14995 Loc, Loc, FD->getNameInfo().getName(), 14996 DestType, FD->getTypeSourceInfo(), 14997 SC_None, false/*isInlineSpecified*/, 14998 FD->hasPrototype(), 14999 false/*isConstexprSpecified*/); 15000 15001 if (FD->getQualifier()) 15002 NewFD->setQualifierInfo(FD->getQualifierLoc()); 15003 15004 SmallVector<ParmVarDecl*, 16> Params; 15005 for (const auto &AI : FT->param_types()) { 15006 ParmVarDecl *Param = 15007 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 15008 Param->setScopeInfo(0, Params.size()); 15009 Params.push_back(Param); 15010 } 15011 NewFD->setParams(Params); 15012 DRE->setDecl(NewFD); 15013 VD = DRE->getDecl(); 15014 } 15015 } 15016 15017 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 15018 if (MD->isInstance()) { 15019 ValueKind = VK_RValue; 15020 Type = S.Context.BoundMemberTy; 15021 } 15022 15023 // Function references aren't l-values in C. 15024 if (!S.getLangOpts().CPlusPlus) 15025 ValueKind = VK_RValue; 15026 15027 // - variables 15028 } else if (isa<VarDecl>(VD)) { 15029 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 15030 Type = RefTy->getPointeeType(); 15031 } else if (Type->isFunctionType()) { 15032 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 15033 << VD << E->getSourceRange(); 15034 return ExprError(); 15035 } 15036 15037 // - nothing else 15038 } else { 15039 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 15040 << VD << E->getSourceRange(); 15041 return ExprError(); 15042 } 15043 15044 // Modifying the declaration like this is friendly to IR-gen but 15045 // also really dangerous. 15046 VD->setType(DestType); 15047 E->setType(Type); 15048 E->setValueKind(ValueKind); 15049 return E; 15050 } 15051 15052 /// Check a cast of an unknown-any type. We intentionally only 15053 /// trigger this for C-style casts. 15054 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 15055 Expr *CastExpr, CastKind &CastKind, 15056 ExprValueKind &VK, CXXCastPath &Path) { 15057 // The type we're casting to must be either void or complete. 15058 if (!CastType->isVoidType() && 15059 RequireCompleteType(TypeRange.getBegin(), CastType, 15060 diag::err_typecheck_cast_to_incomplete)) 15061 return ExprError(); 15062 15063 // Rewrite the casted expression from scratch. 15064 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 15065 if (!result.isUsable()) return ExprError(); 15066 15067 CastExpr = result.get(); 15068 VK = CastExpr->getValueKind(); 15069 CastKind = CK_NoOp; 15070 15071 return CastExpr; 15072 } 15073 15074 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 15075 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 15076 } 15077 15078 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 15079 Expr *arg, QualType ¶mType) { 15080 // If the syntactic form of the argument is not an explicit cast of 15081 // any sort, just do default argument promotion. 15082 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 15083 if (!castArg) { 15084 ExprResult result = DefaultArgumentPromotion(arg); 15085 if (result.isInvalid()) return ExprError(); 15086 paramType = result.get()->getType(); 15087 return result; 15088 } 15089 15090 // Otherwise, use the type that was written in the explicit cast. 15091 assert(!arg->hasPlaceholderType()); 15092 paramType = castArg->getTypeAsWritten(); 15093 15094 // Copy-initialize a parameter of that type. 15095 InitializedEntity entity = 15096 InitializedEntity::InitializeParameter(Context, paramType, 15097 /*consumed*/ false); 15098 return PerformCopyInitialization(entity, callLoc, arg); 15099 } 15100 15101 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 15102 Expr *orig = E; 15103 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 15104 while (true) { 15105 E = E->IgnoreParenImpCasts(); 15106 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 15107 E = call->getCallee(); 15108 diagID = diag::err_uncasted_call_of_unknown_any; 15109 } else { 15110 break; 15111 } 15112 } 15113 15114 SourceLocation loc; 15115 NamedDecl *d; 15116 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 15117 loc = ref->getLocation(); 15118 d = ref->getDecl(); 15119 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 15120 loc = mem->getMemberLoc(); 15121 d = mem->getMemberDecl(); 15122 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 15123 diagID = diag::err_uncasted_call_of_unknown_any; 15124 loc = msg->getSelectorStartLoc(); 15125 d = msg->getMethodDecl(); 15126 if (!d) { 15127 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 15128 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 15129 << orig->getSourceRange(); 15130 return ExprError(); 15131 } 15132 } else { 15133 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 15134 << E->getSourceRange(); 15135 return ExprError(); 15136 } 15137 15138 S.Diag(loc, diagID) << d << orig->getSourceRange(); 15139 15140 // Never recoverable. 15141 return ExprError(); 15142 } 15143 15144 /// Check for operands with placeholder types and complain if found. 15145 /// Returns true if there was an error and no recovery was possible. 15146 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 15147 if (!getLangOpts().CPlusPlus) { 15148 // C cannot handle TypoExpr nodes on either side of a binop because it 15149 // doesn't handle dependent types properly, so make sure any TypoExprs have 15150 // been dealt with before checking the operands. 15151 ExprResult Result = CorrectDelayedTyposInExpr(E); 15152 if (!Result.isUsable()) return ExprError(); 15153 E = Result.get(); 15154 } 15155 15156 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 15157 if (!placeholderType) return E; 15158 15159 switch (placeholderType->getKind()) { 15160 15161 // Overloaded expressions. 15162 case BuiltinType::Overload: { 15163 // Try to resolve a single function template specialization. 15164 // This is obligatory. 15165 ExprResult Result = E; 15166 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 15167 return Result; 15168 15169 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 15170 // leaves Result unchanged on failure. 15171 Result = E; 15172 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) 15173 return Result; 15174 15175 // If that failed, try to recover with a call. 15176 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 15177 /*complain*/ true); 15178 return Result; 15179 } 15180 15181 // Bound member functions. 15182 case BuiltinType::BoundMember: { 15183 ExprResult result = E; 15184 const Expr *BME = E->IgnoreParens(); 15185 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 15186 // Try to give a nicer diagnostic if it is a bound member that we recognize. 15187 if (isa<CXXPseudoDestructorExpr>(BME)) { 15188 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 15189 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 15190 if (ME->getMemberNameInfo().getName().getNameKind() == 15191 DeclarationName::CXXDestructorName) 15192 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 15193 } 15194 tryToRecoverWithCall(result, PD, 15195 /*complain*/ true); 15196 return result; 15197 } 15198 15199 // ARC unbridged casts. 15200 case BuiltinType::ARCUnbridgedCast: { 15201 Expr *realCast = stripARCUnbridgedCast(E); 15202 diagnoseARCUnbridgedCast(realCast); 15203 return realCast; 15204 } 15205 15206 // Expressions of unknown type. 15207 case BuiltinType::UnknownAny: 15208 return diagnoseUnknownAnyExpr(*this, E); 15209 15210 // Pseudo-objects. 15211 case BuiltinType::PseudoObject: 15212 return checkPseudoObjectRValue(E); 15213 15214 case BuiltinType::BuiltinFn: { 15215 // Accept __noop without parens by implicitly converting it to a call expr. 15216 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 15217 if (DRE) { 15218 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 15219 if (FD->getBuiltinID() == Builtin::BI__noop) { 15220 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 15221 CK_BuiltinFnToFnPtr).get(); 15222 return new (Context) CallExpr(Context, E, None, Context.IntTy, 15223 VK_RValue, SourceLocation()); 15224 } 15225 } 15226 15227 Diag(E->getLocStart(), diag::err_builtin_fn_use); 15228 return ExprError(); 15229 } 15230 15231 // Expressions of unknown type. 15232 case BuiltinType::OMPArraySection: 15233 Diag(E->getLocStart(), diag::err_omp_array_section_use); 15234 return ExprError(); 15235 15236 // Everything else should be impossible. 15237 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 15238 case BuiltinType::Id: 15239 #include "clang/Basic/OpenCLImageTypes.def" 15240 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 15241 #define PLACEHOLDER_TYPE(Id, SingletonId) 15242 #include "clang/AST/BuiltinTypes.def" 15243 break; 15244 } 15245 15246 llvm_unreachable("invalid placeholder type!"); 15247 } 15248 15249 bool Sema::CheckCaseExpression(Expr *E) { 15250 if (E->isTypeDependent()) 15251 return true; 15252 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 15253 return E->getType()->isIntegralOrEnumerationType(); 15254 return false; 15255 } 15256 15257 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 15258 ExprResult 15259 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 15260 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 15261 "Unknown Objective-C Boolean value!"); 15262 QualType BoolT = Context.ObjCBuiltinBoolTy; 15263 if (!Context.getBOOLDecl()) { 15264 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 15265 Sema::LookupOrdinaryName); 15266 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 15267 NamedDecl *ND = Result.getFoundDecl(); 15268 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 15269 Context.setBOOLDecl(TD); 15270 } 15271 } 15272 if (Context.getBOOLDecl()) 15273 BoolT = Context.getBOOLType(); 15274 return new (Context) 15275 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 15276 } 15277 15278 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 15279 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 15280 SourceLocation RParen) { 15281 15282 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 15283 15284 auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(), 15285 [&](const AvailabilitySpec &Spec) { 15286 return Spec.getPlatform() == Platform; 15287 }); 15288 15289 VersionTuple Version; 15290 if (Spec != AvailSpecs.end()) 15291 Version = Spec->getVersion(); 15292 15293 return new (Context) 15294 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 15295 } 15296