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) { 175 if (S.getCurFunctionOrMethodDecl()) { 176 S.getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 177 return; 178 } else if (S.getCurBlock() || S.getCurLambda()) { 179 S.getCurFunction()->HasPotentialAvailabilityViolations = true; 180 return; 181 } 182 } 183 184 const ObjCPropertyDecl *ObjCPDecl = nullptr; 185 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 186 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) { 187 AvailabilityResult PDeclResult = PD->getAvailability(nullptr); 188 if (PDeclResult == Result) 189 ObjCPDecl = PD; 190 } 191 } 192 193 S.EmitAvailabilityWarning(Result, D, Message, Loc, UnknownObjCClass, 194 ObjCPDecl, ObjCPropertyAccess); 195 } 196 } 197 198 /// \brief Emit a note explaining that this function is deleted. 199 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 200 assert(Decl->isDeleted()); 201 202 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 203 204 if (Method && Method->isDeleted() && Method->isDefaulted()) { 205 // If the method was explicitly defaulted, point at that declaration. 206 if (!Method->isImplicit()) 207 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 208 209 // Try to diagnose why this special member function was implicitly 210 // deleted. This might fail, if that reason no longer applies. 211 CXXSpecialMember CSM = getSpecialMember(Method); 212 if (CSM != CXXInvalid) 213 ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true); 214 215 return; 216 } 217 218 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 219 if (Ctor && Ctor->isInheritingConstructor()) 220 return NoteDeletedInheritingConstructor(Ctor); 221 222 Diag(Decl->getLocation(), diag::note_availability_specified_here) 223 << Decl << true; 224 } 225 226 /// \brief Determine whether a FunctionDecl was ever declared with an 227 /// explicit storage class. 228 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 229 for (auto I : D->redecls()) { 230 if (I->getStorageClass() != SC_None) 231 return true; 232 } 233 return false; 234 } 235 236 /// \brief Check whether we're in an extern inline function and referring to a 237 /// variable or function with internal linkage (C11 6.7.4p3). 238 /// 239 /// This is only a warning because we used to silently accept this code, but 240 /// in many cases it will not behave correctly. This is not enabled in C++ mode 241 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 242 /// and so while there may still be user mistakes, most of the time we can't 243 /// prove that there are errors. 244 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 245 const NamedDecl *D, 246 SourceLocation Loc) { 247 // This is disabled under C++; there are too many ways for this to fire in 248 // contexts where the warning is a false positive, or where it is technically 249 // correct but benign. 250 if (S.getLangOpts().CPlusPlus) 251 return; 252 253 // Check if this is an inlined function or method. 254 FunctionDecl *Current = S.getCurFunctionDecl(); 255 if (!Current) 256 return; 257 if (!Current->isInlined()) 258 return; 259 if (!Current->isExternallyVisible()) 260 return; 261 262 // Check if the decl has internal linkage. 263 if (D->getFormalLinkage() != InternalLinkage) 264 return; 265 266 // Downgrade from ExtWarn to Extension if 267 // (1) the supposedly external inline function is in the main file, 268 // and probably won't be included anywhere else. 269 // (2) the thing we're referencing is a pure function. 270 // (3) the thing we're referencing is another inline function. 271 // This last can give us false negatives, but it's better than warning on 272 // wrappers for simple C library functions. 273 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 274 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 275 if (!DowngradeWarning && UsedFn) 276 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 277 278 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 279 : diag::ext_internal_in_extern_inline) 280 << /*IsVar=*/!UsedFn << D; 281 282 S.MaybeSuggestAddingStaticToDecl(Current); 283 284 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 285 << D; 286 } 287 288 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 289 const FunctionDecl *First = Cur->getFirstDecl(); 290 291 // Suggest "static" on the function, if possible. 292 if (!hasAnyExplicitStorageClass(First)) { 293 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 294 Diag(DeclBegin, diag::note_convert_inline_to_static) 295 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 296 } 297 } 298 299 /// \brief Determine whether the use of this declaration is valid, and 300 /// emit any corresponding diagnostics. 301 /// 302 /// This routine diagnoses various problems with referencing 303 /// declarations that can occur when using a declaration. For example, 304 /// it might warn if a deprecated or unavailable declaration is being 305 /// used, or produce an error (and return true) if a C++0x deleted 306 /// function is being used. 307 /// 308 /// \returns true if there was an error (this declaration cannot be 309 /// referenced), false otherwise. 310 /// 311 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 312 const ObjCInterfaceDecl *UnknownObjCClass, 313 bool ObjCPropertyAccess) { 314 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 315 // If there were any diagnostics suppressed by template argument deduction, 316 // emit them now. 317 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 318 if (Pos != SuppressedDiagnostics.end()) { 319 for (const PartialDiagnosticAt &Suppressed : Pos->second) 320 Diag(Suppressed.first, Suppressed.second); 321 322 // Clear out the list of suppressed diagnostics, so that we don't emit 323 // them again for this specialization. However, we don't obsolete this 324 // entry from the table, because we want to avoid ever emitting these 325 // diagnostics again. 326 Pos->second.clear(); 327 } 328 329 // C++ [basic.start.main]p3: 330 // The function 'main' shall not be used within a program. 331 if (cast<FunctionDecl>(D)->isMain()) 332 Diag(Loc, diag::ext_main_used); 333 } 334 335 // See if this is an auto-typed variable whose initializer we are parsing. 336 if (ParsingInitForAutoVars.count(D)) { 337 if (isa<BindingDecl>(D)) { 338 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 339 << D->getDeclName(); 340 } else { 341 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 342 << D->getDeclName() << cast<VarDecl>(D)->getType(); 343 } 344 return true; 345 } 346 347 // See if this is a deleted function. 348 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 349 if (FD->isDeleted()) { 350 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 351 if (Ctor && Ctor->isInheritingConstructor()) 352 Diag(Loc, diag::err_deleted_inherited_ctor_use) 353 << Ctor->getParent() 354 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 355 else 356 Diag(Loc, diag::err_deleted_function_use); 357 NoteDeletedFunction(FD); 358 return true; 359 } 360 361 // If the function has a deduced return type, and we can't deduce it, 362 // then we can't use it either. 363 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 364 DeduceReturnType(FD, Loc)) 365 return true; 366 367 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 368 return true; 369 370 if (diagnoseArgIndependentDiagnoseIfAttrs(FD, Loc)) 371 return true; 372 } 373 374 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 375 // Only the variables omp_in and omp_out are allowed in the combiner. 376 // Only the variables omp_priv and omp_orig are allowed in the 377 // initializer-clause. 378 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 379 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 380 isa<VarDecl>(D)) { 381 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 382 << getCurFunction()->HasOMPDeclareReductionCombiner; 383 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 384 return true; 385 } 386 387 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass, 388 ObjCPropertyAccess); 389 390 DiagnoseUnusedOfDecl(*this, D, Loc); 391 392 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 393 394 return false; 395 } 396 397 /// \brief Retrieve the message suffix that should be added to a 398 /// diagnostic complaining about the given function being deleted or 399 /// unavailable. 400 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 401 std::string Message; 402 if (FD->getAvailability(&Message)) 403 return ": " + Message; 404 405 return std::string(); 406 } 407 408 /// DiagnoseSentinelCalls - This routine checks whether a call or 409 /// message-send is to a declaration with the sentinel attribute, and 410 /// if so, it checks that the requirements of the sentinel are 411 /// satisfied. 412 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 413 ArrayRef<Expr *> Args) { 414 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 415 if (!attr) 416 return; 417 418 // The number of formal parameters of the declaration. 419 unsigned numFormalParams; 420 421 // The kind of declaration. This is also an index into a %select in 422 // the diagnostic. 423 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 424 425 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 426 numFormalParams = MD->param_size(); 427 calleeType = CT_Method; 428 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 429 numFormalParams = FD->param_size(); 430 calleeType = CT_Function; 431 } else if (isa<VarDecl>(D)) { 432 QualType type = cast<ValueDecl>(D)->getType(); 433 const FunctionType *fn = nullptr; 434 if (const PointerType *ptr = type->getAs<PointerType>()) { 435 fn = ptr->getPointeeType()->getAs<FunctionType>(); 436 if (!fn) return; 437 calleeType = CT_Function; 438 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 439 fn = ptr->getPointeeType()->castAs<FunctionType>(); 440 calleeType = CT_Block; 441 } else { 442 return; 443 } 444 445 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 446 numFormalParams = proto->getNumParams(); 447 } else { 448 numFormalParams = 0; 449 } 450 } else { 451 return; 452 } 453 454 // "nullPos" is the number of formal parameters at the end which 455 // effectively count as part of the variadic arguments. This is 456 // useful if you would prefer to not have *any* formal parameters, 457 // but the language forces you to have at least one. 458 unsigned nullPos = attr->getNullPos(); 459 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 460 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 461 462 // The number of arguments which should follow the sentinel. 463 unsigned numArgsAfterSentinel = attr->getSentinel(); 464 465 // If there aren't enough arguments for all the formal parameters, 466 // the sentinel, and the args after the sentinel, complain. 467 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 468 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 469 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 470 return; 471 } 472 473 // Otherwise, find the sentinel expression. 474 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 475 if (!sentinelExpr) return; 476 if (sentinelExpr->isValueDependent()) return; 477 if (Context.isSentinelNullExpr(sentinelExpr)) return; 478 479 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 480 // or 'NULL' if those are actually defined in the context. Only use 481 // 'nil' for ObjC methods, where it's much more likely that the 482 // variadic arguments form a list of object pointers. 483 SourceLocation MissingNilLoc 484 = getLocForEndOfToken(sentinelExpr->getLocEnd()); 485 std::string NullValue; 486 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 487 NullValue = "nil"; 488 else if (getLangOpts().CPlusPlus11) 489 NullValue = "nullptr"; 490 else if (PP.isMacroDefined("NULL")) 491 NullValue = "NULL"; 492 else 493 NullValue = "(void*) 0"; 494 495 if (MissingNilLoc.isInvalid()) 496 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 497 else 498 Diag(MissingNilLoc, diag::warn_missing_sentinel) 499 << int(calleeType) 500 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 501 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 502 } 503 504 SourceRange Sema::getExprRange(Expr *E) const { 505 return E ? E->getSourceRange() : SourceRange(); 506 } 507 508 //===----------------------------------------------------------------------===// 509 // Standard Promotions and Conversions 510 //===----------------------------------------------------------------------===// 511 512 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 513 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 514 // Handle any placeholder expressions which made it here. 515 if (E->getType()->isPlaceholderType()) { 516 ExprResult result = CheckPlaceholderExpr(E); 517 if (result.isInvalid()) return ExprError(); 518 E = result.get(); 519 } 520 521 QualType Ty = E->getType(); 522 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 523 524 if (Ty->isFunctionType()) { 525 // If we are here, we are not calling a function but taking 526 // its address (which is not allowed in OpenCL v1.0 s6.8.a.3). 527 if (getLangOpts().OpenCL) { 528 if (Diagnose) 529 Diag(E->getExprLoc(), diag::err_opencl_taking_function_address); 530 return ExprError(); 531 } 532 533 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 534 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 535 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 536 return ExprError(); 537 538 E = ImpCastExprToType(E, Context.getPointerType(Ty), 539 CK_FunctionToPointerDecay).get(); 540 } else if (Ty->isArrayType()) { 541 // In C90 mode, arrays only promote to pointers if the array expression is 542 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 543 // type 'array of type' is converted to an expression that has type 'pointer 544 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 545 // that has type 'array of type' ...". The relevant change is "an lvalue" 546 // (C90) to "an expression" (C99). 547 // 548 // C++ 4.2p1: 549 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 550 // T" can be converted to an rvalue of type "pointer to T". 551 // 552 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 553 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 554 CK_ArrayToPointerDecay).get(); 555 } 556 return E; 557 } 558 559 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 560 // Check to see if we are dereferencing a null pointer. If so, 561 // and if not volatile-qualified, this is undefined behavior that the 562 // optimizer will delete, so warn about it. People sometimes try to use this 563 // to get a deterministic trap and are surprised by clang's behavior. This 564 // only handles the pattern "*null", which is a very syntactic check. 565 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 566 if (UO->getOpcode() == UO_Deref && 567 UO->getSubExpr()->IgnoreParenCasts()-> 568 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 569 !UO->getType().isVolatileQualified()) { 570 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 571 S.PDiag(diag::warn_indirection_through_null) 572 << UO->getSubExpr()->getSourceRange()); 573 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 574 S.PDiag(diag::note_indirection_through_null)); 575 } 576 } 577 578 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 579 SourceLocation AssignLoc, 580 const Expr* RHS) { 581 const ObjCIvarDecl *IV = OIRE->getDecl(); 582 if (!IV) 583 return; 584 585 DeclarationName MemberName = IV->getDeclName(); 586 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 587 if (!Member || !Member->isStr("isa")) 588 return; 589 590 const Expr *Base = OIRE->getBase(); 591 QualType BaseType = Base->getType(); 592 if (OIRE->isArrow()) 593 BaseType = BaseType->getPointeeType(); 594 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 595 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 596 ObjCInterfaceDecl *ClassDeclared = nullptr; 597 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 598 if (!ClassDeclared->getSuperClass() 599 && (*ClassDeclared->ivar_begin()) == IV) { 600 if (RHS) { 601 NamedDecl *ObjectSetClass = 602 S.LookupSingleName(S.TUScope, 603 &S.Context.Idents.get("object_setClass"), 604 SourceLocation(), S.LookupOrdinaryName); 605 if (ObjectSetClass) { 606 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd()); 607 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 608 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 609 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 610 AssignLoc), ",") << 611 FixItHint::CreateInsertion(RHSLocEnd, ")"); 612 } 613 else 614 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 615 } else { 616 NamedDecl *ObjectGetClass = 617 S.LookupSingleName(S.TUScope, 618 &S.Context.Idents.get("object_getClass"), 619 SourceLocation(), S.LookupOrdinaryName); 620 if (ObjectGetClass) 621 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 622 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 623 FixItHint::CreateReplacement( 624 SourceRange(OIRE->getOpLoc(), 625 OIRE->getLocEnd()), ")"); 626 else 627 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 628 } 629 S.Diag(IV->getLocation(), diag::note_ivar_decl); 630 } 631 } 632 } 633 634 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 635 // Handle any placeholder expressions which made it here. 636 if (E->getType()->isPlaceholderType()) { 637 ExprResult result = CheckPlaceholderExpr(E); 638 if (result.isInvalid()) return ExprError(); 639 E = result.get(); 640 } 641 642 // C++ [conv.lval]p1: 643 // A glvalue of a non-function, non-array type T can be 644 // converted to a prvalue. 645 if (!E->isGLValue()) return E; 646 647 QualType T = E->getType(); 648 assert(!T.isNull() && "r-value conversion on typeless expression?"); 649 650 // We don't want to throw lvalue-to-rvalue casts on top of 651 // expressions of certain types in C++. 652 if (getLangOpts().CPlusPlus && 653 (E->getType() == Context.OverloadTy || 654 T->isDependentType() || 655 T->isRecordType())) 656 return E; 657 658 // The C standard is actually really unclear on this point, and 659 // DR106 tells us what the result should be but not why. It's 660 // generally best to say that void types just doesn't undergo 661 // lvalue-to-rvalue at all. Note that expressions of unqualified 662 // 'void' type are never l-values, but qualified void can be. 663 if (T->isVoidType()) 664 return E; 665 666 // OpenCL usually rejects direct accesses to values of 'half' type. 667 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 668 T->isHalfType()) { 669 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 670 << 0 << T; 671 return ExprError(); 672 } 673 674 CheckForNullPointerDereference(*this, E); 675 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 676 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 677 &Context.Idents.get("object_getClass"), 678 SourceLocation(), LookupOrdinaryName); 679 if (ObjectGetClass) 680 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 681 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 682 FixItHint::CreateReplacement( 683 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 684 else 685 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 686 } 687 else if (const ObjCIvarRefExpr *OIRE = 688 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 689 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 690 691 // C++ [conv.lval]p1: 692 // [...] If T is a non-class type, the type of the prvalue is the 693 // cv-unqualified version of T. Otherwise, the type of the 694 // rvalue is T. 695 // 696 // C99 6.3.2.1p2: 697 // If the lvalue has qualified type, the value has the unqualified 698 // version of the type of the lvalue; otherwise, the value has the 699 // type of the lvalue. 700 if (T.hasQualifiers()) 701 T = T.getUnqualifiedType(); 702 703 // Under the MS ABI, lock down the inheritance model now. 704 if (T->isMemberPointerType() && 705 Context.getTargetInfo().getCXXABI().isMicrosoft()) 706 (void)isCompleteType(E->getExprLoc(), T); 707 708 UpdateMarkingForLValueToRValue(E); 709 710 // Loading a __weak object implicitly retains the value, so we need a cleanup to 711 // balance that. 712 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 713 Cleanup.setExprNeedsCleanups(true); 714 715 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 716 nullptr, VK_RValue); 717 718 // C11 6.3.2.1p2: 719 // ... if the lvalue has atomic type, the value has the non-atomic version 720 // of the type of the lvalue ... 721 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 722 T = Atomic->getValueType().getUnqualifiedType(); 723 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 724 nullptr, VK_RValue); 725 } 726 727 return Res; 728 } 729 730 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 731 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 732 if (Res.isInvalid()) 733 return ExprError(); 734 Res = DefaultLvalueConversion(Res.get()); 735 if (Res.isInvalid()) 736 return ExprError(); 737 return Res; 738 } 739 740 /// CallExprUnaryConversions - a special case of an unary conversion 741 /// performed on a function designator of a call expression. 742 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 743 QualType Ty = E->getType(); 744 ExprResult Res = E; 745 // Only do implicit cast for a function type, but not for a pointer 746 // to function type. 747 if (Ty->isFunctionType()) { 748 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 749 CK_FunctionToPointerDecay).get(); 750 if (Res.isInvalid()) 751 return ExprError(); 752 } 753 Res = DefaultLvalueConversion(Res.get()); 754 if (Res.isInvalid()) 755 return ExprError(); 756 return Res.get(); 757 } 758 759 /// UsualUnaryConversions - Performs various conversions that are common to most 760 /// operators (C99 6.3). The conversions of array and function types are 761 /// sometimes suppressed. For example, the array->pointer conversion doesn't 762 /// apply if the array is an argument to the sizeof or address (&) operators. 763 /// In these instances, this routine should *not* be called. 764 ExprResult Sema::UsualUnaryConversions(Expr *E) { 765 // First, convert to an r-value. 766 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 767 if (Res.isInvalid()) 768 return ExprError(); 769 E = Res.get(); 770 771 QualType Ty = E->getType(); 772 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 773 774 // Half FP have to be promoted to float unless it is natively supported 775 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 776 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 777 778 // Try to perform integral promotions if the object has a theoretically 779 // promotable type. 780 if (Ty->isIntegralOrUnscopedEnumerationType()) { 781 // C99 6.3.1.1p2: 782 // 783 // The following may be used in an expression wherever an int or 784 // unsigned int may be used: 785 // - an object or expression with an integer type whose integer 786 // conversion rank is less than or equal to the rank of int 787 // and unsigned int. 788 // - A bit-field of type _Bool, int, signed int, or unsigned int. 789 // 790 // If an int can represent all values of the original type, the 791 // value is converted to an int; otherwise, it is converted to an 792 // unsigned int. These are called the integer promotions. All 793 // other types are unchanged by the integer promotions. 794 795 QualType PTy = Context.isPromotableBitField(E); 796 if (!PTy.isNull()) { 797 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 798 return E; 799 } 800 if (Ty->isPromotableIntegerType()) { 801 QualType PT = Context.getPromotedIntegerType(Ty); 802 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 803 return E; 804 } 805 } 806 return E; 807 } 808 809 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 810 /// do not have a prototype. Arguments that have type float or __fp16 811 /// are promoted to double. All other argument types are converted by 812 /// UsualUnaryConversions(). 813 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 814 QualType Ty = E->getType(); 815 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 816 817 ExprResult Res = UsualUnaryConversions(E); 818 if (Res.isInvalid()) 819 return ExprError(); 820 E = Res.get(); 821 822 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to 823 // double. 824 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 825 if (BTy && (BTy->getKind() == BuiltinType::Half || 826 BTy->getKind() == BuiltinType::Float)) { 827 if (getLangOpts().OpenCL && 828 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 829 if (BTy->getKind() == BuiltinType::Half) { 830 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 831 } 832 } else { 833 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 834 } 835 } 836 837 // C++ performs lvalue-to-rvalue conversion as a default argument 838 // promotion, even on class types, but note: 839 // C++11 [conv.lval]p2: 840 // When an lvalue-to-rvalue conversion occurs in an unevaluated 841 // operand or a subexpression thereof the value contained in the 842 // referenced object is not accessed. Otherwise, if the glvalue 843 // has a class type, the conversion copy-initializes a temporary 844 // of type T from the glvalue and the result of the conversion 845 // is a prvalue for the temporary. 846 // FIXME: add some way to gate this entire thing for correctness in 847 // potentially potentially evaluated contexts. 848 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 849 ExprResult Temp = PerformCopyInitialization( 850 InitializedEntity::InitializeTemporary(E->getType()), 851 E->getExprLoc(), E); 852 if (Temp.isInvalid()) 853 return ExprError(); 854 E = Temp.get(); 855 } 856 857 return E; 858 } 859 860 /// Determine the degree of POD-ness for an expression. 861 /// Incomplete types are considered POD, since this check can be performed 862 /// when we're in an unevaluated context. 863 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 864 if (Ty->isIncompleteType()) { 865 // C++11 [expr.call]p7: 866 // After these conversions, if the argument does not have arithmetic, 867 // enumeration, pointer, pointer to member, or class type, the program 868 // is ill-formed. 869 // 870 // Since we've already performed array-to-pointer and function-to-pointer 871 // decay, the only such type in C++ is cv void. This also handles 872 // initializer lists as variadic arguments. 873 if (Ty->isVoidType()) 874 return VAK_Invalid; 875 876 if (Ty->isObjCObjectType()) 877 return VAK_Invalid; 878 return VAK_Valid; 879 } 880 881 if (Ty.isCXX98PODType(Context)) 882 return VAK_Valid; 883 884 // C++11 [expr.call]p7: 885 // Passing a potentially-evaluated argument of class type (Clause 9) 886 // having a non-trivial copy constructor, a non-trivial move constructor, 887 // or a non-trivial destructor, with no corresponding parameter, 888 // is conditionally-supported with implementation-defined semantics. 889 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 890 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 891 if (!Record->hasNonTrivialCopyConstructor() && 892 !Record->hasNonTrivialMoveConstructor() && 893 !Record->hasNonTrivialDestructor()) 894 return VAK_ValidInCXX11; 895 896 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 897 return VAK_Valid; 898 899 if (Ty->isObjCObjectType()) 900 return VAK_Invalid; 901 902 if (getLangOpts().MSVCCompat) 903 return VAK_MSVCUndefined; 904 905 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 906 // permitted to reject them. We should consider doing so. 907 return VAK_Undefined; 908 } 909 910 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 911 // Don't allow one to pass an Objective-C interface to a vararg. 912 const QualType &Ty = E->getType(); 913 VarArgKind VAK = isValidVarArgType(Ty); 914 915 // Complain about passing non-POD types through varargs. 916 switch (VAK) { 917 case VAK_ValidInCXX11: 918 DiagRuntimeBehavior( 919 E->getLocStart(), nullptr, 920 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 921 << Ty << CT); 922 // Fall through. 923 case VAK_Valid: 924 if (Ty->isRecordType()) { 925 // This is unlikely to be what the user intended. If the class has a 926 // 'c_str' member function, the user probably meant to call that. 927 DiagRuntimeBehavior(E->getLocStart(), nullptr, 928 PDiag(diag::warn_pass_class_arg_to_vararg) 929 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 930 } 931 break; 932 933 case VAK_Undefined: 934 case VAK_MSVCUndefined: 935 DiagRuntimeBehavior( 936 E->getLocStart(), nullptr, 937 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 938 << getLangOpts().CPlusPlus11 << Ty << CT); 939 break; 940 941 case VAK_Invalid: 942 if (Ty->isObjCObjectType()) 943 DiagRuntimeBehavior( 944 E->getLocStart(), nullptr, 945 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 946 << Ty << CT); 947 else 948 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg) 949 << isa<InitListExpr>(E) << Ty << CT; 950 break; 951 } 952 } 953 954 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 955 /// will create a trap if the resulting type is not a POD type. 956 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 957 FunctionDecl *FDecl) { 958 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 959 // Strip the unbridged-cast placeholder expression off, if applicable. 960 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 961 (CT == VariadicMethod || 962 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 963 E = stripARCUnbridgedCast(E); 964 965 // Otherwise, do normal placeholder checking. 966 } else { 967 ExprResult ExprRes = CheckPlaceholderExpr(E); 968 if (ExprRes.isInvalid()) 969 return ExprError(); 970 E = ExprRes.get(); 971 } 972 } 973 974 ExprResult ExprRes = DefaultArgumentPromotion(E); 975 if (ExprRes.isInvalid()) 976 return ExprError(); 977 E = ExprRes.get(); 978 979 // Diagnostics regarding non-POD argument types are 980 // emitted along with format string checking in Sema::CheckFunctionCall(). 981 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 982 // Turn this into a trap. 983 CXXScopeSpec SS; 984 SourceLocation TemplateKWLoc; 985 UnqualifiedId Name; 986 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 987 E->getLocStart()); 988 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 989 Name, true, false); 990 if (TrapFn.isInvalid()) 991 return ExprError(); 992 993 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 994 E->getLocStart(), None, 995 E->getLocEnd()); 996 if (Call.isInvalid()) 997 return ExprError(); 998 999 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 1000 Call.get(), E); 1001 if (Comma.isInvalid()) 1002 return ExprError(); 1003 return Comma.get(); 1004 } 1005 1006 if (!getLangOpts().CPlusPlus && 1007 RequireCompleteType(E->getExprLoc(), E->getType(), 1008 diag::err_call_incomplete_argument)) 1009 return ExprError(); 1010 1011 return E; 1012 } 1013 1014 /// \brief Converts an integer to complex float type. Helper function of 1015 /// UsualArithmeticConversions() 1016 /// 1017 /// \return false if the integer expression is an integer type and is 1018 /// successfully converted to the complex type. 1019 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1020 ExprResult &ComplexExpr, 1021 QualType IntTy, 1022 QualType ComplexTy, 1023 bool SkipCast) { 1024 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1025 if (SkipCast) return false; 1026 if (IntTy->isIntegerType()) { 1027 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1028 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1029 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1030 CK_FloatingRealToComplex); 1031 } else { 1032 assert(IntTy->isComplexIntegerType()); 1033 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1034 CK_IntegralComplexToFloatingComplex); 1035 } 1036 return false; 1037 } 1038 1039 /// \brief Handle arithmetic conversion with complex types. Helper function of 1040 /// UsualArithmeticConversions() 1041 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1042 ExprResult &RHS, QualType LHSType, 1043 QualType RHSType, 1044 bool IsCompAssign) { 1045 // if we have an integer operand, the result is the complex type. 1046 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1047 /*skipCast*/false)) 1048 return LHSType; 1049 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1050 /*skipCast*/IsCompAssign)) 1051 return RHSType; 1052 1053 // This handles complex/complex, complex/float, or float/complex. 1054 // When both operands are complex, the shorter operand is converted to the 1055 // type of the longer, and that is the type of the result. This corresponds 1056 // to what is done when combining two real floating-point operands. 1057 // The fun begins when size promotion occur across type domains. 1058 // From H&S 6.3.4: When one operand is complex and the other is a real 1059 // floating-point type, the less precise type is converted, within it's 1060 // real or complex domain, to the precision of the other type. For example, 1061 // when combining a "long double" with a "double _Complex", the 1062 // "double _Complex" is promoted to "long double _Complex". 1063 1064 // Compute the rank of the two types, regardless of whether they are complex. 1065 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1066 1067 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1068 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1069 QualType LHSElementType = 1070 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1071 QualType RHSElementType = 1072 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1073 1074 QualType ResultType = S.Context.getComplexType(LHSElementType); 1075 if (Order < 0) { 1076 // Promote the precision of the LHS if not an assignment. 1077 ResultType = S.Context.getComplexType(RHSElementType); 1078 if (!IsCompAssign) { 1079 if (LHSComplexType) 1080 LHS = 1081 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1082 else 1083 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1084 } 1085 } else if (Order > 0) { 1086 // Promote the precision of the RHS. 1087 if (RHSComplexType) 1088 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1089 else 1090 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1091 } 1092 return ResultType; 1093 } 1094 1095 /// \brief Hande arithmetic conversion from integer to float. Helper function 1096 /// of UsualArithmeticConversions() 1097 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1098 ExprResult &IntExpr, 1099 QualType FloatTy, QualType IntTy, 1100 bool ConvertFloat, bool ConvertInt) { 1101 if (IntTy->isIntegerType()) { 1102 if (ConvertInt) 1103 // Convert intExpr to the lhs floating point type. 1104 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1105 CK_IntegralToFloating); 1106 return FloatTy; 1107 } 1108 1109 // Convert both sides to the appropriate complex float. 1110 assert(IntTy->isComplexIntegerType()); 1111 QualType result = S.Context.getComplexType(FloatTy); 1112 1113 // _Complex int -> _Complex float 1114 if (ConvertInt) 1115 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1116 CK_IntegralComplexToFloatingComplex); 1117 1118 // float -> _Complex float 1119 if (ConvertFloat) 1120 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1121 CK_FloatingRealToComplex); 1122 1123 return result; 1124 } 1125 1126 /// \brief Handle arithmethic conversion with floating point types. Helper 1127 /// function of UsualArithmeticConversions() 1128 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1129 ExprResult &RHS, QualType LHSType, 1130 QualType RHSType, bool IsCompAssign) { 1131 bool LHSFloat = LHSType->isRealFloatingType(); 1132 bool RHSFloat = RHSType->isRealFloatingType(); 1133 1134 // If we have two real floating types, convert the smaller operand 1135 // to the bigger result. 1136 if (LHSFloat && RHSFloat) { 1137 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1138 if (order > 0) { 1139 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1140 return LHSType; 1141 } 1142 1143 assert(order < 0 && "illegal float comparison"); 1144 if (!IsCompAssign) 1145 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1146 return RHSType; 1147 } 1148 1149 if (LHSFloat) { 1150 // Half FP has to be promoted to float unless it is natively supported 1151 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1152 LHSType = S.Context.FloatTy; 1153 1154 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1155 /*convertFloat=*/!IsCompAssign, 1156 /*convertInt=*/ true); 1157 } 1158 assert(RHSFloat); 1159 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1160 /*convertInt=*/ true, 1161 /*convertFloat=*/!IsCompAssign); 1162 } 1163 1164 /// \brief Diagnose attempts to convert between __float128 and long double if 1165 /// there is no support for such conversion. Helper function of 1166 /// UsualArithmeticConversions(). 1167 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1168 QualType RHSType) { 1169 /* No issue converting if at least one of the types is not a floating point 1170 type or the two types have the same rank. 1171 */ 1172 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1173 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1174 return false; 1175 1176 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1177 "The remaining types must be floating point types."); 1178 1179 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1180 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1181 1182 QualType LHSElemType = LHSComplex ? 1183 LHSComplex->getElementType() : LHSType; 1184 QualType RHSElemType = RHSComplex ? 1185 RHSComplex->getElementType() : RHSType; 1186 1187 // No issue if the two types have the same representation 1188 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1189 &S.Context.getFloatTypeSemantics(RHSElemType)) 1190 return false; 1191 1192 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1193 RHSElemType == S.Context.LongDoubleTy); 1194 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1195 RHSElemType == S.Context.Float128Ty); 1196 1197 /* We've handled the situation where __float128 and long double have the same 1198 representation. The only other allowable conversion is if long double is 1199 really just double. 1200 */ 1201 return Float128AndLongDouble && 1202 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) != 1203 &llvm::APFloat::IEEEdouble()); 1204 } 1205 1206 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1207 1208 namespace { 1209 /// These helper callbacks are placed in an anonymous namespace to 1210 /// permit their use as function template parameters. 1211 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1212 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1213 } 1214 1215 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1216 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1217 CK_IntegralComplexCast); 1218 } 1219 } 1220 1221 /// \brief Handle integer arithmetic conversions. Helper function of 1222 /// UsualArithmeticConversions() 1223 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1224 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1225 ExprResult &RHS, QualType LHSType, 1226 QualType RHSType, bool IsCompAssign) { 1227 // The rules for this case are in C99 6.3.1.8 1228 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1229 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1230 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1231 if (LHSSigned == RHSSigned) { 1232 // Same signedness; use the higher-ranked type 1233 if (order >= 0) { 1234 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1235 return LHSType; 1236 } else if (!IsCompAssign) 1237 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1238 return RHSType; 1239 } else if (order != (LHSSigned ? 1 : -1)) { 1240 // The unsigned type has greater than or equal rank to the 1241 // signed type, so use the unsigned type 1242 if (RHSSigned) { 1243 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1244 return LHSType; 1245 } else if (!IsCompAssign) 1246 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1247 return RHSType; 1248 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1249 // The two types are different widths; if we are here, that 1250 // means the signed type is larger than the unsigned type, so 1251 // use the signed type. 1252 if (LHSSigned) { 1253 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1254 return LHSType; 1255 } else if (!IsCompAssign) 1256 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1257 return RHSType; 1258 } else { 1259 // The signed type is higher-ranked than the unsigned type, 1260 // but isn't actually any bigger (like unsigned int and long 1261 // on most 32-bit systems). Use the unsigned type corresponding 1262 // to the signed type. 1263 QualType result = 1264 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1265 RHS = (*doRHSCast)(S, RHS.get(), result); 1266 if (!IsCompAssign) 1267 LHS = (*doLHSCast)(S, LHS.get(), result); 1268 return result; 1269 } 1270 } 1271 1272 /// \brief Handle conversions with GCC complex int extension. Helper function 1273 /// of UsualArithmeticConversions() 1274 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1275 ExprResult &RHS, QualType LHSType, 1276 QualType RHSType, 1277 bool IsCompAssign) { 1278 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1279 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1280 1281 if (LHSComplexInt && RHSComplexInt) { 1282 QualType LHSEltType = LHSComplexInt->getElementType(); 1283 QualType RHSEltType = RHSComplexInt->getElementType(); 1284 QualType ScalarType = 1285 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1286 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1287 1288 return S.Context.getComplexType(ScalarType); 1289 } 1290 1291 if (LHSComplexInt) { 1292 QualType LHSEltType = LHSComplexInt->getElementType(); 1293 QualType ScalarType = 1294 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1295 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1296 QualType ComplexType = S.Context.getComplexType(ScalarType); 1297 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1298 CK_IntegralRealToComplex); 1299 1300 return ComplexType; 1301 } 1302 1303 assert(RHSComplexInt); 1304 1305 QualType RHSEltType = RHSComplexInt->getElementType(); 1306 QualType ScalarType = 1307 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1308 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1309 QualType ComplexType = S.Context.getComplexType(ScalarType); 1310 1311 if (!IsCompAssign) 1312 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1313 CK_IntegralRealToComplex); 1314 return ComplexType; 1315 } 1316 1317 /// UsualArithmeticConversions - Performs various conversions that are common to 1318 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1319 /// routine returns the first non-arithmetic type found. The client is 1320 /// responsible for emitting appropriate error diagnostics. 1321 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1322 bool IsCompAssign) { 1323 if (!IsCompAssign) { 1324 LHS = UsualUnaryConversions(LHS.get()); 1325 if (LHS.isInvalid()) 1326 return QualType(); 1327 } 1328 1329 RHS = UsualUnaryConversions(RHS.get()); 1330 if (RHS.isInvalid()) 1331 return QualType(); 1332 1333 // For conversion purposes, we ignore any qualifiers. 1334 // For example, "const float" and "float" are equivalent. 1335 QualType LHSType = 1336 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1337 QualType RHSType = 1338 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1339 1340 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1341 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1342 LHSType = AtomicLHS->getValueType(); 1343 1344 // If both types are identical, no conversion is needed. 1345 if (LHSType == RHSType) 1346 return LHSType; 1347 1348 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1349 // The caller can deal with this (e.g. pointer + int). 1350 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1351 return QualType(); 1352 1353 // Apply unary and bitfield promotions to the LHS's type. 1354 QualType LHSUnpromotedType = LHSType; 1355 if (LHSType->isPromotableIntegerType()) 1356 LHSType = Context.getPromotedIntegerType(LHSType); 1357 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1358 if (!LHSBitfieldPromoteTy.isNull()) 1359 LHSType = LHSBitfieldPromoteTy; 1360 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1361 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1362 1363 // If both types are identical, no conversion is needed. 1364 if (LHSType == RHSType) 1365 return LHSType; 1366 1367 // At this point, we have two different arithmetic types. 1368 1369 // Diagnose attempts to convert between __float128 and long double where 1370 // such conversions currently can't be handled. 1371 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1372 return QualType(); 1373 1374 // Handle complex types first (C99 6.3.1.8p1). 1375 if (LHSType->isComplexType() || RHSType->isComplexType()) 1376 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1377 IsCompAssign); 1378 1379 // Now handle "real" floating types (i.e. float, double, long double). 1380 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1381 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1382 IsCompAssign); 1383 1384 // Handle GCC complex int extension. 1385 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1386 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1387 IsCompAssign); 1388 1389 // Finally, we have two differing integer types. 1390 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1391 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1392 } 1393 1394 1395 //===----------------------------------------------------------------------===// 1396 // Semantic Analysis for various Expression Types 1397 //===----------------------------------------------------------------------===// 1398 1399 1400 ExprResult 1401 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1402 SourceLocation DefaultLoc, 1403 SourceLocation RParenLoc, 1404 Expr *ControllingExpr, 1405 ArrayRef<ParsedType> ArgTypes, 1406 ArrayRef<Expr *> ArgExprs) { 1407 unsigned NumAssocs = ArgTypes.size(); 1408 assert(NumAssocs == ArgExprs.size()); 1409 1410 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1411 for (unsigned i = 0; i < NumAssocs; ++i) { 1412 if (ArgTypes[i]) 1413 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1414 else 1415 Types[i] = nullptr; 1416 } 1417 1418 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1419 ControllingExpr, 1420 llvm::makeArrayRef(Types, NumAssocs), 1421 ArgExprs); 1422 delete [] Types; 1423 return ER; 1424 } 1425 1426 ExprResult 1427 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1428 SourceLocation DefaultLoc, 1429 SourceLocation RParenLoc, 1430 Expr *ControllingExpr, 1431 ArrayRef<TypeSourceInfo *> Types, 1432 ArrayRef<Expr *> Exprs) { 1433 unsigned NumAssocs = Types.size(); 1434 assert(NumAssocs == Exprs.size()); 1435 1436 // Decay and strip qualifiers for the controlling expression type, and handle 1437 // placeholder type replacement. See committee discussion from WG14 DR423. 1438 { 1439 EnterExpressionEvaluationContext Unevaluated( 1440 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1441 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1442 if (R.isInvalid()) 1443 return ExprError(); 1444 ControllingExpr = R.get(); 1445 } 1446 1447 // The controlling expression is an unevaluated operand, so side effects are 1448 // likely unintended. 1449 if (!inTemplateInstantiation() && 1450 ControllingExpr->HasSideEffects(Context, false)) 1451 Diag(ControllingExpr->getExprLoc(), 1452 diag::warn_side_effects_unevaluated_context); 1453 1454 bool TypeErrorFound = false, 1455 IsResultDependent = ControllingExpr->isTypeDependent(), 1456 ContainsUnexpandedParameterPack 1457 = ControllingExpr->containsUnexpandedParameterPack(); 1458 1459 for (unsigned i = 0; i < NumAssocs; ++i) { 1460 if (Exprs[i]->containsUnexpandedParameterPack()) 1461 ContainsUnexpandedParameterPack = true; 1462 1463 if (Types[i]) { 1464 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1465 ContainsUnexpandedParameterPack = true; 1466 1467 if (Types[i]->getType()->isDependentType()) { 1468 IsResultDependent = true; 1469 } else { 1470 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1471 // complete object type other than a variably modified type." 1472 unsigned D = 0; 1473 if (Types[i]->getType()->isIncompleteType()) 1474 D = diag::err_assoc_type_incomplete; 1475 else if (!Types[i]->getType()->isObjectType()) 1476 D = diag::err_assoc_type_nonobject; 1477 else if (Types[i]->getType()->isVariablyModifiedType()) 1478 D = diag::err_assoc_type_variably_modified; 1479 1480 if (D != 0) { 1481 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1482 << Types[i]->getTypeLoc().getSourceRange() 1483 << Types[i]->getType(); 1484 TypeErrorFound = true; 1485 } 1486 1487 // C11 6.5.1.1p2 "No two generic associations in the same generic 1488 // selection shall specify compatible types." 1489 for (unsigned j = i+1; j < NumAssocs; ++j) 1490 if (Types[j] && !Types[j]->getType()->isDependentType() && 1491 Context.typesAreCompatible(Types[i]->getType(), 1492 Types[j]->getType())) { 1493 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1494 diag::err_assoc_compatible_types) 1495 << Types[j]->getTypeLoc().getSourceRange() 1496 << Types[j]->getType() 1497 << Types[i]->getType(); 1498 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1499 diag::note_compat_assoc) 1500 << Types[i]->getTypeLoc().getSourceRange() 1501 << Types[i]->getType(); 1502 TypeErrorFound = true; 1503 } 1504 } 1505 } 1506 } 1507 if (TypeErrorFound) 1508 return ExprError(); 1509 1510 // If we determined that the generic selection is result-dependent, don't 1511 // try to compute the result expression. 1512 if (IsResultDependent) 1513 return new (Context) GenericSelectionExpr( 1514 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1515 ContainsUnexpandedParameterPack); 1516 1517 SmallVector<unsigned, 1> CompatIndices; 1518 unsigned DefaultIndex = -1U; 1519 for (unsigned i = 0; i < NumAssocs; ++i) { 1520 if (!Types[i]) 1521 DefaultIndex = i; 1522 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1523 Types[i]->getType())) 1524 CompatIndices.push_back(i); 1525 } 1526 1527 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1528 // type compatible with at most one of the types named in its generic 1529 // association list." 1530 if (CompatIndices.size() > 1) { 1531 // We strip parens here because the controlling expression is typically 1532 // parenthesized in macro definitions. 1533 ControllingExpr = ControllingExpr->IgnoreParens(); 1534 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1535 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1536 << (unsigned) CompatIndices.size(); 1537 for (unsigned I : CompatIndices) { 1538 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1539 diag::note_compat_assoc) 1540 << Types[I]->getTypeLoc().getSourceRange() 1541 << Types[I]->getType(); 1542 } 1543 return ExprError(); 1544 } 1545 1546 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1547 // its controlling expression shall have type compatible with exactly one of 1548 // the types named in its generic association list." 1549 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1550 // We strip parens here because the controlling expression is typically 1551 // parenthesized in macro definitions. 1552 ControllingExpr = ControllingExpr->IgnoreParens(); 1553 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1554 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1555 return ExprError(); 1556 } 1557 1558 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1559 // type name that is compatible with the type of the controlling expression, 1560 // then the result expression of the generic selection is the expression 1561 // in that generic association. Otherwise, the result expression of the 1562 // generic selection is the expression in the default generic association." 1563 unsigned ResultIndex = 1564 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1565 1566 return new (Context) GenericSelectionExpr( 1567 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1568 ContainsUnexpandedParameterPack, ResultIndex); 1569 } 1570 1571 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1572 /// location of the token and the offset of the ud-suffix within it. 1573 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1574 unsigned Offset) { 1575 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1576 S.getLangOpts()); 1577 } 1578 1579 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1580 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1581 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1582 IdentifierInfo *UDSuffix, 1583 SourceLocation UDSuffixLoc, 1584 ArrayRef<Expr*> Args, 1585 SourceLocation LitEndLoc) { 1586 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1587 1588 QualType ArgTy[2]; 1589 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1590 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1591 if (ArgTy[ArgIdx]->isArrayType()) 1592 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1593 } 1594 1595 DeclarationName OpName = 1596 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1597 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1598 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1599 1600 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1601 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1602 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1603 /*AllowStringTemplate*/ false, 1604 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1605 return ExprError(); 1606 1607 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1608 } 1609 1610 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1611 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1612 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1613 /// multiple tokens. However, the common case is that StringToks points to one 1614 /// string. 1615 /// 1616 ExprResult 1617 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1618 assert(!StringToks.empty() && "Must have at least one string!"); 1619 1620 StringLiteralParser Literal(StringToks, PP); 1621 if (Literal.hadError) 1622 return ExprError(); 1623 1624 SmallVector<SourceLocation, 4> StringTokLocs; 1625 for (const Token &Tok : StringToks) 1626 StringTokLocs.push_back(Tok.getLocation()); 1627 1628 QualType CharTy = Context.CharTy; 1629 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1630 if (Literal.isWide()) { 1631 CharTy = Context.getWideCharType(); 1632 Kind = StringLiteral::Wide; 1633 } else if (Literal.isUTF8()) { 1634 Kind = StringLiteral::UTF8; 1635 } else if (Literal.isUTF16()) { 1636 CharTy = Context.Char16Ty; 1637 Kind = StringLiteral::UTF16; 1638 } else if (Literal.isUTF32()) { 1639 CharTy = Context.Char32Ty; 1640 Kind = StringLiteral::UTF32; 1641 } else if (Literal.isPascal()) { 1642 CharTy = Context.UnsignedCharTy; 1643 } 1644 1645 QualType CharTyConst = CharTy; 1646 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1647 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1648 CharTyConst.addConst(); 1649 1650 // Get an array type for the string, according to C99 6.4.5. This includes 1651 // the nul terminator character as well as the string length for pascal 1652 // strings. 1653 QualType StrTy = Context.getConstantArrayType(CharTyConst, 1654 llvm::APInt(32, Literal.GetNumStringChars()+1), 1655 ArrayType::Normal, 0); 1656 1657 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 1658 if (getLangOpts().OpenCL) { 1659 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant); 1660 } 1661 1662 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1663 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1664 Kind, Literal.Pascal, StrTy, 1665 &StringTokLocs[0], 1666 StringTokLocs.size()); 1667 if (Literal.getUDSuffix().empty()) 1668 return Lit; 1669 1670 // We're building a user-defined literal. 1671 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1672 SourceLocation UDSuffixLoc = 1673 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1674 Literal.getUDSuffixOffset()); 1675 1676 // Make sure we're allowed user-defined literals here. 1677 if (!UDLScope) 1678 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1679 1680 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1681 // operator "" X (str, len) 1682 QualType SizeType = Context.getSizeType(); 1683 1684 DeclarationName OpName = 1685 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1686 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1687 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1688 1689 QualType ArgTy[] = { 1690 Context.getArrayDecayedType(StrTy), SizeType 1691 }; 1692 1693 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1694 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1695 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1696 /*AllowStringTemplate*/ true, 1697 /*DiagnoseMissing*/ true)) { 1698 1699 case LOLR_Cooked: { 1700 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1701 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1702 StringTokLocs[0]); 1703 Expr *Args[] = { Lit, LenArg }; 1704 1705 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1706 } 1707 1708 case LOLR_StringTemplate: { 1709 TemplateArgumentListInfo ExplicitArgs; 1710 1711 unsigned CharBits = Context.getIntWidth(CharTy); 1712 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1713 llvm::APSInt Value(CharBits, CharIsUnsigned); 1714 1715 TemplateArgument TypeArg(CharTy); 1716 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1717 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1718 1719 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1720 Value = Lit->getCodeUnit(I); 1721 TemplateArgument Arg(Context, Value, CharTy); 1722 TemplateArgumentLocInfo ArgInfo; 1723 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1724 } 1725 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1726 &ExplicitArgs); 1727 } 1728 case LOLR_Raw: 1729 case LOLR_Template: 1730 case LOLR_ErrorNoDiagnostic: 1731 llvm_unreachable("unexpected literal operator lookup result"); 1732 case LOLR_Error: 1733 return ExprError(); 1734 } 1735 llvm_unreachable("unexpected literal operator lookup result"); 1736 } 1737 1738 ExprResult 1739 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1740 SourceLocation Loc, 1741 const CXXScopeSpec *SS) { 1742 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1743 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1744 } 1745 1746 /// BuildDeclRefExpr - Build an expression that references a 1747 /// declaration that does not require a closure capture. 1748 ExprResult 1749 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1750 const DeclarationNameInfo &NameInfo, 1751 const CXXScopeSpec *SS, NamedDecl *FoundD, 1752 const TemplateArgumentListInfo *TemplateArgs) { 1753 bool RefersToCapturedVariable = 1754 isa<VarDecl>(D) && 1755 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1756 1757 DeclRefExpr *E; 1758 if (isa<VarTemplateSpecializationDecl>(D)) { 1759 VarTemplateSpecializationDecl *VarSpec = 1760 cast<VarTemplateSpecializationDecl>(D); 1761 1762 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1763 : NestedNameSpecifierLoc(), 1764 VarSpec->getTemplateKeywordLoc(), D, 1765 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK, 1766 FoundD, TemplateArgs); 1767 } else { 1768 assert(!TemplateArgs && "No template arguments for non-variable" 1769 " template specialization references"); 1770 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1771 : NestedNameSpecifierLoc(), 1772 SourceLocation(), D, RefersToCapturedVariable, 1773 NameInfo, Ty, VK, FoundD); 1774 } 1775 1776 MarkDeclRefReferenced(E); 1777 1778 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1779 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && 1780 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart())) 1781 recordUseOfEvaluatedWeak(E); 1782 1783 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1784 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 1785 FD = IFD->getAnonField(); 1786 if (FD) { 1787 UnusedPrivateFields.remove(FD); 1788 // Just in case we're building an illegal pointer-to-member. 1789 if (FD->isBitField()) 1790 E->setObjectKind(OK_BitField); 1791 } 1792 1793 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1794 // designates a bit-field. 1795 if (auto *BD = dyn_cast<BindingDecl>(D)) 1796 if (auto *BE = BD->getBinding()) 1797 E->setObjectKind(BE->getObjectKind()); 1798 1799 return E; 1800 } 1801 1802 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1803 /// possibly a list of template arguments. 1804 /// 1805 /// If this produces template arguments, it is permitted to call 1806 /// DecomposeTemplateName. 1807 /// 1808 /// This actually loses a lot of source location information for 1809 /// non-standard name kinds; we should consider preserving that in 1810 /// some way. 1811 void 1812 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1813 TemplateArgumentListInfo &Buffer, 1814 DeclarationNameInfo &NameInfo, 1815 const TemplateArgumentListInfo *&TemplateArgs) { 1816 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1817 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1818 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1819 1820 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1821 Id.TemplateId->NumArgs); 1822 translateTemplateArguments(TemplateArgsPtr, Buffer); 1823 1824 TemplateName TName = Id.TemplateId->Template.get(); 1825 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1826 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1827 TemplateArgs = &Buffer; 1828 } else { 1829 NameInfo = GetNameFromUnqualifiedId(Id); 1830 TemplateArgs = nullptr; 1831 } 1832 } 1833 1834 static void emitEmptyLookupTypoDiagnostic( 1835 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1836 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1837 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1838 DeclContext *Ctx = 1839 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1840 if (!TC) { 1841 // Emit a special diagnostic for failed member lookups. 1842 // FIXME: computing the declaration context might fail here (?) 1843 if (Ctx) 1844 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1845 << SS.getRange(); 1846 else 1847 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1848 return; 1849 } 1850 1851 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1852 bool DroppedSpecifier = 1853 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1854 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1855 ? diag::note_implicit_param_decl 1856 : diag::note_previous_decl; 1857 if (!Ctx) 1858 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1859 SemaRef.PDiag(NoteID)); 1860 else 1861 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1862 << Typo << Ctx << DroppedSpecifier 1863 << SS.getRange(), 1864 SemaRef.PDiag(NoteID)); 1865 } 1866 1867 /// Diagnose an empty lookup. 1868 /// 1869 /// \return false if new lookup candidates were found 1870 bool 1871 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1872 std::unique_ptr<CorrectionCandidateCallback> CCC, 1873 TemplateArgumentListInfo *ExplicitTemplateArgs, 1874 ArrayRef<Expr *> Args, TypoExpr **Out) { 1875 DeclarationName Name = R.getLookupName(); 1876 1877 unsigned diagnostic = diag::err_undeclared_var_use; 1878 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1879 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1880 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1881 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1882 diagnostic = diag::err_undeclared_use; 1883 diagnostic_suggest = diag::err_undeclared_use_suggest; 1884 } 1885 1886 // If the original lookup was an unqualified lookup, fake an 1887 // unqualified lookup. This is useful when (for example) the 1888 // original lookup would not have found something because it was a 1889 // dependent name. 1890 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1891 while (DC) { 1892 if (isa<CXXRecordDecl>(DC)) { 1893 LookupQualifiedName(R, DC); 1894 1895 if (!R.empty()) { 1896 // Don't give errors about ambiguities in this lookup. 1897 R.suppressDiagnostics(); 1898 1899 // During a default argument instantiation the CurContext points 1900 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1901 // function parameter list, hence add an explicit check. 1902 bool isDefaultArgument = 1903 !CodeSynthesisContexts.empty() && 1904 CodeSynthesisContexts.back().Kind == 1905 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 1906 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1907 bool isInstance = CurMethod && 1908 CurMethod->isInstance() && 1909 DC == CurMethod->getParent() && !isDefaultArgument; 1910 1911 // Give a code modification hint to insert 'this->'. 1912 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1913 // Actually quite difficult! 1914 if (getLangOpts().MSVCCompat) 1915 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1916 if (isInstance) { 1917 Diag(R.getNameLoc(), diagnostic) << Name 1918 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1919 CheckCXXThisCapture(R.getNameLoc()); 1920 } else { 1921 Diag(R.getNameLoc(), diagnostic) << Name; 1922 } 1923 1924 // Do we really want to note all of these? 1925 for (NamedDecl *D : R) 1926 Diag(D->getLocation(), diag::note_dependent_var_use); 1927 1928 // Return true if we are inside a default argument instantiation 1929 // and the found name refers to an instance member function, otherwise 1930 // the function calling DiagnoseEmptyLookup will try to create an 1931 // implicit member call and this is wrong for default argument. 1932 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1933 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1934 return true; 1935 } 1936 1937 // Tell the callee to try to recover. 1938 return false; 1939 } 1940 1941 R.clear(); 1942 } 1943 1944 // In Microsoft mode, if we are performing lookup from within a friend 1945 // function definition declared at class scope then we must set 1946 // DC to the lexical parent to be able to search into the parent 1947 // class. 1948 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1949 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1950 DC->getLexicalParent()->isRecord()) 1951 DC = DC->getLexicalParent(); 1952 else 1953 DC = DC->getParent(); 1954 } 1955 1956 // We didn't find anything, so try to correct for a typo. 1957 TypoCorrection Corrected; 1958 if (S && Out) { 1959 SourceLocation TypoLoc = R.getNameLoc(); 1960 assert(!ExplicitTemplateArgs && 1961 "Diagnosing an empty lookup with explicit template args!"); 1962 *Out = CorrectTypoDelayed( 1963 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC), 1964 [=](const TypoCorrection &TC) { 1965 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 1966 diagnostic, diagnostic_suggest); 1967 }, 1968 nullptr, CTK_ErrorRecovery); 1969 if (*Out) 1970 return true; 1971 } else if (S && (Corrected = 1972 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, 1973 &SS, std::move(CCC), CTK_ErrorRecovery))) { 1974 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1975 bool DroppedSpecifier = 1976 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1977 R.setLookupName(Corrected.getCorrection()); 1978 1979 bool AcceptableWithRecovery = false; 1980 bool AcceptableWithoutRecovery = false; 1981 NamedDecl *ND = Corrected.getFoundDecl(); 1982 if (ND) { 1983 if (Corrected.isOverloaded()) { 1984 OverloadCandidateSet OCS(R.getNameLoc(), 1985 OverloadCandidateSet::CSK_Normal); 1986 OverloadCandidateSet::iterator Best; 1987 for (NamedDecl *CD : Corrected) { 1988 if (FunctionTemplateDecl *FTD = 1989 dyn_cast<FunctionTemplateDecl>(CD)) 1990 AddTemplateOverloadCandidate( 1991 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1992 Args, OCS); 1993 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 1994 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1995 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1996 Args, OCS); 1997 } 1998 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1999 case OR_Success: 2000 ND = Best->FoundDecl; 2001 Corrected.setCorrectionDecl(ND); 2002 break; 2003 default: 2004 // FIXME: Arbitrarily pick the first declaration for the note. 2005 Corrected.setCorrectionDecl(ND); 2006 break; 2007 } 2008 } 2009 R.addDecl(ND); 2010 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2011 CXXRecordDecl *Record = nullptr; 2012 if (Corrected.getCorrectionSpecifier()) { 2013 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2014 Record = Ty->getAsCXXRecordDecl(); 2015 } 2016 if (!Record) 2017 Record = cast<CXXRecordDecl>( 2018 ND->getDeclContext()->getRedeclContext()); 2019 R.setNamingClass(Record); 2020 } 2021 2022 auto *UnderlyingND = ND->getUnderlyingDecl(); 2023 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2024 isa<FunctionTemplateDecl>(UnderlyingND); 2025 // FIXME: If we ended up with a typo for a type name or 2026 // Objective-C class name, we're in trouble because the parser 2027 // is in the wrong place to recover. Suggest the typo 2028 // correction, but don't make it a fix-it since we're not going 2029 // to recover well anyway. 2030 AcceptableWithoutRecovery = 2031 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND); 2032 } else { 2033 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2034 // because we aren't able to recover. 2035 AcceptableWithoutRecovery = true; 2036 } 2037 2038 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2039 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2040 ? diag::note_implicit_param_decl 2041 : diag::note_previous_decl; 2042 if (SS.isEmpty()) 2043 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2044 PDiag(NoteID), AcceptableWithRecovery); 2045 else 2046 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2047 << Name << computeDeclContext(SS, false) 2048 << DroppedSpecifier << SS.getRange(), 2049 PDiag(NoteID), AcceptableWithRecovery); 2050 2051 // Tell the callee whether to try to recover. 2052 return !AcceptableWithRecovery; 2053 } 2054 } 2055 R.clear(); 2056 2057 // Emit a special diagnostic for failed member lookups. 2058 // FIXME: computing the declaration context might fail here (?) 2059 if (!SS.isEmpty()) { 2060 Diag(R.getNameLoc(), diag::err_no_member) 2061 << Name << computeDeclContext(SS, false) 2062 << SS.getRange(); 2063 return true; 2064 } 2065 2066 // Give up, we can't recover. 2067 Diag(R.getNameLoc(), diagnostic) << Name; 2068 return true; 2069 } 2070 2071 /// In Microsoft mode, if we are inside a template class whose parent class has 2072 /// dependent base classes, and we can't resolve an unqualified identifier, then 2073 /// assume the identifier is a member of a dependent base class. We can only 2074 /// recover successfully in static methods, instance methods, and other contexts 2075 /// where 'this' is available. This doesn't precisely match MSVC's 2076 /// instantiation model, but it's close enough. 2077 static Expr * 2078 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2079 DeclarationNameInfo &NameInfo, 2080 SourceLocation TemplateKWLoc, 2081 const TemplateArgumentListInfo *TemplateArgs) { 2082 // Only try to recover from lookup into dependent bases in static methods or 2083 // contexts where 'this' is available. 2084 QualType ThisType = S.getCurrentThisType(); 2085 const CXXRecordDecl *RD = nullptr; 2086 if (!ThisType.isNull()) 2087 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2088 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2089 RD = MD->getParent(); 2090 if (!RD || !RD->hasAnyDependentBases()) 2091 return nullptr; 2092 2093 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2094 // is available, suggest inserting 'this->' as a fixit. 2095 SourceLocation Loc = NameInfo.getLoc(); 2096 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2097 DB << NameInfo.getName() << RD; 2098 2099 if (!ThisType.isNull()) { 2100 DB << FixItHint::CreateInsertion(Loc, "this->"); 2101 return CXXDependentScopeMemberExpr::Create( 2102 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2103 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2104 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 2105 } 2106 2107 // Synthesize a fake NNS that points to the derived class. This will 2108 // perform name lookup during template instantiation. 2109 CXXScopeSpec SS; 2110 auto *NNS = 2111 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2112 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2113 return DependentScopeDeclRefExpr::Create( 2114 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2115 TemplateArgs); 2116 } 2117 2118 ExprResult 2119 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2120 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2121 bool HasTrailingLParen, bool IsAddressOfOperand, 2122 std::unique_ptr<CorrectionCandidateCallback> CCC, 2123 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2124 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2125 "cannot be direct & operand and have a trailing lparen"); 2126 if (SS.isInvalid()) 2127 return ExprError(); 2128 2129 TemplateArgumentListInfo TemplateArgsBuffer; 2130 2131 // Decompose the UnqualifiedId into the following data. 2132 DeclarationNameInfo NameInfo; 2133 const TemplateArgumentListInfo *TemplateArgs; 2134 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2135 2136 DeclarationName Name = NameInfo.getName(); 2137 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2138 SourceLocation NameLoc = NameInfo.getLoc(); 2139 2140 if (II && II->isEditorPlaceholder()) { 2141 // FIXME: When typed placeholders are supported we can create a typed 2142 // placeholder expression node. 2143 return ExprError(); 2144 } 2145 2146 // C++ [temp.dep.expr]p3: 2147 // An id-expression is type-dependent if it contains: 2148 // -- an identifier that was declared with a dependent type, 2149 // (note: handled after lookup) 2150 // -- a template-id that is dependent, 2151 // (note: handled in BuildTemplateIdExpr) 2152 // -- a conversion-function-id that specifies a dependent type, 2153 // -- a nested-name-specifier that contains a class-name that 2154 // names a dependent type. 2155 // Determine whether this is a member of an unknown specialization; 2156 // we need to handle these differently. 2157 bool DependentID = false; 2158 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2159 Name.getCXXNameType()->isDependentType()) { 2160 DependentID = true; 2161 } else if (SS.isSet()) { 2162 if (DeclContext *DC = computeDeclContext(SS, false)) { 2163 if (RequireCompleteDeclContext(SS, DC)) 2164 return ExprError(); 2165 } else { 2166 DependentID = true; 2167 } 2168 } 2169 2170 if (DependentID) 2171 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2172 IsAddressOfOperand, TemplateArgs); 2173 2174 // Perform the required lookup. 2175 LookupResult R(*this, NameInfo, 2176 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 2177 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 2178 if (TemplateArgs) { 2179 // Lookup the template name again to correctly establish the context in 2180 // which it was found. This is really unfortunate as we already did the 2181 // lookup to determine that it was a template name in the first place. If 2182 // this becomes a performance hit, we can work harder to preserve those 2183 // results until we get here but it's likely not worth it. 2184 bool MemberOfUnknownSpecialization; 2185 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2186 MemberOfUnknownSpecialization); 2187 2188 if (MemberOfUnknownSpecialization || 2189 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2190 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2191 IsAddressOfOperand, TemplateArgs); 2192 } else { 2193 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2194 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2195 2196 // If the result might be in a dependent base class, this is a dependent 2197 // id-expression. 2198 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2199 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2200 IsAddressOfOperand, TemplateArgs); 2201 2202 // If this reference is in an Objective-C method, then we need to do 2203 // some special Objective-C lookup, too. 2204 if (IvarLookupFollowUp) { 2205 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2206 if (E.isInvalid()) 2207 return ExprError(); 2208 2209 if (Expr *Ex = E.getAs<Expr>()) 2210 return Ex; 2211 } 2212 } 2213 2214 if (R.isAmbiguous()) 2215 return ExprError(); 2216 2217 // This could be an implicitly declared function reference (legal in C90, 2218 // extension in C99, forbidden in C++). 2219 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2220 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2221 if (D) R.addDecl(D); 2222 } 2223 2224 // Determine whether this name might be a candidate for 2225 // argument-dependent lookup. 2226 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2227 2228 if (R.empty() && !ADL) { 2229 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2230 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2231 TemplateKWLoc, TemplateArgs)) 2232 return E; 2233 } 2234 2235 // Don't diagnose an empty lookup for inline assembly. 2236 if (IsInlineAsmIdentifier) 2237 return ExprError(); 2238 2239 // If this name wasn't predeclared and if this is not a function 2240 // call, diagnose the problem. 2241 TypoExpr *TE = nullptr; 2242 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2243 II, SS.isValid() ? SS.getScopeRep() : nullptr); 2244 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; 2245 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2246 "Typo correction callback misconfigured"); 2247 if (CCC) { 2248 // Make sure the callback knows what the typo being diagnosed is. 2249 CCC->setTypoName(II); 2250 if (SS.isValid()) 2251 CCC->setTypoNNS(SS.getScopeRep()); 2252 } 2253 if (DiagnoseEmptyLookup(S, SS, R, 2254 CCC ? std::move(CCC) : std::move(DefaultValidator), 2255 nullptr, None, &TE)) { 2256 if (TE && KeywordReplacement) { 2257 auto &State = getTypoExprState(TE); 2258 auto BestTC = State.Consumer->getNextCorrection(); 2259 if (BestTC.isKeyword()) { 2260 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2261 if (State.DiagHandler) 2262 State.DiagHandler(BestTC); 2263 KeywordReplacement->startToken(); 2264 KeywordReplacement->setKind(II->getTokenID()); 2265 KeywordReplacement->setIdentifierInfo(II); 2266 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2267 // Clean up the state associated with the TypoExpr, since it has 2268 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2269 clearDelayedTypo(TE); 2270 // Signal that a correction to a keyword was performed by returning a 2271 // valid-but-null ExprResult. 2272 return (Expr*)nullptr; 2273 } 2274 State.Consumer->resetCorrectionStream(); 2275 } 2276 return TE ? TE : ExprError(); 2277 } 2278 2279 assert(!R.empty() && 2280 "DiagnoseEmptyLookup returned false but added no results"); 2281 2282 // If we found an Objective-C instance variable, let 2283 // LookupInObjCMethod build the appropriate expression to 2284 // reference the ivar. 2285 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2286 R.clear(); 2287 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2288 // In a hopelessly buggy code, Objective-C instance variable 2289 // lookup fails and no expression will be built to reference it. 2290 if (!E.isInvalid() && !E.get()) 2291 return ExprError(); 2292 return E; 2293 } 2294 } 2295 2296 // This is guaranteed from this point on. 2297 assert(!R.empty() || ADL); 2298 2299 // Check whether this might be a C++ implicit instance member access. 2300 // C++ [class.mfct.non-static]p3: 2301 // When an id-expression that is not part of a class member access 2302 // syntax and not used to form a pointer to member is used in the 2303 // body of a non-static member function of class X, if name lookup 2304 // resolves the name in the id-expression to a non-static non-type 2305 // member of some class C, the id-expression is transformed into a 2306 // class member access expression using (*this) as the 2307 // postfix-expression to the left of the . operator. 2308 // 2309 // But we don't actually need to do this for '&' operands if R 2310 // resolved to a function or overloaded function set, because the 2311 // expression is ill-formed if it actually works out to be a 2312 // non-static member function: 2313 // 2314 // C++ [expr.ref]p4: 2315 // Otherwise, if E1.E2 refers to a non-static member function. . . 2316 // [t]he expression can be used only as the left-hand operand of a 2317 // member function call. 2318 // 2319 // There are other safeguards against such uses, but it's important 2320 // to get this right here so that we don't end up making a 2321 // spuriously dependent expression if we're inside a dependent 2322 // instance method. 2323 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2324 bool MightBeImplicitMember; 2325 if (!IsAddressOfOperand) 2326 MightBeImplicitMember = true; 2327 else if (!SS.isEmpty()) 2328 MightBeImplicitMember = false; 2329 else if (R.isOverloadedResult()) 2330 MightBeImplicitMember = false; 2331 else if (R.isUnresolvableResult()) 2332 MightBeImplicitMember = true; 2333 else 2334 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2335 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2336 isa<MSPropertyDecl>(R.getFoundDecl()); 2337 2338 if (MightBeImplicitMember) 2339 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2340 R, TemplateArgs, S); 2341 } 2342 2343 if (TemplateArgs || TemplateKWLoc.isValid()) { 2344 2345 // In C++1y, if this is a variable template id, then check it 2346 // in BuildTemplateIdExpr(). 2347 // The single lookup result must be a variable template declaration. 2348 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId && 2349 Id.TemplateId->Kind == TNK_Var_template) { 2350 assert(R.getAsSingle<VarTemplateDecl>() && 2351 "There should only be one declaration found."); 2352 } 2353 2354 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2355 } 2356 2357 return BuildDeclarationNameExpr(SS, R, ADL); 2358 } 2359 2360 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2361 /// declaration name, generally during template instantiation. 2362 /// There's a large number of things which don't need to be done along 2363 /// this path. 2364 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2365 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2366 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2367 DeclContext *DC = computeDeclContext(SS, false); 2368 if (!DC) 2369 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2370 NameInfo, /*TemplateArgs=*/nullptr); 2371 2372 if (RequireCompleteDeclContext(SS, DC)) 2373 return ExprError(); 2374 2375 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2376 LookupQualifiedName(R, DC); 2377 2378 if (R.isAmbiguous()) 2379 return ExprError(); 2380 2381 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2382 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2383 NameInfo, /*TemplateArgs=*/nullptr); 2384 2385 if (R.empty()) { 2386 Diag(NameInfo.getLoc(), diag::err_no_member) 2387 << NameInfo.getName() << DC << SS.getRange(); 2388 return ExprError(); 2389 } 2390 2391 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2392 // Diagnose a missing typename if this resolved unambiguously to a type in 2393 // a dependent context. If we can recover with a type, downgrade this to 2394 // a warning in Microsoft compatibility mode. 2395 unsigned DiagID = diag::err_typename_missing; 2396 if (RecoveryTSI && getLangOpts().MSVCCompat) 2397 DiagID = diag::ext_typename_missing; 2398 SourceLocation Loc = SS.getBeginLoc(); 2399 auto D = Diag(Loc, DiagID); 2400 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2401 << SourceRange(Loc, NameInfo.getEndLoc()); 2402 2403 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2404 // context. 2405 if (!RecoveryTSI) 2406 return ExprError(); 2407 2408 // Only issue the fixit if we're prepared to recover. 2409 D << FixItHint::CreateInsertion(Loc, "typename "); 2410 2411 // Recover by pretending this was an elaborated type. 2412 QualType Ty = Context.getTypeDeclType(TD); 2413 TypeLocBuilder TLB; 2414 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2415 2416 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2417 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2418 QTL.setElaboratedKeywordLoc(SourceLocation()); 2419 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2420 2421 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2422 2423 return ExprEmpty(); 2424 } 2425 2426 // Defend against this resolving to an implicit member access. We usually 2427 // won't get here if this might be a legitimate a class member (we end up in 2428 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2429 // a pointer-to-member or in an unevaluated context in C++11. 2430 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2431 return BuildPossibleImplicitMemberExpr(SS, 2432 /*TemplateKWLoc=*/SourceLocation(), 2433 R, /*TemplateArgs=*/nullptr, S); 2434 2435 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2436 } 2437 2438 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2439 /// detected that we're currently inside an ObjC method. Perform some 2440 /// additional lookup. 2441 /// 2442 /// Ideally, most of this would be done by lookup, but there's 2443 /// actually quite a lot of extra work involved. 2444 /// 2445 /// Returns a null sentinel to indicate trivial success. 2446 ExprResult 2447 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2448 IdentifierInfo *II, bool AllowBuiltinCreation) { 2449 SourceLocation Loc = Lookup.getNameLoc(); 2450 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2451 2452 // Check for error condition which is already reported. 2453 if (!CurMethod) 2454 return ExprError(); 2455 2456 // There are two cases to handle here. 1) scoped lookup could have failed, 2457 // in which case we should look for an ivar. 2) scoped lookup could have 2458 // found a decl, but that decl is outside the current instance method (i.e. 2459 // a global variable). In these two cases, we do a lookup for an ivar with 2460 // this name, if the lookup sucedes, we replace it our current decl. 2461 2462 // If we're in a class method, we don't normally want to look for 2463 // ivars. But if we don't find anything else, and there's an 2464 // ivar, that's an error. 2465 bool IsClassMethod = CurMethod->isClassMethod(); 2466 2467 bool LookForIvars; 2468 if (Lookup.empty()) 2469 LookForIvars = true; 2470 else if (IsClassMethod) 2471 LookForIvars = false; 2472 else 2473 LookForIvars = (Lookup.isSingleResult() && 2474 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2475 ObjCInterfaceDecl *IFace = nullptr; 2476 if (LookForIvars) { 2477 IFace = CurMethod->getClassInterface(); 2478 ObjCInterfaceDecl *ClassDeclared; 2479 ObjCIvarDecl *IV = nullptr; 2480 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2481 // Diagnose using an ivar in a class method. 2482 if (IsClassMethod) 2483 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2484 << IV->getDeclName()); 2485 2486 // If we're referencing an invalid decl, just return this as a silent 2487 // error node. The error diagnostic was already emitted on the decl. 2488 if (IV->isInvalidDecl()) 2489 return ExprError(); 2490 2491 // Check if referencing a field with __attribute__((deprecated)). 2492 if (DiagnoseUseOfDecl(IV, Loc)) 2493 return ExprError(); 2494 2495 // Diagnose the use of an ivar outside of the declaring class. 2496 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2497 !declaresSameEntity(ClassDeclared, IFace) && 2498 !getLangOpts().DebuggerSupport) 2499 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2500 2501 // FIXME: This should use a new expr for a direct reference, don't 2502 // turn this into Self->ivar, just return a BareIVarExpr or something. 2503 IdentifierInfo &II = Context.Idents.get("self"); 2504 UnqualifiedId SelfName; 2505 SelfName.setIdentifier(&II, SourceLocation()); 2506 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2507 CXXScopeSpec SelfScopeSpec; 2508 SourceLocation TemplateKWLoc; 2509 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2510 SelfName, false, false); 2511 if (SelfExpr.isInvalid()) 2512 return ExprError(); 2513 2514 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2515 if (SelfExpr.isInvalid()) 2516 return ExprError(); 2517 2518 MarkAnyDeclReferenced(Loc, IV, true); 2519 2520 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2521 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2522 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2523 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2524 2525 ObjCIvarRefExpr *Result = new (Context) 2526 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2527 IV->getLocation(), SelfExpr.get(), true, true); 2528 2529 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2530 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2531 recordUseOfEvaluatedWeak(Result); 2532 } 2533 if (getLangOpts().ObjCAutoRefCount) { 2534 if (CurContext->isClosure()) 2535 Diag(Loc, diag::warn_implicitly_retains_self) 2536 << FixItHint::CreateInsertion(Loc, "self->"); 2537 } 2538 2539 return Result; 2540 } 2541 } else if (CurMethod->isInstanceMethod()) { 2542 // We should warn if a local variable hides an ivar. 2543 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2544 ObjCInterfaceDecl *ClassDeclared; 2545 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2546 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2547 declaresSameEntity(IFace, ClassDeclared)) 2548 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2549 } 2550 } 2551 } else if (Lookup.isSingleResult() && 2552 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2553 // If accessing a stand-alone ivar in a class method, this is an error. 2554 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2555 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2556 << IV->getDeclName()); 2557 } 2558 2559 if (Lookup.empty() && II && AllowBuiltinCreation) { 2560 // FIXME. Consolidate this with similar code in LookupName. 2561 if (unsigned BuiltinID = II->getBuiltinID()) { 2562 if (!(getLangOpts().CPlusPlus && 2563 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2564 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2565 S, Lookup.isForRedeclaration(), 2566 Lookup.getNameLoc()); 2567 if (D) Lookup.addDecl(D); 2568 } 2569 } 2570 } 2571 // Sentinel value saying that we didn't do anything special. 2572 return ExprResult((Expr *)nullptr); 2573 } 2574 2575 /// \brief Cast a base object to a member's actual type. 2576 /// 2577 /// Logically this happens in three phases: 2578 /// 2579 /// * First we cast from the base type to the naming class. 2580 /// The naming class is the class into which we were looking 2581 /// when we found the member; it's the qualifier type if a 2582 /// qualifier was provided, and otherwise it's the base type. 2583 /// 2584 /// * Next we cast from the naming class to the declaring class. 2585 /// If the member we found was brought into a class's scope by 2586 /// a using declaration, this is that class; otherwise it's 2587 /// the class declaring the member. 2588 /// 2589 /// * Finally we cast from the declaring class to the "true" 2590 /// declaring class of the member. This conversion does not 2591 /// obey access control. 2592 ExprResult 2593 Sema::PerformObjectMemberConversion(Expr *From, 2594 NestedNameSpecifier *Qualifier, 2595 NamedDecl *FoundDecl, 2596 NamedDecl *Member) { 2597 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2598 if (!RD) 2599 return From; 2600 2601 QualType DestRecordType; 2602 QualType DestType; 2603 QualType FromRecordType; 2604 QualType FromType = From->getType(); 2605 bool PointerConversions = false; 2606 if (isa<FieldDecl>(Member)) { 2607 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2608 2609 if (FromType->getAs<PointerType>()) { 2610 DestType = Context.getPointerType(DestRecordType); 2611 FromRecordType = FromType->getPointeeType(); 2612 PointerConversions = true; 2613 } else { 2614 DestType = DestRecordType; 2615 FromRecordType = FromType; 2616 } 2617 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2618 if (Method->isStatic()) 2619 return From; 2620 2621 DestType = Method->getThisType(Context); 2622 DestRecordType = DestType->getPointeeType(); 2623 2624 if (FromType->getAs<PointerType>()) { 2625 FromRecordType = FromType->getPointeeType(); 2626 PointerConversions = true; 2627 } else { 2628 FromRecordType = FromType; 2629 DestType = DestRecordType; 2630 } 2631 } else { 2632 // No conversion necessary. 2633 return From; 2634 } 2635 2636 if (DestType->isDependentType() || FromType->isDependentType()) 2637 return From; 2638 2639 // If the unqualified types are the same, no conversion is necessary. 2640 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2641 return From; 2642 2643 SourceRange FromRange = From->getSourceRange(); 2644 SourceLocation FromLoc = FromRange.getBegin(); 2645 2646 ExprValueKind VK = From->getValueKind(); 2647 2648 // C++ [class.member.lookup]p8: 2649 // [...] Ambiguities can often be resolved by qualifying a name with its 2650 // class name. 2651 // 2652 // If the member was a qualified name and the qualified referred to a 2653 // specific base subobject type, we'll cast to that intermediate type 2654 // first and then to the object in which the member is declared. That allows 2655 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2656 // 2657 // class Base { public: int x; }; 2658 // class Derived1 : public Base { }; 2659 // class Derived2 : public Base { }; 2660 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2661 // 2662 // void VeryDerived::f() { 2663 // x = 17; // error: ambiguous base subobjects 2664 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2665 // } 2666 if (Qualifier && Qualifier->getAsType()) { 2667 QualType QType = QualType(Qualifier->getAsType(), 0); 2668 assert(QType->isRecordType() && "lookup done with non-record type"); 2669 2670 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2671 2672 // In C++98, the qualifier type doesn't actually have to be a base 2673 // type of the object type, in which case we just ignore it. 2674 // Otherwise build the appropriate casts. 2675 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2676 CXXCastPath BasePath; 2677 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2678 FromLoc, FromRange, &BasePath)) 2679 return ExprError(); 2680 2681 if (PointerConversions) 2682 QType = Context.getPointerType(QType); 2683 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2684 VK, &BasePath).get(); 2685 2686 FromType = QType; 2687 FromRecordType = QRecordType; 2688 2689 // If the qualifier type was the same as the destination type, 2690 // we're done. 2691 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2692 return From; 2693 } 2694 } 2695 2696 bool IgnoreAccess = false; 2697 2698 // If we actually found the member through a using declaration, cast 2699 // down to the using declaration's type. 2700 // 2701 // Pointer equality is fine here because only one declaration of a 2702 // class ever has member declarations. 2703 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2704 assert(isa<UsingShadowDecl>(FoundDecl)); 2705 QualType URecordType = Context.getTypeDeclType( 2706 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2707 2708 // We only need to do this if the naming-class to declaring-class 2709 // conversion is non-trivial. 2710 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2711 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2712 CXXCastPath BasePath; 2713 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2714 FromLoc, FromRange, &BasePath)) 2715 return ExprError(); 2716 2717 QualType UType = URecordType; 2718 if (PointerConversions) 2719 UType = Context.getPointerType(UType); 2720 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2721 VK, &BasePath).get(); 2722 FromType = UType; 2723 FromRecordType = URecordType; 2724 } 2725 2726 // We don't do access control for the conversion from the 2727 // declaring class to the true declaring class. 2728 IgnoreAccess = true; 2729 } 2730 2731 CXXCastPath BasePath; 2732 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2733 FromLoc, FromRange, &BasePath, 2734 IgnoreAccess)) 2735 return ExprError(); 2736 2737 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2738 VK, &BasePath); 2739 } 2740 2741 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2742 const LookupResult &R, 2743 bool HasTrailingLParen) { 2744 // Only when used directly as the postfix-expression of a call. 2745 if (!HasTrailingLParen) 2746 return false; 2747 2748 // Never if a scope specifier was provided. 2749 if (SS.isSet()) 2750 return false; 2751 2752 // Only in C++ or ObjC++. 2753 if (!getLangOpts().CPlusPlus) 2754 return false; 2755 2756 // Turn off ADL when we find certain kinds of declarations during 2757 // normal lookup: 2758 for (NamedDecl *D : R) { 2759 // C++0x [basic.lookup.argdep]p3: 2760 // -- a declaration of a class member 2761 // Since using decls preserve this property, we check this on the 2762 // original decl. 2763 if (D->isCXXClassMember()) 2764 return false; 2765 2766 // C++0x [basic.lookup.argdep]p3: 2767 // -- a block-scope function declaration that is not a 2768 // using-declaration 2769 // NOTE: we also trigger this for function templates (in fact, we 2770 // don't check the decl type at all, since all other decl types 2771 // turn off ADL anyway). 2772 if (isa<UsingShadowDecl>(D)) 2773 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2774 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2775 return false; 2776 2777 // C++0x [basic.lookup.argdep]p3: 2778 // -- a declaration that is neither a function or a function 2779 // template 2780 // And also for builtin functions. 2781 if (isa<FunctionDecl>(D)) { 2782 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2783 2784 // But also builtin functions. 2785 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2786 return false; 2787 } else if (!isa<FunctionTemplateDecl>(D)) 2788 return false; 2789 } 2790 2791 return true; 2792 } 2793 2794 2795 /// Diagnoses obvious problems with the use of the given declaration 2796 /// as an expression. This is only actually called for lookups that 2797 /// were not overloaded, and it doesn't promise that the declaration 2798 /// will in fact be used. 2799 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2800 if (D->isInvalidDecl()) 2801 return true; 2802 2803 if (isa<TypedefNameDecl>(D)) { 2804 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2805 return true; 2806 } 2807 2808 if (isa<ObjCInterfaceDecl>(D)) { 2809 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2810 return true; 2811 } 2812 2813 if (isa<NamespaceDecl>(D)) { 2814 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2815 return true; 2816 } 2817 2818 return false; 2819 } 2820 2821 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2822 LookupResult &R, bool NeedsADL, 2823 bool AcceptInvalidDecl) { 2824 // If this is a single, fully-resolved result and we don't need ADL, 2825 // just build an ordinary singleton decl ref. 2826 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2827 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2828 R.getRepresentativeDecl(), nullptr, 2829 AcceptInvalidDecl); 2830 2831 // We only need to check the declaration if there's exactly one 2832 // result, because in the overloaded case the results can only be 2833 // functions and function templates. 2834 if (R.isSingleResult() && 2835 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2836 return ExprError(); 2837 2838 // Otherwise, just build an unresolved lookup expression. Suppress 2839 // any lookup-related diagnostics; we'll hash these out later, when 2840 // we've picked a target. 2841 R.suppressDiagnostics(); 2842 2843 UnresolvedLookupExpr *ULE 2844 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2845 SS.getWithLocInContext(Context), 2846 R.getLookupNameInfo(), 2847 NeedsADL, R.isOverloadedResult(), 2848 R.begin(), R.end()); 2849 2850 return ULE; 2851 } 2852 2853 static void 2854 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 2855 ValueDecl *var, DeclContext *DC); 2856 2857 /// \brief Complete semantic analysis for a reference to the given declaration. 2858 ExprResult Sema::BuildDeclarationNameExpr( 2859 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2860 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2861 bool AcceptInvalidDecl) { 2862 assert(D && "Cannot refer to a NULL declaration"); 2863 assert(!isa<FunctionTemplateDecl>(D) && 2864 "Cannot refer unambiguously to a function template"); 2865 2866 SourceLocation Loc = NameInfo.getLoc(); 2867 if (CheckDeclInExpr(*this, Loc, D)) 2868 return ExprError(); 2869 2870 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2871 // Specifically diagnose references to class templates that are missing 2872 // a template argument list. 2873 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2874 << Template << SS.getRange(); 2875 Diag(Template->getLocation(), diag::note_template_decl_here); 2876 return ExprError(); 2877 } 2878 2879 // Make sure that we're referring to a value. 2880 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2881 if (!VD) { 2882 Diag(Loc, diag::err_ref_non_value) 2883 << D << SS.getRange(); 2884 Diag(D->getLocation(), diag::note_declared_at); 2885 return ExprError(); 2886 } 2887 2888 // Check whether this declaration can be used. Note that we suppress 2889 // this check when we're going to perform argument-dependent lookup 2890 // on this function name, because this might not be the function 2891 // that overload resolution actually selects. 2892 if (DiagnoseUseOfDecl(VD, Loc)) 2893 return ExprError(); 2894 2895 // Only create DeclRefExpr's for valid Decl's. 2896 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2897 return ExprError(); 2898 2899 // Handle members of anonymous structs and unions. If we got here, 2900 // and the reference is to a class member indirect field, then this 2901 // must be the subject of a pointer-to-member expression. 2902 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2903 if (!indirectField->isCXXClassMember()) 2904 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2905 indirectField); 2906 2907 { 2908 QualType type = VD->getType(); 2909 if (auto *FPT = type->getAs<FunctionProtoType>()) { 2910 // C++ [except.spec]p17: 2911 // An exception-specification is considered to be needed when: 2912 // - in an expression, the function is the unique lookup result or 2913 // the selected member of a set of overloaded functions. 2914 ResolveExceptionSpec(Loc, FPT); 2915 type = VD->getType(); 2916 } 2917 ExprValueKind valueKind = VK_RValue; 2918 2919 switch (D->getKind()) { 2920 // Ignore all the non-ValueDecl kinds. 2921 #define ABSTRACT_DECL(kind) 2922 #define VALUE(type, base) 2923 #define DECL(type, base) \ 2924 case Decl::type: 2925 #include "clang/AST/DeclNodes.inc" 2926 llvm_unreachable("invalid value decl kind"); 2927 2928 // These shouldn't make it here. 2929 case Decl::ObjCAtDefsField: 2930 case Decl::ObjCIvar: 2931 llvm_unreachable("forming non-member reference to ivar?"); 2932 2933 // Enum constants are always r-values and never references. 2934 // Unresolved using declarations are dependent. 2935 case Decl::EnumConstant: 2936 case Decl::UnresolvedUsingValue: 2937 case Decl::OMPDeclareReduction: 2938 valueKind = VK_RValue; 2939 break; 2940 2941 // Fields and indirect fields that got here must be for 2942 // pointer-to-member expressions; we just call them l-values for 2943 // internal consistency, because this subexpression doesn't really 2944 // exist in the high-level semantics. 2945 case Decl::Field: 2946 case Decl::IndirectField: 2947 assert(getLangOpts().CPlusPlus && 2948 "building reference to field in C?"); 2949 2950 // These can't have reference type in well-formed programs, but 2951 // for internal consistency we do this anyway. 2952 type = type.getNonReferenceType(); 2953 valueKind = VK_LValue; 2954 break; 2955 2956 // Non-type template parameters are either l-values or r-values 2957 // depending on the type. 2958 case Decl::NonTypeTemplateParm: { 2959 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2960 type = reftype->getPointeeType(); 2961 valueKind = VK_LValue; // even if the parameter is an r-value reference 2962 break; 2963 } 2964 2965 // For non-references, we need to strip qualifiers just in case 2966 // the template parameter was declared as 'const int' or whatever. 2967 valueKind = VK_RValue; 2968 type = type.getUnqualifiedType(); 2969 break; 2970 } 2971 2972 case Decl::Var: 2973 case Decl::VarTemplateSpecialization: 2974 case Decl::VarTemplatePartialSpecialization: 2975 case Decl::Decomposition: 2976 case Decl::OMPCapturedExpr: 2977 // In C, "extern void blah;" is valid and is an r-value. 2978 if (!getLangOpts().CPlusPlus && 2979 !type.hasQualifiers() && 2980 type->isVoidType()) { 2981 valueKind = VK_RValue; 2982 break; 2983 } 2984 // fallthrough 2985 2986 case Decl::ImplicitParam: 2987 case Decl::ParmVar: { 2988 // These are always l-values. 2989 valueKind = VK_LValue; 2990 type = type.getNonReferenceType(); 2991 2992 // FIXME: Does the addition of const really only apply in 2993 // potentially-evaluated contexts? Since the variable isn't actually 2994 // captured in an unevaluated context, it seems that the answer is no. 2995 if (!isUnevaluatedContext()) { 2996 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2997 if (!CapturedType.isNull()) 2998 type = CapturedType; 2999 } 3000 3001 break; 3002 } 3003 3004 case Decl::Binding: { 3005 // These are always lvalues. 3006 valueKind = VK_LValue; 3007 type = type.getNonReferenceType(); 3008 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3009 // decides how that's supposed to work. 3010 auto *BD = cast<BindingDecl>(VD); 3011 if (BD->getDeclContext()->isFunctionOrMethod() && 3012 BD->getDeclContext() != CurContext) 3013 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 3014 break; 3015 } 3016 3017 case Decl::Function: { 3018 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3019 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3020 type = Context.BuiltinFnTy; 3021 valueKind = VK_RValue; 3022 break; 3023 } 3024 } 3025 3026 const FunctionType *fty = type->castAs<FunctionType>(); 3027 3028 // If we're referring to a function with an __unknown_anytype 3029 // result type, make the entire expression __unknown_anytype. 3030 if (fty->getReturnType() == Context.UnknownAnyTy) { 3031 type = Context.UnknownAnyTy; 3032 valueKind = VK_RValue; 3033 break; 3034 } 3035 3036 // Functions are l-values in C++. 3037 if (getLangOpts().CPlusPlus) { 3038 valueKind = VK_LValue; 3039 break; 3040 } 3041 3042 // C99 DR 316 says that, if a function type comes from a 3043 // function definition (without a prototype), that type is only 3044 // used for checking compatibility. Therefore, when referencing 3045 // the function, we pretend that we don't have the full function 3046 // type. 3047 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3048 isa<FunctionProtoType>(fty)) 3049 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3050 fty->getExtInfo()); 3051 3052 // Functions are r-values in C. 3053 valueKind = VK_RValue; 3054 break; 3055 } 3056 3057 case Decl::CXXDeductionGuide: 3058 llvm_unreachable("building reference to deduction guide"); 3059 3060 case Decl::MSProperty: 3061 valueKind = VK_LValue; 3062 break; 3063 3064 case Decl::CXXMethod: 3065 // If we're referring to a method with an __unknown_anytype 3066 // result type, make the entire expression __unknown_anytype. 3067 // This should only be possible with a type written directly. 3068 if (const FunctionProtoType *proto 3069 = dyn_cast<FunctionProtoType>(VD->getType())) 3070 if (proto->getReturnType() == Context.UnknownAnyTy) { 3071 type = Context.UnknownAnyTy; 3072 valueKind = VK_RValue; 3073 break; 3074 } 3075 3076 // C++ methods are l-values if static, r-values if non-static. 3077 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3078 valueKind = VK_LValue; 3079 break; 3080 } 3081 // fallthrough 3082 3083 case Decl::CXXConversion: 3084 case Decl::CXXDestructor: 3085 case Decl::CXXConstructor: 3086 valueKind = VK_RValue; 3087 break; 3088 } 3089 3090 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3091 TemplateArgs); 3092 } 3093 } 3094 3095 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3096 SmallString<32> &Target) { 3097 Target.resize(CharByteWidth * (Source.size() + 1)); 3098 char *ResultPtr = &Target[0]; 3099 const llvm::UTF8 *ErrorPtr; 3100 bool success = 3101 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3102 (void)success; 3103 assert(success); 3104 Target.resize(ResultPtr - &Target[0]); 3105 } 3106 3107 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3108 PredefinedExpr::IdentType IT) { 3109 // Pick the current block, lambda, captured statement or function. 3110 Decl *currentDecl = nullptr; 3111 if (const BlockScopeInfo *BSI = getCurBlock()) 3112 currentDecl = BSI->TheDecl; 3113 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3114 currentDecl = LSI->CallOperator; 3115 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3116 currentDecl = CSI->TheCapturedDecl; 3117 else 3118 currentDecl = getCurFunctionOrMethodDecl(); 3119 3120 if (!currentDecl) { 3121 Diag(Loc, diag::ext_predef_outside_function); 3122 currentDecl = Context.getTranslationUnitDecl(); 3123 } 3124 3125 QualType ResTy; 3126 StringLiteral *SL = nullptr; 3127 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3128 ResTy = Context.DependentTy; 3129 else { 3130 // Pre-defined identifiers are of type char[x], where x is the length of 3131 // the string. 3132 auto Str = PredefinedExpr::ComputeName(IT, currentDecl); 3133 unsigned Length = Str.length(); 3134 3135 llvm::APInt LengthI(32, Length + 1); 3136 if (IT == PredefinedExpr::LFunction) { 3137 ResTy = Context.WideCharTy.withConst(); 3138 SmallString<32> RawChars; 3139 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3140 Str, RawChars); 3141 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3142 /*IndexTypeQuals*/ 0); 3143 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3144 /*Pascal*/ false, ResTy, Loc); 3145 } else { 3146 ResTy = Context.CharTy.withConst(); 3147 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3148 /*IndexTypeQuals*/ 0); 3149 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3150 /*Pascal*/ false, ResTy, Loc); 3151 } 3152 } 3153 3154 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL); 3155 } 3156 3157 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3158 PredefinedExpr::IdentType IT; 3159 3160 switch (Kind) { 3161 default: llvm_unreachable("Unknown simple primary expr!"); 3162 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3163 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 3164 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 3165 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS] 3166 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 3167 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 3168 } 3169 3170 return BuildPredefinedExpr(Loc, IT); 3171 } 3172 3173 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3174 SmallString<16> CharBuffer; 3175 bool Invalid = false; 3176 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3177 if (Invalid) 3178 return ExprError(); 3179 3180 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3181 PP, Tok.getKind()); 3182 if (Literal.hadError()) 3183 return ExprError(); 3184 3185 QualType Ty; 3186 if (Literal.isWide()) 3187 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3188 else if (Literal.isUTF16()) 3189 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3190 else if (Literal.isUTF32()) 3191 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3192 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3193 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3194 else 3195 Ty = Context.CharTy; // 'x' -> char in C++ 3196 3197 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3198 if (Literal.isWide()) 3199 Kind = CharacterLiteral::Wide; 3200 else if (Literal.isUTF16()) 3201 Kind = CharacterLiteral::UTF16; 3202 else if (Literal.isUTF32()) 3203 Kind = CharacterLiteral::UTF32; 3204 else if (Literal.isUTF8()) 3205 Kind = CharacterLiteral::UTF8; 3206 3207 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3208 Tok.getLocation()); 3209 3210 if (Literal.getUDSuffix().empty()) 3211 return Lit; 3212 3213 // We're building a user-defined literal. 3214 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3215 SourceLocation UDSuffixLoc = 3216 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3217 3218 // Make sure we're allowed user-defined literals here. 3219 if (!UDLScope) 3220 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3221 3222 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3223 // operator "" X (ch) 3224 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3225 Lit, Tok.getLocation()); 3226 } 3227 3228 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3229 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3230 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3231 Context.IntTy, Loc); 3232 } 3233 3234 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3235 QualType Ty, SourceLocation Loc) { 3236 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3237 3238 using llvm::APFloat; 3239 APFloat Val(Format); 3240 3241 APFloat::opStatus result = Literal.GetFloatValue(Val); 3242 3243 // Overflow is always an error, but underflow is only an error if 3244 // we underflowed to zero (APFloat reports denormals as underflow). 3245 if ((result & APFloat::opOverflow) || 3246 ((result & APFloat::opUnderflow) && Val.isZero())) { 3247 unsigned diagnostic; 3248 SmallString<20> buffer; 3249 if (result & APFloat::opOverflow) { 3250 diagnostic = diag::warn_float_overflow; 3251 APFloat::getLargest(Format).toString(buffer); 3252 } else { 3253 diagnostic = diag::warn_float_underflow; 3254 APFloat::getSmallest(Format).toString(buffer); 3255 } 3256 3257 S.Diag(Loc, diagnostic) 3258 << Ty 3259 << StringRef(buffer.data(), buffer.size()); 3260 } 3261 3262 bool isExact = (result == APFloat::opOK); 3263 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3264 } 3265 3266 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3267 assert(E && "Invalid expression"); 3268 3269 if (E->isValueDependent()) 3270 return false; 3271 3272 QualType QT = E->getType(); 3273 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3274 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3275 return true; 3276 } 3277 3278 llvm::APSInt ValueAPS; 3279 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3280 3281 if (R.isInvalid()) 3282 return true; 3283 3284 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3285 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3286 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3287 << ValueAPS.toString(10) << ValueIsPositive; 3288 return true; 3289 } 3290 3291 return false; 3292 } 3293 3294 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3295 // Fast path for a single digit (which is quite common). A single digit 3296 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3297 if (Tok.getLength() == 1) { 3298 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3299 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3300 } 3301 3302 SmallString<128> SpellingBuffer; 3303 // NumericLiteralParser wants to overread by one character. Add padding to 3304 // the buffer in case the token is copied to the buffer. If getSpelling() 3305 // returns a StringRef to the memory buffer, it should have a null char at 3306 // the EOF, so it is also safe. 3307 SpellingBuffer.resize(Tok.getLength() + 1); 3308 3309 // Get the spelling of the token, which eliminates trigraphs, etc. 3310 bool Invalid = false; 3311 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3312 if (Invalid) 3313 return ExprError(); 3314 3315 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3316 if (Literal.hadError) 3317 return ExprError(); 3318 3319 if (Literal.hasUDSuffix()) { 3320 // We're building a user-defined literal. 3321 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3322 SourceLocation UDSuffixLoc = 3323 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3324 3325 // Make sure we're allowed user-defined literals here. 3326 if (!UDLScope) 3327 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3328 3329 QualType CookedTy; 3330 if (Literal.isFloatingLiteral()) { 3331 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3332 // long double, the literal is treated as a call of the form 3333 // operator "" X (f L) 3334 CookedTy = Context.LongDoubleTy; 3335 } else { 3336 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3337 // unsigned long long, the literal is treated as a call of the form 3338 // operator "" X (n ULL) 3339 CookedTy = Context.UnsignedLongLongTy; 3340 } 3341 3342 DeclarationName OpName = 3343 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3344 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3345 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3346 3347 SourceLocation TokLoc = Tok.getLocation(); 3348 3349 // Perform literal operator lookup to determine if we're building a raw 3350 // literal or a cooked one. 3351 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3352 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3353 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3354 /*AllowStringTemplate*/ false, 3355 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3356 case LOLR_ErrorNoDiagnostic: 3357 // Lookup failure for imaginary constants isn't fatal, there's still the 3358 // GNU extension producing _Complex types. 3359 break; 3360 case LOLR_Error: 3361 return ExprError(); 3362 case LOLR_Cooked: { 3363 Expr *Lit; 3364 if (Literal.isFloatingLiteral()) { 3365 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3366 } else { 3367 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3368 if (Literal.GetIntegerValue(ResultVal)) 3369 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3370 << /* Unsigned */ 1; 3371 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3372 Tok.getLocation()); 3373 } 3374 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3375 } 3376 3377 case LOLR_Raw: { 3378 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3379 // literal is treated as a call of the form 3380 // operator "" X ("n") 3381 unsigned Length = Literal.getUDSuffixOffset(); 3382 QualType StrTy = Context.getConstantArrayType( 3383 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 3384 ArrayType::Normal, 0); 3385 Expr *Lit = StringLiteral::Create( 3386 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3387 /*Pascal*/false, StrTy, &TokLoc, 1); 3388 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3389 } 3390 3391 case LOLR_Template: { 3392 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3393 // template), L is treated as a call fo the form 3394 // operator "" X <'c1', 'c2', ... 'ck'>() 3395 // where n is the source character sequence c1 c2 ... ck. 3396 TemplateArgumentListInfo ExplicitArgs; 3397 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3398 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3399 llvm::APSInt Value(CharBits, CharIsUnsigned); 3400 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3401 Value = TokSpelling[I]; 3402 TemplateArgument Arg(Context, Value, Context.CharTy); 3403 TemplateArgumentLocInfo ArgInfo; 3404 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3405 } 3406 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3407 &ExplicitArgs); 3408 } 3409 case LOLR_StringTemplate: 3410 llvm_unreachable("unexpected literal operator lookup result"); 3411 } 3412 } 3413 3414 Expr *Res; 3415 3416 if (Literal.isFloatingLiteral()) { 3417 QualType Ty; 3418 if (Literal.isHalf){ 3419 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3420 Ty = Context.HalfTy; 3421 else { 3422 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3423 return ExprError(); 3424 } 3425 } else if (Literal.isFloat) 3426 Ty = Context.FloatTy; 3427 else if (Literal.isLong) 3428 Ty = Context.LongDoubleTy; 3429 else if (Literal.isFloat128) 3430 Ty = Context.Float128Ty; 3431 else 3432 Ty = Context.DoubleTy; 3433 3434 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3435 3436 if (Ty == Context.DoubleTy) { 3437 if (getLangOpts().SinglePrecisionConstants) { 3438 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3439 if (BTy->getKind() != BuiltinType::Float) { 3440 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3441 } 3442 } else if (getLangOpts().OpenCL && 3443 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3444 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3445 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3446 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3447 } 3448 } 3449 } else if (!Literal.isIntegerLiteral()) { 3450 return ExprError(); 3451 } else { 3452 QualType Ty; 3453 3454 // 'long long' is a C99 or C++11 feature. 3455 if (!getLangOpts().C99 && Literal.isLongLong) { 3456 if (getLangOpts().CPlusPlus) 3457 Diag(Tok.getLocation(), 3458 getLangOpts().CPlusPlus11 ? 3459 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3460 else 3461 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3462 } 3463 3464 // Get the value in the widest-possible width. 3465 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3466 llvm::APInt ResultVal(MaxWidth, 0); 3467 3468 if (Literal.GetIntegerValue(ResultVal)) { 3469 // If this value didn't fit into uintmax_t, error and force to ull. 3470 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3471 << /* Unsigned */ 1; 3472 Ty = Context.UnsignedLongLongTy; 3473 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3474 "long long is not intmax_t?"); 3475 } else { 3476 // If this value fits into a ULL, try to figure out what else it fits into 3477 // according to the rules of C99 6.4.4.1p5. 3478 3479 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3480 // be an unsigned int. 3481 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3482 3483 // Check from smallest to largest, picking the smallest type we can. 3484 unsigned Width = 0; 3485 3486 // Microsoft specific integer suffixes are explicitly sized. 3487 if (Literal.MicrosoftInteger) { 3488 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3489 Width = 8; 3490 Ty = Context.CharTy; 3491 } else { 3492 Width = Literal.MicrosoftInteger; 3493 Ty = Context.getIntTypeForBitwidth(Width, 3494 /*Signed=*/!Literal.isUnsigned); 3495 } 3496 } 3497 3498 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3499 // Are int/unsigned possibilities? 3500 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3501 3502 // Does it fit in a unsigned int? 3503 if (ResultVal.isIntN(IntSize)) { 3504 // Does it fit in a signed int? 3505 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3506 Ty = Context.IntTy; 3507 else if (AllowUnsigned) 3508 Ty = Context.UnsignedIntTy; 3509 Width = IntSize; 3510 } 3511 } 3512 3513 // Are long/unsigned long possibilities? 3514 if (Ty.isNull() && !Literal.isLongLong) { 3515 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3516 3517 // Does it fit in a unsigned long? 3518 if (ResultVal.isIntN(LongSize)) { 3519 // Does it fit in a signed long? 3520 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3521 Ty = Context.LongTy; 3522 else if (AllowUnsigned) 3523 Ty = Context.UnsignedLongTy; 3524 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3525 // is compatible. 3526 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3527 const unsigned LongLongSize = 3528 Context.getTargetInfo().getLongLongWidth(); 3529 Diag(Tok.getLocation(), 3530 getLangOpts().CPlusPlus 3531 ? Literal.isLong 3532 ? diag::warn_old_implicitly_unsigned_long_cxx 3533 : /*C++98 UB*/ diag:: 3534 ext_old_implicitly_unsigned_long_cxx 3535 : diag::warn_old_implicitly_unsigned_long) 3536 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3537 : /*will be ill-formed*/ 1); 3538 Ty = Context.UnsignedLongTy; 3539 } 3540 Width = LongSize; 3541 } 3542 } 3543 3544 // Check long long if needed. 3545 if (Ty.isNull()) { 3546 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3547 3548 // Does it fit in a unsigned long long? 3549 if (ResultVal.isIntN(LongLongSize)) { 3550 // Does it fit in a signed long long? 3551 // To be compatible with MSVC, hex integer literals ending with the 3552 // LL or i64 suffix are always signed in Microsoft mode. 3553 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3554 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3555 Ty = Context.LongLongTy; 3556 else if (AllowUnsigned) 3557 Ty = Context.UnsignedLongLongTy; 3558 Width = LongLongSize; 3559 } 3560 } 3561 3562 // If we still couldn't decide a type, we probably have something that 3563 // does not fit in a signed long long, but has no U suffix. 3564 if (Ty.isNull()) { 3565 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3566 Ty = Context.UnsignedLongLongTy; 3567 Width = Context.getTargetInfo().getLongLongWidth(); 3568 } 3569 3570 if (ResultVal.getBitWidth() != Width) 3571 ResultVal = ResultVal.trunc(Width); 3572 } 3573 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3574 } 3575 3576 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3577 if (Literal.isImaginary) { 3578 Res = new (Context) ImaginaryLiteral(Res, 3579 Context.getComplexType(Res->getType())); 3580 3581 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3582 } 3583 return Res; 3584 } 3585 3586 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3587 assert(E && "ActOnParenExpr() missing expr"); 3588 return new (Context) ParenExpr(L, R, E); 3589 } 3590 3591 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3592 SourceLocation Loc, 3593 SourceRange ArgRange) { 3594 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3595 // scalar or vector data type argument..." 3596 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3597 // type (C99 6.2.5p18) or void. 3598 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3599 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3600 << T << ArgRange; 3601 return true; 3602 } 3603 3604 assert((T->isVoidType() || !T->isIncompleteType()) && 3605 "Scalar types should always be complete"); 3606 return false; 3607 } 3608 3609 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3610 SourceLocation Loc, 3611 SourceRange ArgRange, 3612 UnaryExprOrTypeTrait TraitKind) { 3613 // Invalid types must be hard errors for SFINAE in C++. 3614 if (S.LangOpts.CPlusPlus) 3615 return true; 3616 3617 // C99 6.5.3.4p1: 3618 if (T->isFunctionType() && 3619 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3620 // sizeof(function)/alignof(function) is allowed as an extension. 3621 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3622 << TraitKind << ArgRange; 3623 return false; 3624 } 3625 3626 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3627 // this is an error (OpenCL v1.1 s6.3.k) 3628 if (T->isVoidType()) { 3629 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3630 : diag::ext_sizeof_alignof_void_type; 3631 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3632 return false; 3633 } 3634 3635 return true; 3636 } 3637 3638 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3639 SourceLocation Loc, 3640 SourceRange ArgRange, 3641 UnaryExprOrTypeTrait TraitKind) { 3642 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3643 // runtime doesn't allow it. 3644 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3645 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3646 << T << (TraitKind == UETT_SizeOf) 3647 << ArgRange; 3648 return true; 3649 } 3650 3651 return false; 3652 } 3653 3654 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3655 /// pointer type is equal to T) and emit a warning if it is. 3656 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3657 Expr *E) { 3658 // Don't warn if the operation changed the type. 3659 if (T != E->getType()) 3660 return; 3661 3662 // Now look for array decays. 3663 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3664 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3665 return; 3666 3667 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3668 << ICE->getType() 3669 << ICE->getSubExpr()->getType(); 3670 } 3671 3672 /// \brief Check the constraints on expression operands to unary type expression 3673 /// and type traits. 3674 /// 3675 /// Completes any types necessary and validates the constraints on the operand 3676 /// expression. The logic mostly mirrors the type-based overload, but may modify 3677 /// the expression as it completes the type for that expression through template 3678 /// instantiation, etc. 3679 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3680 UnaryExprOrTypeTrait ExprKind) { 3681 QualType ExprTy = E->getType(); 3682 assert(!ExprTy->isReferenceType()); 3683 3684 if (ExprKind == UETT_VecStep) 3685 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3686 E->getSourceRange()); 3687 3688 // Whitelist some types as extensions 3689 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3690 E->getSourceRange(), ExprKind)) 3691 return false; 3692 3693 // 'alignof' applied to an expression only requires the base element type of 3694 // the expression to be complete. 'sizeof' requires the expression's type to 3695 // be complete (and will attempt to complete it if it's an array of unknown 3696 // bound). 3697 if (ExprKind == UETT_AlignOf) { 3698 if (RequireCompleteType(E->getExprLoc(), 3699 Context.getBaseElementType(E->getType()), 3700 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3701 E->getSourceRange())) 3702 return true; 3703 } else { 3704 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3705 ExprKind, E->getSourceRange())) 3706 return true; 3707 } 3708 3709 // Completing the expression's type may have changed it. 3710 ExprTy = E->getType(); 3711 assert(!ExprTy->isReferenceType()); 3712 3713 if (ExprTy->isFunctionType()) { 3714 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3715 << ExprKind << E->getSourceRange(); 3716 return true; 3717 } 3718 3719 // The operand for sizeof and alignof is in an unevaluated expression context, 3720 // so side effects could result in unintended consequences. 3721 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) && 3722 !inTemplateInstantiation() && E->HasSideEffects(Context, false)) 3723 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3724 3725 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3726 E->getSourceRange(), ExprKind)) 3727 return true; 3728 3729 if (ExprKind == UETT_SizeOf) { 3730 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3731 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3732 QualType OType = PVD->getOriginalType(); 3733 QualType Type = PVD->getType(); 3734 if (Type->isPointerType() && OType->isArrayType()) { 3735 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3736 << Type << OType; 3737 Diag(PVD->getLocation(), diag::note_declared_at); 3738 } 3739 } 3740 } 3741 3742 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3743 // decays into a pointer and returns an unintended result. This is most 3744 // likely a typo for "sizeof(array) op x". 3745 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3746 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3747 BO->getLHS()); 3748 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3749 BO->getRHS()); 3750 } 3751 } 3752 3753 return false; 3754 } 3755 3756 /// \brief Check the constraints on operands to unary expression and type 3757 /// traits. 3758 /// 3759 /// This will complete any types necessary, and validate the various constraints 3760 /// on those operands. 3761 /// 3762 /// The UsualUnaryConversions() function is *not* called by this routine. 3763 /// C99 6.3.2.1p[2-4] all state: 3764 /// Except when it is the operand of the sizeof operator ... 3765 /// 3766 /// C++ [expr.sizeof]p4 3767 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3768 /// standard conversions are not applied to the operand of sizeof. 3769 /// 3770 /// This policy is followed for all of the unary trait expressions. 3771 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3772 SourceLocation OpLoc, 3773 SourceRange ExprRange, 3774 UnaryExprOrTypeTrait ExprKind) { 3775 if (ExprType->isDependentType()) 3776 return false; 3777 3778 // C++ [expr.sizeof]p2: 3779 // When applied to a reference or a reference type, the result 3780 // is the size of the referenced type. 3781 // C++11 [expr.alignof]p3: 3782 // When alignof is applied to a reference type, the result 3783 // shall be the alignment of the referenced type. 3784 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3785 ExprType = Ref->getPointeeType(); 3786 3787 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3788 // When alignof or _Alignof is applied to an array type, the result 3789 // is the alignment of the element type. 3790 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign) 3791 ExprType = Context.getBaseElementType(ExprType); 3792 3793 if (ExprKind == UETT_VecStep) 3794 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3795 3796 // Whitelist some types as extensions 3797 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3798 ExprKind)) 3799 return false; 3800 3801 if (RequireCompleteType(OpLoc, ExprType, 3802 diag::err_sizeof_alignof_incomplete_type, 3803 ExprKind, ExprRange)) 3804 return true; 3805 3806 if (ExprType->isFunctionType()) { 3807 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3808 << ExprKind << ExprRange; 3809 return true; 3810 } 3811 3812 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3813 ExprKind)) 3814 return true; 3815 3816 return false; 3817 } 3818 3819 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3820 E = E->IgnoreParens(); 3821 3822 // Cannot know anything else if the expression is dependent. 3823 if (E->isTypeDependent()) 3824 return false; 3825 3826 if (E->getObjectKind() == OK_BitField) { 3827 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3828 << 1 << E->getSourceRange(); 3829 return true; 3830 } 3831 3832 ValueDecl *D = nullptr; 3833 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3834 D = DRE->getDecl(); 3835 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3836 D = ME->getMemberDecl(); 3837 } 3838 3839 // If it's a field, require the containing struct to have a 3840 // complete definition so that we can compute the layout. 3841 // 3842 // This can happen in C++11 onwards, either by naming the member 3843 // in a way that is not transformed into a member access expression 3844 // (in an unevaluated operand, for instance), or by naming the member 3845 // in a trailing-return-type. 3846 // 3847 // For the record, since __alignof__ on expressions is a GCC 3848 // extension, GCC seems to permit this but always gives the 3849 // nonsensical answer 0. 3850 // 3851 // We don't really need the layout here --- we could instead just 3852 // directly check for all the appropriate alignment-lowing 3853 // attributes --- but that would require duplicating a lot of 3854 // logic that just isn't worth duplicating for such a marginal 3855 // use-case. 3856 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3857 // Fast path this check, since we at least know the record has a 3858 // definition if we can find a member of it. 3859 if (!FD->getParent()->isCompleteDefinition()) { 3860 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3861 << E->getSourceRange(); 3862 return true; 3863 } 3864 3865 // Otherwise, if it's a field, and the field doesn't have 3866 // reference type, then it must have a complete type (or be a 3867 // flexible array member, which we explicitly want to 3868 // white-list anyway), which makes the following checks trivial. 3869 if (!FD->getType()->isReferenceType()) 3870 return false; 3871 } 3872 3873 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3874 } 3875 3876 bool Sema::CheckVecStepExpr(Expr *E) { 3877 E = E->IgnoreParens(); 3878 3879 // Cannot know anything else if the expression is dependent. 3880 if (E->isTypeDependent()) 3881 return false; 3882 3883 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3884 } 3885 3886 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 3887 CapturingScopeInfo *CSI) { 3888 assert(T->isVariablyModifiedType()); 3889 assert(CSI != nullptr); 3890 3891 // We're going to walk down into the type and look for VLA expressions. 3892 do { 3893 const Type *Ty = T.getTypePtr(); 3894 switch (Ty->getTypeClass()) { 3895 #define TYPE(Class, Base) 3896 #define ABSTRACT_TYPE(Class, Base) 3897 #define NON_CANONICAL_TYPE(Class, Base) 3898 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 3899 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 3900 #include "clang/AST/TypeNodes.def" 3901 T = QualType(); 3902 break; 3903 // These types are never variably-modified. 3904 case Type::Builtin: 3905 case Type::Complex: 3906 case Type::Vector: 3907 case Type::ExtVector: 3908 case Type::Record: 3909 case Type::Enum: 3910 case Type::Elaborated: 3911 case Type::TemplateSpecialization: 3912 case Type::ObjCObject: 3913 case Type::ObjCInterface: 3914 case Type::ObjCObjectPointer: 3915 case Type::ObjCTypeParam: 3916 case Type::Pipe: 3917 llvm_unreachable("type class is never variably-modified!"); 3918 case Type::Adjusted: 3919 T = cast<AdjustedType>(Ty)->getOriginalType(); 3920 break; 3921 case Type::Decayed: 3922 T = cast<DecayedType>(Ty)->getPointeeType(); 3923 break; 3924 case Type::Pointer: 3925 T = cast<PointerType>(Ty)->getPointeeType(); 3926 break; 3927 case Type::BlockPointer: 3928 T = cast<BlockPointerType>(Ty)->getPointeeType(); 3929 break; 3930 case Type::LValueReference: 3931 case Type::RValueReference: 3932 T = cast<ReferenceType>(Ty)->getPointeeType(); 3933 break; 3934 case Type::MemberPointer: 3935 T = cast<MemberPointerType>(Ty)->getPointeeType(); 3936 break; 3937 case Type::ConstantArray: 3938 case Type::IncompleteArray: 3939 // Losing element qualification here is fine. 3940 T = cast<ArrayType>(Ty)->getElementType(); 3941 break; 3942 case Type::VariableArray: { 3943 // Losing element qualification here is fine. 3944 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 3945 3946 // Unknown size indication requires no size computation. 3947 // Otherwise, evaluate and record it. 3948 if (auto Size = VAT->getSizeExpr()) { 3949 if (!CSI->isVLATypeCaptured(VAT)) { 3950 RecordDecl *CapRecord = nullptr; 3951 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 3952 CapRecord = LSI->Lambda; 3953 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 3954 CapRecord = CRSI->TheRecordDecl; 3955 } 3956 if (CapRecord) { 3957 auto ExprLoc = Size->getExprLoc(); 3958 auto SizeType = Context.getSizeType(); 3959 // Build the non-static data member. 3960 auto Field = 3961 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc, 3962 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 3963 /*BW*/ nullptr, /*Mutable*/ false, 3964 /*InitStyle*/ ICIS_NoInit); 3965 Field->setImplicit(true); 3966 Field->setAccess(AS_private); 3967 Field->setCapturedVLAType(VAT); 3968 CapRecord->addDecl(Field); 3969 3970 CSI->addVLATypeCapture(ExprLoc, SizeType); 3971 } 3972 } 3973 } 3974 T = VAT->getElementType(); 3975 break; 3976 } 3977 case Type::FunctionProto: 3978 case Type::FunctionNoProto: 3979 T = cast<FunctionType>(Ty)->getReturnType(); 3980 break; 3981 case Type::Paren: 3982 case Type::TypeOf: 3983 case Type::UnaryTransform: 3984 case Type::Attributed: 3985 case Type::SubstTemplateTypeParm: 3986 case Type::PackExpansion: 3987 // Keep walking after single level desugaring. 3988 T = T.getSingleStepDesugaredType(Context); 3989 break; 3990 case Type::Typedef: 3991 T = cast<TypedefType>(Ty)->desugar(); 3992 break; 3993 case Type::Decltype: 3994 T = cast<DecltypeType>(Ty)->desugar(); 3995 break; 3996 case Type::Auto: 3997 case Type::DeducedTemplateSpecialization: 3998 T = cast<DeducedType>(Ty)->getDeducedType(); 3999 break; 4000 case Type::TypeOfExpr: 4001 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4002 break; 4003 case Type::Atomic: 4004 T = cast<AtomicType>(Ty)->getValueType(); 4005 break; 4006 } 4007 } while (!T.isNull() && T->isVariablyModifiedType()); 4008 } 4009 4010 /// \brief Build a sizeof or alignof expression given a type operand. 4011 ExprResult 4012 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4013 SourceLocation OpLoc, 4014 UnaryExprOrTypeTrait ExprKind, 4015 SourceRange R) { 4016 if (!TInfo) 4017 return ExprError(); 4018 4019 QualType T = TInfo->getType(); 4020 4021 if (!T->isDependentType() && 4022 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4023 return ExprError(); 4024 4025 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4026 if (auto *TT = T->getAs<TypedefType>()) { 4027 for (auto I = FunctionScopes.rbegin(), 4028 E = std::prev(FunctionScopes.rend()); 4029 I != E; ++I) { 4030 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4031 if (CSI == nullptr) 4032 break; 4033 DeclContext *DC = nullptr; 4034 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4035 DC = LSI->CallOperator; 4036 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4037 DC = CRSI->TheCapturedDecl; 4038 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4039 DC = BSI->TheDecl; 4040 if (DC) { 4041 if (DC->containsDecl(TT->getDecl())) 4042 break; 4043 captureVariablyModifiedType(Context, T, CSI); 4044 } 4045 } 4046 } 4047 } 4048 4049 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4050 return new (Context) UnaryExprOrTypeTraitExpr( 4051 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4052 } 4053 4054 /// \brief Build a sizeof or alignof expression given an expression 4055 /// operand. 4056 ExprResult 4057 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4058 UnaryExprOrTypeTrait ExprKind) { 4059 ExprResult PE = CheckPlaceholderExpr(E); 4060 if (PE.isInvalid()) 4061 return ExprError(); 4062 4063 E = PE.get(); 4064 4065 // Verify that the operand is valid. 4066 bool isInvalid = false; 4067 if (E->isTypeDependent()) { 4068 // Delay type-checking for type-dependent expressions. 4069 } else if (ExprKind == UETT_AlignOf) { 4070 isInvalid = CheckAlignOfExpr(*this, E); 4071 } else if (ExprKind == UETT_VecStep) { 4072 isInvalid = CheckVecStepExpr(E); 4073 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4074 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4075 isInvalid = true; 4076 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4077 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4078 isInvalid = true; 4079 } else { 4080 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4081 } 4082 4083 if (isInvalid) 4084 return ExprError(); 4085 4086 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4087 PE = TransformToPotentiallyEvaluated(E); 4088 if (PE.isInvalid()) return ExprError(); 4089 E = PE.get(); 4090 } 4091 4092 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4093 return new (Context) UnaryExprOrTypeTraitExpr( 4094 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4095 } 4096 4097 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4098 /// expr and the same for @c alignof and @c __alignof 4099 /// Note that the ArgRange is invalid if isType is false. 4100 ExprResult 4101 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4102 UnaryExprOrTypeTrait ExprKind, bool IsType, 4103 void *TyOrEx, SourceRange ArgRange) { 4104 // If error parsing type, ignore. 4105 if (!TyOrEx) return ExprError(); 4106 4107 if (IsType) { 4108 TypeSourceInfo *TInfo; 4109 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4110 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4111 } 4112 4113 Expr *ArgEx = (Expr *)TyOrEx; 4114 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4115 return Result; 4116 } 4117 4118 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4119 bool IsReal) { 4120 if (V.get()->isTypeDependent()) 4121 return S.Context.DependentTy; 4122 4123 // _Real and _Imag are only l-values for normal l-values. 4124 if (V.get()->getObjectKind() != OK_Ordinary) { 4125 V = S.DefaultLvalueConversion(V.get()); 4126 if (V.isInvalid()) 4127 return QualType(); 4128 } 4129 4130 // These operators return the element type of a complex type. 4131 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4132 return CT->getElementType(); 4133 4134 // Otherwise they pass through real integer and floating point types here. 4135 if (V.get()->getType()->isArithmeticType()) 4136 return V.get()->getType(); 4137 4138 // Test for placeholders. 4139 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4140 if (PR.isInvalid()) return QualType(); 4141 if (PR.get() != V.get()) { 4142 V = PR; 4143 return CheckRealImagOperand(S, V, Loc, IsReal); 4144 } 4145 4146 // Reject anything else. 4147 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4148 << (IsReal ? "__real" : "__imag"); 4149 return QualType(); 4150 } 4151 4152 4153 4154 ExprResult 4155 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4156 tok::TokenKind Kind, Expr *Input) { 4157 UnaryOperatorKind Opc; 4158 switch (Kind) { 4159 default: llvm_unreachable("Unknown unary op!"); 4160 case tok::plusplus: Opc = UO_PostInc; break; 4161 case tok::minusminus: Opc = UO_PostDec; break; 4162 } 4163 4164 // Since this might is a postfix expression, get rid of ParenListExprs. 4165 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4166 if (Result.isInvalid()) return ExprError(); 4167 Input = Result.get(); 4168 4169 return BuildUnaryOp(S, OpLoc, Opc, Input); 4170 } 4171 4172 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 4173 /// 4174 /// \return true on error 4175 static bool checkArithmeticOnObjCPointer(Sema &S, 4176 SourceLocation opLoc, 4177 Expr *op) { 4178 assert(op->getType()->isObjCObjectPointerType()); 4179 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4180 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4181 return false; 4182 4183 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4184 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4185 << op->getSourceRange(); 4186 return true; 4187 } 4188 4189 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4190 auto *BaseNoParens = Base->IgnoreParens(); 4191 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4192 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4193 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4194 } 4195 4196 ExprResult 4197 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4198 Expr *idx, SourceLocation rbLoc) { 4199 if (base && !base->getType().isNull() && 4200 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4201 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4202 /*Length=*/nullptr, rbLoc); 4203 4204 // Since this might be a postfix expression, get rid of ParenListExprs. 4205 if (isa<ParenListExpr>(base)) { 4206 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4207 if (result.isInvalid()) return ExprError(); 4208 base = result.get(); 4209 } 4210 4211 // Handle any non-overload placeholder types in the base and index 4212 // expressions. We can't handle overloads here because the other 4213 // operand might be an overloadable type, in which case the overload 4214 // resolution for the operator overload should get the first crack 4215 // at the overload. 4216 bool IsMSPropertySubscript = false; 4217 if (base->getType()->isNonOverloadPlaceholderType()) { 4218 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4219 if (!IsMSPropertySubscript) { 4220 ExprResult result = CheckPlaceholderExpr(base); 4221 if (result.isInvalid()) 4222 return ExprError(); 4223 base = result.get(); 4224 } 4225 } 4226 if (idx->getType()->isNonOverloadPlaceholderType()) { 4227 ExprResult result = CheckPlaceholderExpr(idx); 4228 if (result.isInvalid()) return ExprError(); 4229 idx = result.get(); 4230 } 4231 4232 // Build an unanalyzed expression if either operand is type-dependent. 4233 if (getLangOpts().CPlusPlus && 4234 (base->isTypeDependent() || idx->isTypeDependent())) { 4235 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4236 VK_LValue, OK_Ordinary, rbLoc); 4237 } 4238 4239 // MSDN, property (C++) 4240 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4241 // This attribute can also be used in the declaration of an empty array in a 4242 // class or structure definition. For example: 4243 // __declspec(property(get=GetX, put=PutX)) int x[]; 4244 // The above statement indicates that x[] can be used with one or more array 4245 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4246 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4247 if (IsMSPropertySubscript) { 4248 // Build MS property subscript expression if base is MS property reference 4249 // or MS property subscript. 4250 return new (Context) MSPropertySubscriptExpr( 4251 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4252 } 4253 4254 // Use C++ overloaded-operator rules if either operand has record 4255 // type. The spec says to do this if either type is *overloadable*, 4256 // but enum types can't declare subscript operators or conversion 4257 // operators, so there's nothing interesting for overload resolution 4258 // to do if there aren't any record types involved. 4259 // 4260 // ObjC pointers have their own subscripting logic that is not tied 4261 // to overload resolution and so should not take this path. 4262 if (getLangOpts().CPlusPlus && 4263 (base->getType()->isRecordType() || 4264 (!base->getType()->isObjCObjectPointerType() && 4265 idx->getType()->isRecordType()))) { 4266 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4267 } 4268 4269 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4270 } 4271 4272 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4273 Expr *LowerBound, 4274 SourceLocation ColonLoc, Expr *Length, 4275 SourceLocation RBLoc) { 4276 if (Base->getType()->isPlaceholderType() && 4277 !Base->getType()->isSpecificPlaceholderType( 4278 BuiltinType::OMPArraySection)) { 4279 ExprResult Result = CheckPlaceholderExpr(Base); 4280 if (Result.isInvalid()) 4281 return ExprError(); 4282 Base = Result.get(); 4283 } 4284 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4285 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4286 if (Result.isInvalid()) 4287 return ExprError(); 4288 Result = DefaultLvalueConversion(Result.get()); 4289 if (Result.isInvalid()) 4290 return ExprError(); 4291 LowerBound = Result.get(); 4292 } 4293 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4294 ExprResult Result = CheckPlaceholderExpr(Length); 4295 if (Result.isInvalid()) 4296 return ExprError(); 4297 Result = DefaultLvalueConversion(Result.get()); 4298 if (Result.isInvalid()) 4299 return ExprError(); 4300 Length = Result.get(); 4301 } 4302 4303 // Build an unanalyzed expression if either operand is type-dependent. 4304 if (Base->isTypeDependent() || 4305 (LowerBound && 4306 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4307 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4308 return new (Context) 4309 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4310 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4311 } 4312 4313 // Perform default conversions. 4314 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4315 QualType ResultTy; 4316 if (OriginalTy->isAnyPointerType()) { 4317 ResultTy = OriginalTy->getPointeeType(); 4318 } else if (OriginalTy->isArrayType()) { 4319 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4320 } else { 4321 return ExprError( 4322 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4323 << Base->getSourceRange()); 4324 } 4325 // C99 6.5.2.1p1 4326 if (LowerBound) { 4327 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4328 LowerBound); 4329 if (Res.isInvalid()) 4330 return ExprError(Diag(LowerBound->getExprLoc(), 4331 diag::err_omp_typecheck_section_not_integer) 4332 << 0 << LowerBound->getSourceRange()); 4333 LowerBound = Res.get(); 4334 4335 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4336 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4337 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4338 << 0 << LowerBound->getSourceRange(); 4339 } 4340 if (Length) { 4341 auto Res = 4342 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4343 if (Res.isInvalid()) 4344 return ExprError(Diag(Length->getExprLoc(), 4345 diag::err_omp_typecheck_section_not_integer) 4346 << 1 << Length->getSourceRange()); 4347 Length = Res.get(); 4348 4349 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4350 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4351 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4352 << 1 << Length->getSourceRange(); 4353 } 4354 4355 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4356 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4357 // type. Note that functions are not objects, and that (in C99 parlance) 4358 // incomplete types are not object types. 4359 if (ResultTy->isFunctionType()) { 4360 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4361 << ResultTy << Base->getSourceRange(); 4362 return ExprError(); 4363 } 4364 4365 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4366 diag::err_omp_section_incomplete_type, Base)) 4367 return ExprError(); 4368 4369 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4370 llvm::APSInt LowerBoundValue; 4371 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) { 4372 // OpenMP 4.5, [2.4 Array Sections] 4373 // The array section must be a subset of the original array. 4374 if (LowerBoundValue.isNegative()) { 4375 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4376 << LowerBound->getSourceRange(); 4377 return ExprError(); 4378 } 4379 } 4380 } 4381 4382 if (Length) { 4383 llvm::APSInt LengthValue; 4384 if (Length->EvaluateAsInt(LengthValue, Context)) { 4385 // OpenMP 4.5, [2.4 Array Sections] 4386 // The length must evaluate to non-negative integers. 4387 if (LengthValue.isNegative()) { 4388 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4389 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4390 << Length->getSourceRange(); 4391 return ExprError(); 4392 } 4393 } 4394 } else if (ColonLoc.isValid() && 4395 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4396 !OriginalTy->isVariableArrayType()))) { 4397 // OpenMP 4.5, [2.4 Array Sections] 4398 // When the size of the array dimension is not known, the length must be 4399 // specified explicitly. 4400 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4401 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4402 return ExprError(); 4403 } 4404 4405 if (!Base->getType()->isSpecificPlaceholderType( 4406 BuiltinType::OMPArraySection)) { 4407 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4408 if (Result.isInvalid()) 4409 return ExprError(); 4410 Base = Result.get(); 4411 } 4412 return new (Context) 4413 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4414 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4415 } 4416 4417 ExprResult 4418 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4419 Expr *Idx, SourceLocation RLoc) { 4420 Expr *LHSExp = Base; 4421 Expr *RHSExp = Idx; 4422 4423 ExprValueKind VK = VK_LValue; 4424 ExprObjectKind OK = OK_Ordinary; 4425 4426 // Per C++ core issue 1213, the result is an xvalue if either operand is 4427 // a non-lvalue array, and an lvalue otherwise. 4428 if (getLangOpts().CPlusPlus11 && 4429 ((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) || 4430 (RHSExp->getType()->isArrayType() && !RHSExp->isLValue()))) 4431 VK = VK_XValue; 4432 4433 // Perform default conversions. 4434 if (!LHSExp->getType()->getAs<VectorType>()) { 4435 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4436 if (Result.isInvalid()) 4437 return ExprError(); 4438 LHSExp = Result.get(); 4439 } 4440 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4441 if (Result.isInvalid()) 4442 return ExprError(); 4443 RHSExp = Result.get(); 4444 4445 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4446 4447 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4448 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4449 // in the subscript position. As a result, we need to derive the array base 4450 // and index from the expression types. 4451 Expr *BaseExpr, *IndexExpr; 4452 QualType ResultType; 4453 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4454 BaseExpr = LHSExp; 4455 IndexExpr = RHSExp; 4456 ResultType = Context.DependentTy; 4457 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4458 BaseExpr = LHSExp; 4459 IndexExpr = RHSExp; 4460 ResultType = PTy->getPointeeType(); 4461 } else if (const ObjCObjectPointerType *PTy = 4462 LHSTy->getAs<ObjCObjectPointerType>()) { 4463 BaseExpr = LHSExp; 4464 IndexExpr = RHSExp; 4465 4466 // Use custom logic if this should be the pseudo-object subscript 4467 // expression. 4468 if (!LangOpts.isSubscriptPointerArithmetic()) 4469 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4470 nullptr); 4471 4472 ResultType = PTy->getPointeeType(); 4473 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4474 // Handle the uncommon case of "123[Ptr]". 4475 BaseExpr = RHSExp; 4476 IndexExpr = LHSExp; 4477 ResultType = PTy->getPointeeType(); 4478 } else if (const ObjCObjectPointerType *PTy = 4479 RHSTy->getAs<ObjCObjectPointerType>()) { 4480 // Handle the uncommon case of "123[Ptr]". 4481 BaseExpr = RHSExp; 4482 IndexExpr = LHSExp; 4483 ResultType = PTy->getPointeeType(); 4484 if (!LangOpts.isSubscriptPointerArithmetic()) { 4485 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4486 << ResultType << BaseExpr->getSourceRange(); 4487 return ExprError(); 4488 } 4489 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4490 BaseExpr = LHSExp; // vectors: V[123] 4491 IndexExpr = RHSExp; 4492 VK = LHSExp->getValueKind(); 4493 if (VK != VK_RValue) 4494 OK = OK_VectorComponent; 4495 4496 // FIXME: need to deal with const... 4497 ResultType = VTy->getElementType(); 4498 } else if (LHSTy->isArrayType()) { 4499 // If we see an array that wasn't promoted by 4500 // DefaultFunctionArrayLvalueConversion, it must be an array that 4501 // wasn't promoted because of the C90 rule that doesn't 4502 // allow promoting non-lvalue arrays. Warn, then 4503 // force the promotion here. 4504 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4505 LHSExp->getSourceRange(); 4506 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4507 CK_ArrayToPointerDecay).get(); 4508 LHSTy = LHSExp->getType(); 4509 4510 BaseExpr = LHSExp; 4511 IndexExpr = RHSExp; 4512 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4513 } else if (RHSTy->isArrayType()) { 4514 // Same as previous, except for 123[f().a] case 4515 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4516 RHSExp->getSourceRange(); 4517 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4518 CK_ArrayToPointerDecay).get(); 4519 RHSTy = RHSExp->getType(); 4520 4521 BaseExpr = RHSExp; 4522 IndexExpr = LHSExp; 4523 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4524 } else { 4525 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4526 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4527 } 4528 // C99 6.5.2.1p1 4529 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4530 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4531 << IndexExpr->getSourceRange()); 4532 4533 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4534 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4535 && !IndexExpr->isTypeDependent()) 4536 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4537 4538 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4539 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4540 // type. Note that Functions are not objects, and that (in C99 parlance) 4541 // incomplete types are not object types. 4542 if (ResultType->isFunctionType()) { 4543 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 4544 << ResultType << BaseExpr->getSourceRange(); 4545 return ExprError(); 4546 } 4547 4548 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4549 // GNU extension: subscripting on pointer to void 4550 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4551 << BaseExpr->getSourceRange(); 4552 4553 // C forbids expressions of unqualified void type from being l-values. 4554 // See IsCForbiddenLValueType. 4555 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4556 } else if (!ResultType->isDependentType() && 4557 RequireCompleteType(LLoc, ResultType, 4558 diag::err_subscript_incomplete_type, BaseExpr)) 4559 return ExprError(); 4560 4561 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4562 !ResultType.isCForbiddenLValueType()); 4563 4564 return new (Context) 4565 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4566 } 4567 4568 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 4569 ParmVarDecl *Param) { 4570 if (Param->hasUnparsedDefaultArg()) { 4571 Diag(CallLoc, 4572 diag::err_use_of_default_argument_to_function_declared_later) << 4573 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4574 Diag(UnparsedDefaultArgLocs[Param], 4575 diag::note_default_argument_declared_here); 4576 return true; 4577 } 4578 4579 if (Param->hasUninstantiatedDefaultArg()) { 4580 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4581 4582 EnterExpressionEvaluationContext EvalContext( 4583 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 4584 4585 // Instantiate the expression. 4586 MultiLevelTemplateArgumentList MutiLevelArgList 4587 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4588 4589 InstantiatingTemplate Inst(*this, CallLoc, Param, 4590 MutiLevelArgList.getInnermost()); 4591 if (Inst.isInvalid()) 4592 return true; 4593 if (Inst.isAlreadyInstantiating()) { 4594 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4595 Param->setInvalidDecl(); 4596 return true; 4597 } 4598 4599 ExprResult Result; 4600 { 4601 // C++ [dcl.fct.default]p5: 4602 // The names in the [default argument] expression are bound, and 4603 // the semantic constraints are checked, at the point where the 4604 // default argument expression appears. 4605 ContextRAII SavedContext(*this, FD); 4606 LocalInstantiationScope Local(*this); 4607 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 4608 /*DirectInit*/false); 4609 } 4610 if (Result.isInvalid()) 4611 return true; 4612 4613 // Check the expression as an initializer for the parameter. 4614 InitializedEntity Entity 4615 = InitializedEntity::InitializeParameter(Context, Param); 4616 InitializationKind Kind 4617 = InitializationKind::CreateCopy(Param->getLocation(), 4618 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 4619 Expr *ResultE = Result.getAs<Expr>(); 4620 4621 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4622 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4623 if (Result.isInvalid()) 4624 return true; 4625 4626 Result = ActOnFinishFullExpr(Result.getAs<Expr>(), 4627 Param->getOuterLocStart()); 4628 if (Result.isInvalid()) 4629 return true; 4630 4631 // Remember the instantiated default argument. 4632 Param->setDefaultArg(Result.getAs<Expr>()); 4633 if (ASTMutationListener *L = getASTMutationListener()) { 4634 L->DefaultArgumentInstantiated(Param); 4635 } 4636 } 4637 4638 // If the default argument expression is not set yet, we are building it now. 4639 if (!Param->hasInit()) { 4640 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4641 Param->setInvalidDecl(); 4642 return true; 4643 } 4644 4645 // If the default expression creates temporaries, we need to 4646 // push them to the current stack of expression temporaries so they'll 4647 // be properly destroyed. 4648 // FIXME: We should really be rebuilding the default argument with new 4649 // bound temporaries; see the comment in PR5810. 4650 // We don't need to do that with block decls, though, because 4651 // blocks in default argument expression can never capture anything. 4652 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 4653 // Set the "needs cleanups" bit regardless of whether there are 4654 // any explicit objects. 4655 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 4656 4657 // Append all the objects to the cleanup list. Right now, this 4658 // should always be a no-op, because blocks in default argument 4659 // expressions should never be able to capture anything. 4660 assert(!Init->getNumObjects() && 4661 "default argument expression has capturing blocks?"); 4662 } 4663 4664 // We already type-checked the argument, so we know it works. 4665 // Just mark all of the declarations in this potentially-evaluated expression 4666 // as being "referenced". 4667 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4668 /*SkipLocalVariables=*/true); 4669 return false; 4670 } 4671 4672 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4673 FunctionDecl *FD, ParmVarDecl *Param) { 4674 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 4675 return ExprError(); 4676 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4677 } 4678 4679 Sema::VariadicCallType 4680 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4681 Expr *Fn) { 4682 if (Proto && Proto->isVariadic()) { 4683 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4684 return VariadicConstructor; 4685 else if (Fn && Fn->getType()->isBlockPointerType()) 4686 return VariadicBlock; 4687 else if (FDecl) { 4688 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4689 if (Method->isInstance()) 4690 return VariadicMethod; 4691 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4692 return VariadicMethod; 4693 return VariadicFunction; 4694 } 4695 return VariadicDoesNotApply; 4696 } 4697 4698 namespace { 4699 class FunctionCallCCC : public FunctionCallFilterCCC { 4700 public: 4701 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4702 unsigned NumArgs, MemberExpr *ME) 4703 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4704 FunctionName(FuncName) {} 4705 4706 bool ValidateCandidate(const TypoCorrection &candidate) override { 4707 if (!candidate.getCorrectionSpecifier() || 4708 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4709 return false; 4710 } 4711 4712 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4713 } 4714 4715 private: 4716 const IdentifierInfo *const FunctionName; 4717 }; 4718 } 4719 4720 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4721 FunctionDecl *FDecl, 4722 ArrayRef<Expr *> Args) { 4723 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4724 DeclarationName FuncName = FDecl->getDeclName(); 4725 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart(); 4726 4727 if (TypoCorrection Corrected = S.CorrectTypo( 4728 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4729 S.getScopeForContext(S.CurContext), nullptr, 4730 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4731 Args.size(), ME), 4732 Sema::CTK_ErrorRecovery)) { 4733 if (NamedDecl *ND = Corrected.getFoundDecl()) { 4734 if (Corrected.isOverloaded()) { 4735 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4736 OverloadCandidateSet::iterator Best; 4737 for (NamedDecl *CD : Corrected) { 4738 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 4739 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4740 OCS); 4741 } 4742 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4743 case OR_Success: 4744 ND = Best->FoundDecl; 4745 Corrected.setCorrectionDecl(ND); 4746 break; 4747 default: 4748 break; 4749 } 4750 } 4751 ND = ND->getUnderlyingDecl(); 4752 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 4753 return Corrected; 4754 } 4755 } 4756 return TypoCorrection(); 4757 } 4758 4759 /// ConvertArgumentsForCall - Converts the arguments specified in 4760 /// Args/NumArgs to the parameter types of the function FDecl with 4761 /// function prototype Proto. Call is the call expression itself, and 4762 /// Fn is the function expression. For a C++ member function, this 4763 /// routine does not attempt to convert the object argument. Returns 4764 /// true if the call is ill-formed. 4765 bool 4766 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4767 FunctionDecl *FDecl, 4768 const FunctionProtoType *Proto, 4769 ArrayRef<Expr *> Args, 4770 SourceLocation RParenLoc, 4771 bool IsExecConfig) { 4772 // Bail out early if calling a builtin with custom typechecking. 4773 if (FDecl) 4774 if (unsigned ID = FDecl->getBuiltinID()) 4775 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4776 return false; 4777 4778 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4779 // assignment, to the types of the corresponding parameter, ... 4780 unsigned NumParams = Proto->getNumParams(); 4781 bool Invalid = false; 4782 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4783 unsigned FnKind = Fn->getType()->isBlockPointerType() 4784 ? 1 /* block */ 4785 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4786 : 0 /* function */); 4787 4788 // If too few arguments are available (and we don't have default 4789 // arguments for the remaining parameters), don't make the call. 4790 if (Args.size() < NumParams) { 4791 if (Args.size() < MinArgs) { 4792 TypoCorrection TC; 4793 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4794 unsigned diag_id = 4795 MinArgs == NumParams && !Proto->isVariadic() 4796 ? diag::err_typecheck_call_too_few_args_suggest 4797 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4798 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4799 << static_cast<unsigned>(Args.size()) 4800 << TC.getCorrectionRange()); 4801 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4802 Diag(RParenLoc, 4803 MinArgs == NumParams && !Proto->isVariadic() 4804 ? diag::err_typecheck_call_too_few_args_one 4805 : diag::err_typecheck_call_too_few_args_at_least_one) 4806 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4807 else 4808 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4809 ? diag::err_typecheck_call_too_few_args 4810 : diag::err_typecheck_call_too_few_args_at_least) 4811 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4812 << Fn->getSourceRange(); 4813 4814 // Emit the location of the prototype. 4815 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4816 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4817 << FDecl; 4818 4819 return true; 4820 } 4821 Call->setNumArgs(Context, NumParams); 4822 } 4823 4824 // If too many are passed and not variadic, error on the extras and drop 4825 // them. 4826 if (Args.size() > NumParams) { 4827 if (!Proto->isVariadic()) { 4828 TypoCorrection TC; 4829 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4830 unsigned diag_id = 4831 MinArgs == NumParams && !Proto->isVariadic() 4832 ? diag::err_typecheck_call_too_many_args_suggest 4833 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4834 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4835 << static_cast<unsigned>(Args.size()) 4836 << TC.getCorrectionRange()); 4837 } else if (NumParams == 1 && FDecl && 4838 FDecl->getParamDecl(0)->getDeclName()) 4839 Diag(Args[NumParams]->getLocStart(), 4840 MinArgs == NumParams 4841 ? diag::err_typecheck_call_too_many_args_one 4842 : diag::err_typecheck_call_too_many_args_at_most_one) 4843 << FnKind << FDecl->getParamDecl(0) 4844 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4845 << SourceRange(Args[NumParams]->getLocStart(), 4846 Args.back()->getLocEnd()); 4847 else 4848 Diag(Args[NumParams]->getLocStart(), 4849 MinArgs == NumParams 4850 ? diag::err_typecheck_call_too_many_args 4851 : diag::err_typecheck_call_too_many_args_at_most) 4852 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4853 << Fn->getSourceRange() 4854 << SourceRange(Args[NumParams]->getLocStart(), 4855 Args.back()->getLocEnd()); 4856 4857 // Emit the location of the prototype. 4858 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4859 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4860 << FDecl; 4861 4862 // This deletes the extra arguments. 4863 Call->setNumArgs(Context, NumParams); 4864 return true; 4865 } 4866 } 4867 SmallVector<Expr *, 8> AllArgs; 4868 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4869 4870 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4871 Proto, 0, Args, AllArgs, CallType); 4872 if (Invalid) 4873 return true; 4874 unsigned TotalNumArgs = AllArgs.size(); 4875 for (unsigned i = 0; i < TotalNumArgs; ++i) 4876 Call->setArg(i, AllArgs[i]); 4877 4878 return false; 4879 } 4880 4881 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4882 const FunctionProtoType *Proto, 4883 unsigned FirstParam, ArrayRef<Expr *> Args, 4884 SmallVectorImpl<Expr *> &AllArgs, 4885 VariadicCallType CallType, bool AllowExplicit, 4886 bool IsListInitialization) { 4887 unsigned NumParams = Proto->getNumParams(); 4888 bool Invalid = false; 4889 size_t ArgIx = 0; 4890 // Continue to check argument types (even if we have too few/many args). 4891 for (unsigned i = FirstParam; i < NumParams; i++) { 4892 QualType ProtoArgType = Proto->getParamType(i); 4893 4894 Expr *Arg; 4895 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4896 if (ArgIx < Args.size()) { 4897 Arg = Args[ArgIx++]; 4898 4899 if (RequireCompleteType(Arg->getLocStart(), 4900 ProtoArgType, 4901 diag::err_call_incomplete_argument, Arg)) 4902 return true; 4903 4904 // Strip the unbridged-cast placeholder expression off, if applicable. 4905 bool CFAudited = false; 4906 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4907 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4908 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4909 Arg = stripARCUnbridgedCast(Arg); 4910 else if (getLangOpts().ObjCAutoRefCount && 4911 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4912 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4913 CFAudited = true; 4914 4915 InitializedEntity Entity = 4916 Param ? InitializedEntity::InitializeParameter(Context, Param, 4917 ProtoArgType) 4918 : InitializedEntity::InitializeParameter( 4919 Context, ProtoArgType, Proto->isParamConsumed(i)); 4920 4921 // Remember that parameter belongs to a CF audited API. 4922 if (CFAudited) 4923 Entity.setParameterCFAudited(); 4924 4925 ExprResult ArgE = PerformCopyInitialization( 4926 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 4927 if (ArgE.isInvalid()) 4928 return true; 4929 4930 Arg = ArgE.getAs<Expr>(); 4931 } else { 4932 assert(Param && "can't use default arguments without a known callee"); 4933 4934 ExprResult ArgExpr = 4935 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4936 if (ArgExpr.isInvalid()) 4937 return true; 4938 4939 Arg = ArgExpr.getAs<Expr>(); 4940 } 4941 4942 // Check for array bounds violations for each argument to the call. This 4943 // check only triggers warnings when the argument isn't a more complex Expr 4944 // with its own checking, such as a BinaryOperator. 4945 CheckArrayAccess(Arg); 4946 4947 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4948 CheckStaticArrayArgument(CallLoc, Param, Arg); 4949 4950 AllArgs.push_back(Arg); 4951 } 4952 4953 // If this is a variadic call, handle args passed through "...". 4954 if (CallType != VariadicDoesNotApply) { 4955 // Assume that extern "C" functions with variadic arguments that 4956 // return __unknown_anytype aren't *really* variadic. 4957 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4958 FDecl->isExternC()) { 4959 for (Expr *A : Args.slice(ArgIx)) { 4960 QualType paramType; // ignored 4961 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 4962 Invalid |= arg.isInvalid(); 4963 AllArgs.push_back(arg.get()); 4964 } 4965 4966 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4967 } else { 4968 for (Expr *A : Args.slice(ArgIx)) { 4969 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 4970 Invalid |= Arg.isInvalid(); 4971 AllArgs.push_back(Arg.get()); 4972 } 4973 } 4974 4975 // Check for array bounds violations. 4976 for (Expr *A : Args.slice(ArgIx)) 4977 CheckArrayAccess(A); 4978 } 4979 return Invalid; 4980 } 4981 4982 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4983 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4984 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4985 TL = DTL.getOriginalLoc(); 4986 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4987 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4988 << ATL.getLocalSourceRange(); 4989 } 4990 4991 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4992 /// array parameter, check that it is non-null, and that if it is formed by 4993 /// array-to-pointer decay, the underlying array is sufficiently large. 4994 /// 4995 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4996 /// array type derivation, then for each call to the function, the value of the 4997 /// corresponding actual argument shall provide access to the first element of 4998 /// an array with at least as many elements as specified by the size expression. 4999 void 5000 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 5001 ParmVarDecl *Param, 5002 const Expr *ArgExpr) { 5003 // Static array parameters are not supported in C++. 5004 if (!Param || getLangOpts().CPlusPlus) 5005 return; 5006 5007 QualType OrigTy = Param->getOriginalType(); 5008 5009 const ArrayType *AT = Context.getAsArrayType(OrigTy); 5010 if (!AT || AT->getSizeModifier() != ArrayType::Static) 5011 return; 5012 5013 if (ArgExpr->isNullPointerConstant(Context, 5014 Expr::NPC_NeverValueDependent)) { 5015 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 5016 DiagnoseCalleeStaticArrayParam(*this, Param); 5017 return; 5018 } 5019 5020 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 5021 if (!CAT) 5022 return; 5023 5024 const ConstantArrayType *ArgCAT = 5025 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 5026 if (!ArgCAT) 5027 return; 5028 5029 if (ArgCAT->getSize().ult(CAT->getSize())) { 5030 Diag(CallLoc, diag::warn_static_array_too_small) 5031 << ArgExpr->getSourceRange() 5032 << (unsigned) ArgCAT->getSize().getZExtValue() 5033 << (unsigned) CAT->getSize().getZExtValue(); 5034 DiagnoseCalleeStaticArrayParam(*this, Param); 5035 } 5036 } 5037 5038 /// Given a function expression of unknown-any type, try to rebuild it 5039 /// to have a function type. 5040 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 5041 5042 /// Is the given type a placeholder that we need to lower out 5043 /// immediately during argument processing? 5044 static bool isPlaceholderToRemoveAsArg(QualType type) { 5045 // Placeholders are never sugared. 5046 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 5047 if (!placeholder) return false; 5048 5049 switch (placeholder->getKind()) { 5050 // Ignore all the non-placeholder types. 5051 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 5052 case BuiltinType::Id: 5053 #include "clang/Basic/OpenCLImageTypes.def" 5054 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 5055 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 5056 #include "clang/AST/BuiltinTypes.def" 5057 return false; 5058 5059 // We cannot lower out overload sets; they might validly be resolved 5060 // by the call machinery. 5061 case BuiltinType::Overload: 5062 return false; 5063 5064 // Unbridged casts in ARC can be handled in some call positions and 5065 // should be left in place. 5066 case BuiltinType::ARCUnbridgedCast: 5067 return false; 5068 5069 // Pseudo-objects should be converted as soon as possible. 5070 case BuiltinType::PseudoObject: 5071 return true; 5072 5073 // The debugger mode could theoretically but currently does not try 5074 // to resolve unknown-typed arguments based on known parameter types. 5075 case BuiltinType::UnknownAny: 5076 return true; 5077 5078 // These are always invalid as call arguments and should be reported. 5079 case BuiltinType::BoundMember: 5080 case BuiltinType::BuiltinFn: 5081 case BuiltinType::OMPArraySection: 5082 return true; 5083 5084 } 5085 llvm_unreachable("bad builtin type kind"); 5086 } 5087 5088 /// Check an argument list for placeholders that we won't try to 5089 /// handle later. 5090 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5091 // Apply this processing to all the arguments at once instead of 5092 // dying at the first failure. 5093 bool hasInvalid = false; 5094 for (size_t i = 0, e = args.size(); i != e; i++) { 5095 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5096 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5097 if (result.isInvalid()) hasInvalid = true; 5098 else args[i] = result.get(); 5099 } else if (hasInvalid) { 5100 (void)S.CorrectDelayedTyposInExpr(args[i]); 5101 } 5102 } 5103 return hasInvalid; 5104 } 5105 5106 /// If a builtin function has a pointer argument with no explicit address 5107 /// space, then it should be able to accept a pointer to any address 5108 /// space as input. In order to do this, we need to replace the 5109 /// standard builtin declaration with one that uses the same address space 5110 /// as the call. 5111 /// 5112 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5113 /// it does not contain any pointer arguments without 5114 /// an address space qualifer. Otherwise the rewritten 5115 /// FunctionDecl is returned. 5116 /// TODO: Handle pointer return types. 5117 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5118 const FunctionDecl *FDecl, 5119 MultiExprArg ArgExprs) { 5120 5121 QualType DeclType = FDecl->getType(); 5122 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5123 5124 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 5125 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 5126 return nullptr; 5127 5128 bool NeedsNewDecl = false; 5129 unsigned i = 0; 5130 SmallVector<QualType, 8> OverloadParams; 5131 5132 for (QualType ParamType : FT->param_types()) { 5133 5134 // Convert array arguments to pointer to simplify type lookup. 5135 ExprResult ArgRes = 5136 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5137 if (ArgRes.isInvalid()) 5138 return nullptr; 5139 Expr *Arg = ArgRes.get(); 5140 QualType ArgType = Arg->getType(); 5141 if (!ParamType->isPointerType() || 5142 ParamType.getQualifiers().hasAddressSpace() || 5143 !ArgType->isPointerType() || 5144 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 5145 OverloadParams.push_back(ParamType); 5146 continue; 5147 } 5148 5149 NeedsNewDecl = true; 5150 unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace(); 5151 5152 QualType PointeeType = ParamType->getPointeeType(); 5153 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5154 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5155 } 5156 5157 if (!NeedsNewDecl) 5158 return nullptr; 5159 5160 FunctionProtoType::ExtProtoInfo EPI; 5161 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5162 OverloadParams, EPI); 5163 DeclContext *Parent = Context.getTranslationUnitDecl(); 5164 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5165 FDecl->getLocation(), 5166 FDecl->getLocation(), 5167 FDecl->getIdentifier(), 5168 OverloadTy, 5169 /*TInfo=*/nullptr, 5170 SC_Extern, false, 5171 /*hasPrototype=*/true); 5172 SmallVector<ParmVarDecl*, 16> Params; 5173 FT = cast<FunctionProtoType>(OverloadTy); 5174 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5175 QualType ParamType = FT->getParamType(i); 5176 ParmVarDecl *Parm = 5177 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5178 SourceLocation(), nullptr, ParamType, 5179 /*TInfo=*/nullptr, SC_None, nullptr); 5180 Parm->setScopeInfo(0, i); 5181 Params.push_back(Parm); 5182 } 5183 OverloadDecl->setParams(Params); 5184 return OverloadDecl; 5185 } 5186 5187 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 5188 FunctionDecl *Callee, 5189 MultiExprArg ArgExprs) { 5190 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 5191 // similar attributes) really don't like it when functions are called with an 5192 // invalid number of args. 5193 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 5194 /*PartialOverloading=*/false) && 5195 !Callee->isVariadic()) 5196 return; 5197 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 5198 return; 5199 5200 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) { 5201 S.Diag(Fn->getLocStart(), 5202 isa<CXXMethodDecl>(Callee) 5203 ? diag::err_ovl_no_viable_member_function_in_call 5204 : diag::err_ovl_no_viable_function_in_call) 5205 << Callee << Callee->getSourceRange(); 5206 S.Diag(Callee->getLocation(), 5207 diag::note_ovl_candidate_disabled_by_function_cond_attr) 5208 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5209 return; 5210 } 5211 } 5212 5213 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 5214 /// This provides the location of the left/right parens and a list of comma 5215 /// locations. 5216 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5217 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5218 Expr *ExecConfig, bool IsExecConfig) { 5219 // Since this might be a postfix expression, get rid of ParenListExprs. 5220 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 5221 if (Result.isInvalid()) return ExprError(); 5222 Fn = Result.get(); 5223 5224 if (checkArgsForPlaceholders(*this, ArgExprs)) 5225 return ExprError(); 5226 5227 if (getLangOpts().CPlusPlus) { 5228 // If this is a pseudo-destructor expression, build the call immediately. 5229 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5230 if (!ArgExprs.empty()) { 5231 // Pseudo-destructor calls should not have any arguments. 5232 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 5233 << FixItHint::CreateRemoval( 5234 SourceRange(ArgExprs.front()->getLocStart(), 5235 ArgExprs.back()->getLocEnd())); 5236 } 5237 5238 return new (Context) 5239 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc); 5240 } 5241 if (Fn->getType() == Context.PseudoObjectTy) { 5242 ExprResult result = CheckPlaceholderExpr(Fn); 5243 if (result.isInvalid()) return ExprError(); 5244 Fn = result.get(); 5245 } 5246 5247 // Determine whether this is a dependent call inside a C++ template, 5248 // in which case we won't do any semantic analysis now. 5249 bool Dependent = false; 5250 if (Fn->isTypeDependent()) 5251 Dependent = true; 5252 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5253 Dependent = true; 5254 5255 if (Dependent) { 5256 if (ExecConfig) { 5257 return new (Context) CUDAKernelCallExpr( 5258 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5259 Context.DependentTy, VK_RValue, RParenLoc); 5260 } else { 5261 return new (Context) CallExpr( 5262 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5263 } 5264 } 5265 5266 // Determine whether this is a call to an object (C++ [over.call.object]). 5267 if (Fn->getType()->isRecordType()) 5268 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 5269 RParenLoc); 5270 5271 if (Fn->getType() == Context.UnknownAnyTy) { 5272 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5273 if (result.isInvalid()) return ExprError(); 5274 Fn = result.get(); 5275 } 5276 5277 if (Fn->getType() == Context.BoundMemberTy) { 5278 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5279 RParenLoc); 5280 } 5281 } 5282 5283 // Check for overloaded calls. This can happen even in C due to extensions. 5284 if (Fn->getType() == Context.OverloadTy) { 5285 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5286 5287 // We aren't supposed to apply this logic if there's an '&' involved. 5288 if (!find.HasFormOfMemberPointer) { 5289 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5290 return new (Context) CallExpr( 5291 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5292 OverloadExpr *ovl = find.Expression; 5293 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5294 return BuildOverloadedCallExpr( 5295 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 5296 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 5297 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5298 RParenLoc); 5299 } 5300 } 5301 5302 // If we're directly calling a function, get the appropriate declaration. 5303 if (Fn->getType() == Context.UnknownAnyTy) { 5304 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5305 if (result.isInvalid()) return ExprError(); 5306 Fn = result.get(); 5307 } 5308 5309 Expr *NakedFn = Fn->IgnoreParens(); 5310 5311 bool CallingNDeclIndirectly = false; 5312 NamedDecl *NDecl = nullptr; 5313 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5314 if (UnOp->getOpcode() == UO_AddrOf) { 5315 CallingNDeclIndirectly = true; 5316 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5317 } 5318 } 5319 5320 if (isa<DeclRefExpr>(NakedFn)) { 5321 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 5322 5323 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5324 if (FDecl && FDecl->getBuiltinID()) { 5325 // Rewrite the function decl for this builtin by replacing parameters 5326 // with no explicit address space with the address space of the arguments 5327 // in ArgExprs. 5328 if ((FDecl = 5329 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5330 NDecl = FDecl; 5331 Fn = DeclRefExpr::Create( 5332 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 5333 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl); 5334 } 5335 } 5336 } else if (isa<MemberExpr>(NakedFn)) 5337 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5338 5339 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5340 if (CallingNDeclIndirectly && 5341 !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 5342 Fn->getLocStart())) 5343 return ExprError(); 5344 5345 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 5346 return ExprError(); 5347 5348 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 5349 } 5350 5351 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5352 ExecConfig, IsExecConfig); 5353 } 5354 5355 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5356 /// 5357 /// __builtin_astype( value, dst type ) 5358 /// 5359 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5360 SourceLocation BuiltinLoc, 5361 SourceLocation RParenLoc) { 5362 ExprValueKind VK = VK_RValue; 5363 ExprObjectKind OK = OK_Ordinary; 5364 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5365 QualType SrcTy = E->getType(); 5366 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5367 return ExprError(Diag(BuiltinLoc, 5368 diag::err_invalid_astype_of_different_size) 5369 << DstTy 5370 << SrcTy 5371 << E->getSourceRange()); 5372 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5373 } 5374 5375 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5376 /// provided arguments. 5377 /// 5378 /// __builtin_convertvector( value, dst type ) 5379 /// 5380 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5381 SourceLocation BuiltinLoc, 5382 SourceLocation RParenLoc) { 5383 TypeSourceInfo *TInfo; 5384 GetTypeFromParser(ParsedDestTy, &TInfo); 5385 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5386 } 5387 5388 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5389 /// i.e. an expression not of \p OverloadTy. The expression should 5390 /// unary-convert to an expression of function-pointer or 5391 /// block-pointer type. 5392 /// 5393 /// \param NDecl the declaration being called, if available 5394 ExprResult 5395 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5396 SourceLocation LParenLoc, 5397 ArrayRef<Expr *> Args, 5398 SourceLocation RParenLoc, 5399 Expr *Config, bool IsExecConfig) { 5400 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5401 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5402 5403 // Functions with 'interrupt' attribute cannot be called directly. 5404 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5405 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5406 return ExprError(); 5407 } 5408 5409 // Interrupt handlers don't save off the VFP regs automatically on ARM, 5410 // so there's some risk when calling out to non-interrupt handler functions 5411 // that the callee might not preserve them. This is easy to diagnose here, 5412 // but can be very challenging to debug. 5413 if (auto *Caller = getCurFunctionDecl()) 5414 if (Caller->hasAttr<ARMInterruptAttr>()) { 5415 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 5416 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) 5417 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 5418 } 5419 5420 // Promote the function operand. 5421 // We special-case function promotion here because we only allow promoting 5422 // builtin functions to function pointers in the callee of a call. 5423 ExprResult Result; 5424 if (BuiltinID && 5425 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5426 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 5427 CK_BuiltinFnToFnPtr).get(); 5428 } else { 5429 Result = CallExprUnaryConversions(Fn); 5430 } 5431 if (Result.isInvalid()) 5432 return ExprError(); 5433 Fn = Result.get(); 5434 5435 // Make the call expr early, before semantic checks. This guarantees cleanup 5436 // of arguments and function on error. 5437 CallExpr *TheCall; 5438 if (Config) 5439 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 5440 cast<CallExpr>(Config), Args, 5441 Context.BoolTy, VK_RValue, 5442 RParenLoc); 5443 else 5444 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 5445 VK_RValue, RParenLoc); 5446 5447 if (!getLangOpts().CPlusPlus) { 5448 // C cannot always handle TypoExpr nodes in builtin calls and direct 5449 // function calls as their argument checking don't necessarily handle 5450 // dependent types properly, so make sure any TypoExprs have been 5451 // dealt with. 5452 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5453 if (!Result.isUsable()) return ExprError(); 5454 TheCall = dyn_cast<CallExpr>(Result.get()); 5455 if (!TheCall) return Result; 5456 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5457 } 5458 5459 // Bail out early if calling a builtin with custom typechecking. 5460 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5461 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5462 5463 retry: 5464 const FunctionType *FuncT; 5465 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5466 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5467 // have type pointer to function". 5468 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5469 if (!FuncT) 5470 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5471 << Fn->getType() << Fn->getSourceRange()); 5472 } else if (const BlockPointerType *BPT = 5473 Fn->getType()->getAs<BlockPointerType>()) { 5474 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5475 } else { 5476 // Handle calls to expressions of unknown-any type. 5477 if (Fn->getType() == Context.UnknownAnyTy) { 5478 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5479 if (rewrite.isInvalid()) return ExprError(); 5480 Fn = rewrite.get(); 5481 TheCall->setCallee(Fn); 5482 goto retry; 5483 } 5484 5485 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5486 << Fn->getType() << Fn->getSourceRange()); 5487 } 5488 5489 if (getLangOpts().CUDA) { 5490 if (Config) { 5491 // CUDA: Kernel calls must be to global functions 5492 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5493 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5494 << FDecl->getName() << Fn->getSourceRange()); 5495 5496 // CUDA: Kernel function must have 'void' return type 5497 if (!FuncT->getReturnType()->isVoidType()) 5498 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5499 << Fn->getType() << Fn->getSourceRange()); 5500 } else { 5501 // CUDA: Calls to global functions must be configured 5502 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5503 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5504 << FDecl->getName() << Fn->getSourceRange()); 5505 } 5506 } 5507 5508 // Check for a valid return type 5509 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall, 5510 FDecl)) 5511 return ExprError(); 5512 5513 // We know the result type of the call, set it. 5514 TheCall->setType(FuncT->getCallResultType(Context)); 5515 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5516 5517 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 5518 if (Proto) { 5519 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5520 IsExecConfig)) 5521 return ExprError(); 5522 } else { 5523 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5524 5525 if (FDecl) { 5526 // Check if we have too few/too many template arguments, based 5527 // on our knowledge of the function definition. 5528 const FunctionDecl *Def = nullptr; 5529 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5530 Proto = Def->getType()->getAs<FunctionProtoType>(); 5531 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5532 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5533 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5534 } 5535 5536 // If the function we're calling isn't a function prototype, but we have 5537 // a function prototype from a prior declaratiom, use that prototype. 5538 if (!FDecl->hasPrototype()) 5539 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5540 } 5541 5542 // Promote the arguments (C99 6.5.2.2p6). 5543 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5544 Expr *Arg = Args[i]; 5545 5546 if (Proto && i < Proto->getNumParams()) { 5547 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5548 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5549 ExprResult ArgE = 5550 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5551 if (ArgE.isInvalid()) 5552 return true; 5553 5554 Arg = ArgE.getAs<Expr>(); 5555 5556 } else { 5557 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5558 5559 if (ArgE.isInvalid()) 5560 return true; 5561 5562 Arg = ArgE.getAs<Expr>(); 5563 } 5564 5565 if (RequireCompleteType(Arg->getLocStart(), 5566 Arg->getType(), 5567 diag::err_call_incomplete_argument, Arg)) 5568 return ExprError(); 5569 5570 TheCall->setArg(i, Arg); 5571 } 5572 } 5573 5574 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5575 if (!Method->isStatic()) 5576 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5577 << Fn->getSourceRange()); 5578 5579 // Check for sentinels 5580 if (NDecl) 5581 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5582 5583 // Do special checking on direct calls to functions. 5584 if (FDecl) { 5585 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5586 return ExprError(); 5587 5588 if (BuiltinID) 5589 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5590 } else if (NDecl) { 5591 if (CheckPointerCall(NDecl, TheCall, Proto)) 5592 return ExprError(); 5593 } else { 5594 if (CheckOtherCall(TheCall, Proto)) 5595 return ExprError(); 5596 } 5597 5598 return MaybeBindToTemporary(TheCall); 5599 } 5600 5601 ExprResult 5602 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5603 SourceLocation RParenLoc, Expr *InitExpr) { 5604 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5605 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 5606 5607 TypeSourceInfo *TInfo; 5608 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5609 if (!TInfo) 5610 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5611 5612 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5613 } 5614 5615 ExprResult 5616 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5617 SourceLocation RParenLoc, Expr *LiteralExpr) { 5618 QualType literalType = TInfo->getType(); 5619 5620 if (literalType->isArrayType()) { 5621 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5622 diag::err_illegal_decl_array_incomplete_type, 5623 SourceRange(LParenLoc, 5624 LiteralExpr->getSourceRange().getEnd()))) 5625 return ExprError(); 5626 if (literalType->isVariableArrayType()) 5627 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5628 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5629 } else if (!literalType->isDependentType() && 5630 RequireCompleteType(LParenLoc, literalType, 5631 diag::err_typecheck_decl_incomplete_type, 5632 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5633 return ExprError(); 5634 5635 InitializedEntity Entity 5636 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5637 InitializationKind Kind 5638 = InitializationKind::CreateCStyleCast(LParenLoc, 5639 SourceRange(LParenLoc, RParenLoc), 5640 /*InitList=*/true); 5641 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5642 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5643 &literalType); 5644 if (Result.isInvalid()) 5645 return ExprError(); 5646 LiteralExpr = Result.get(); 5647 5648 bool isFileScope = !CurContext->isFunctionOrMethod(); 5649 if (isFileScope && 5650 !LiteralExpr->isTypeDependent() && 5651 !LiteralExpr->isValueDependent() && 5652 !literalType->isDependentType()) { // 6.5.2.5p3 5653 if (CheckForConstantInitializer(LiteralExpr, literalType)) 5654 return ExprError(); 5655 } 5656 5657 // In C, compound literals are l-values for some reason. 5658 // For GCC compatibility, in C++, file-scope array compound literals with 5659 // constant initializers are also l-values, and compound literals are 5660 // otherwise prvalues. 5661 // 5662 // (GCC also treats C++ list-initialized file-scope array prvalues with 5663 // constant initializers as l-values, but that's non-conforming, so we don't 5664 // follow it there.) 5665 // 5666 // FIXME: It would be better to handle the lvalue cases as materializing and 5667 // lifetime-extending a temporary object, but our materialized temporaries 5668 // representation only supports lifetime extension from a variable, not "out 5669 // of thin air". 5670 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 5671 // is bound to the result of applying array-to-pointer decay to the compound 5672 // literal. 5673 // FIXME: GCC supports compound literals of reference type, which should 5674 // obviously have a value kind derived from the kind of reference involved. 5675 ExprValueKind VK = 5676 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 5677 ? VK_RValue 5678 : VK_LValue; 5679 5680 return MaybeBindToTemporary( 5681 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 5682 VK, LiteralExpr, isFileScope)); 5683 } 5684 5685 ExprResult 5686 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 5687 SourceLocation RBraceLoc) { 5688 // Immediately handle non-overload placeholders. Overloads can be 5689 // resolved contextually, but everything else here can't. 5690 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 5691 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 5692 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 5693 5694 // Ignore failures; dropping the entire initializer list because 5695 // of one failure would be terrible for indexing/etc. 5696 if (result.isInvalid()) continue; 5697 5698 InitArgList[I] = result.get(); 5699 } 5700 } 5701 5702 // Semantic analysis for initializers is done by ActOnDeclarator() and 5703 // CheckInitializer() - it requires knowledge of the object being intialized. 5704 5705 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 5706 RBraceLoc); 5707 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 5708 return E; 5709 } 5710 5711 /// Do an explicit extend of the given block pointer if we're in ARC. 5712 void Sema::maybeExtendBlockObject(ExprResult &E) { 5713 assert(E.get()->getType()->isBlockPointerType()); 5714 assert(E.get()->isRValue()); 5715 5716 // Only do this in an r-value context. 5717 if (!getLangOpts().ObjCAutoRefCount) return; 5718 5719 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 5720 CK_ARCExtendBlockObject, E.get(), 5721 /*base path*/ nullptr, VK_RValue); 5722 Cleanup.setExprNeedsCleanups(true); 5723 } 5724 5725 /// Prepare a conversion of the given expression to an ObjC object 5726 /// pointer type. 5727 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 5728 QualType type = E.get()->getType(); 5729 if (type->isObjCObjectPointerType()) { 5730 return CK_BitCast; 5731 } else if (type->isBlockPointerType()) { 5732 maybeExtendBlockObject(E); 5733 return CK_BlockPointerToObjCPointerCast; 5734 } else { 5735 assert(type->isPointerType()); 5736 return CK_CPointerToObjCPointerCast; 5737 } 5738 } 5739 5740 /// Prepares for a scalar cast, performing all the necessary stages 5741 /// except the final cast and returning the kind required. 5742 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 5743 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 5744 // Also, callers should have filtered out the invalid cases with 5745 // pointers. Everything else should be possible. 5746 5747 QualType SrcTy = Src.get()->getType(); 5748 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 5749 return CK_NoOp; 5750 5751 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 5752 case Type::STK_MemberPointer: 5753 llvm_unreachable("member pointer type in C"); 5754 5755 case Type::STK_CPointer: 5756 case Type::STK_BlockPointer: 5757 case Type::STK_ObjCObjectPointer: 5758 switch (DestTy->getScalarTypeKind()) { 5759 case Type::STK_CPointer: { 5760 unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace(); 5761 unsigned DestAS = DestTy->getPointeeType().getAddressSpace(); 5762 if (SrcAS != DestAS) 5763 return CK_AddressSpaceConversion; 5764 return CK_BitCast; 5765 } 5766 case Type::STK_BlockPointer: 5767 return (SrcKind == Type::STK_BlockPointer 5768 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 5769 case Type::STK_ObjCObjectPointer: 5770 if (SrcKind == Type::STK_ObjCObjectPointer) 5771 return CK_BitCast; 5772 if (SrcKind == Type::STK_CPointer) 5773 return CK_CPointerToObjCPointerCast; 5774 maybeExtendBlockObject(Src); 5775 return CK_BlockPointerToObjCPointerCast; 5776 case Type::STK_Bool: 5777 return CK_PointerToBoolean; 5778 case Type::STK_Integral: 5779 return CK_PointerToIntegral; 5780 case Type::STK_Floating: 5781 case Type::STK_FloatingComplex: 5782 case Type::STK_IntegralComplex: 5783 case Type::STK_MemberPointer: 5784 llvm_unreachable("illegal cast from pointer"); 5785 } 5786 llvm_unreachable("Should have returned before this"); 5787 5788 case Type::STK_Bool: // casting from bool is like casting from an integer 5789 case Type::STK_Integral: 5790 switch (DestTy->getScalarTypeKind()) { 5791 case Type::STK_CPointer: 5792 case Type::STK_ObjCObjectPointer: 5793 case Type::STK_BlockPointer: 5794 if (Src.get()->isNullPointerConstant(Context, 5795 Expr::NPC_ValueDependentIsNull)) 5796 return CK_NullToPointer; 5797 return CK_IntegralToPointer; 5798 case Type::STK_Bool: 5799 return CK_IntegralToBoolean; 5800 case Type::STK_Integral: 5801 return CK_IntegralCast; 5802 case Type::STK_Floating: 5803 return CK_IntegralToFloating; 5804 case Type::STK_IntegralComplex: 5805 Src = ImpCastExprToType(Src.get(), 5806 DestTy->castAs<ComplexType>()->getElementType(), 5807 CK_IntegralCast); 5808 return CK_IntegralRealToComplex; 5809 case Type::STK_FloatingComplex: 5810 Src = ImpCastExprToType(Src.get(), 5811 DestTy->castAs<ComplexType>()->getElementType(), 5812 CK_IntegralToFloating); 5813 return CK_FloatingRealToComplex; 5814 case Type::STK_MemberPointer: 5815 llvm_unreachable("member pointer type in C"); 5816 } 5817 llvm_unreachable("Should have returned before this"); 5818 5819 case Type::STK_Floating: 5820 switch (DestTy->getScalarTypeKind()) { 5821 case Type::STK_Floating: 5822 return CK_FloatingCast; 5823 case Type::STK_Bool: 5824 return CK_FloatingToBoolean; 5825 case Type::STK_Integral: 5826 return CK_FloatingToIntegral; 5827 case Type::STK_FloatingComplex: 5828 Src = ImpCastExprToType(Src.get(), 5829 DestTy->castAs<ComplexType>()->getElementType(), 5830 CK_FloatingCast); 5831 return CK_FloatingRealToComplex; 5832 case Type::STK_IntegralComplex: 5833 Src = ImpCastExprToType(Src.get(), 5834 DestTy->castAs<ComplexType>()->getElementType(), 5835 CK_FloatingToIntegral); 5836 return CK_IntegralRealToComplex; 5837 case Type::STK_CPointer: 5838 case Type::STK_ObjCObjectPointer: 5839 case Type::STK_BlockPointer: 5840 llvm_unreachable("valid float->pointer cast?"); 5841 case Type::STK_MemberPointer: 5842 llvm_unreachable("member pointer type in C"); 5843 } 5844 llvm_unreachable("Should have returned before this"); 5845 5846 case Type::STK_FloatingComplex: 5847 switch (DestTy->getScalarTypeKind()) { 5848 case Type::STK_FloatingComplex: 5849 return CK_FloatingComplexCast; 5850 case Type::STK_IntegralComplex: 5851 return CK_FloatingComplexToIntegralComplex; 5852 case Type::STK_Floating: { 5853 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5854 if (Context.hasSameType(ET, DestTy)) 5855 return CK_FloatingComplexToReal; 5856 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 5857 return CK_FloatingCast; 5858 } 5859 case Type::STK_Bool: 5860 return CK_FloatingComplexToBoolean; 5861 case Type::STK_Integral: 5862 Src = ImpCastExprToType(Src.get(), 5863 SrcTy->castAs<ComplexType>()->getElementType(), 5864 CK_FloatingComplexToReal); 5865 return CK_FloatingToIntegral; 5866 case Type::STK_CPointer: 5867 case Type::STK_ObjCObjectPointer: 5868 case Type::STK_BlockPointer: 5869 llvm_unreachable("valid complex float->pointer cast?"); 5870 case Type::STK_MemberPointer: 5871 llvm_unreachable("member pointer type in C"); 5872 } 5873 llvm_unreachable("Should have returned before this"); 5874 5875 case Type::STK_IntegralComplex: 5876 switch (DestTy->getScalarTypeKind()) { 5877 case Type::STK_FloatingComplex: 5878 return CK_IntegralComplexToFloatingComplex; 5879 case Type::STK_IntegralComplex: 5880 return CK_IntegralComplexCast; 5881 case Type::STK_Integral: { 5882 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5883 if (Context.hasSameType(ET, DestTy)) 5884 return CK_IntegralComplexToReal; 5885 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 5886 return CK_IntegralCast; 5887 } 5888 case Type::STK_Bool: 5889 return CK_IntegralComplexToBoolean; 5890 case Type::STK_Floating: 5891 Src = ImpCastExprToType(Src.get(), 5892 SrcTy->castAs<ComplexType>()->getElementType(), 5893 CK_IntegralComplexToReal); 5894 return CK_IntegralToFloating; 5895 case Type::STK_CPointer: 5896 case Type::STK_ObjCObjectPointer: 5897 case Type::STK_BlockPointer: 5898 llvm_unreachable("valid complex int->pointer cast?"); 5899 case Type::STK_MemberPointer: 5900 llvm_unreachable("member pointer type in C"); 5901 } 5902 llvm_unreachable("Should have returned before this"); 5903 } 5904 5905 llvm_unreachable("Unhandled scalar cast"); 5906 } 5907 5908 static bool breakDownVectorType(QualType type, uint64_t &len, 5909 QualType &eltType) { 5910 // Vectors are simple. 5911 if (const VectorType *vecType = type->getAs<VectorType>()) { 5912 len = vecType->getNumElements(); 5913 eltType = vecType->getElementType(); 5914 assert(eltType->isScalarType()); 5915 return true; 5916 } 5917 5918 // We allow lax conversion to and from non-vector types, but only if 5919 // they're real types (i.e. non-complex, non-pointer scalar types). 5920 if (!type->isRealType()) return false; 5921 5922 len = 1; 5923 eltType = type; 5924 return true; 5925 } 5926 5927 /// Are the two types lax-compatible vector types? That is, given 5928 /// that one of them is a vector, do they have equal storage sizes, 5929 /// where the storage size is the number of elements times the element 5930 /// size? 5931 /// 5932 /// This will also return false if either of the types is neither a 5933 /// vector nor a real type. 5934 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 5935 assert(destTy->isVectorType() || srcTy->isVectorType()); 5936 5937 // Disallow lax conversions between scalars and ExtVectors (these 5938 // conversions are allowed for other vector types because common headers 5939 // depend on them). Most scalar OP ExtVector cases are handled by the 5940 // splat path anyway, which does what we want (convert, not bitcast). 5941 // What this rules out for ExtVectors is crazy things like char4*float. 5942 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 5943 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 5944 5945 uint64_t srcLen, destLen; 5946 QualType srcEltTy, destEltTy; 5947 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 5948 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 5949 5950 // ASTContext::getTypeSize will return the size rounded up to a 5951 // power of 2, so instead of using that, we need to use the raw 5952 // element size multiplied by the element count. 5953 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 5954 uint64_t destEltSize = Context.getTypeSize(destEltTy); 5955 5956 return (srcLen * srcEltSize == destLen * destEltSize); 5957 } 5958 5959 /// Is this a legal conversion between two types, one of which is 5960 /// known to be a vector type? 5961 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 5962 assert(destTy->isVectorType() || srcTy->isVectorType()); 5963 5964 if (!Context.getLangOpts().LaxVectorConversions) 5965 return false; 5966 return areLaxCompatibleVectorTypes(srcTy, destTy); 5967 } 5968 5969 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5970 CastKind &Kind) { 5971 assert(VectorTy->isVectorType() && "Not a vector type!"); 5972 5973 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 5974 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 5975 return Diag(R.getBegin(), 5976 Ty->isVectorType() ? 5977 diag::err_invalid_conversion_between_vectors : 5978 diag::err_invalid_conversion_between_vector_and_integer) 5979 << VectorTy << Ty << R; 5980 } else 5981 return Diag(R.getBegin(), 5982 diag::err_invalid_conversion_between_vector_and_scalar) 5983 << VectorTy << Ty << R; 5984 5985 Kind = CK_BitCast; 5986 return false; 5987 } 5988 5989 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 5990 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 5991 5992 if (DestElemTy == SplattedExpr->getType()) 5993 return SplattedExpr; 5994 5995 assert(DestElemTy->isFloatingType() || 5996 DestElemTy->isIntegralOrEnumerationType()); 5997 5998 CastKind CK; 5999 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 6000 // OpenCL requires that we convert `true` boolean expressions to -1, but 6001 // only when splatting vectors. 6002 if (DestElemTy->isFloatingType()) { 6003 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 6004 // in two steps: boolean to signed integral, then to floating. 6005 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 6006 CK_BooleanToSignedIntegral); 6007 SplattedExpr = CastExprRes.get(); 6008 CK = CK_IntegralToFloating; 6009 } else { 6010 CK = CK_BooleanToSignedIntegral; 6011 } 6012 } else { 6013 ExprResult CastExprRes = SplattedExpr; 6014 CK = PrepareScalarCast(CastExprRes, DestElemTy); 6015 if (CastExprRes.isInvalid()) 6016 return ExprError(); 6017 SplattedExpr = CastExprRes.get(); 6018 } 6019 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 6020 } 6021 6022 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 6023 Expr *CastExpr, CastKind &Kind) { 6024 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 6025 6026 QualType SrcTy = CastExpr->getType(); 6027 6028 // If SrcTy is a VectorType, the total size must match to explicitly cast to 6029 // an ExtVectorType. 6030 // In OpenCL, casts between vectors of different types are not allowed. 6031 // (See OpenCL 6.2). 6032 if (SrcTy->isVectorType()) { 6033 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) 6034 || (getLangOpts().OpenCL && 6035 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 6036 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 6037 << DestTy << SrcTy << R; 6038 return ExprError(); 6039 } 6040 Kind = CK_BitCast; 6041 return CastExpr; 6042 } 6043 6044 // All non-pointer scalars can be cast to ExtVector type. The appropriate 6045 // conversion will take place first from scalar to elt type, and then 6046 // splat from elt type to vector. 6047 if (SrcTy->isPointerType()) 6048 return Diag(R.getBegin(), 6049 diag::err_invalid_conversion_between_vector_and_scalar) 6050 << DestTy << SrcTy << R; 6051 6052 Kind = CK_VectorSplat; 6053 return prepareVectorSplat(DestTy, CastExpr); 6054 } 6055 6056 ExprResult 6057 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 6058 Declarator &D, ParsedType &Ty, 6059 SourceLocation RParenLoc, Expr *CastExpr) { 6060 assert(!D.isInvalidType() && (CastExpr != nullptr) && 6061 "ActOnCastExpr(): missing type or expr"); 6062 6063 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 6064 if (D.isInvalidType()) 6065 return ExprError(); 6066 6067 if (getLangOpts().CPlusPlus) { 6068 // Check that there are no default arguments (C++ only). 6069 CheckExtraCXXDefaultArguments(D); 6070 } else { 6071 // Make sure any TypoExprs have been dealt with. 6072 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 6073 if (!Res.isUsable()) 6074 return ExprError(); 6075 CastExpr = Res.get(); 6076 } 6077 6078 checkUnusedDeclAttributes(D); 6079 6080 QualType castType = castTInfo->getType(); 6081 Ty = CreateParsedType(castType, castTInfo); 6082 6083 bool isVectorLiteral = false; 6084 6085 // Check for an altivec or OpenCL literal, 6086 // i.e. all the elements are integer constants. 6087 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 6088 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 6089 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 6090 && castType->isVectorType() && (PE || PLE)) { 6091 if (PLE && PLE->getNumExprs() == 0) { 6092 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 6093 return ExprError(); 6094 } 6095 if (PE || PLE->getNumExprs() == 1) { 6096 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 6097 if (!E->getType()->isVectorType()) 6098 isVectorLiteral = true; 6099 } 6100 else 6101 isVectorLiteral = true; 6102 } 6103 6104 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 6105 // then handle it as such. 6106 if (isVectorLiteral) 6107 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 6108 6109 // If the Expr being casted is a ParenListExpr, handle it specially. 6110 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 6111 // sequence of BinOp comma operators. 6112 if (isa<ParenListExpr>(CastExpr)) { 6113 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 6114 if (Result.isInvalid()) return ExprError(); 6115 CastExpr = Result.get(); 6116 } 6117 6118 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6119 !getSourceManager().isInSystemMacro(LParenLoc)) 6120 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6121 6122 CheckTollFreeBridgeCast(castType, CastExpr); 6123 6124 CheckObjCBridgeRelatedCast(castType, CastExpr); 6125 6126 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 6127 6128 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6129 } 6130 6131 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6132 SourceLocation RParenLoc, Expr *E, 6133 TypeSourceInfo *TInfo) { 6134 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6135 "Expected paren or paren list expression"); 6136 6137 Expr **exprs; 6138 unsigned numExprs; 6139 Expr *subExpr; 6140 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6141 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6142 LiteralLParenLoc = PE->getLParenLoc(); 6143 LiteralRParenLoc = PE->getRParenLoc(); 6144 exprs = PE->getExprs(); 6145 numExprs = PE->getNumExprs(); 6146 } else { // isa<ParenExpr> by assertion at function entrance 6147 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6148 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6149 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6150 exprs = &subExpr; 6151 numExprs = 1; 6152 } 6153 6154 QualType Ty = TInfo->getType(); 6155 assert(Ty->isVectorType() && "Expected vector type"); 6156 6157 SmallVector<Expr *, 8> initExprs; 6158 const VectorType *VTy = Ty->getAs<VectorType>(); 6159 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 6160 6161 // '(...)' form of vector initialization in AltiVec: the number of 6162 // initializers must be one or must match the size of the vector. 6163 // If a single value is specified in the initializer then it will be 6164 // replicated to all the components of the vector 6165 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6166 // The number of initializers must be one or must match the size of the 6167 // vector. If a single value is specified in the initializer then it will 6168 // be replicated to all the components of the vector 6169 if (numExprs == 1) { 6170 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6171 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6172 if (Literal.isInvalid()) 6173 return ExprError(); 6174 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6175 PrepareScalarCast(Literal, ElemTy)); 6176 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6177 } 6178 else if (numExprs < numElems) { 6179 Diag(E->getExprLoc(), 6180 diag::err_incorrect_number_of_vector_initializers); 6181 return ExprError(); 6182 } 6183 else 6184 initExprs.append(exprs, exprs + numExprs); 6185 } 6186 else { 6187 // For OpenCL, when the number of initializers is a single value, 6188 // it will be replicated to all components of the vector. 6189 if (getLangOpts().OpenCL && 6190 VTy->getVectorKind() == VectorType::GenericVector && 6191 numExprs == 1) { 6192 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6193 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6194 if (Literal.isInvalid()) 6195 return ExprError(); 6196 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6197 PrepareScalarCast(Literal, ElemTy)); 6198 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6199 } 6200 6201 initExprs.append(exprs, exprs + numExprs); 6202 } 6203 // FIXME: This means that pretty-printing the final AST will produce curly 6204 // braces instead of the original commas. 6205 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6206 initExprs, LiteralRParenLoc); 6207 initE->setType(Ty); 6208 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6209 } 6210 6211 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6212 /// the ParenListExpr into a sequence of comma binary operators. 6213 ExprResult 6214 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6215 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6216 if (!E) 6217 return OrigExpr; 6218 6219 ExprResult Result(E->getExpr(0)); 6220 6221 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6222 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6223 E->getExpr(i)); 6224 6225 if (Result.isInvalid()) return ExprError(); 6226 6227 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6228 } 6229 6230 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6231 SourceLocation R, 6232 MultiExprArg Val) { 6233 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 6234 return expr; 6235 } 6236 6237 /// \brief Emit a specialized diagnostic when one expression is a null pointer 6238 /// constant and the other is not a pointer. Returns true if a diagnostic is 6239 /// emitted. 6240 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6241 SourceLocation QuestionLoc) { 6242 Expr *NullExpr = LHSExpr; 6243 Expr *NonPointerExpr = RHSExpr; 6244 Expr::NullPointerConstantKind NullKind = 6245 NullExpr->isNullPointerConstant(Context, 6246 Expr::NPC_ValueDependentIsNotNull); 6247 6248 if (NullKind == Expr::NPCK_NotNull) { 6249 NullExpr = RHSExpr; 6250 NonPointerExpr = LHSExpr; 6251 NullKind = 6252 NullExpr->isNullPointerConstant(Context, 6253 Expr::NPC_ValueDependentIsNotNull); 6254 } 6255 6256 if (NullKind == Expr::NPCK_NotNull) 6257 return false; 6258 6259 if (NullKind == Expr::NPCK_ZeroExpression) 6260 return false; 6261 6262 if (NullKind == Expr::NPCK_ZeroLiteral) { 6263 // In this case, check to make sure that we got here from a "NULL" 6264 // string in the source code. 6265 NullExpr = NullExpr->IgnoreParenImpCasts(); 6266 SourceLocation loc = NullExpr->getExprLoc(); 6267 if (!findMacroSpelling(loc, "NULL")) 6268 return false; 6269 } 6270 6271 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6272 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6273 << NonPointerExpr->getType() << DiagType 6274 << NonPointerExpr->getSourceRange(); 6275 return true; 6276 } 6277 6278 /// \brief Return false if the condition expression is valid, true otherwise. 6279 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6280 QualType CondTy = Cond->getType(); 6281 6282 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6283 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6284 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6285 << CondTy << Cond->getSourceRange(); 6286 return true; 6287 } 6288 6289 // C99 6.5.15p2 6290 if (CondTy->isScalarType()) return false; 6291 6292 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6293 << CondTy << Cond->getSourceRange(); 6294 return true; 6295 } 6296 6297 /// \brief Handle when one or both operands are void type. 6298 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6299 ExprResult &RHS) { 6300 Expr *LHSExpr = LHS.get(); 6301 Expr *RHSExpr = RHS.get(); 6302 6303 if (!LHSExpr->getType()->isVoidType()) 6304 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6305 << RHSExpr->getSourceRange(); 6306 if (!RHSExpr->getType()->isVoidType()) 6307 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6308 << LHSExpr->getSourceRange(); 6309 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6310 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6311 return S.Context.VoidTy; 6312 } 6313 6314 /// \brief Return false if the NullExpr can be promoted to PointerTy, 6315 /// true otherwise. 6316 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6317 QualType PointerTy) { 6318 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6319 !NullExpr.get()->isNullPointerConstant(S.Context, 6320 Expr::NPC_ValueDependentIsNull)) 6321 return true; 6322 6323 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6324 return false; 6325 } 6326 6327 /// \brief Checks compatibility between two pointers and return the resulting 6328 /// type. 6329 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6330 ExprResult &RHS, 6331 SourceLocation Loc) { 6332 QualType LHSTy = LHS.get()->getType(); 6333 QualType RHSTy = RHS.get()->getType(); 6334 6335 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6336 // Two identical pointers types are always compatible. 6337 return LHSTy; 6338 } 6339 6340 QualType lhptee, rhptee; 6341 6342 // Get the pointee types. 6343 bool IsBlockPointer = false; 6344 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6345 lhptee = LHSBTy->getPointeeType(); 6346 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6347 IsBlockPointer = true; 6348 } else { 6349 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6350 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6351 } 6352 6353 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6354 // differently qualified versions of compatible types, the result type is 6355 // a pointer to an appropriately qualified version of the composite 6356 // type. 6357 6358 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6359 // clause doesn't make sense for our extensions. E.g. address space 2 should 6360 // be incompatible with address space 3: they may live on different devices or 6361 // anything. 6362 Qualifiers lhQual = lhptee.getQualifiers(); 6363 Qualifiers rhQual = rhptee.getQualifiers(); 6364 6365 unsigned ResultAddrSpace = 0; 6366 unsigned LAddrSpace = lhQual.getAddressSpace(); 6367 unsigned RAddrSpace = rhQual.getAddressSpace(); 6368 if (S.getLangOpts().OpenCL) { 6369 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 6370 // spaces is disallowed. 6371 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 6372 ResultAddrSpace = LAddrSpace; 6373 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 6374 ResultAddrSpace = RAddrSpace; 6375 else { 6376 S.Diag(Loc, 6377 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 6378 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 6379 << RHS.get()->getSourceRange(); 6380 return QualType(); 6381 } 6382 } 6383 6384 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6385 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 6386 lhQual.removeCVRQualifiers(); 6387 rhQual.removeCVRQualifiers(); 6388 6389 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 6390 // (C99 6.7.3) for address spaces. We assume that the check should behave in 6391 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 6392 // qual types are compatible iff 6393 // * corresponded types are compatible 6394 // * CVR qualifiers are equal 6395 // * address spaces are equal 6396 // Thus for conditional operator we merge CVR and address space unqualified 6397 // pointees and if there is a composite type we return a pointer to it with 6398 // merged qualifiers. 6399 if (S.getLangOpts().OpenCL) { 6400 LHSCastKind = LAddrSpace == ResultAddrSpace 6401 ? CK_BitCast 6402 : CK_AddressSpaceConversion; 6403 RHSCastKind = RAddrSpace == ResultAddrSpace 6404 ? CK_BitCast 6405 : CK_AddressSpaceConversion; 6406 lhQual.removeAddressSpace(); 6407 rhQual.removeAddressSpace(); 6408 } 6409 6410 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 6411 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 6412 6413 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 6414 6415 if (CompositeTy.isNull()) { 6416 // In this situation, we assume void* type. No especially good 6417 // reason, but this is what gcc does, and we do have to pick 6418 // to get a consistent AST. 6419 QualType incompatTy; 6420 incompatTy = S.Context.getPointerType( 6421 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 6422 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 6423 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 6424 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 6425 // for casts between types with incompatible address space qualifiers. 6426 // For the following code the compiler produces casts between global and 6427 // local address spaces of the corresponded innermost pointees: 6428 // local int *global *a; 6429 // global int *global *b; 6430 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 6431 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 6432 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6433 << RHS.get()->getSourceRange(); 6434 return incompatTy; 6435 } 6436 6437 // The pointer types are compatible. 6438 // In case of OpenCL ResultTy should have the address space qualifier 6439 // which is a superset of address spaces of both the 2nd and the 3rd 6440 // operands of the conditional operator. 6441 QualType ResultTy = [&, ResultAddrSpace]() { 6442 if (S.getLangOpts().OpenCL) { 6443 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 6444 CompositeQuals.setAddressSpace(ResultAddrSpace); 6445 return S.Context 6446 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 6447 .withCVRQualifiers(MergedCVRQual); 6448 } 6449 return CompositeTy.withCVRQualifiers(MergedCVRQual); 6450 }(); 6451 if (IsBlockPointer) 6452 ResultTy = S.Context.getBlockPointerType(ResultTy); 6453 else 6454 ResultTy = S.Context.getPointerType(ResultTy); 6455 6456 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 6457 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 6458 return ResultTy; 6459 } 6460 6461 /// \brief Return the resulting type when the operands are both block pointers. 6462 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 6463 ExprResult &LHS, 6464 ExprResult &RHS, 6465 SourceLocation Loc) { 6466 QualType LHSTy = LHS.get()->getType(); 6467 QualType RHSTy = RHS.get()->getType(); 6468 6469 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 6470 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 6471 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 6472 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6473 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6474 return destType; 6475 } 6476 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 6477 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6478 << RHS.get()->getSourceRange(); 6479 return QualType(); 6480 } 6481 6482 // We have 2 block pointer types. 6483 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6484 } 6485 6486 /// \brief Return the resulting type when the operands are both pointers. 6487 static QualType 6488 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 6489 ExprResult &RHS, 6490 SourceLocation Loc) { 6491 // get the pointer types 6492 QualType LHSTy = LHS.get()->getType(); 6493 QualType RHSTy = RHS.get()->getType(); 6494 6495 // get the "pointed to" types 6496 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6497 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6498 6499 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 6500 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 6501 // Figure out necessary qualifiers (C99 6.5.15p6) 6502 QualType destPointee 6503 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6504 QualType destType = S.Context.getPointerType(destPointee); 6505 // Add qualifiers if necessary. 6506 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6507 // Promote to void*. 6508 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6509 return destType; 6510 } 6511 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 6512 QualType destPointee 6513 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6514 QualType destType = S.Context.getPointerType(destPointee); 6515 // Add qualifiers if necessary. 6516 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6517 // Promote to void*. 6518 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6519 return destType; 6520 } 6521 6522 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6523 } 6524 6525 /// \brief Return false if the first expression is not an integer and the second 6526 /// expression is not a pointer, true otherwise. 6527 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 6528 Expr* PointerExpr, SourceLocation Loc, 6529 bool IsIntFirstExpr) { 6530 if (!PointerExpr->getType()->isPointerType() || 6531 !Int.get()->getType()->isIntegerType()) 6532 return false; 6533 6534 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 6535 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 6536 6537 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 6538 << Expr1->getType() << Expr2->getType() 6539 << Expr1->getSourceRange() << Expr2->getSourceRange(); 6540 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 6541 CK_IntegralToPointer); 6542 return true; 6543 } 6544 6545 /// \brief Simple conversion between integer and floating point types. 6546 /// 6547 /// Used when handling the OpenCL conditional operator where the 6548 /// condition is a vector while the other operands are scalar. 6549 /// 6550 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 6551 /// types are either integer or floating type. Between the two 6552 /// operands, the type with the higher rank is defined as the "result 6553 /// type". The other operand needs to be promoted to the same type. No 6554 /// other type promotion is allowed. We cannot use 6555 /// UsualArithmeticConversions() for this purpose, since it always 6556 /// promotes promotable types. 6557 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 6558 ExprResult &RHS, 6559 SourceLocation QuestionLoc) { 6560 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 6561 if (LHS.isInvalid()) 6562 return QualType(); 6563 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 6564 if (RHS.isInvalid()) 6565 return QualType(); 6566 6567 // For conversion purposes, we ignore any qualifiers. 6568 // For example, "const float" and "float" are equivalent. 6569 QualType LHSType = 6570 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6571 QualType RHSType = 6572 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6573 6574 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 6575 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6576 << LHSType << LHS.get()->getSourceRange(); 6577 return QualType(); 6578 } 6579 6580 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 6581 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6582 << RHSType << RHS.get()->getSourceRange(); 6583 return QualType(); 6584 } 6585 6586 // If both types are identical, no conversion is needed. 6587 if (LHSType == RHSType) 6588 return LHSType; 6589 6590 // Now handle "real" floating types (i.e. float, double, long double). 6591 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 6592 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 6593 /*IsCompAssign = */ false); 6594 6595 // Finally, we have two differing integer types. 6596 return handleIntegerConversion<doIntegralCast, doIntegralCast> 6597 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 6598 } 6599 6600 /// \brief Convert scalar operands to a vector that matches the 6601 /// condition in length. 6602 /// 6603 /// Used when handling the OpenCL conditional operator where the 6604 /// condition is a vector while the other operands are scalar. 6605 /// 6606 /// We first compute the "result type" for the scalar operands 6607 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 6608 /// into a vector of that type where the length matches the condition 6609 /// vector type. s6.11.6 requires that the element types of the result 6610 /// and the condition must have the same number of bits. 6611 static QualType 6612 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 6613 QualType CondTy, SourceLocation QuestionLoc) { 6614 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 6615 if (ResTy.isNull()) return QualType(); 6616 6617 const VectorType *CV = CondTy->getAs<VectorType>(); 6618 assert(CV); 6619 6620 // Determine the vector result type 6621 unsigned NumElements = CV->getNumElements(); 6622 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 6623 6624 // Ensure that all types have the same number of bits 6625 if (S.Context.getTypeSize(CV->getElementType()) 6626 != S.Context.getTypeSize(ResTy)) { 6627 // Since VectorTy is created internally, it does not pretty print 6628 // with an OpenCL name. Instead, we just print a description. 6629 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 6630 SmallString<64> Str; 6631 llvm::raw_svector_ostream OS(Str); 6632 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 6633 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6634 << CondTy << OS.str(); 6635 return QualType(); 6636 } 6637 6638 // Convert operands to the vector result type 6639 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 6640 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 6641 6642 return VectorTy; 6643 } 6644 6645 /// \brief Return false if this is a valid OpenCL condition vector 6646 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 6647 SourceLocation QuestionLoc) { 6648 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 6649 // integral type. 6650 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 6651 assert(CondTy); 6652 QualType EleTy = CondTy->getElementType(); 6653 if (EleTy->isIntegerType()) return false; 6654 6655 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6656 << Cond->getType() << Cond->getSourceRange(); 6657 return true; 6658 } 6659 6660 /// \brief Return false if the vector condition type and the vector 6661 /// result type are compatible. 6662 /// 6663 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 6664 /// number of elements, and their element types have the same number 6665 /// of bits. 6666 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 6667 SourceLocation QuestionLoc) { 6668 const VectorType *CV = CondTy->getAs<VectorType>(); 6669 const VectorType *RV = VecResTy->getAs<VectorType>(); 6670 assert(CV && RV); 6671 6672 if (CV->getNumElements() != RV->getNumElements()) { 6673 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 6674 << CondTy << VecResTy; 6675 return true; 6676 } 6677 6678 QualType CVE = CV->getElementType(); 6679 QualType RVE = RV->getElementType(); 6680 6681 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 6682 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6683 << CondTy << VecResTy; 6684 return true; 6685 } 6686 6687 return false; 6688 } 6689 6690 /// \brief Return the resulting type for the conditional operator in 6691 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 6692 /// s6.3.i) when the condition is a vector type. 6693 static QualType 6694 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 6695 ExprResult &LHS, ExprResult &RHS, 6696 SourceLocation QuestionLoc) { 6697 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 6698 if (Cond.isInvalid()) 6699 return QualType(); 6700 QualType CondTy = Cond.get()->getType(); 6701 6702 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 6703 return QualType(); 6704 6705 // If either operand is a vector then find the vector type of the 6706 // result as specified in OpenCL v1.1 s6.3.i. 6707 if (LHS.get()->getType()->isVectorType() || 6708 RHS.get()->getType()->isVectorType()) { 6709 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 6710 /*isCompAssign*/false, 6711 /*AllowBothBool*/true, 6712 /*AllowBoolConversions*/false); 6713 if (VecResTy.isNull()) return QualType(); 6714 // The result type must match the condition type as specified in 6715 // OpenCL v1.1 s6.11.6. 6716 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 6717 return QualType(); 6718 return VecResTy; 6719 } 6720 6721 // Both operands are scalar. 6722 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 6723 } 6724 6725 /// \brief Return true if the Expr is block type 6726 static bool checkBlockType(Sema &S, const Expr *E) { 6727 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 6728 QualType Ty = CE->getCallee()->getType(); 6729 if (Ty->isBlockPointerType()) { 6730 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 6731 return true; 6732 } 6733 } 6734 return false; 6735 } 6736 6737 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 6738 /// In that case, LHS = cond. 6739 /// C99 6.5.15 6740 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 6741 ExprResult &RHS, ExprValueKind &VK, 6742 ExprObjectKind &OK, 6743 SourceLocation QuestionLoc) { 6744 6745 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 6746 if (!LHSResult.isUsable()) return QualType(); 6747 LHS = LHSResult; 6748 6749 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 6750 if (!RHSResult.isUsable()) return QualType(); 6751 RHS = RHSResult; 6752 6753 // C++ is sufficiently different to merit its own checker. 6754 if (getLangOpts().CPlusPlus) 6755 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 6756 6757 VK = VK_RValue; 6758 OK = OK_Ordinary; 6759 6760 // The OpenCL operator with a vector condition is sufficiently 6761 // different to merit its own checker. 6762 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 6763 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 6764 6765 // First, check the condition. 6766 Cond = UsualUnaryConversions(Cond.get()); 6767 if (Cond.isInvalid()) 6768 return QualType(); 6769 if (checkCondition(*this, Cond.get(), QuestionLoc)) 6770 return QualType(); 6771 6772 // Now check the two expressions. 6773 if (LHS.get()->getType()->isVectorType() || 6774 RHS.get()->getType()->isVectorType()) 6775 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 6776 /*AllowBothBool*/true, 6777 /*AllowBoolConversions*/false); 6778 6779 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 6780 if (LHS.isInvalid() || RHS.isInvalid()) 6781 return QualType(); 6782 6783 QualType LHSTy = LHS.get()->getType(); 6784 QualType RHSTy = RHS.get()->getType(); 6785 6786 // Diagnose attempts to convert between __float128 and long double where 6787 // such conversions currently can't be handled. 6788 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 6789 Diag(QuestionLoc, 6790 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 6791 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6792 return QualType(); 6793 } 6794 6795 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 6796 // selection operator (?:). 6797 if (getLangOpts().OpenCL && 6798 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 6799 return QualType(); 6800 } 6801 6802 // If both operands have arithmetic type, do the usual arithmetic conversions 6803 // to find a common type: C99 6.5.15p3,5. 6804 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 6805 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 6806 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 6807 6808 return ResTy; 6809 } 6810 6811 // If both operands are the same structure or union type, the result is that 6812 // type. 6813 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 6814 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 6815 if (LHSRT->getDecl() == RHSRT->getDecl()) 6816 // "If both the operands have structure or union type, the result has 6817 // that type." This implies that CV qualifiers are dropped. 6818 return LHSTy.getUnqualifiedType(); 6819 // FIXME: Type of conditional expression must be complete in C mode. 6820 } 6821 6822 // C99 6.5.15p5: "If both operands have void type, the result has void type." 6823 // The following || allows only one side to be void (a GCC-ism). 6824 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 6825 return checkConditionalVoidType(*this, LHS, RHS); 6826 } 6827 6828 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 6829 // the type of the other operand." 6830 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 6831 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 6832 6833 // All objective-c pointer type analysis is done here. 6834 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 6835 QuestionLoc); 6836 if (LHS.isInvalid() || RHS.isInvalid()) 6837 return QualType(); 6838 if (!compositeType.isNull()) 6839 return compositeType; 6840 6841 6842 // Handle block pointer types. 6843 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 6844 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 6845 QuestionLoc); 6846 6847 // Check constraints for C object pointers types (C99 6.5.15p3,6). 6848 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 6849 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 6850 QuestionLoc); 6851 6852 // GCC compatibility: soften pointer/integer mismatch. Note that 6853 // null pointers have been filtered out by this point. 6854 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 6855 /*isIntFirstExpr=*/true)) 6856 return RHSTy; 6857 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 6858 /*isIntFirstExpr=*/false)) 6859 return LHSTy; 6860 6861 // Emit a better diagnostic if one of the expressions is a null pointer 6862 // constant and the other is not a pointer type. In this case, the user most 6863 // likely forgot to take the address of the other expression. 6864 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 6865 return QualType(); 6866 6867 // Otherwise, the operands are not compatible. 6868 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 6869 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6870 << RHS.get()->getSourceRange(); 6871 return QualType(); 6872 } 6873 6874 /// FindCompositeObjCPointerType - Helper method to find composite type of 6875 /// two objective-c pointer types of the two input expressions. 6876 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 6877 SourceLocation QuestionLoc) { 6878 QualType LHSTy = LHS.get()->getType(); 6879 QualType RHSTy = RHS.get()->getType(); 6880 6881 // Handle things like Class and struct objc_class*. Here we case the result 6882 // to the pseudo-builtin, because that will be implicitly cast back to the 6883 // redefinition type if an attempt is made to access its fields. 6884 if (LHSTy->isObjCClassType() && 6885 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 6886 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6887 return LHSTy; 6888 } 6889 if (RHSTy->isObjCClassType() && 6890 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 6891 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6892 return RHSTy; 6893 } 6894 // And the same for struct objc_object* / id 6895 if (LHSTy->isObjCIdType() && 6896 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 6897 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6898 return LHSTy; 6899 } 6900 if (RHSTy->isObjCIdType() && 6901 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 6902 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6903 return RHSTy; 6904 } 6905 // And the same for struct objc_selector* / SEL 6906 if (Context.isObjCSelType(LHSTy) && 6907 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 6908 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 6909 return LHSTy; 6910 } 6911 if (Context.isObjCSelType(RHSTy) && 6912 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 6913 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 6914 return RHSTy; 6915 } 6916 // Check constraints for Objective-C object pointers types. 6917 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 6918 6919 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 6920 // Two identical object pointer types are always compatible. 6921 return LHSTy; 6922 } 6923 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 6924 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 6925 QualType compositeType = LHSTy; 6926 6927 // If both operands are interfaces and either operand can be 6928 // assigned to the other, use that type as the composite 6929 // type. This allows 6930 // xxx ? (A*) a : (B*) b 6931 // where B is a subclass of A. 6932 // 6933 // Additionally, as for assignment, if either type is 'id' 6934 // allow silent coercion. Finally, if the types are 6935 // incompatible then make sure to use 'id' as the composite 6936 // type so the result is acceptable for sending messages to. 6937 6938 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 6939 // It could return the composite type. 6940 if (!(compositeType = 6941 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 6942 // Nothing more to do. 6943 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 6944 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 6945 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 6946 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 6947 } else if ((LHSTy->isObjCQualifiedIdType() || 6948 RHSTy->isObjCQualifiedIdType()) && 6949 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 6950 // Need to handle "id<xx>" explicitly. 6951 // GCC allows qualified id and any Objective-C type to devolve to 6952 // id. Currently localizing to here until clear this should be 6953 // part of ObjCQualifiedIdTypesAreCompatible. 6954 compositeType = Context.getObjCIdType(); 6955 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 6956 compositeType = Context.getObjCIdType(); 6957 } else { 6958 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 6959 << LHSTy << RHSTy 6960 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6961 QualType incompatTy = Context.getObjCIdType(); 6962 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6963 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6964 return incompatTy; 6965 } 6966 // The object pointer types are compatible. 6967 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 6968 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 6969 return compositeType; 6970 } 6971 // Check Objective-C object pointer types and 'void *' 6972 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 6973 if (getLangOpts().ObjCAutoRefCount) { 6974 // ARC forbids the implicit conversion of object pointers to 'void *', 6975 // so these types are not compatible. 6976 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6977 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6978 LHS = RHS = true; 6979 return QualType(); 6980 } 6981 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6982 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6983 QualType destPointee 6984 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6985 QualType destType = Context.getPointerType(destPointee); 6986 // Add qualifiers if necessary. 6987 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6988 // Promote to void*. 6989 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6990 return destType; 6991 } 6992 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 6993 if (getLangOpts().ObjCAutoRefCount) { 6994 // ARC forbids the implicit conversion of object pointers to 'void *', 6995 // so these types are not compatible. 6996 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6997 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6998 LHS = RHS = true; 6999 return QualType(); 7000 } 7001 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 7002 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 7003 QualType destPointee 7004 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7005 QualType destType = Context.getPointerType(destPointee); 7006 // Add qualifiers if necessary. 7007 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7008 // Promote to void*. 7009 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7010 return destType; 7011 } 7012 return QualType(); 7013 } 7014 7015 /// SuggestParentheses - Emit a note with a fixit hint that wraps 7016 /// ParenRange in parentheses. 7017 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 7018 const PartialDiagnostic &Note, 7019 SourceRange ParenRange) { 7020 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 7021 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 7022 EndLoc.isValid()) { 7023 Self.Diag(Loc, Note) 7024 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 7025 << FixItHint::CreateInsertion(EndLoc, ")"); 7026 } else { 7027 // We can't display the parentheses, so just show the bare note. 7028 Self.Diag(Loc, Note) << ParenRange; 7029 } 7030 } 7031 7032 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 7033 return BinaryOperator::isAdditiveOp(Opc) || 7034 BinaryOperator::isMultiplicativeOp(Opc) || 7035 BinaryOperator::isShiftOp(Opc); 7036 } 7037 7038 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 7039 /// expression, either using a built-in or overloaded operator, 7040 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 7041 /// expression. 7042 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 7043 Expr **RHSExprs) { 7044 // Don't strip parenthesis: we should not warn if E is in parenthesis. 7045 E = E->IgnoreImpCasts(); 7046 E = E->IgnoreConversionOperator(); 7047 E = E->IgnoreImpCasts(); 7048 7049 // Built-in binary operator. 7050 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 7051 if (IsArithmeticOp(OP->getOpcode())) { 7052 *Opcode = OP->getOpcode(); 7053 *RHSExprs = OP->getRHS(); 7054 return true; 7055 } 7056 } 7057 7058 // Overloaded operator. 7059 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 7060 if (Call->getNumArgs() != 2) 7061 return false; 7062 7063 // Make sure this is really a binary operator that is safe to pass into 7064 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 7065 OverloadedOperatorKind OO = Call->getOperator(); 7066 if (OO < OO_Plus || OO > OO_Arrow || 7067 OO == OO_PlusPlus || OO == OO_MinusMinus) 7068 return false; 7069 7070 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 7071 if (IsArithmeticOp(OpKind)) { 7072 *Opcode = OpKind; 7073 *RHSExprs = Call->getArg(1); 7074 return true; 7075 } 7076 } 7077 7078 return false; 7079 } 7080 7081 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 7082 /// or is a logical expression such as (x==y) which has int type, but is 7083 /// commonly interpreted as boolean. 7084 static bool ExprLooksBoolean(Expr *E) { 7085 E = E->IgnoreParenImpCasts(); 7086 7087 if (E->getType()->isBooleanType()) 7088 return true; 7089 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 7090 return OP->isComparisonOp() || OP->isLogicalOp(); 7091 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 7092 return OP->getOpcode() == UO_LNot; 7093 if (E->getType()->isPointerType()) 7094 return true; 7095 7096 return false; 7097 } 7098 7099 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 7100 /// and binary operator are mixed in a way that suggests the programmer assumed 7101 /// the conditional operator has higher precedence, for example: 7102 /// "int x = a + someBinaryCondition ? 1 : 2". 7103 static void DiagnoseConditionalPrecedence(Sema &Self, 7104 SourceLocation OpLoc, 7105 Expr *Condition, 7106 Expr *LHSExpr, 7107 Expr *RHSExpr) { 7108 BinaryOperatorKind CondOpcode; 7109 Expr *CondRHS; 7110 7111 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 7112 return; 7113 if (!ExprLooksBoolean(CondRHS)) 7114 return; 7115 7116 // The condition is an arithmetic binary expression, with a right- 7117 // hand side that looks boolean, so warn. 7118 7119 Self.Diag(OpLoc, diag::warn_precedence_conditional) 7120 << Condition->getSourceRange() 7121 << BinaryOperator::getOpcodeStr(CondOpcode); 7122 7123 SuggestParentheses(Self, OpLoc, 7124 Self.PDiag(diag::note_precedence_silence) 7125 << BinaryOperator::getOpcodeStr(CondOpcode), 7126 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 7127 7128 SuggestParentheses(Self, OpLoc, 7129 Self.PDiag(diag::note_precedence_conditional_first), 7130 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 7131 } 7132 7133 /// Compute the nullability of a conditional expression. 7134 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 7135 QualType LHSTy, QualType RHSTy, 7136 ASTContext &Ctx) { 7137 if (!ResTy->isAnyPointerType()) 7138 return ResTy; 7139 7140 auto GetNullability = [&Ctx](QualType Ty) { 7141 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 7142 if (Kind) 7143 return *Kind; 7144 return NullabilityKind::Unspecified; 7145 }; 7146 7147 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 7148 NullabilityKind MergedKind; 7149 7150 // Compute nullability of a binary conditional expression. 7151 if (IsBin) { 7152 if (LHSKind == NullabilityKind::NonNull) 7153 MergedKind = NullabilityKind::NonNull; 7154 else 7155 MergedKind = RHSKind; 7156 // Compute nullability of a normal conditional expression. 7157 } else { 7158 if (LHSKind == NullabilityKind::Nullable || 7159 RHSKind == NullabilityKind::Nullable) 7160 MergedKind = NullabilityKind::Nullable; 7161 else if (LHSKind == NullabilityKind::NonNull) 7162 MergedKind = RHSKind; 7163 else if (RHSKind == NullabilityKind::NonNull) 7164 MergedKind = LHSKind; 7165 else 7166 MergedKind = NullabilityKind::Unspecified; 7167 } 7168 7169 // Return if ResTy already has the correct nullability. 7170 if (GetNullability(ResTy) == MergedKind) 7171 return ResTy; 7172 7173 // Strip all nullability from ResTy. 7174 while (ResTy->getNullability(Ctx)) 7175 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 7176 7177 // Create a new AttributedType with the new nullability kind. 7178 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 7179 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 7180 } 7181 7182 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7183 /// in the case of a the GNU conditional expr extension. 7184 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7185 SourceLocation ColonLoc, 7186 Expr *CondExpr, Expr *LHSExpr, 7187 Expr *RHSExpr) { 7188 if (!getLangOpts().CPlusPlus) { 7189 // C cannot handle TypoExpr nodes in the condition because it 7190 // doesn't handle dependent types properly, so make sure any TypoExprs have 7191 // been dealt with before checking the operands. 7192 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7193 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7194 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7195 7196 if (!CondResult.isUsable()) 7197 return ExprError(); 7198 7199 if (LHSExpr) { 7200 if (!LHSResult.isUsable()) 7201 return ExprError(); 7202 } 7203 7204 if (!RHSResult.isUsable()) 7205 return ExprError(); 7206 7207 CondExpr = CondResult.get(); 7208 LHSExpr = LHSResult.get(); 7209 RHSExpr = RHSResult.get(); 7210 } 7211 7212 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7213 // was the condition. 7214 OpaqueValueExpr *opaqueValue = nullptr; 7215 Expr *commonExpr = nullptr; 7216 if (!LHSExpr) { 7217 commonExpr = CondExpr; 7218 // Lower out placeholder types first. This is important so that we don't 7219 // try to capture a placeholder. This happens in few cases in C++; such 7220 // as Objective-C++'s dictionary subscripting syntax. 7221 if (commonExpr->hasPlaceholderType()) { 7222 ExprResult result = CheckPlaceholderExpr(commonExpr); 7223 if (!result.isUsable()) return ExprError(); 7224 commonExpr = result.get(); 7225 } 7226 // We usually want to apply unary conversions *before* saving, except 7227 // in the special case of a C++ l-value conditional. 7228 if (!(getLangOpts().CPlusPlus 7229 && !commonExpr->isTypeDependent() 7230 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7231 && commonExpr->isGLValue() 7232 && commonExpr->isOrdinaryOrBitFieldObject() 7233 && RHSExpr->isOrdinaryOrBitFieldObject() 7234 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7235 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7236 if (commonRes.isInvalid()) 7237 return ExprError(); 7238 commonExpr = commonRes.get(); 7239 } 7240 7241 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7242 commonExpr->getType(), 7243 commonExpr->getValueKind(), 7244 commonExpr->getObjectKind(), 7245 commonExpr); 7246 LHSExpr = CondExpr = opaqueValue; 7247 } 7248 7249 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 7250 ExprValueKind VK = VK_RValue; 7251 ExprObjectKind OK = OK_Ordinary; 7252 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7253 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7254 VK, OK, QuestionLoc); 7255 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7256 RHS.isInvalid()) 7257 return ExprError(); 7258 7259 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7260 RHS.get()); 7261 7262 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 7263 7264 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 7265 Context); 7266 7267 if (!commonExpr) 7268 return new (Context) 7269 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 7270 RHS.get(), result, VK, OK); 7271 7272 return new (Context) BinaryConditionalOperator( 7273 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 7274 ColonLoc, result, VK, OK); 7275 } 7276 7277 // checkPointerTypesForAssignment - This is a very tricky routine (despite 7278 // being closely modeled after the C99 spec:-). The odd characteristic of this 7279 // routine is it effectively iqnores the qualifiers on the top level pointee. 7280 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 7281 // FIXME: add a couple examples in this comment. 7282 static Sema::AssignConvertType 7283 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 7284 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7285 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7286 7287 // get the "pointed to" type (ignoring qualifiers at the top level) 7288 const Type *lhptee, *rhptee; 7289 Qualifiers lhq, rhq; 7290 std::tie(lhptee, lhq) = 7291 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 7292 std::tie(rhptee, rhq) = 7293 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 7294 7295 Sema::AssignConvertType ConvTy = Sema::Compatible; 7296 7297 // C99 6.5.16.1p1: This following citation is common to constraints 7298 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 7299 // qualifiers of the type *pointed to* by the right; 7300 7301 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 7302 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 7303 lhq.compatiblyIncludesObjCLifetime(rhq)) { 7304 // Ignore lifetime for further calculation. 7305 lhq.removeObjCLifetime(); 7306 rhq.removeObjCLifetime(); 7307 } 7308 7309 if (!lhq.compatiblyIncludes(rhq)) { 7310 // Treat address-space mismatches as fatal. TODO: address subspaces 7311 if (!lhq.isAddressSpaceSupersetOf(rhq)) 7312 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7313 7314 // It's okay to add or remove GC or lifetime qualifiers when converting to 7315 // and from void*. 7316 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 7317 .compatiblyIncludes( 7318 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 7319 && (lhptee->isVoidType() || rhptee->isVoidType())) 7320 ; // keep old 7321 7322 // Treat lifetime mismatches as fatal. 7323 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 7324 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7325 7326 // For GCC/MS compatibility, other qualifier mismatches are treated 7327 // as still compatible in C. 7328 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7329 } 7330 7331 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 7332 // incomplete type and the other is a pointer to a qualified or unqualified 7333 // version of void... 7334 if (lhptee->isVoidType()) { 7335 if (rhptee->isIncompleteOrObjectType()) 7336 return ConvTy; 7337 7338 // As an extension, we allow cast to/from void* to function pointer. 7339 assert(rhptee->isFunctionType()); 7340 return Sema::FunctionVoidPointer; 7341 } 7342 7343 if (rhptee->isVoidType()) { 7344 if (lhptee->isIncompleteOrObjectType()) 7345 return ConvTy; 7346 7347 // As an extension, we allow cast to/from void* to function pointer. 7348 assert(lhptee->isFunctionType()); 7349 return Sema::FunctionVoidPointer; 7350 } 7351 7352 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7353 // unqualified versions of compatible types, ... 7354 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7355 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7356 // Check if the pointee types are compatible ignoring the sign. 7357 // We explicitly check for char so that we catch "char" vs 7358 // "unsigned char" on systems where "char" is unsigned. 7359 if (lhptee->isCharType()) 7360 ltrans = S.Context.UnsignedCharTy; 7361 else if (lhptee->hasSignedIntegerRepresentation()) 7362 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7363 7364 if (rhptee->isCharType()) 7365 rtrans = S.Context.UnsignedCharTy; 7366 else if (rhptee->hasSignedIntegerRepresentation()) 7367 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 7368 7369 if (ltrans == rtrans) { 7370 // Types are compatible ignoring the sign. Qualifier incompatibility 7371 // takes priority over sign incompatibility because the sign 7372 // warning can be disabled. 7373 if (ConvTy != Sema::Compatible) 7374 return ConvTy; 7375 7376 return Sema::IncompatiblePointerSign; 7377 } 7378 7379 // If we are a multi-level pointer, it's possible that our issue is simply 7380 // one of qualification - e.g. char ** -> const char ** is not allowed. If 7381 // the eventual target type is the same and the pointers have the same 7382 // level of indirection, this must be the issue. 7383 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 7384 do { 7385 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 7386 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 7387 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 7388 7389 if (lhptee == rhptee) 7390 return Sema::IncompatibleNestedPointerQualifiers; 7391 } 7392 7393 // General pointer incompatibility takes priority over qualifiers. 7394 return Sema::IncompatiblePointer; 7395 } 7396 if (!S.getLangOpts().CPlusPlus && 7397 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 7398 return Sema::IncompatiblePointer; 7399 return ConvTy; 7400 } 7401 7402 /// checkBlockPointerTypesForAssignment - This routine determines whether two 7403 /// block pointer types are compatible or whether a block and normal pointer 7404 /// are compatible. It is more restrict than comparing two function pointer 7405 // types. 7406 static Sema::AssignConvertType 7407 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 7408 QualType RHSType) { 7409 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7410 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7411 7412 QualType lhptee, rhptee; 7413 7414 // get the "pointed to" type (ignoring qualifiers at the top level) 7415 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 7416 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 7417 7418 // In C++, the types have to match exactly. 7419 if (S.getLangOpts().CPlusPlus) 7420 return Sema::IncompatibleBlockPointer; 7421 7422 Sema::AssignConvertType ConvTy = Sema::Compatible; 7423 7424 // For blocks we enforce that qualifiers are identical. 7425 Qualifiers LQuals = lhptee.getLocalQualifiers(); 7426 Qualifiers RQuals = rhptee.getLocalQualifiers(); 7427 if (S.getLangOpts().OpenCL) { 7428 LQuals.removeAddressSpace(); 7429 RQuals.removeAddressSpace(); 7430 } 7431 if (LQuals != RQuals) 7432 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7433 7434 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 7435 // assignment. 7436 // The current behavior is similar to C++ lambdas. A block might be 7437 // assigned to a variable iff its return type and parameters are compatible 7438 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 7439 // an assignment. Presumably it should behave in way that a function pointer 7440 // assignment does in C, so for each parameter and return type: 7441 // * CVR and address space of LHS should be a superset of CVR and address 7442 // space of RHS. 7443 // * unqualified types should be compatible. 7444 if (S.getLangOpts().OpenCL) { 7445 if (!S.Context.typesAreBlockPointerCompatible( 7446 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 7447 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 7448 return Sema::IncompatibleBlockPointer; 7449 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 7450 return Sema::IncompatibleBlockPointer; 7451 7452 return ConvTy; 7453 } 7454 7455 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 7456 /// for assignment compatibility. 7457 static Sema::AssignConvertType 7458 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 7459 QualType RHSType) { 7460 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 7461 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 7462 7463 if (LHSType->isObjCBuiltinType()) { 7464 // Class is not compatible with ObjC object pointers. 7465 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 7466 !RHSType->isObjCQualifiedClassType()) 7467 return Sema::IncompatiblePointer; 7468 return Sema::Compatible; 7469 } 7470 if (RHSType->isObjCBuiltinType()) { 7471 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 7472 !LHSType->isObjCQualifiedClassType()) 7473 return Sema::IncompatiblePointer; 7474 return Sema::Compatible; 7475 } 7476 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7477 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7478 7479 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 7480 // make an exception for id<P> 7481 !LHSType->isObjCQualifiedIdType()) 7482 return Sema::CompatiblePointerDiscardsQualifiers; 7483 7484 if (S.Context.typesAreCompatible(LHSType, RHSType)) 7485 return Sema::Compatible; 7486 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 7487 return Sema::IncompatibleObjCQualifiedId; 7488 return Sema::IncompatiblePointer; 7489 } 7490 7491 Sema::AssignConvertType 7492 Sema::CheckAssignmentConstraints(SourceLocation Loc, 7493 QualType LHSType, QualType RHSType) { 7494 // Fake up an opaque expression. We don't actually care about what 7495 // cast operations are required, so if CheckAssignmentConstraints 7496 // adds casts to this they'll be wasted, but fortunately that doesn't 7497 // usually happen on valid code. 7498 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 7499 ExprResult RHSPtr = &RHSExpr; 7500 CastKind K = CK_Invalid; 7501 7502 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 7503 } 7504 7505 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 7506 /// has code to accommodate several GCC extensions when type checking 7507 /// pointers. Here are some objectionable examples that GCC considers warnings: 7508 /// 7509 /// int a, *pint; 7510 /// short *pshort; 7511 /// struct foo *pfoo; 7512 /// 7513 /// pint = pshort; // warning: assignment from incompatible pointer type 7514 /// a = pint; // warning: assignment makes integer from pointer without a cast 7515 /// pint = a; // warning: assignment makes pointer from integer without a cast 7516 /// pint = pfoo; // warning: assignment from incompatible pointer type 7517 /// 7518 /// As a result, the code for dealing with pointers is more complex than the 7519 /// C99 spec dictates. 7520 /// 7521 /// Sets 'Kind' for any result kind except Incompatible. 7522 Sema::AssignConvertType 7523 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 7524 CastKind &Kind, bool ConvertRHS) { 7525 QualType RHSType = RHS.get()->getType(); 7526 QualType OrigLHSType = LHSType; 7527 7528 // Get canonical types. We're not formatting these types, just comparing 7529 // them. 7530 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 7531 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 7532 7533 // Common case: no conversion required. 7534 if (LHSType == RHSType) { 7535 Kind = CK_NoOp; 7536 return Compatible; 7537 } 7538 7539 // If we have an atomic type, try a non-atomic assignment, then just add an 7540 // atomic qualification step. 7541 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 7542 Sema::AssignConvertType result = 7543 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 7544 if (result != Compatible) 7545 return result; 7546 if (Kind != CK_NoOp && ConvertRHS) 7547 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 7548 Kind = CK_NonAtomicToAtomic; 7549 return Compatible; 7550 } 7551 7552 // If the left-hand side is a reference type, then we are in a 7553 // (rare!) case where we've allowed the use of references in C, 7554 // e.g., as a parameter type in a built-in function. In this case, 7555 // just make sure that the type referenced is compatible with the 7556 // right-hand side type. The caller is responsible for adjusting 7557 // LHSType so that the resulting expression does not have reference 7558 // type. 7559 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 7560 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 7561 Kind = CK_LValueBitCast; 7562 return Compatible; 7563 } 7564 return Incompatible; 7565 } 7566 7567 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 7568 // to the same ExtVector type. 7569 if (LHSType->isExtVectorType()) { 7570 if (RHSType->isExtVectorType()) 7571 return Incompatible; 7572 if (RHSType->isArithmeticType()) { 7573 // CK_VectorSplat does T -> vector T, so first cast to the element type. 7574 if (ConvertRHS) 7575 RHS = prepareVectorSplat(LHSType, RHS.get()); 7576 Kind = CK_VectorSplat; 7577 return Compatible; 7578 } 7579 } 7580 7581 // Conversions to or from vector type. 7582 if (LHSType->isVectorType() || RHSType->isVectorType()) { 7583 if (LHSType->isVectorType() && RHSType->isVectorType()) { 7584 // Allow assignments of an AltiVec vector type to an equivalent GCC 7585 // vector type and vice versa 7586 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7587 Kind = CK_BitCast; 7588 return Compatible; 7589 } 7590 7591 // If we are allowing lax vector conversions, and LHS and RHS are both 7592 // vectors, the total size only needs to be the same. This is a bitcast; 7593 // no bits are changed but the result type is different. 7594 if (isLaxVectorConversion(RHSType, LHSType)) { 7595 Kind = CK_BitCast; 7596 return IncompatibleVectors; 7597 } 7598 } 7599 7600 // When the RHS comes from another lax conversion (e.g. binops between 7601 // scalars and vectors) the result is canonicalized as a vector. When the 7602 // LHS is also a vector, the lax is allowed by the condition above. Handle 7603 // the case where LHS is a scalar. 7604 if (LHSType->isScalarType()) { 7605 const VectorType *VecType = RHSType->getAs<VectorType>(); 7606 if (VecType && VecType->getNumElements() == 1 && 7607 isLaxVectorConversion(RHSType, LHSType)) { 7608 ExprResult *VecExpr = &RHS; 7609 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 7610 Kind = CK_BitCast; 7611 return Compatible; 7612 } 7613 } 7614 7615 return Incompatible; 7616 } 7617 7618 // Diagnose attempts to convert between __float128 and long double where 7619 // such conversions currently can't be handled. 7620 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 7621 return Incompatible; 7622 7623 // Arithmetic conversions. 7624 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 7625 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 7626 if (ConvertRHS) 7627 Kind = PrepareScalarCast(RHS, LHSType); 7628 return Compatible; 7629 } 7630 7631 // Conversions to normal pointers. 7632 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 7633 // U* -> T* 7634 if (isa<PointerType>(RHSType)) { 7635 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7636 unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 7637 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7638 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 7639 } 7640 7641 // int -> T* 7642 if (RHSType->isIntegerType()) { 7643 Kind = CK_IntegralToPointer; // FIXME: null? 7644 return IntToPointer; 7645 } 7646 7647 // C pointers are not compatible with ObjC object pointers, 7648 // with two exceptions: 7649 if (isa<ObjCObjectPointerType>(RHSType)) { 7650 // - conversions to void* 7651 if (LHSPointer->getPointeeType()->isVoidType()) { 7652 Kind = CK_BitCast; 7653 return Compatible; 7654 } 7655 7656 // - conversions from 'Class' to the redefinition type 7657 if (RHSType->isObjCClassType() && 7658 Context.hasSameType(LHSType, 7659 Context.getObjCClassRedefinitionType())) { 7660 Kind = CK_BitCast; 7661 return Compatible; 7662 } 7663 7664 Kind = CK_BitCast; 7665 return IncompatiblePointer; 7666 } 7667 7668 // U^ -> void* 7669 if (RHSType->getAs<BlockPointerType>()) { 7670 if (LHSPointer->getPointeeType()->isVoidType()) { 7671 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7672 unsigned AddrSpaceR = RHSType->getAs<BlockPointerType>() 7673 ->getPointeeType() 7674 .getAddressSpace(); 7675 Kind = 7676 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7677 return Compatible; 7678 } 7679 } 7680 7681 return Incompatible; 7682 } 7683 7684 // Conversions to block pointers. 7685 if (isa<BlockPointerType>(LHSType)) { 7686 // U^ -> T^ 7687 if (RHSType->isBlockPointerType()) { 7688 unsigned AddrSpaceL = LHSType->getAs<BlockPointerType>() 7689 ->getPointeeType() 7690 .getAddressSpace(); 7691 unsigned AddrSpaceR = RHSType->getAs<BlockPointerType>() 7692 ->getPointeeType() 7693 .getAddressSpace(); 7694 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7695 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 7696 } 7697 7698 // int or null -> T^ 7699 if (RHSType->isIntegerType()) { 7700 Kind = CK_IntegralToPointer; // FIXME: null 7701 return IntToBlockPointer; 7702 } 7703 7704 // id -> T^ 7705 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 7706 Kind = CK_AnyPointerToBlockPointerCast; 7707 return Compatible; 7708 } 7709 7710 // void* -> T^ 7711 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 7712 if (RHSPT->getPointeeType()->isVoidType()) { 7713 Kind = CK_AnyPointerToBlockPointerCast; 7714 return Compatible; 7715 } 7716 7717 return Incompatible; 7718 } 7719 7720 // Conversions to Objective-C pointers. 7721 if (isa<ObjCObjectPointerType>(LHSType)) { 7722 // A* -> B* 7723 if (RHSType->isObjCObjectPointerType()) { 7724 Kind = CK_BitCast; 7725 Sema::AssignConvertType result = 7726 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 7727 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 7728 result == Compatible && 7729 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 7730 result = IncompatibleObjCWeakRef; 7731 return result; 7732 } 7733 7734 // int or null -> A* 7735 if (RHSType->isIntegerType()) { 7736 Kind = CK_IntegralToPointer; // FIXME: null 7737 return IntToPointer; 7738 } 7739 7740 // In general, C pointers are not compatible with ObjC object pointers, 7741 // with two exceptions: 7742 if (isa<PointerType>(RHSType)) { 7743 Kind = CK_CPointerToObjCPointerCast; 7744 7745 // - conversions from 'void*' 7746 if (RHSType->isVoidPointerType()) { 7747 return Compatible; 7748 } 7749 7750 // - conversions to 'Class' from its redefinition type 7751 if (LHSType->isObjCClassType() && 7752 Context.hasSameType(RHSType, 7753 Context.getObjCClassRedefinitionType())) { 7754 return Compatible; 7755 } 7756 7757 return IncompatiblePointer; 7758 } 7759 7760 // Only under strict condition T^ is compatible with an Objective-C pointer. 7761 if (RHSType->isBlockPointerType() && 7762 LHSType->isBlockCompatibleObjCPointerType(Context)) { 7763 if (ConvertRHS) 7764 maybeExtendBlockObject(RHS); 7765 Kind = CK_BlockPointerToObjCPointerCast; 7766 return Compatible; 7767 } 7768 7769 return Incompatible; 7770 } 7771 7772 // Conversions from pointers that are not covered by the above. 7773 if (isa<PointerType>(RHSType)) { 7774 // T* -> _Bool 7775 if (LHSType == Context.BoolTy) { 7776 Kind = CK_PointerToBoolean; 7777 return Compatible; 7778 } 7779 7780 // T* -> int 7781 if (LHSType->isIntegerType()) { 7782 Kind = CK_PointerToIntegral; 7783 return PointerToInt; 7784 } 7785 7786 return Incompatible; 7787 } 7788 7789 // Conversions from Objective-C pointers that are not covered by the above. 7790 if (isa<ObjCObjectPointerType>(RHSType)) { 7791 // T* -> _Bool 7792 if (LHSType == Context.BoolTy) { 7793 Kind = CK_PointerToBoolean; 7794 return Compatible; 7795 } 7796 7797 // T* -> int 7798 if (LHSType->isIntegerType()) { 7799 Kind = CK_PointerToIntegral; 7800 return PointerToInt; 7801 } 7802 7803 return Incompatible; 7804 } 7805 7806 // struct A -> struct B 7807 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 7808 if (Context.typesAreCompatible(LHSType, RHSType)) { 7809 Kind = CK_NoOp; 7810 return Compatible; 7811 } 7812 } 7813 7814 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 7815 Kind = CK_IntToOCLSampler; 7816 return Compatible; 7817 } 7818 7819 return Incompatible; 7820 } 7821 7822 /// \brief Constructs a transparent union from an expression that is 7823 /// used to initialize the transparent union. 7824 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 7825 ExprResult &EResult, QualType UnionType, 7826 FieldDecl *Field) { 7827 // Build an initializer list that designates the appropriate member 7828 // of the transparent union. 7829 Expr *E = EResult.get(); 7830 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 7831 E, SourceLocation()); 7832 Initializer->setType(UnionType); 7833 Initializer->setInitializedFieldInUnion(Field); 7834 7835 // Build a compound literal constructing a value of the transparent 7836 // union type from this initializer list. 7837 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 7838 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 7839 VK_RValue, Initializer, false); 7840 } 7841 7842 Sema::AssignConvertType 7843 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 7844 ExprResult &RHS) { 7845 QualType RHSType = RHS.get()->getType(); 7846 7847 // If the ArgType is a Union type, we want to handle a potential 7848 // transparent_union GCC extension. 7849 const RecordType *UT = ArgType->getAsUnionType(); 7850 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 7851 return Incompatible; 7852 7853 // The field to initialize within the transparent union. 7854 RecordDecl *UD = UT->getDecl(); 7855 FieldDecl *InitField = nullptr; 7856 // It's compatible if the expression matches any of the fields. 7857 for (auto *it : UD->fields()) { 7858 if (it->getType()->isPointerType()) { 7859 // If the transparent union contains a pointer type, we allow: 7860 // 1) void pointer 7861 // 2) null pointer constant 7862 if (RHSType->isPointerType()) 7863 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 7864 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 7865 InitField = it; 7866 break; 7867 } 7868 7869 if (RHS.get()->isNullPointerConstant(Context, 7870 Expr::NPC_ValueDependentIsNull)) { 7871 RHS = ImpCastExprToType(RHS.get(), it->getType(), 7872 CK_NullToPointer); 7873 InitField = it; 7874 break; 7875 } 7876 } 7877 7878 CastKind Kind = CK_Invalid; 7879 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 7880 == Compatible) { 7881 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 7882 InitField = it; 7883 break; 7884 } 7885 } 7886 7887 if (!InitField) 7888 return Incompatible; 7889 7890 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 7891 return Compatible; 7892 } 7893 7894 Sema::AssignConvertType 7895 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 7896 bool Diagnose, 7897 bool DiagnoseCFAudited, 7898 bool ConvertRHS) { 7899 // We need to be able to tell the caller whether we diagnosed a problem, if 7900 // they ask us to issue diagnostics. 7901 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 7902 7903 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 7904 // we can't avoid *all* modifications at the moment, so we need some somewhere 7905 // to put the updated value. 7906 ExprResult LocalRHS = CallerRHS; 7907 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 7908 7909 if (getLangOpts().CPlusPlus) { 7910 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 7911 // C++ 5.17p3: If the left operand is not of class type, the 7912 // expression is implicitly converted (C++ 4) to the 7913 // cv-unqualified type of the left operand. 7914 QualType RHSType = RHS.get()->getType(); 7915 if (Diagnose) { 7916 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7917 AA_Assigning); 7918 } else { 7919 ImplicitConversionSequence ICS = 7920 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7921 /*SuppressUserConversions=*/false, 7922 /*AllowExplicit=*/false, 7923 /*InOverloadResolution=*/false, 7924 /*CStyle=*/false, 7925 /*AllowObjCWritebackConversion=*/false); 7926 if (ICS.isFailure()) 7927 return Incompatible; 7928 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7929 ICS, AA_Assigning); 7930 } 7931 if (RHS.isInvalid()) 7932 return Incompatible; 7933 Sema::AssignConvertType result = Compatible; 7934 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 7935 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 7936 result = IncompatibleObjCWeakRef; 7937 return result; 7938 } 7939 7940 // FIXME: Currently, we fall through and treat C++ classes like C 7941 // structures. 7942 // FIXME: We also fall through for atomics; not sure what should 7943 // happen there, though. 7944 } else if (RHS.get()->getType() == Context.OverloadTy) { 7945 // As a set of extensions to C, we support overloading on functions. These 7946 // functions need to be resolved here. 7947 DeclAccessPair DAP; 7948 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 7949 RHS.get(), LHSType, /*Complain=*/false, DAP)) 7950 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 7951 else 7952 return Incompatible; 7953 } 7954 7955 // C99 6.5.16.1p1: the left operand is a pointer and the right is 7956 // a null pointer constant. 7957 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 7958 LHSType->isBlockPointerType()) && 7959 RHS.get()->isNullPointerConstant(Context, 7960 Expr::NPC_ValueDependentIsNull)) { 7961 if (Diagnose || ConvertRHS) { 7962 CastKind Kind; 7963 CXXCastPath Path; 7964 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 7965 /*IgnoreBaseAccess=*/false, Diagnose); 7966 if (ConvertRHS) 7967 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 7968 } 7969 return Compatible; 7970 } 7971 7972 // This check seems unnatural, however it is necessary to ensure the proper 7973 // conversion of functions/arrays. If the conversion were done for all 7974 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 7975 // expressions that suppress this implicit conversion (&, sizeof). 7976 // 7977 // Suppress this for references: C++ 8.5.3p5. 7978 if (!LHSType->isReferenceType()) { 7979 // FIXME: We potentially allocate here even if ConvertRHS is false. 7980 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 7981 if (RHS.isInvalid()) 7982 return Incompatible; 7983 } 7984 7985 Expr *PRE = RHS.get()->IgnoreParenCasts(); 7986 if (Diagnose && isa<ObjCProtocolExpr>(PRE)) { 7987 ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol(); 7988 if (PDecl && !PDecl->hasDefinition()) { 7989 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName(); 7990 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl; 7991 } 7992 } 7993 7994 CastKind Kind = CK_Invalid; 7995 Sema::AssignConvertType result = 7996 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 7997 7998 // C99 6.5.16.1p2: The value of the right operand is converted to the 7999 // type of the assignment expression. 8000 // CheckAssignmentConstraints allows the left-hand side to be a reference, 8001 // so that we can use references in built-in functions even in C. 8002 // The getNonReferenceType() call makes sure that the resulting expression 8003 // does not have reference type. 8004 if (result != Incompatible && RHS.get()->getType() != LHSType) { 8005 QualType Ty = LHSType.getNonLValueExprType(Context); 8006 Expr *E = RHS.get(); 8007 8008 // Check for various Objective-C errors. If we are not reporting 8009 // diagnostics and just checking for errors, e.g., during overload 8010 // resolution, return Incompatible to indicate the failure. 8011 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8012 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 8013 Diagnose, DiagnoseCFAudited) != ACR_okay) { 8014 if (!Diagnose) 8015 return Incompatible; 8016 } 8017 if (getLangOpts().ObjC1 && 8018 (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType, 8019 E->getType(), E, Diagnose) || 8020 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 8021 if (!Diagnose) 8022 return Incompatible; 8023 // Replace the expression with a corrected version and continue so we 8024 // can find further errors. 8025 RHS = E; 8026 return Compatible; 8027 } 8028 8029 if (ConvertRHS) 8030 RHS = ImpCastExprToType(E, Ty, Kind); 8031 } 8032 return result; 8033 } 8034 8035 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 8036 ExprResult &RHS) { 8037 Diag(Loc, diag::err_typecheck_invalid_operands) 8038 << LHS.get()->getType() << RHS.get()->getType() 8039 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8040 return QualType(); 8041 } 8042 8043 // Diagnose cases where a scalar was implicitly converted to a vector and 8044 // diagnose the underlying types. Otherwise, diagnose the error 8045 // as invalid vector logical operands for non-C++ cases. 8046 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 8047 ExprResult &RHS) { 8048 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 8049 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 8050 8051 bool LHSNatVec = LHSType->isVectorType(); 8052 bool RHSNatVec = RHSType->isVectorType(); 8053 8054 if (!(LHSNatVec && RHSNatVec)) { 8055 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 8056 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 8057 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8058 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 8059 << Vector->getSourceRange(); 8060 return QualType(); 8061 } 8062 8063 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8064 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 8065 << RHS.get()->getSourceRange(); 8066 8067 return QualType(); 8068 } 8069 8070 /// Try to convert a value of non-vector type to a vector type by converting 8071 /// the type to the element type of the vector and then performing a splat. 8072 /// If the language is OpenCL, we only use conversions that promote scalar 8073 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 8074 /// for float->int. 8075 /// 8076 /// \param scalar - if non-null, actually perform the conversions 8077 /// \return true if the operation fails (but without diagnosing the failure) 8078 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 8079 QualType scalarTy, 8080 QualType vectorEltTy, 8081 QualType vectorTy) { 8082 // The conversion to apply to the scalar before splatting it, 8083 // if necessary. 8084 CastKind scalarCast = CK_Invalid; 8085 8086 if (vectorEltTy->isIntegralType(S.Context)) { 8087 if (!scalarTy->isIntegralType(S.Context)) 8088 return true; 8089 if (S.getLangOpts().OpenCL && 8090 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0) 8091 return true; 8092 scalarCast = CK_IntegralCast; 8093 } else if (vectorEltTy->isRealFloatingType()) { 8094 if (scalarTy->isRealFloatingType()) { 8095 if (S.getLangOpts().OpenCL && 8096 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) 8097 return true; 8098 scalarCast = CK_FloatingCast; 8099 } 8100 else if (scalarTy->isIntegralType(S.Context)) 8101 scalarCast = CK_IntegralToFloating; 8102 else 8103 return true; 8104 } else { 8105 return true; 8106 } 8107 8108 // Adjust scalar if desired. 8109 if (scalar) { 8110 if (scalarCast != CK_Invalid) 8111 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 8112 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 8113 } 8114 return false; 8115 } 8116 8117 /// Test if a (constant) integer Int can be casted to another integer type 8118 /// IntTy without losing precision. 8119 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 8120 QualType OtherIntTy) { 8121 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8122 8123 // Reject cases where the value of the Int is unknown as that would 8124 // possibly cause truncation, but accept cases where the scalar can be 8125 // demoted without loss of precision. 8126 llvm::APSInt Result; 8127 bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context); 8128 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 8129 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 8130 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 8131 8132 if (CstInt) { 8133 // If the scalar is constant and is of a higher order and has more active 8134 // bits that the vector element type, reject it. 8135 unsigned NumBits = IntSigned 8136 ? (Result.isNegative() ? Result.getMinSignedBits() 8137 : Result.getActiveBits()) 8138 : Result.getActiveBits(); 8139 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 8140 return true; 8141 8142 // If the signedness of the scalar type and the vector element type 8143 // differs and the number of bits is greater than that of the vector 8144 // element reject it. 8145 return (IntSigned != OtherIntSigned && 8146 NumBits > S.Context.getIntWidth(OtherIntTy)); 8147 } 8148 8149 // Reject cases where the value of the scalar is not constant and it's 8150 // order is greater than that of the vector element type. 8151 return (Order < 0); 8152 } 8153 8154 /// Test if a (constant) integer Int can be casted to floating point type 8155 /// FloatTy without losing precision. 8156 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 8157 QualType FloatTy) { 8158 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8159 8160 // Determine if the integer constant can be expressed as a floating point 8161 // number of the appropiate type. 8162 llvm::APSInt Result; 8163 bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context); 8164 uint64_t Bits = 0; 8165 if (CstInt) { 8166 // Reject constants that would be truncated if they were converted to 8167 // the floating point type. Test by simple to/from conversion. 8168 // FIXME: Ideally the conversion to an APFloat and from an APFloat 8169 // could be avoided if there was a convertFromAPInt method 8170 // which could signal back if implicit truncation occurred. 8171 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 8172 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 8173 llvm::APFloat::rmTowardZero); 8174 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 8175 !IntTy->hasSignedIntegerRepresentation()); 8176 bool Ignored = false; 8177 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 8178 &Ignored); 8179 if (Result != ConvertBack) 8180 return true; 8181 } else { 8182 // Reject types that cannot be fully encoded into the mantissa of 8183 // the float. 8184 Bits = S.Context.getTypeSize(IntTy); 8185 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 8186 S.Context.getFloatTypeSemantics(FloatTy)); 8187 if (Bits > FloatPrec) 8188 return true; 8189 } 8190 8191 return false; 8192 } 8193 8194 /// Attempt to convert and splat Scalar into a vector whose types matches 8195 /// Vector following GCC conversion rules. The rule is that implicit 8196 /// conversion can occur when Scalar can be casted to match Vector's element 8197 /// type without causing truncation of Scalar. 8198 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 8199 ExprResult *Vector) { 8200 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 8201 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 8202 const VectorType *VT = VectorTy->getAs<VectorType>(); 8203 8204 assert(!isa<ExtVectorType>(VT) && 8205 "ExtVectorTypes should not be handled here!"); 8206 8207 QualType VectorEltTy = VT->getElementType(); 8208 8209 // Reject cases where the vector element type or the scalar element type are 8210 // not integral or floating point types. 8211 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 8212 return true; 8213 8214 // The conversion to apply to the scalar before splatting it, 8215 // if necessary. 8216 CastKind ScalarCast = CK_NoOp; 8217 8218 // Accept cases where the vector elements are integers and the scalar is 8219 // an integer. 8220 // FIXME: Notionally if the scalar was a floating point value with a precise 8221 // integral representation, we could cast it to an appropriate integer 8222 // type and then perform the rest of the checks here. GCC will perform 8223 // this conversion in some cases as determined by the input language. 8224 // We should accept it on a language independent basis. 8225 if (VectorEltTy->isIntegralType(S.Context) && 8226 ScalarTy->isIntegralType(S.Context) && 8227 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 8228 8229 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 8230 return true; 8231 8232 ScalarCast = CK_IntegralCast; 8233 } else if (VectorEltTy->isRealFloatingType()) { 8234 if (ScalarTy->isRealFloatingType()) { 8235 8236 // Reject cases where the scalar type is not a constant and has a higher 8237 // Order than the vector element type. 8238 llvm::APFloat Result(0.0); 8239 bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context); 8240 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 8241 if (!CstScalar && Order < 0) 8242 return true; 8243 8244 // If the scalar cannot be safely casted to the vector element type, 8245 // reject it. 8246 if (CstScalar) { 8247 bool Truncated = false; 8248 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 8249 llvm::APFloat::rmNearestTiesToEven, &Truncated); 8250 if (Truncated) 8251 return true; 8252 } 8253 8254 ScalarCast = CK_FloatingCast; 8255 } else if (ScalarTy->isIntegralType(S.Context)) { 8256 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 8257 return true; 8258 8259 ScalarCast = CK_IntegralToFloating; 8260 } else 8261 return true; 8262 } 8263 8264 // Adjust scalar if desired. 8265 if (Scalar) { 8266 if (ScalarCast != CK_NoOp) 8267 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 8268 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 8269 } 8270 return false; 8271 } 8272 8273 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 8274 SourceLocation Loc, bool IsCompAssign, 8275 bool AllowBothBool, 8276 bool AllowBoolConversions) { 8277 if (!IsCompAssign) { 8278 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 8279 if (LHS.isInvalid()) 8280 return QualType(); 8281 } 8282 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 8283 if (RHS.isInvalid()) 8284 return QualType(); 8285 8286 // For conversion purposes, we ignore any qualifiers. 8287 // For example, "const float" and "float" are equivalent. 8288 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 8289 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 8290 8291 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 8292 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 8293 assert(LHSVecType || RHSVecType); 8294 8295 // AltiVec-style "vector bool op vector bool" combinations are allowed 8296 // for some operators but not others. 8297 if (!AllowBothBool && 8298 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8299 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8300 return InvalidOperands(Loc, LHS, RHS); 8301 8302 // If the vector types are identical, return. 8303 if (Context.hasSameType(LHSType, RHSType)) 8304 return LHSType; 8305 8306 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 8307 if (LHSVecType && RHSVecType && 8308 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8309 if (isa<ExtVectorType>(LHSVecType)) { 8310 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8311 return LHSType; 8312 } 8313 8314 if (!IsCompAssign) 8315 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8316 return RHSType; 8317 } 8318 8319 // AllowBoolConversions says that bool and non-bool AltiVec vectors 8320 // can be mixed, with the result being the non-bool type. The non-bool 8321 // operand must have integer element type. 8322 if (AllowBoolConversions && LHSVecType && RHSVecType && 8323 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 8324 (Context.getTypeSize(LHSVecType->getElementType()) == 8325 Context.getTypeSize(RHSVecType->getElementType()))) { 8326 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 8327 LHSVecType->getElementType()->isIntegerType() && 8328 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 8329 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8330 return LHSType; 8331 } 8332 if (!IsCompAssign && 8333 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8334 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 8335 RHSVecType->getElementType()->isIntegerType()) { 8336 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8337 return RHSType; 8338 } 8339 } 8340 8341 // If there's a vector type and a scalar, try to convert the scalar to 8342 // the vector element type and splat. 8343 if (!RHSVecType) { 8344 if (isa<ExtVectorType>(LHSVecType)) { 8345 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 8346 LHSVecType->getElementType(), LHSType)) 8347 return LHSType; 8348 } else { 8349 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 8350 return LHSType; 8351 } 8352 } 8353 if (!LHSVecType) { 8354 if (isa<ExtVectorType>(RHSVecType)) { 8355 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 8356 LHSType, RHSVecType->getElementType(), 8357 RHSType)) 8358 return RHSType; 8359 } else { 8360 if (LHS.get()->getValueKind() == VK_LValue || 8361 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 8362 return RHSType; 8363 } 8364 } 8365 8366 // FIXME: The code below also handles conversion between vectors and 8367 // non-scalars, we should break this down into fine grained specific checks 8368 // and emit proper diagnostics. 8369 QualType VecType = LHSVecType ? LHSType : RHSType; 8370 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 8371 QualType OtherType = LHSVecType ? RHSType : LHSType; 8372 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 8373 if (isLaxVectorConversion(OtherType, VecType)) { 8374 // If we're allowing lax vector conversions, only the total (data) size 8375 // needs to be the same. For non compound assignment, if one of the types is 8376 // scalar, the result is always the vector type. 8377 if (!IsCompAssign) { 8378 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 8379 return VecType; 8380 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 8381 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 8382 // type. Note that this is already done by non-compound assignments in 8383 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 8384 // <1 x T> -> T. The result is also a vector type. 8385 } else if (OtherType->isExtVectorType() || 8386 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 8387 ExprResult *RHSExpr = &RHS; 8388 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 8389 return VecType; 8390 } 8391 } 8392 8393 // Okay, the expression is invalid. 8394 8395 // If there's a non-vector, non-real operand, diagnose that. 8396 if ((!RHSVecType && !RHSType->isRealType()) || 8397 (!LHSVecType && !LHSType->isRealType())) { 8398 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 8399 << LHSType << RHSType 8400 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8401 return QualType(); 8402 } 8403 8404 // OpenCL V1.1 6.2.6.p1: 8405 // If the operands are of more than one vector type, then an error shall 8406 // occur. Implicit conversions between vector types are not permitted, per 8407 // section 6.2.1. 8408 if (getLangOpts().OpenCL && 8409 RHSVecType && isa<ExtVectorType>(RHSVecType) && 8410 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 8411 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 8412 << RHSType; 8413 return QualType(); 8414 } 8415 8416 8417 // If there is a vector type that is not a ExtVector and a scalar, we reach 8418 // this point if scalar could not be converted to the vector's element type 8419 // without truncation. 8420 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 8421 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 8422 QualType Scalar = LHSVecType ? RHSType : LHSType; 8423 QualType Vector = LHSVecType ? LHSType : RHSType; 8424 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 8425 Diag(Loc, 8426 diag::err_typecheck_vector_not_convertable_implict_truncation) 8427 << ScalarOrVector << Scalar << Vector; 8428 8429 return QualType(); 8430 } 8431 8432 // Otherwise, use the generic diagnostic. 8433 Diag(Loc, diag::err_typecheck_vector_not_convertable) 8434 << LHSType << RHSType 8435 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8436 return QualType(); 8437 } 8438 8439 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 8440 // expression. These are mainly cases where the null pointer is used as an 8441 // integer instead of a pointer. 8442 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 8443 SourceLocation Loc, bool IsCompare) { 8444 // The canonical way to check for a GNU null is with isNullPointerConstant, 8445 // but we use a bit of a hack here for speed; this is a relatively 8446 // hot path, and isNullPointerConstant is slow. 8447 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 8448 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 8449 8450 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 8451 8452 // Avoid analyzing cases where the result will either be invalid (and 8453 // diagnosed as such) or entirely valid and not something to warn about. 8454 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 8455 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 8456 return; 8457 8458 // Comparison operations would not make sense with a null pointer no matter 8459 // what the other expression is. 8460 if (!IsCompare) { 8461 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 8462 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 8463 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 8464 return; 8465 } 8466 8467 // The rest of the operations only make sense with a null pointer 8468 // if the other expression is a pointer. 8469 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 8470 NonNullType->canDecayToPointerType()) 8471 return; 8472 8473 S.Diag(Loc, diag::warn_null_in_comparison_operation) 8474 << LHSNull /* LHS is NULL */ << NonNullType 8475 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8476 } 8477 8478 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 8479 ExprResult &RHS, 8480 SourceLocation Loc, bool IsDiv) { 8481 // Check for division/remainder by zero. 8482 llvm::APSInt RHSValue; 8483 if (!RHS.get()->isValueDependent() && 8484 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0) 8485 S.DiagRuntimeBehavior(Loc, RHS.get(), 8486 S.PDiag(diag::warn_remainder_division_by_zero) 8487 << IsDiv << RHS.get()->getSourceRange()); 8488 } 8489 8490 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 8491 SourceLocation Loc, 8492 bool IsCompAssign, bool IsDiv) { 8493 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8494 8495 if (LHS.get()->getType()->isVectorType() || 8496 RHS.get()->getType()->isVectorType()) 8497 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8498 /*AllowBothBool*/getLangOpts().AltiVec, 8499 /*AllowBoolConversions*/false); 8500 8501 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8502 if (LHS.isInvalid() || RHS.isInvalid()) 8503 return QualType(); 8504 8505 8506 if (compType.isNull() || !compType->isArithmeticType()) 8507 return InvalidOperands(Loc, LHS, RHS); 8508 if (IsDiv) 8509 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 8510 return compType; 8511 } 8512 8513 QualType Sema::CheckRemainderOperands( 8514 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 8515 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8516 8517 if (LHS.get()->getType()->isVectorType() || 8518 RHS.get()->getType()->isVectorType()) { 8519 if (LHS.get()->getType()->hasIntegerRepresentation() && 8520 RHS.get()->getType()->hasIntegerRepresentation()) 8521 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8522 /*AllowBothBool*/getLangOpts().AltiVec, 8523 /*AllowBoolConversions*/false); 8524 return InvalidOperands(Loc, LHS, RHS); 8525 } 8526 8527 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8528 if (LHS.isInvalid() || RHS.isInvalid()) 8529 return QualType(); 8530 8531 if (compType.isNull() || !compType->isIntegerType()) 8532 return InvalidOperands(Loc, LHS, RHS); 8533 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 8534 return compType; 8535 } 8536 8537 /// \brief Diagnose invalid arithmetic on two void pointers. 8538 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 8539 Expr *LHSExpr, Expr *RHSExpr) { 8540 S.Diag(Loc, S.getLangOpts().CPlusPlus 8541 ? diag::err_typecheck_pointer_arith_void_type 8542 : diag::ext_gnu_void_ptr) 8543 << 1 /* two pointers */ << LHSExpr->getSourceRange() 8544 << RHSExpr->getSourceRange(); 8545 } 8546 8547 /// \brief Diagnose invalid arithmetic on a void pointer. 8548 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 8549 Expr *Pointer) { 8550 S.Diag(Loc, S.getLangOpts().CPlusPlus 8551 ? diag::err_typecheck_pointer_arith_void_type 8552 : diag::ext_gnu_void_ptr) 8553 << 0 /* one pointer */ << Pointer->getSourceRange(); 8554 } 8555 8556 /// \brief Diagnose invalid arithmetic on two function pointers. 8557 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 8558 Expr *LHS, Expr *RHS) { 8559 assert(LHS->getType()->isAnyPointerType()); 8560 assert(RHS->getType()->isAnyPointerType()); 8561 S.Diag(Loc, S.getLangOpts().CPlusPlus 8562 ? diag::err_typecheck_pointer_arith_function_type 8563 : diag::ext_gnu_ptr_func_arith) 8564 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 8565 // We only show the second type if it differs from the first. 8566 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 8567 RHS->getType()) 8568 << RHS->getType()->getPointeeType() 8569 << LHS->getSourceRange() << RHS->getSourceRange(); 8570 } 8571 8572 /// \brief Diagnose invalid arithmetic on a function pointer. 8573 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 8574 Expr *Pointer) { 8575 assert(Pointer->getType()->isAnyPointerType()); 8576 S.Diag(Loc, S.getLangOpts().CPlusPlus 8577 ? diag::err_typecheck_pointer_arith_function_type 8578 : diag::ext_gnu_ptr_func_arith) 8579 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 8580 << 0 /* one pointer, so only one type */ 8581 << Pointer->getSourceRange(); 8582 } 8583 8584 /// \brief Emit error if Operand is incomplete pointer type 8585 /// 8586 /// \returns True if pointer has incomplete type 8587 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 8588 Expr *Operand) { 8589 QualType ResType = Operand->getType(); 8590 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8591 ResType = ResAtomicType->getValueType(); 8592 8593 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 8594 QualType PointeeTy = ResType->getPointeeType(); 8595 return S.RequireCompleteType(Loc, PointeeTy, 8596 diag::err_typecheck_arithmetic_incomplete_type, 8597 PointeeTy, Operand->getSourceRange()); 8598 } 8599 8600 /// \brief Check the validity of an arithmetic pointer operand. 8601 /// 8602 /// If the operand has pointer type, this code will check for pointer types 8603 /// which are invalid in arithmetic operations. These will be diagnosed 8604 /// appropriately, including whether or not the use is supported as an 8605 /// extension. 8606 /// 8607 /// \returns True when the operand is valid to use (even if as an extension). 8608 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 8609 Expr *Operand) { 8610 QualType ResType = Operand->getType(); 8611 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8612 ResType = ResAtomicType->getValueType(); 8613 8614 if (!ResType->isAnyPointerType()) return true; 8615 8616 QualType PointeeTy = ResType->getPointeeType(); 8617 if (PointeeTy->isVoidType()) { 8618 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 8619 return !S.getLangOpts().CPlusPlus; 8620 } 8621 if (PointeeTy->isFunctionType()) { 8622 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 8623 return !S.getLangOpts().CPlusPlus; 8624 } 8625 8626 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 8627 8628 return true; 8629 } 8630 8631 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 8632 /// operands. 8633 /// 8634 /// This routine will diagnose any invalid arithmetic on pointer operands much 8635 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 8636 /// for emitting a single diagnostic even for operations where both LHS and RHS 8637 /// are (potentially problematic) pointers. 8638 /// 8639 /// \returns True when the operand is valid to use (even if as an extension). 8640 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 8641 Expr *LHSExpr, Expr *RHSExpr) { 8642 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 8643 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 8644 if (!isLHSPointer && !isRHSPointer) return true; 8645 8646 QualType LHSPointeeTy, RHSPointeeTy; 8647 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 8648 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 8649 8650 // if both are pointers check if operation is valid wrt address spaces 8651 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 8652 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 8653 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 8654 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 8655 S.Diag(Loc, 8656 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8657 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 8658 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 8659 return false; 8660 } 8661 } 8662 8663 // Check for arithmetic on pointers to incomplete types. 8664 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 8665 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 8666 if (isLHSVoidPtr || isRHSVoidPtr) { 8667 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 8668 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 8669 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 8670 8671 return !S.getLangOpts().CPlusPlus; 8672 } 8673 8674 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 8675 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 8676 if (isLHSFuncPtr || isRHSFuncPtr) { 8677 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 8678 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 8679 RHSExpr); 8680 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 8681 8682 return !S.getLangOpts().CPlusPlus; 8683 } 8684 8685 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 8686 return false; 8687 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 8688 return false; 8689 8690 return true; 8691 } 8692 8693 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 8694 /// literal. 8695 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 8696 Expr *LHSExpr, Expr *RHSExpr) { 8697 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 8698 Expr* IndexExpr = RHSExpr; 8699 if (!StrExpr) { 8700 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 8701 IndexExpr = LHSExpr; 8702 } 8703 8704 bool IsStringPlusInt = StrExpr && 8705 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 8706 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 8707 return; 8708 8709 llvm::APSInt index; 8710 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 8711 unsigned StrLenWithNull = StrExpr->getLength() + 1; 8712 if (index.isNonNegative() && 8713 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 8714 index.isUnsigned())) 8715 return; 8716 } 8717 8718 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8719 Self.Diag(OpLoc, diag::warn_string_plus_int) 8720 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 8721 8722 // Only print a fixit for "str" + int, not for int + "str". 8723 if (IndexExpr == RHSExpr) { 8724 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8725 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8726 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8727 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8728 << FixItHint::CreateInsertion(EndLoc, "]"); 8729 } else 8730 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8731 } 8732 8733 /// \brief Emit a warning when adding a char literal to a string. 8734 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 8735 Expr *LHSExpr, Expr *RHSExpr) { 8736 const Expr *StringRefExpr = LHSExpr; 8737 const CharacterLiteral *CharExpr = 8738 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 8739 8740 if (!CharExpr) { 8741 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 8742 StringRefExpr = RHSExpr; 8743 } 8744 8745 if (!CharExpr || !StringRefExpr) 8746 return; 8747 8748 const QualType StringType = StringRefExpr->getType(); 8749 8750 // Return if not a PointerType. 8751 if (!StringType->isAnyPointerType()) 8752 return; 8753 8754 // Return if not a CharacterType. 8755 if (!StringType->getPointeeType()->isAnyCharacterType()) 8756 return; 8757 8758 ASTContext &Ctx = Self.getASTContext(); 8759 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8760 8761 const QualType CharType = CharExpr->getType(); 8762 if (!CharType->isAnyCharacterType() && 8763 CharType->isIntegerType() && 8764 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 8765 Self.Diag(OpLoc, diag::warn_string_plus_char) 8766 << DiagRange << Ctx.CharTy; 8767 } else { 8768 Self.Diag(OpLoc, diag::warn_string_plus_char) 8769 << DiagRange << CharExpr->getType(); 8770 } 8771 8772 // Only print a fixit for str + char, not for char + str. 8773 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 8774 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8775 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8776 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8777 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8778 << FixItHint::CreateInsertion(EndLoc, "]"); 8779 } else { 8780 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8781 } 8782 } 8783 8784 /// \brief Emit error when two pointers are incompatible. 8785 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 8786 Expr *LHSExpr, Expr *RHSExpr) { 8787 assert(LHSExpr->getType()->isAnyPointerType()); 8788 assert(RHSExpr->getType()->isAnyPointerType()); 8789 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 8790 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 8791 << RHSExpr->getSourceRange(); 8792 } 8793 8794 // C99 6.5.6 8795 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 8796 SourceLocation Loc, BinaryOperatorKind Opc, 8797 QualType* CompLHSTy) { 8798 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8799 8800 if (LHS.get()->getType()->isVectorType() || 8801 RHS.get()->getType()->isVectorType()) { 8802 QualType compType = CheckVectorOperands( 8803 LHS, RHS, Loc, CompLHSTy, 8804 /*AllowBothBool*/getLangOpts().AltiVec, 8805 /*AllowBoolConversions*/getLangOpts().ZVector); 8806 if (CompLHSTy) *CompLHSTy = compType; 8807 return compType; 8808 } 8809 8810 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8811 if (LHS.isInvalid() || RHS.isInvalid()) 8812 return QualType(); 8813 8814 // Diagnose "string literal" '+' int and string '+' "char literal". 8815 if (Opc == BO_Add) { 8816 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 8817 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 8818 } 8819 8820 // handle the common case first (both operands are arithmetic). 8821 if (!compType.isNull() && compType->isArithmeticType()) { 8822 if (CompLHSTy) *CompLHSTy = compType; 8823 return compType; 8824 } 8825 8826 // Type-checking. Ultimately the pointer's going to be in PExp; 8827 // note that we bias towards the LHS being the pointer. 8828 Expr *PExp = LHS.get(), *IExp = RHS.get(); 8829 8830 bool isObjCPointer; 8831 if (PExp->getType()->isPointerType()) { 8832 isObjCPointer = false; 8833 } else if (PExp->getType()->isObjCObjectPointerType()) { 8834 isObjCPointer = true; 8835 } else { 8836 std::swap(PExp, IExp); 8837 if (PExp->getType()->isPointerType()) { 8838 isObjCPointer = false; 8839 } else if (PExp->getType()->isObjCObjectPointerType()) { 8840 isObjCPointer = true; 8841 } else { 8842 return InvalidOperands(Loc, LHS, RHS); 8843 } 8844 } 8845 assert(PExp->getType()->isAnyPointerType()); 8846 8847 if (!IExp->getType()->isIntegerType()) 8848 return InvalidOperands(Loc, LHS, RHS); 8849 8850 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 8851 return QualType(); 8852 8853 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 8854 return QualType(); 8855 8856 // Check array bounds for pointer arithemtic 8857 CheckArrayAccess(PExp, IExp); 8858 8859 if (CompLHSTy) { 8860 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 8861 if (LHSTy.isNull()) { 8862 LHSTy = LHS.get()->getType(); 8863 if (LHSTy->isPromotableIntegerType()) 8864 LHSTy = Context.getPromotedIntegerType(LHSTy); 8865 } 8866 *CompLHSTy = LHSTy; 8867 } 8868 8869 return PExp->getType(); 8870 } 8871 8872 // C99 6.5.6 8873 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 8874 SourceLocation Loc, 8875 QualType* CompLHSTy) { 8876 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8877 8878 if (LHS.get()->getType()->isVectorType() || 8879 RHS.get()->getType()->isVectorType()) { 8880 QualType compType = CheckVectorOperands( 8881 LHS, RHS, Loc, CompLHSTy, 8882 /*AllowBothBool*/getLangOpts().AltiVec, 8883 /*AllowBoolConversions*/getLangOpts().ZVector); 8884 if (CompLHSTy) *CompLHSTy = compType; 8885 return compType; 8886 } 8887 8888 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8889 if (LHS.isInvalid() || RHS.isInvalid()) 8890 return QualType(); 8891 8892 // Enforce type constraints: C99 6.5.6p3. 8893 8894 // Handle the common case first (both operands are arithmetic). 8895 if (!compType.isNull() && compType->isArithmeticType()) { 8896 if (CompLHSTy) *CompLHSTy = compType; 8897 return compType; 8898 } 8899 8900 // Either ptr - int or ptr - ptr. 8901 if (LHS.get()->getType()->isAnyPointerType()) { 8902 QualType lpointee = LHS.get()->getType()->getPointeeType(); 8903 8904 // Diagnose bad cases where we step over interface counts. 8905 if (LHS.get()->getType()->isObjCObjectPointerType() && 8906 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 8907 return QualType(); 8908 8909 // The result type of a pointer-int computation is the pointer type. 8910 if (RHS.get()->getType()->isIntegerType()) { 8911 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 8912 return QualType(); 8913 8914 // Check array bounds for pointer arithemtic 8915 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 8916 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 8917 8918 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8919 return LHS.get()->getType(); 8920 } 8921 8922 // Handle pointer-pointer subtractions. 8923 if (const PointerType *RHSPTy 8924 = RHS.get()->getType()->getAs<PointerType>()) { 8925 QualType rpointee = RHSPTy->getPointeeType(); 8926 8927 if (getLangOpts().CPlusPlus) { 8928 // Pointee types must be the same: C++ [expr.add] 8929 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 8930 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8931 } 8932 } else { 8933 // Pointee types must be compatible C99 6.5.6p3 8934 if (!Context.typesAreCompatible( 8935 Context.getCanonicalType(lpointee).getUnqualifiedType(), 8936 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 8937 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8938 return QualType(); 8939 } 8940 } 8941 8942 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 8943 LHS.get(), RHS.get())) 8944 return QualType(); 8945 8946 // The pointee type may have zero size. As an extension, a structure or 8947 // union may have zero size or an array may have zero length. In this 8948 // case subtraction does not make sense. 8949 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 8950 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 8951 if (ElementSize.isZero()) { 8952 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 8953 << rpointee.getUnqualifiedType() 8954 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8955 } 8956 } 8957 8958 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8959 return Context.getPointerDiffType(); 8960 } 8961 } 8962 8963 return InvalidOperands(Loc, LHS, RHS); 8964 } 8965 8966 static bool isScopedEnumerationType(QualType T) { 8967 if (const EnumType *ET = T->getAs<EnumType>()) 8968 return ET->getDecl()->isScoped(); 8969 return false; 8970 } 8971 8972 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 8973 SourceLocation Loc, BinaryOperatorKind Opc, 8974 QualType LHSType) { 8975 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 8976 // so skip remaining warnings as we don't want to modify values within Sema. 8977 if (S.getLangOpts().OpenCL) 8978 return; 8979 8980 llvm::APSInt Right; 8981 // Check right/shifter operand 8982 if (RHS.get()->isValueDependent() || 8983 !RHS.get()->EvaluateAsInt(Right, S.Context)) 8984 return; 8985 8986 if (Right.isNegative()) { 8987 S.DiagRuntimeBehavior(Loc, RHS.get(), 8988 S.PDiag(diag::warn_shift_negative) 8989 << RHS.get()->getSourceRange()); 8990 return; 8991 } 8992 llvm::APInt LeftBits(Right.getBitWidth(), 8993 S.Context.getTypeSize(LHS.get()->getType())); 8994 if (Right.uge(LeftBits)) { 8995 S.DiagRuntimeBehavior(Loc, RHS.get(), 8996 S.PDiag(diag::warn_shift_gt_typewidth) 8997 << RHS.get()->getSourceRange()); 8998 return; 8999 } 9000 if (Opc != BO_Shl) 9001 return; 9002 9003 // When left shifting an ICE which is signed, we can check for overflow which 9004 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 9005 // integers have defined behavior modulo one more than the maximum value 9006 // representable in the result type, so never warn for those. 9007 llvm::APSInt Left; 9008 if (LHS.get()->isValueDependent() || 9009 LHSType->hasUnsignedIntegerRepresentation() || 9010 !LHS.get()->EvaluateAsInt(Left, S.Context)) 9011 return; 9012 9013 // If LHS does not have a signed type and non-negative value 9014 // then, the behavior is undefined. Warn about it. 9015 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) { 9016 S.DiagRuntimeBehavior(Loc, LHS.get(), 9017 S.PDiag(diag::warn_shift_lhs_negative) 9018 << LHS.get()->getSourceRange()); 9019 return; 9020 } 9021 9022 llvm::APInt ResultBits = 9023 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 9024 if (LeftBits.uge(ResultBits)) 9025 return; 9026 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 9027 Result = Result.shl(Right); 9028 9029 // Print the bit representation of the signed integer as an unsigned 9030 // hexadecimal number. 9031 SmallString<40> HexResult; 9032 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 9033 9034 // If we are only missing a sign bit, this is less likely to result in actual 9035 // bugs -- if the result is cast back to an unsigned type, it will have the 9036 // expected value. Thus we place this behind a different warning that can be 9037 // turned off separately if needed. 9038 if (LeftBits == ResultBits - 1) { 9039 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 9040 << HexResult << LHSType 9041 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9042 return; 9043 } 9044 9045 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 9046 << HexResult.str() << Result.getMinSignedBits() << LHSType 9047 << Left.getBitWidth() << LHS.get()->getSourceRange() 9048 << RHS.get()->getSourceRange(); 9049 } 9050 9051 /// \brief Return the resulting type when a vector is shifted 9052 /// by a scalar or vector shift amount. 9053 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 9054 SourceLocation Loc, bool IsCompAssign) { 9055 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 9056 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 9057 !LHS.get()->getType()->isVectorType()) { 9058 S.Diag(Loc, diag::err_shift_rhs_only_vector) 9059 << RHS.get()->getType() << LHS.get()->getType() 9060 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9061 return QualType(); 9062 } 9063 9064 if (!IsCompAssign) { 9065 LHS = S.UsualUnaryConversions(LHS.get()); 9066 if (LHS.isInvalid()) return QualType(); 9067 } 9068 9069 RHS = S.UsualUnaryConversions(RHS.get()); 9070 if (RHS.isInvalid()) return QualType(); 9071 9072 QualType LHSType = LHS.get()->getType(); 9073 // Note that LHS might be a scalar because the routine calls not only in 9074 // OpenCL case. 9075 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 9076 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 9077 9078 // Note that RHS might not be a vector. 9079 QualType RHSType = RHS.get()->getType(); 9080 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 9081 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 9082 9083 // The operands need to be integers. 9084 if (!LHSEleType->isIntegerType()) { 9085 S.Diag(Loc, diag::err_typecheck_expect_int) 9086 << LHS.get()->getType() << LHS.get()->getSourceRange(); 9087 return QualType(); 9088 } 9089 9090 if (!RHSEleType->isIntegerType()) { 9091 S.Diag(Loc, diag::err_typecheck_expect_int) 9092 << RHS.get()->getType() << RHS.get()->getSourceRange(); 9093 return QualType(); 9094 } 9095 9096 if (!LHSVecTy) { 9097 assert(RHSVecTy); 9098 if (IsCompAssign) 9099 return RHSType; 9100 if (LHSEleType != RHSEleType) { 9101 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 9102 LHSEleType = RHSEleType; 9103 } 9104 QualType VecTy = 9105 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 9106 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 9107 LHSType = VecTy; 9108 } else if (RHSVecTy) { 9109 // OpenCL v1.1 s6.3.j says that for vector types, the operators 9110 // are applied component-wise. So if RHS is a vector, then ensure 9111 // that the number of elements is the same as LHS... 9112 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 9113 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 9114 << LHS.get()->getType() << RHS.get()->getType() 9115 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9116 return QualType(); 9117 } 9118 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 9119 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 9120 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 9121 if (LHSBT != RHSBT && 9122 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 9123 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 9124 << LHS.get()->getType() << RHS.get()->getType() 9125 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9126 } 9127 } 9128 } else { 9129 // ...else expand RHS to match the number of elements in LHS. 9130 QualType VecTy = 9131 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 9132 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 9133 } 9134 9135 return LHSType; 9136 } 9137 9138 // C99 6.5.7 9139 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 9140 SourceLocation Loc, BinaryOperatorKind Opc, 9141 bool IsCompAssign) { 9142 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9143 9144 // Vector shifts promote their scalar inputs to vector type. 9145 if (LHS.get()->getType()->isVectorType() || 9146 RHS.get()->getType()->isVectorType()) { 9147 if (LangOpts.ZVector) { 9148 // The shift operators for the z vector extensions work basically 9149 // like general shifts, except that neither the LHS nor the RHS is 9150 // allowed to be a "vector bool". 9151 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 9152 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 9153 return InvalidOperands(Loc, LHS, RHS); 9154 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 9155 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9156 return InvalidOperands(Loc, LHS, RHS); 9157 } 9158 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 9159 } 9160 9161 // Shifts don't perform usual arithmetic conversions, they just do integer 9162 // promotions on each operand. C99 6.5.7p3 9163 9164 // For the LHS, do usual unary conversions, but then reset them away 9165 // if this is a compound assignment. 9166 ExprResult OldLHS = LHS; 9167 LHS = UsualUnaryConversions(LHS.get()); 9168 if (LHS.isInvalid()) 9169 return QualType(); 9170 QualType LHSType = LHS.get()->getType(); 9171 if (IsCompAssign) LHS = OldLHS; 9172 9173 // The RHS is simpler. 9174 RHS = UsualUnaryConversions(RHS.get()); 9175 if (RHS.isInvalid()) 9176 return QualType(); 9177 QualType RHSType = RHS.get()->getType(); 9178 9179 // C99 6.5.7p2: Each of the operands shall have integer type. 9180 if (!LHSType->hasIntegerRepresentation() || 9181 !RHSType->hasIntegerRepresentation()) 9182 return InvalidOperands(Loc, LHS, RHS); 9183 9184 // C++0x: Don't allow scoped enums. FIXME: Use something better than 9185 // hasIntegerRepresentation() above instead of this. 9186 if (isScopedEnumerationType(LHSType) || 9187 isScopedEnumerationType(RHSType)) { 9188 return InvalidOperands(Loc, LHS, RHS); 9189 } 9190 // Sanity-check shift operands 9191 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 9192 9193 // "The type of the result is that of the promoted left operand." 9194 return LHSType; 9195 } 9196 9197 static bool IsWithinTemplateSpecialization(Decl *D) { 9198 if (DeclContext *DC = D->getDeclContext()) { 9199 if (isa<ClassTemplateSpecializationDecl>(DC)) 9200 return true; 9201 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 9202 return FD->isFunctionTemplateSpecialization(); 9203 } 9204 return false; 9205 } 9206 9207 /// If two different enums are compared, raise a warning. 9208 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 9209 Expr *RHS) { 9210 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 9211 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 9212 9213 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 9214 if (!LHSEnumType) 9215 return; 9216 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 9217 if (!RHSEnumType) 9218 return; 9219 9220 // Ignore anonymous enums. 9221 if (!LHSEnumType->getDecl()->getIdentifier()) 9222 return; 9223 if (!RHSEnumType->getDecl()->getIdentifier()) 9224 return; 9225 9226 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 9227 return; 9228 9229 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 9230 << LHSStrippedType << RHSStrippedType 9231 << LHS->getSourceRange() << RHS->getSourceRange(); 9232 } 9233 9234 /// \brief Diagnose bad pointer comparisons. 9235 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 9236 ExprResult &LHS, ExprResult &RHS, 9237 bool IsError) { 9238 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 9239 : diag::ext_typecheck_comparison_of_distinct_pointers) 9240 << LHS.get()->getType() << RHS.get()->getType() 9241 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9242 } 9243 9244 /// \brief Returns false if the pointers are converted to a composite type, 9245 /// true otherwise. 9246 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 9247 ExprResult &LHS, ExprResult &RHS) { 9248 // C++ [expr.rel]p2: 9249 // [...] Pointer conversions (4.10) and qualification 9250 // conversions (4.4) are performed on pointer operands (or on 9251 // a pointer operand and a null pointer constant) to bring 9252 // them to their composite pointer type. [...] 9253 // 9254 // C++ [expr.eq]p1 uses the same notion for (in)equality 9255 // comparisons of pointers. 9256 9257 QualType LHSType = LHS.get()->getType(); 9258 QualType RHSType = RHS.get()->getType(); 9259 assert(LHSType->isPointerType() || RHSType->isPointerType() || 9260 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 9261 9262 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 9263 if (T.isNull()) { 9264 if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) && 9265 (RHSType->isPointerType() || RHSType->isMemberPointerType())) 9266 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 9267 else 9268 S.InvalidOperands(Loc, LHS, RHS); 9269 return true; 9270 } 9271 9272 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 9273 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 9274 return false; 9275 } 9276 9277 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 9278 ExprResult &LHS, 9279 ExprResult &RHS, 9280 bool IsError) { 9281 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 9282 : diag::ext_typecheck_comparison_of_fptr_to_void) 9283 << LHS.get()->getType() << RHS.get()->getType() 9284 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9285 } 9286 9287 static bool isObjCObjectLiteral(ExprResult &E) { 9288 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 9289 case Stmt::ObjCArrayLiteralClass: 9290 case Stmt::ObjCDictionaryLiteralClass: 9291 case Stmt::ObjCStringLiteralClass: 9292 case Stmt::ObjCBoxedExprClass: 9293 return true; 9294 default: 9295 // Note that ObjCBoolLiteral is NOT an object literal! 9296 return false; 9297 } 9298 } 9299 9300 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 9301 const ObjCObjectPointerType *Type = 9302 LHS->getType()->getAs<ObjCObjectPointerType>(); 9303 9304 // If this is not actually an Objective-C object, bail out. 9305 if (!Type) 9306 return false; 9307 9308 // Get the LHS object's interface type. 9309 QualType InterfaceType = Type->getPointeeType(); 9310 9311 // If the RHS isn't an Objective-C object, bail out. 9312 if (!RHS->getType()->isObjCObjectPointerType()) 9313 return false; 9314 9315 // Try to find the -isEqual: method. 9316 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 9317 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 9318 InterfaceType, 9319 /*instance=*/true); 9320 if (!Method) { 9321 if (Type->isObjCIdType()) { 9322 // For 'id', just check the global pool. 9323 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 9324 /*receiverId=*/true); 9325 } else { 9326 // Check protocols. 9327 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 9328 /*instance=*/true); 9329 } 9330 } 9331 9332 if (!Method) 9333 return false; 9334 9335 QualType T = Method->parameters()[0]->getType(); 9336 if (!T->isObjCObjectPointerType()) 9337 return false; 9338 9339 QualType R = Method->getReturnType(); 9340 if (!R->isScalarType()) 9341 return false; 9342 9343 return true; 9344 } 9345 9346 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 9347 FromE = FromE->IgnoreParenImpCasts(); 9348 switch (FromE->getStmtClass()) { 9349 default: 9350 break; 9351 case Stmt::ObjCStringLiteralClass: 9352 // "string literal" 9353 return LK_String; 9354 case Stmt::ObjCArrayLiteralClass: 9355 // "array literal" 9356 return LK_Array; 9357 case Stmt::ObjCDictionaryLiteralClass: 9358 // "dictionary literal" 9359 return LK_Dictionary; 9360 case Stmt::BlockExprClass: 9361 return LK_Block; 9362 case Stmt::ObjCBoxedExprClass: { 9363 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 9364 switch (Inner->getStmtClass()) { 9365 case Stmt::IntegerLiteralClass: 9366 case Stmt::FloatingLiteralClass: 9367 case Stmt::CharacterLiteralClass: 9368 case Stmt::ObjCBoolLiteralExprClass: 9369 case Stmt::CXXBoolLiteralExprClass: 9370 // "numeric literal" 9371 return LK_Numeric; 9372 case Stmt::ImplicitCastExprClass: { 9373 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 9374 // Boolean literals can be represented by implicit casts. 9375 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 9376 return LK_Numeric; 9377 break; 9378 } 9379 default: 9380 break; 9381 } 9382 return LK_Boxed; 9383 } 9384 } 9385 return LK_None; 9386 } 9387 9388 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 9389 ExprResult &LHS, ExprResult &RHS, 9390 BinaryOperator::Opcode Opc){ 9391 Expr *Literal; 9392 Expr *Other; 9393 if (isObjCObjectLiteral(LHS)) { 9394 Literal = LHS.get(); 9395 Other = RHS.get(); 9396 } else { 9397 Literal = RHS.get(); 9398 Other = LHS.get(); 9399 } 9400 9401 // Don't warn on comparisons against nil. 9402 Other = Other->IgnoreParenCasts(); 9403 if (Other->isNullPointerConstant(S.getASTContext(), 9404 Expr::NPC_ValueDependentIsNotNull)) 9405 return; 9406 9407 // This should be kept in sync with warn_objc_literal_comparison. 9408 // LK_String should always be after the other literals, since it has its own 9409 // warning flag. 9410 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 9411 assert(LiteralKind != Sema::LK_Block); 9412 if (LiteralKind == Sema::LK_None) { 9413 llvm_unreachable("Unknown Objective-C object literal kind"); 9414 } 9415 9416 if (LiteralKind == Sema::LK_String) 9417 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 9418 << Literal->getSourceRange(); 9419 else 9420 S.Diag(Loc, diag::warn_objc_literal_comparison) 9421 << LiteralKind << Literal->getSourceRange(); 9422 9423 if (BinaryOperator::isEqualityOp(Opc) && 9424 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 9425 SourceLocation Start = LHS.get()->getLocStart(); 9426 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd()); 9427 CharSourceRange OpRange = 9428 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 9429 9430 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 9431 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 9432 << FixItHint::CreateReplacement(OpRange, " isEqual:") 9433 << FixItHint::CreateInsertion(End, "]"); 9434 } 9435 } 9436 9437 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 9438 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 9439 ExprResult &RHS, SourceLocation Loc, 9440 BinaryOperatorKind Opc) { 9441 // Check that left hand side is !something. 9442 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 9443 if (!UO || UO->getOpcode() != UO_LNot) return; 9444 9445 // Only check if the right hand side is non-bool arithmetic type. 9446 if (RHS.get()->isKnownToHaveBooleanValue()) return; 9447 9448 // Make sure that the something in !something is not bool. 9449 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 9450 if (SubExpr->isKnownToHaveBooleanValue()) return; 9451 9452 // Emit warning. 9453 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 9454 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 9455 << Loc << IsBitwiseOp; 9456 9457 // First note suggest !(x < y) 9458 SourceLocation FirstOpen = SubExpr->getLocStart(); 9459 SourceLocation FirstClose = RHS.get()->getLocEnd(); 9460 FirstClose = S.getLocForEndOfToken(FirstClose); 9461 if (FirstClose.isInvalid()) 9462 FirstOpen = SourceLocation(); 9463 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 9464 << IsBitwiseOp 9465 << FixItHint::CreateInsertion(FirstOpen, "(") 9466 << FixItHint::CreateInsertion(FirstClose, ")"); 9467 9468 // Second note suggests (!x) < y 9469 SourceLocation SecondOpen = LHS.get()->getLocStart(); 9470 SourceLocation SecondClose = LHS.get()->getLocEnd(); 9471 SecondClose = S.getLocForEndOfToken(SecondClose); 9472 if (SecondClose.isInvalid()) 9473 SecondOpen = SourceLocation(); 9474 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 9475 << FixItHint::CreateInsertion(SecondOpen, "(") 9476 << FixItHint::CreateInsertion(SecondClose, ")"); 9477 } 9478 9479 // Get the decl for a simple expression: a reference to a variable, 9480 // an implicit C++ field reference, or an implicit ObjC ivar reference. 9481 static ValueDecl *getCompareDecl(Expr *E) { 9482 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E)) 9483 return DR->getDecl(); 9484 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 9485 if (Ivar->isFreeIvar()) 9486 return Ivar->getDecl(); 9487 } 9488 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) { 9489 if (Mem->isImplicitAccess()) 9490 return Mem->getMemberDecl(); 9491 } 9492 return nullptr; 9493 } 9494 9495 // C99 6.5.8, C++ [expr.rel] 9496 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 9497 SourceLocation Loc, BinaryOperatorKind Opc, 9498 bool IsRelational) { 9499 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 9500 9501 // Handle vector comparisons separately. 9502 if (LHS.get()->getType()->isVectorType() || 9503 RHS.get()->getType()->isVectorType()) 9504 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 9505 9506 QualType LHSType = LHS.get()->getType(); 9507 QualType RHSType = RHS.get()->getType(); 9508 9509 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 9510 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 9511 9512 checkEnumComparison(*this, Loc, LHS.get(), RHS.get()); 9513 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 9514 9515 if (!LHSType->hasFloatingRepresentation() && 9516 !(LHSType->isBlockPointerType() && IsRelational) && 9517 !LHS.get()->getLocStart().isMacroID() && 9518 !RHS.get()->getLocStart().isMacroID() && 9519 !inTemplateInstantiation()) { 9520 // For non-floating point types, check for self-comparisons of the form 9521 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9522 // often indicate logic errors in the program. 9523 // 9524 // NOTE: Don't warn about comparison expressions resulting from macro 9525 // expansion. Also don't warn about comparisons which are only self 9526 // comparisons within a template specialization. The warnings should catch 9527 // obvious cases in the definition of the template anyways. The idea is to 9528 // warn when the typed comparison operator will always evaluate to the same 9529 // result. 9530 ValueDecl *DL = getCompareDecl(LHSStripped); 9531 ValueDecl *DR = getCompareDecl(RHSStripped); 9532 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) { 9533 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 9534 << 0 // self- 9535 << (Opc == BO_EQ 9536 || Opc == BO_LE 9537 || Opc == BO_GE)); 9538 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() && 9539 !DL->getType()->isReferenceType() && 9540 !DR->getType()->isReferenceType()) { 9541 // what is it always going to eval to? 9542 char always_evals_to; 9543 switch(Opc) { 9544 case BO_EQ: // e.g. array1 == array2 9545 always_evals_to = 0; // false 9546 break; 9547 case BO_NE: // e.g. array1 != array2 9548 always_evals_to = 1; // true 9549 break; 9550 default: 9551 // best we can say is 'a constant' 9552 always_evals_to = 2; // e.g. array1 <= array2 9553 break; 9554 } 9555 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 9556 << 1 // array 9557 << always_evals_to); 9558 } 9559 9560 if (isa<CastExpr>(LHSStripped)) 9561 LHSStripped = LHSStripped->IgnoreParenCasts(); 9562 if (isa<CastExpr>(RHSStripped)) 9563 RHSStripped = RHSStripped->IgnoreParenCasts(); 9564 9565 // Warn about comparisons against a string constant (unless the other 9566 // operand is null), the user probably wants strcmp. 9567 Expr *literalString = nullptr; 9568 Expr *literalStringStripped = nullptr; 9569 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 9570 !RHSStripped->isNullPointerConstant(Context, 9571 Expr::NPC_ValueDependentIsNull)) { 9572 literalString = LHS.get(); 9573 literalStringStripped = LHSStripped; 9574 } else if ((isa<StringLiteral>(RHSStripped) || 9575 isa<ObjCEncodeExpr>(RHSStripped)) && 9576 !LHSStripped->isNullPointerConstant(Context, 9577 Expr::NPC_ValueDependentIsNull)) { 9578 literalString = RHS.get(); 9579 literalStringStripped = RHSStripped; 9580 } 9581 9582 if (literalString) { 9583 DiagRuntimeBehavior(Loc, nullptr, 9584 PDiag(diag::warn_stringcompare) 9585 << isa<ObjCEncodeExpr>(literalStringStripped) 9586 << literalString->getSourceRange()); 9587 } 9588 } 9589 9590 // C99 6.5.8p3 / C99 6.5.9p4 9591 UsualArithmeticConversions(LHS, RHS); 9592 if (LHS.isInvalid() || RHS.isInvalid()) 9593 return QualType(); 9594 9595 LHSType = LHS.get()->getType(); 9596 RHSType = RHS.get()->getType(); 9597 9598 // The result of comparisons is 'bool' in C++, 'int' in C. 9599 QualType ResultTy = Context.getLogicalOperationType(); 9600 9601 if (IsRelational) { 9602 if (LHSType->isRealType() && RHSType->isRealType()) 9603 return ResultTy; 9604 } else { 9605 // Check for comparisons of floating point operands using != and ==. 9606 if (LHSType->hasFloatingRepresentation()) 9607 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9608 9609 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 9610 return ResultTy; 9611 } 9612 9613 const Expr::NullPointerConstantKind LHSNullKind = 9614 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9615 const Expr::NullPointerConstantKind RHSNullKind = 9616 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9617 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 9618 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 9619 9620 if (!IsRelational && LHSIsNull != RHSIsNull) { 9621 bool IsEquality = Opc == BO_EQ; 9622 if (RHSIsNull) 9623 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 9624 RHS.get()->getSourceRange()); 9625 else 9626 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 9627 LHS.get()->getSourceRange()); 9628 } 9629 9630 if ((LHSType->isIntegerType() && !LHSIsNull) || 9631 (RHSType->isIntegerType() && !RHSIsNull)) { 9632 // Skip normal pointer conversion checks in this case; we have better 9633 // diagnostics for this below. 9634 } else if (getLangOpts().CPlusPlus) { 9635 // Equality comparison of a function pointer to a void pointer is invalid, 9636 // but we allow it as an extension. 9637 // FIXME: If we really want to allow this, should it be part of composite 9638 // pointer type computation so it works in conditionals too? 9639 if (!IsRelational && 9640 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 9641 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 9642 // This is a gcc extension compatibility comparison. 9643 // In a SFINAE context, we treat this as a hard error to maintain 9644 // conformance with the C++ standard. 9645 diagnoseFunctionPointerToVoidComparison( 9646 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 9647 9648 if (isSFINAEContext()) 9649 return QualType(); 9650 9651 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9652 return ResultTy; 9653 } 9654 9655 // C++ [expr.eq]p2: 9656 // If at least one operand is a pointer [...] bring them to their 9657 // composite pointer type. 9658 // C++ [expr.rel]p2: 9659 // If both operands are pointers, [...] bring them to their composite 9660 // pointer type. 9661 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 9662 (IsRelational ? 2 : 1) && 9663 (!LangOpts.ObjCAutoRefCount || 9664 !(LHSType->isObjCObjectPointerType() || 9665 RHSType->isObjCObjectPointerType()))) { 9666 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9667 return QualType(); 9668 else 9669 return ResultTy; 9670 } 9671 } else if (LHSType->isPointerType() && 9672 RHSType->isPointerType()) { // C99 6.5.8p2 9673 // All of the following pointer-related warnings are GCC extensions, except 9674 // when handling null pointer constants. 9675 QualType LCanPointeeTy = 9676 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9677 QualType RCanPointeeTy = 9678 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9679 9680 // C99 6.5.9p2 and C99 6.5.8p2 9681 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 9682 RCanPointeeTy.getUnqualifiedType())) { 9683 // Valid unless a relational comparison of function pointers 9684 if (IsRelational && LCanPointeeTy->isFunctionType()) { 9685 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 9686 << LHSType << RHSType << LHS.get()->getSourceRange() 9687 << RHS.get()->getSourceRange(); 9688 } 9689 } else if (!IsRelational && 9690 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 9691 // Valid unless comparison between non-null pointer and function pointer 9692 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 9693 && !LHSIsNull && !RHSIsNull) 9694 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 9695 /*isError*/false); 9696 } else { 9697 // Invalid 9698 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 9699 } 9700 if (LCanPointeeTy != RCanPointeeTy) { 9701 // Treat NULL constant as a special case in OpenCL. 9702 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 9703 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 9704 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 9705 Diag(Loc, 9706 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 9707 << LHSType << RHSType << 0 /* comparison */ 9708 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9709 } 9710 } 9711 unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace(); 9712 unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace(); 9713 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 9714 : CK_BitCast; 9715 if (LHSIsNull && !RHSIsNull) 9716 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 9717 else 9718 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 9719 } 9720 return ResultTy; 9721 } 9722 9723 if (getLangOpts().CPlusPlus) { 9724 // C++ [expr.eq]p4: 9725 // Two operands of type std::nullptr_t or one operand of type 9726 // std::nullptr_t and the other a null pointer constant compare equal. 9727 if (!IsRelational && LHSIsNull && RHSIsNull) { 9728 if (LHSType->isNullPtrType()) { 9729 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9730 return ResultTy; 9731 } 9732 if (RHSType->isNullPtrType()) { 9733 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9734 return ResultTy; 9735 } 9736 } 9737 9738 // Comparison of Objective-C pointers and block pointers against nullptr_t. 9739 // These aren't covered by the composite pointer type rules. 9740 if (!IsRelational && RHSType->isNullPtrType() && 9741 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 9742 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9743 return ResultTy; 9744 } 9745 if (!IsRelational && LHSType->isNullPtrType() && 9746 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 9747 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9748 return ResultTy; 9749 } 9750 9751 if (IsRelational && 9752 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 9753 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 9754 // HACK: Relational comparison of nullptr_t against a pointer type is 9755 // invalid per DR583, but we allow it within std::less<> and friends, 9756 // since otherwise common uses of it break. 9757 // FIXME: Consider removing this hack once LWG fixes std::less<> and 9758 // friends to have std::nullptr_t overload candidates. 9759 DeclContext *DC = CurContext; 9760 if (isa<FunctionDecl>(DC)) 9761 DC = DC->getParent(); 9762 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 9763 if (CTSD->isInStdNamespace() && 9764 llvm::StringSwitch<bool>(CTSD->getName()) 9765 .Cases("less", "less_equal", "greater", "greater_equal", true) 9766 .Default(false)) { 9767 if (RHSType->isNullPtrType()) 9768 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9769 else 9770 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9771 return ResultTy; 9772 } 9773 } 9774 } 9775 9776 // C++ [expr.eq]p2: 9777 // If at least one operand is a pointer to member, [...] bring them to 9778 // their composite pointer type. 9779 if (!IsRelational && 9780 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 9781 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9782 return QualType(); 9783 else 9784 return ResultTy; 9785 } 9786 9787 // Handle scoped enumeration types specifically, since they don't promote 9788 // to integers. 9789 if (LHS.get()->getType()->isEnumeralType() && 9790 Context.hasSameUnqualifiedType(LHS.get()->getType(), 9791 RHS.get()->getType())) 9792 return ResultTy; 9793 } 9794 9795 // Handle block pointer types. 9796 if (!IsRelational && LHSType->isBlockPointerType() && 9797 RHSType->isBlockPointerType()) { 9798 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 9799 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 9800 9801 if (!LHSIsNull && !RHSIsNull && 9802 !Context.typesAreCompatible(lpointee, rpointee)) { 9803 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9804 << LHSType << RHSType << LHS.get()->getSourceRange() 9805 << RHS.get()->getSourceRange(); 9806 } 9807 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9808 return ResultTy; 9809 } 9810 9811 // Allow block pointers to be compared with null pointer constants. 9812 if (!IsRelational 9813 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 9814 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 9815 if (!LHSIsNull && !RHSIsNull) { 9816 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 9817 ->getPointeeType()->isVoidType()) 9818 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 9819 ->getPointeeType()->isVoidType()))) 9820 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9821 << LHSType << RHSType << LHS.get()->getSourceRange() 9822 << RHS.get()->getSourceRange(); 9823 } 9824 if (LHSIsNull && !RHSIsNull) 9825 LHS = ImpCastExprToType(LHS.get(), RHSType, 9826 RHSType->isPointerType() ? CK_BitCast 9827 : CK_AnyPointerToBlockPointerCast); 9828 else 9829 RHS = ImpCastExprToType(RHS.get(), LHSType, 9830 LHSType->isPointerType() ? CK_BitCast 9831 : CK_AnyPointerToBlockPointerCast); 9832 return ResultTy; 9833 } 9834 9835 if (LHSType->isObjCObjectPointerType() || 9836 RHSType->isObjCObjectPointerType()) { 9837 const PointerType *LPT = LHSType->getAs<PointerType>(); 9838 const PointerType *RPT = RHSType->getAs<PointerType>(); 9839 if (LPT || RPT) { 9840 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 9841 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 9842 9843 if (!LPtrToVoid && !RPtrToVoid && 9844 !Context.typesAreCompatible(LHSType, RHSType)) { 9845 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9846 /*isError*/false); 9847 } 9848 if (LHSIsNull && !RHSIsNull) { 9849 Expr *E = LHS.get(); 9850 if (getLangOpts().ObjCAutoRefCount) 9851 CheckObjCConversion(SourceRange(), RHSType, E, 9852 CCK_ImplicitConversion); 9853 LHS = ImpCastExprToType(E, RHSType, 9854 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9855 } 9856 else { 9857 Expr *E = RHS.get(); 9858 if (getLangOpts().ObjCAutoRefCount) 9859 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 9860 /*Diagnose=*/true, 9861 /*DiagnoseCFAudited=*/false, Opc); 9862 RHS = ImpCastExprToType(E, LHSType, 9863 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9864 } 9865 return ResultTy; 9866 } 9867 if (LHSType->isObjCObjectPointerType() && 9868 RHSType->isObjCObjectPointerType()) { 9869 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 9870 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9871 /*isError*/false); 9872 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 9873 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 9874 9875 if (LHSIsNull && !RHSIsNull) 9876 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9877 else 9878 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9879 return ResultTy; 9880 } 9881 } 9882 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 9883 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 9884 unsigned DiagID = 0; 9885 bool isError = false; 9886 if (LangOpts.DebuggerSupport) { 9887 // Under a debugger, allow the comparison of pointers to integers, 9888 // since users tend to want to compare addresses. 9889 } else if ((LHSIsNull && LHSType->isIntegerType()) || 9890 (RHSIsNull && RHSType->isIntegerType())) { 9891 if (IsRelational) { 9892 isError = getLangOpts().CPlusPlus; 9893 DiagID = 9894 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 9895 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 9896 } 9897 } else if (getLangOpts().CPlusPlus) { 9898 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 9899 isError = true; 9900 } else if (IsRelational) 9901 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 9902 else 9903 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 9904 9905 if (DiagID) { 9906 Diag(Loc, DiagID) 9907 << LHSType << RHSType << LHS.get()->getSourceRange() 9908 << RHS.get()->getSourceRange(); 9909 if (isError) 9910 return QualType(); 9911 } 9912 9913 if (LHSType->isIntegerType()) 9914 LHS = ImpCastExprToType(LHS.get(), RHSType, 9915 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 9916 else 9917 RHS = ImpCastExprToType(RHS.get(), LHSType, 9918 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 9919 return ResultTy; 9920 } 9921 9922 // Handle block pointers. 9923 if (!IsRelational && RHSIsNull 9924 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 9925 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9926 return ResultTy; 9927 } 9928 if (!IsRelational && LHSIsNull 9929 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 9930 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9931 return ResultTy; 9932 } 9933 9934 if (getLangOpts().OpenCLVersion >= 200) { 9935 if (LHSIsNull && RHSType->isQueueT()) { 9936 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9937 return ResultTy; 9938 } 9939 9940 if (LHSType->isQueueT() && RHSIsNull) { 9941 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9942 return ResultTy; 9943 } 9944 } 9945 9946 return InvalidOperands(Loc, LHS, RHS); 9947 } 9948 9949 // Return a signed ext_vector_type that is of identical size and number of 9950 // elements. For floating point vectors, return an integer type of identical 9951 // size and number of elements. In the non ext_vector_type case, search from 9952 // the largest type to the smallest type to avoid cases where long long == long, 9953 // where long gets picked over long long. 9954 QualType Sema::GetSignedVectorType(QualType V) { 9955 const VectorType *VTy = V->getAs<VectorType>(); 9956 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 9957 9958 if (isa<ExtVectorType>(VTy)) { 9959 if (TypeSize == Context.getTypeSize(Context.CharTy)) 9960 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 9961 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 9962 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 9963 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 9964 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 9965 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 9966 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 9967 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 9968 "Unhandled vector element size in vector compare"); 9969 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 9970 } 9971 9972 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 9973 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 9974 VectorType::GenericVector); 9975 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 9976 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 9977 VectorType::GenericVector); 9978 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 9979 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 9980 VectorType::GenericVector); 9981 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 9982 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 9983 VectorType::GenericVector); 9984 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 9985 "Unhandled vector element size in vector compare"); 9986 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 9987 VectorType::GenericVector); 9988 } 9989 9990 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 9991 /// operates on extended vector types. Instead of producing an IntTy result, 9992 /// like a scalar comparison, a vector comparison produces a vector of integer 9993 /// types. 9994 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 9995 SourceLocation Loc, 9996 bool IsRelational) { 9997 // Check to make sure we're operating on vectors of the same type and width, 9998 // Allowing one side to be a scalar of element type. 9999 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 10000 /*AllowBothBool*/true, 10001 /*AllowBoolConversions*/getLangOpts().ZVector); 10002 if (vType.isNull()) 10003 return vType; 10004 10005 QualType LHSType = LHS.get()->getType(); 10006 10007 // If AltiVec, the comparison results in a numeric type, i.e. 10008 // bool for C++, int for C 10009 if (getLangOpts().AltiVec && 10010 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 10011 return Context.getLogicalOperationType(); 10012 10013 // For non-floating point types, check for self-comparisons of the form 10014 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 10015 // often indicate logic errors in the program. 10016 if (!LHSType->hasFloatingRepresentation() && !inTemplateInstantiation()) { 10017 if (DeclRefExpr* DRL 10018 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 10019 if (DeclRefExpr* DRR 10020 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 10021 if (DRL->getDecl() == DRR->getDecl()) 10022 DiagRuntimeBehavior(Loc, nullptr, 10023 PDiag(diag::warn_comparison_always) 10024 << 0 // self- 10025 << 2 // "a constant" 10026 ); 10027 } 10028 10029 // Check for comparisons of floating point operands using != and ==. 10030 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 10031 assert (RHS.get()->getType()->hasFloatingRepresentation()); 10032 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 10033 } 10034 10035 // Return a signed type for the vector. 10036 return GetSignedVectorType(vType); 10037 } 10038 10039 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 10040 SourceLocation Loc) { 10041 // Ensure that either both operands are of the same vector type, or 10042 // one operand is of a vector type and the other is of its element type. 10043 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 10044 /*AllowBothBool*/true, 10045 /*AllowBoolConversions*/false); 10046 if (vType.isNull()) 10047 return InvalidOperands(Loc, LHS, RHS); 10048 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 10049 vType->hasFloatingRepresentation()) 10050 return InvalidOperands(Loc, LHS, RHS); 10051 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 10052 // usage of the logical operators && and || with vectors in C. This 10053 // check could be notionally dropped. 10054 if (!getLangOpts().CPlusPlus && 10055 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 10056 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 10057 10058 return GetSignedVectorType(LHS.get()->getType()); 10059 } 10060 10061 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 10062 SourceLocation Loc, 10063 BinaryOperatorKind Opc) { 10064 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 10065 10066 bool IsCompAssign = 10067 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 10068 10069 if (LHS.get()->getType()->isVectorType() || 10070 RHS.get()->getType()->isVectorType()) { 10071 if (LHS.get()->getType()->hasIntegerRepresentation() && 10072 RHS.get()->getType()->hasIntegerRepresentation()) 10073 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10074 /*AllowBothBool*/true, 10075 /*AllowBoolConversions*/getLangOpts().ZVector); 10076 return InvalidOperands(Loc, LHS, RHS); 10077 } 10078 10079 if (Opc == BO_And) 10080 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 10081 10082 ExprResult LHSResult = LHS, RHSResult = RHS; 10083 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 10084 IsCompAssign); 10085 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 10086 return QualType(); 10087 LHS = LHSResult.get(); 10088 RHS = RHSResult.get(); 10089 10090 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 10091 return compType; 10092 return InvalidOperands(Loc, LHS, RHS); 10093 } 10094 10095 // C99 6.5.[13,14] 10096 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 10097 SourceLocation Loc, 10098 BinaryOperatorKind Opc) { 10099 // Check vector operands differently. 10100 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 10101 return CheckVectorLogicalOperands(LHS, RHS, Loc); 10102 10103 // Diagnose cases where the user write a logical and/or but probably meant a 10104 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 10105 // is a constant. 10106 if (LHS.get()->getType()->isIntegerType() && 10107 !LHS.get()->getType()->isBooleanType() && 10108 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 10109 // Don't warn in macros or template instantiations. 10110 !Loc.isMacroID() && !inTemplateInstantiation()) { 10111 // If the RHS can be constant folded, and if it constant folds to something 10112 // that isn't 0 or 1 (which indicate a potential logical operation that 10113 // happened to fold to true/false) then warn. 10114 // Parens on the RHS are ignored. 10115 llvm::APSInt Result; 10116 if (RHS.get()->EvaluateAsInt(Result, Context)) 10117 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 10118 !RHS.get()->getExprLoc().isMacroID()) || 10119 (Result != 0 && Result != 1)) { 10120 Diag(Loc, diag::warn_logical_instead_of_bitwise) 10121 << RHS.get()->getSourceRange() 10122 << (Opc == BO_LAnd ? "&&" : "||"); 10123 // Suggest replacing the logical operator with the bitwise version 10124 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 10125 << (Opc == BO_LAnd ? "&" : "|") 10126 << FixItHint::CreateReplacement(SourceRange( 10127 Loc, getLocForEndOfToken(Loc)), 10128 Opc == BO_LAnd ? "&" : "|"); 10129 if (Opc == BO_LAnd) 10130 // Suggest replacing "Foo() && kNonZero" with "Foo()" 10131 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 10132 << FixItHint::CreateRemoval( 10133 SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()), 10134 RHS.get()->getLocEnd())); 10135 } 10136 } 10137 10138 if (!Context.getLangOpts().CPlusPlus) { 10139 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 10140 // not operate on the built-in scalar and vector float types. 10141 if (Context.getLangOpts().OpenCL && 10142 Context.getLangOpts().OpenCLVersion < 120) { 10143 if (LHS.get()->getType()->isFloatingType() || 10144 RHS.get()->getType()->isFloatingType()) 10145 return InvalidOperands(Loc, LHS, RHS); 10146 } 10147 10148 LHS = UsualUnaryConversions(LHS.get()); 10149 if (LHS.isInvalid()) 10150 return QualType(); 10151 10152 RHS = UsualUnaryConversions(RHS.get()); 10153 if (RHS.isInvalid()) 10154 return QualType(); 10155 10156 if (!LHS.get()->getType()->isScalarType() || 10157 !RHS.get()->getType()->isScalarType()) 10158 return InvalidOperands(Loc, LHS, RHS); 10159 10160 return Context.IntTy; 10161 } 10162 10163 // The following is safe because we only use this method for 10164 // non-overloadable operands. 10165 10166 // C++ [expr.log.and]p1 10167 // C++ [expr.log.or]p1 10168 // The operands are both contextually converted to type bool. 10169 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 10170 if (LHSRes.isInvalid()) 10171 return InvalidOperands(Loc, LHS, RHS); 10172 LHS = LHSRes; 10173 10174 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 10175 if (RHSRes.isInvalid()) 10176 return InvalidOperands(Loc, LHS, RHS); 10177 RHS = RHSRes; 10178 10179 // C++ [expr.log.and]p2 10180 // C++ [expr.log.or]p2 10181 // The result is a bool. 10182 return Context.BoolTy; 10183 } 10184 10185 static bool IsReadonlyMessage(Expr *E, Sema &S) { 10186 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 10187 if (!ME) return false; 10188 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 10189 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 10190 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 10191 if (!Base) return false; 10192 return Base->getMethodDecl() != nullptr; 10193 } 10194 10195 /// Is the given expression (which must be 'const') a reference to a 10196 /// variable which was originally non-const, but which has become 10197 /// 'const' due to being captured within a block? 10198 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 10199 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 10200 assert(E->isLValue() && E->getType().isConstQualified()); 10201 E = E->IgnoreParens(); 10202 10203 // Must be a reference to a declaration from an enclosing scope. 10204 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 10205 if (!DRE) return NCCK_None; 10206 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 10207 10208 // The declaration must be a variable which is not declared 'const'. 10209 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 10210 if (!var) return NCCK_None; 10211 if (var->getType().isConstQualified()) return NCCK_None; 10212 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 10213 10214 // Decide whether the first capture was for a block or a lambda. 10215 DeclContext *DC = S.CurContext, *Prev = nullptr; 10216 // Decide whether the first capture was for a block or a lambda. 10217 while (DC) { 10218 // For init-capture, it is possible that the variable belongs to the 10219 // template pattern of the current context. 10220 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 10221 if (var->isInitCapture() && 10222 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 10223 break; 10224 if (DC == var->getDeclContext()) 10225 break; 10226 Prev = DC; 10227 DC = DC->getParent(); 10228 } 10229 // Unless we have an init-capture, we've gone one step too far. 10230 if (!var->isInitCapture()) 10231 DC = Prev; 10232 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 10233 } 10234 10235 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 10236 Ty = Ty.getNonReferenceType(); 10237 if (IsDereference && Ty->isPointerType()) 10238 Ty = Ty->getPointeeType(); 10239 return !Ty.isConstQualified(); 10240 } 10241 10242 /// Emit the "read-only variable not assignable" error and print notes to give 10243 /// more information about why the variable is not assignable, such as pointing 10244 /// to the declaration of a const variable, showing that a method is const, or 10245 /// that the function is returning a const reference. 10246 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 10247 SourceLocation Loc) { 10248 // Update err_typecheck_assign_const and note_typecheck_assign_const 10249 // when this enum is changed. 10250 enum { 10251 ConstFunction, 10252 ConstVariable, 10253 ConstMember, 10254 ConstMethod, 10255 ConstUnknown, // Keep as last element 10256 }; 10257 10258 SourceRange ExprRange = E->getSourceRange(); 10259 10260 // Only emit one error on the first const found. All other consts will emit 10261 // a note to the error. 10262 bool DiagnosticEmitted = false; 10263 10264 // Track if the current expression is the result of a dereference, and if the 10265 // next checked expression is the result of a dereference. 10266 bool IsDereference = false; 10267 bool NextIsDereference = false; 10268 10269 // Loop to process MemberExpr chains. 10270 while (true) { 10271 IsDereference = NextIsDereference; 10272 10273 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 10274 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 10275 NextIsDereference = ME->isArrow(); 10276 const ValueDecl *VD = ME->getMemberDecl(); 10277 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 10278 // Mutable fields can be modified even if the class is const. 10279 if (Field->isMutable()) { 10280 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 10281 break; 10282 } 10283 10284 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 10285 if (!DiagnosticEmitted) { 10286 S.Diag(Loc, diag::err_typecheck_assign_const) 10287 << ExprRange << ConstMember << false /*static*/ << Field 10288 << Field->getType(); 10289 DiagnosticEmitted = true; 10290 } 10291 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10292 << ConstMember << false /*static*/ << Field << Field->getType() 10293 << Field->getSourceRange(); 10294 } 10295 E = ME->getBase(); 10296 continue; 10297 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 10298 if (VDecl->getType().isConstQualified()) { 10299 if (!DiagnosticEmitted) { 10300 S.Diag(Loc, diag::err_typecheck_assign_const) 10301 << ExprRange << ConstMember << true /*static*/ << VDecl 10302 << VDecl->getType(); 10303 DiagnosticEmitted = true; 10304 } 10305 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10306 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 10307 << VDecl->getSourceRange(); 10308 } 10309 // Static fields do not inherit constness from parents. 10310 break; 10311 } 10312 break; 10313 } // End MemberExpr 10314 break; 10315 } 10316 10317 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 10318 // Function calls 10319 const FunctionDecl *FD = CE->getDirectCallee(); 10320 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 10321 if (!DiagnosticEmitted) { 10322 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 10323 << ConstFunction << FD; 10324 DiagnosticEmitted = true; 10325 } 10326 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 10327 diag::note_typecheck_assign_const) 10328 << ConstFunction << FD << FD->getReturnType() 10329 << FD->getReturnTypeSourceRange(); 10330 } 10331 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 10332 // Point to variable declaration. 10333 if (const ValueDecl *VD = DRE->getDecl()) { 10334 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 10335 if (!DiagnosticEmitted) { 10336 S.Diag(Loc, diag::err_typecheck_assign_const) 10337 << ExprRange << ConstVariable << VD << VD->getType(); 10338 DiagnosticEmitted = true; 10339 } 10340 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10341 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 10342 } 10343 } 10344 } else if (isa<CXXThisExpr>(E)) { 10345 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 10346 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 10347 if (MD->isConst()) { 10348 if (!DiagnosticEmitted) { 10349 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 10350 << ConstMethod << MD; 10351 DiagnosticEmitted = true; 10352 } 10353 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 10354 << ConstMethod << MD << MD->getSourceRange(); 10355 } 10356 } 10357 } 10358 } 10359 10360 if (DiagnosticEmitted) 10361 return; 10362 10363 // Can't determine a more specific message, so display the generic error. 10364 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 10365 } 10366 10367 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 10368 /// emit an error and return true. If so, return false. 10369 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 10370 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 10371 10372 S.CheckShadowingDeclModification(E, Loc); 10373 10374 SourceLocation OrigLoc = Loc; 10375 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 10376 &Loc); 10377 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 10378 IsLV = Expr::MLV_InvalidMessageExpression; 10379 if (IsLV == Expr::MLV_Valid) 10380 return false; 10381 10382 unsigned DiagID = 0; 10383 bool NeedType = false; 10384 switch (IsLV) { // C99 6.5.16p2 10385 case Expr::MLV_ConstQualified: 10386 // Use a specialized diagnostic when we're assigning to an object 10387 // from an enclosing function or block. 10388 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 10389 if (NCCK == NCCK_Block) 10390 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 10391 else 10392 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 10393 break; 10394 } 10395 10396 // In ARC, use some specialized diagnostics for occasions where we 10397 // infer 'const'. These are always pseudo-strong variables. 10398 if (S.getLangOpts().ObjCAutoRefCount) { 10399 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 10400 if (declRef && isa<VarDecl>(declRef->getDecl())) { 10401 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 10402 10403 // Use the normal diagnostic if it's pseudo-__strong but the 10404 // user actually wrote 'const'. 10405 if (var->isARCPseudoStrong() && 10406 (!var->getTypeSourceInfo() || 10407 !var->getTypeSourceInfo()->getType().isConstQualified())) { 10408 // There are two pseudo-strong cases: 10409 // - self 10410 ObjCMethodDecl *method = S.getCurMethodDecl(); 10411 if (method && var == method->getSelfDecl()) 10412 DiagID = method->isClassMethod() 10413 ? diag::err_typecheck_arc_assign_self_class_method 10414 : diag::err_typecheck_arc_assign_self; 10415 10416 // - fast enumeration variables 10417 else 10418 DiagID = diag::err_typecheck_arr_assign_enumeration; 10419 10420 SourceRange Assign; 10421 if (Loc != OrigLoc) 10422 Assign = SourceRange(OrigLoc, OrigLoc); 10423 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10424 // We need to preserve the AST regardless, so migration tool 10425 // can do its job. 10426 return false; 10427 } 10428 } 10429 } 10430 10431 // If none of the special cases above are triggered, then this is a 10432 // simple const assignment. 10433 if (DiagID == 0) { 10434 DiagnoseConstAssignment(S, E, Loc); 10435 return true; 10436 } 10437 10438 break; 10439 case Expr::MLV_ConstAddrSpace: 10440 DiagnoseConstAssignment(S, E, Loc); 10441 return true; 10442 case Expr::MLV_ArrayType: 10443 case Expr::MLV_ArrayTemporary: 10444 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 10445 NeedType = true; 10446 break; 10447 case Expr::MLV_NotObjectType: 10448 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 10449 NeedType = true; 10450 break; 10451 case Expr::MLV_LValueCast: 10452 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 10453 break; 10454 case Expr::MLV_Valid: 10455 llvm_unreachable("did not take early return for MLV_Valid"); 10456 case Expr::MLV_InvalidExpression: 10457 case Expr::MLV_MemberFunction: 10458 case Expr::MLV_ClassTemporary: 10459 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 10460 break; 10461 case Expr::MLV_IncompleteType: 10462 case Expr::MLV_IncompleteVoidType: 10463 return S.RequireCompleteType(Loc, E->getType(), 10464 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 10465 case Expr::MLV_DuplicateVectorComponents: 10466 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 10467 break; 10468 case Expr::MLV_NoSetterProperty: 10469 llvm_unreachable("readonly properties should be processed differently"); 10470 case Expr::MLV_InvalidMessageExpression: 10471 DiagID = diag::err_readonly_message_assignment; 10472 break; 10473 case Expr::MLV_SubObjCPropertySetting: 10474 DiagID = diag::err_no_subobject_property_setting; 10475 break; 10476 } 10477 10478 SourceRange Assign; 10479 if (Loc != OrigLoc) 10480 Assign = SourceRange(OrigLoc, OrigLoc); 10481 if (NeedType) 10482 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 10483 else 10484 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10485 return true; 10486 } 10487 10488 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 10489 SourceLocation Loc, 10490 Sema &Sema) { 10491 // C / C++ fields 10492 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 10493 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 10494 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 10495 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 10496 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 10497 } 10498 10499 // Objective-C instance variables 10500 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 10501 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 10502 if (OL && OR && OL->getDecl() == OR->getDecl()) { 10503 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 10504 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 10505 if (RL && RR && RL->getDecl() == RR->getDecl()) 10506 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 10507 } 10508 } 10509 10510 // C99 6.5.16.1 10511 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 10512 SourceLocation Loc, 10513 QualType CompoundType) { 10514 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 10515 10516 // Verify that LHS is a modifiable lvalue, and emit error if not. 10517 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 10518 return QualType(); 10519 10520 QualType LHSType = LHSExpr->getType(); 10521 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 10522 CompoundType; 10523 // OpenCL v1.2 s6.1.1.1 p2: 10524 // The half data type can only be used to declare a pointer to a buffer that 10525 // contains half values 10526 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 10527 LHSType->isHalfType()) { 10528 Diag(Loc, diag::err_opencl_half_load_store) << 1 10529 << LHSType.getUnqualifiedType(); 10530 return QualType(); 10531 } 10532 10533 AssignConvertType ConvTy; 10534 if (CompoundType.isNull()) { 10535 Expr *RHSCheck = RHS.get(); 10536 10537 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 10538 10539 QualType LHSTy(LHSType); 10540 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 10541 if (RHS.isInvalid()) 10542 return QualType(); 10543 // Special case of NSObject attributes on c-style pointer types. 10544 if (ConvTy == IncompatiblePointer && 10545 ((Context.isObjCNSObjectType(LHSType) && 10546 RHSType->isObjCObjectPointerType()) || 10547 (Context.isObjCNSObjectType(RHSType) && 10548 LHSType->isObjCObjectPointerType()))) 10549 ConvTy = Compatible; 10550 10551 if (ConvTy == Compatible && 10552 LHSType->isObjCObjectType()) 10553 Diag(Loc, diag::err_objc_object_assignment) 10554 << LHSType; 10555 10556 // If the RHS is a unary plus or minus, check to see if they = and + are 10557 // right next to each other. If so, the user may have typo'd "x =+ 4" 10558 // instead of "x += 4". 10559 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 10560 RHSCheck = ICE->getSubExpr(); 10561 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 10562 if ((UO->getOpcode() == UO_Plus || 10563 UO->getOpcode() == UO_Minus) && 10564 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 10565 // Only if the two operators are exactly adjacent. 10566 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 10567 // And there is a space or other character before the subexpr of the 10568 // unary +/-. We don't want to warn on "x=-1". 10569 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 10570 UO->getSubExpr()->getLocStart().isFileID()) { 10571 Diag(Loc, diag::warn_not_compound_assign) 10572 << (UO->getOpcode() == UO_Plus ? "+" : "-") 10573 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 10574 } 10575 } 10576 10577 if (ConvTy == Compatible) { 10578 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 10579 // Warn about retain cycles where a block captures the LHS, but 10580 // not if the LHS is a simple variable into which the block is 10581 // being stored...unless that variable can be captured by reference! 10582 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 10583 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 10584 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 10585 checkRetainCycles(LHSExpr, RHS.get()); 10586 } 10587 10588 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 10589 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 10590 // It is safe to assign a weak reference into a strong variable. 10591 // Although this code can still have problems: 10592 // id x = self.weakProp; 10593 // id y = self.weakProp; 10594 // we do not warn to warn spuriously when 'x' and 'y' are on separate 10595 // paths through the function. This should be revisited if 10596 // -Wrepeated-use-of-weak is made flow-sensitive. 10597 // For ObjCWeak only, we do not warn if the assign is to a non-weak 10598 // variable, which will be valid for the current autorelease scope. 10599 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 10600 RHS.get()->getLocStart())) 10601 getCurFunction()->markSafeWeakUse(RHS.get()); 10602 10603 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 10604 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 10605 } 10606 } 10607 } else { 10608 // Compound assignment "x += y" 10609 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 10610 } 10611 10612 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 10613 RHS.get(), AA_Assigning)) 10614 return QualType(); 10615 10616 CheckForNullPointerDereference(*this, LHSExpr); 10617 10618 // C99 6.5.16p3: The type of an assignment expression is the type of the 10619 // left operand unless the left operand has qualified type, in which case 10620 // it is the unqualified version of the type of the left operand. 10621 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 10622 // is converted to the type of the assignment expression (above). 10623 // C++ 5.17p1: the type of the assignment expression is that of its left 10624 // operand. 10625 return (getLangOpts().CPlusPlus 10626 ? LHSType : LHSType.getUnqualifiedType()); 10627 } 10628 10629 // Only ignore explicit casts to void. 10630 static bool IgnoreCommaOperand(const Expr *E) { 10631 E = E->IgnoreParens(); 10632 10633 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 10634 if (CE->getCastKind() == CK_ToVoid) { 10635 return true; 10636 } 10637 } 10638 10639 return false; 10640 } 10641 10642 // Look for instances where it is likely the comma operator is confused with 10643 // another operator. There is a whitelist of acceptable expressions for the 10644 // left hand side of the comma operator, otherwise emit a warning. 10645 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 10646 // No warnings in macros 10647 if (Loc.isMacroID()) 10648 return; 10649 10650 // Don't warn in template instantiations. 10651 if (inTemplateInstantiation()) 10652 return; 10653 10654 // Scope isn't fine-grained enough to whitelist the specific cases, so 10655 // instead, skip more than needed, then call back into here with the 10656 // CommaVisitor in SemaStmt.cpp. 10657 // The whitelisted locations are the initialization and increment portions 10658 // of a for loop. The additional checks are on the condition of 10659 // if statements, do/while loops, and for loops. 10660 const unsigned ForIncrementFlags = 10661 Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope; 10662 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 10663 const unsigned ScopeFlags = getCurScope()->getFlags(); 10664 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 10665 (ScopeFlags & ForInitFlags) == ForInitFlags) 10666 return; 10667 10668 // If there are multiple comma operators used together, get the RHS of the 10669 // of the comma operator as the LHS. 10670 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 10671 if (BO->getOpcode() != BO_Comma) 10672 break; 10673 LHS = BO->getRHS(); 10674 } 10675 10676 // Only allow some expressions on LHS to not warn. 10677 if (IgnoreCommaOperand(LHS)) 10678 return; 10679 10680 Diag(Loc, diag::warn_comma_operator); 10681 Diag(LHS->getLocStart(), diag::note_cast_to_void) 10682 << LHS->getSourceRange() 10683 << FixItHint::CreateInsertion(LHS->getLocStart(), 10684 LangOpts.CPlusPlus ? "static_cast<void>(" 10685 : "(void)(") 10686 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()), 10687 ")"); 10688 } 10689 10690 // C99 6.5.17 10691 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 10692 SourceLocation Loc) { 10693 LHS = S.CheckPlaceholderExpr(LHS.get()); 10694 RHS = S.CheckPlaceholderExpr(RHS.get()); 10695 if (LHS.isInvalid() || RHS.isInvalid()) 10696 return QualType(); 10697 10698 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 10699 // operands, but not unary promotions. 10700 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 10701 10702 // So we treat the LHS as a ignored value, and in C++ we allow the 10703 // containing site to determine what should be done with the RHS. 10704 LHS = S.IgnoredValueConversions(LHS.get()); 10705 if (LHS.isInvalid()) 10706 return QualType(); 10707 10708 S.DiagnoseUnusedExprResult(LHS.get()); 10709 10710 if (!S.getLangOpts().CPlusPlus) { 10711 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 10712 if (RHS.isInvalid()) 10713 return QualType(); 10714 if (!RHS.get()->getType()->isVoidType()) 10715 S.RequireCompleteType(Loc, RHS.get()->getType(), 10716 diag::err_incomplete_type); 10717 } 10718 10719 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 10720 S.DiagnoseCommaOperator(LHS.get(), Loc); 10721 10722 return RHS.get()->getType(); 10723 } 10724 10725 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 10726 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 10727 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 10728 ExprValueKind &VK, 10729 ExprObjectKind &OK, 10730 SourceLocation OpLoc, 10731 bool IsInc, bool IsPrefix) { 10732 if (Op->isTypeDependent()) 10733 return S.Context.DependentTy; 10734 10735 QualType ResType = Op->getType(); 10736 // Atomic types can be used for increment / decrement where the non-atomic 10737 // versions can, so ignore the _Atomic() specifier for the purpose of 10738 // checking. 10739 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10740 ResType = ResAtomicType->getValueType(); 10741 10742 assert(!ResType.isNull() && "no type for increment/decrement expression"); 10743 10744 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 10745 // Decrement of bool is not allowed. 10746 if (!IsInc) { 10747 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 10748 return QualType(); 10749 } 10750 // Increment of bool sets it to true, but is deprecated. 10751 S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool 10752 : diag::warn_increment_bool) 10753 << Op->getSourceRange(); 10754 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 10755 // Error on enum increments and decrements in C++ mode 10756 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 10757 return QualType(); 10758 } else if (ResType->isRealType()) { 10759 // OK! 10760 } else if (ResType->isPointerType()) { 10761 // C99 6.5.2.4p2, 6.5.6p2 10762 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 10763 return QualType(); 10764 } else if (ResType->isObjCObjectPointerType()) { 10765 // On modern runtimes, ObjC pointer arithmetic is forbidden. 10766 // Otherwise, we just need a complete type. 10767 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 10768 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 10769 return QualType(); 10770 } else if (ResType->isAnyComplexType()) { 10771 // C99 does not support ++/-- on complex types, we allow as an extension. 10772 S.Diag(OpLoc, diag::ext_integer_increment_complex) 10773 << ResType << Op->getSourceRange(); 10774 } else if (ResType->isPlaceholderType()) { 10775 ExprResult PR = S.CheckPlaceholderExpr(Op); 10776 if (PR.isInvalid()) return QualType(); 10777 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 10778 IsInc, IsPrefix); 10779 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 10780 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 10781 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 10782 (ResType->getAs<VectorType>()->getVectorKind() != 10783 VectorType::AltiVecBool)) { 10784 // The z vector extensions allow ++ and -- for non-bool vectors. 10785 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 10786 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 10787 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 10788 } else { 10789 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 10790 << ResType << int(IsInc) << Op->getSourceRange(); 10791 return QualType(); 10792 } 10793 // At this point, we know we have a real, complex or pointer type. 10794 // Now make sure the operand is a modifiable lvalue. 10795 if (CheckForModifiableLvalue(Op, OpLoc, S)) 10796 return QualType(); 10797 // In C++, a prefix increment is the same type as the operand. Otherwise 10798 // (in C or with postfix), the increment is the unqualified type of the 10799 // operand. 10800 if (IsPrefix && S.getLangOpts().CPlusPlus) { 10801 VK = VK_LValue; 10802 OK = Op->getObjectKind(); 10803 return ResType; 10804 } else { 10805 VK = VK_RValue; 10806 return ResType.getUnqualifiedType(); 10807 } 10808 } 10809 10810 10811 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 10812 /// This routine allows us to typecheck complex/recursive expressions 10813 /// where the declaration is needed for type checking. We only need to 10814 /// handle cases when the expression references a function designator 10815 /// or is an lvalue. Here are some examples: 10816 /// - &(x) => x 10817 /// - &*****f => f for f a function designator. 10818 /// - &s.xx => s 10819 /// - &s.zz[1].yy -> s, if zz is an array 10820 /// - *(x + 1) -> x, if x is an array 10821 /// - &"123"[2] -> 0 10822 /// - & __real__ x -> x 10823 static ValueDecl *getPrimaryDecl(Expr *E) { 10824 switch (E->getStmtClass()) { 10825 case Stmt::DeclRefExprClass: 10826 return cast<DeclRefExpr>(E)->getDecl(); 10827 case Stmt::MemberExprClass: 10828 // If this is an arrow operator, the address is an offset from 10829 // the base's value, so the object the base refers to is 10830 // irrelevant. 10831 if (cast<MemberExpr>(E)->isArrow()) 10832 return nullptr; 10833 // Otherwise, the expression refers to a part of the base 10834 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 10835 case Stmt::ArraySubscriptExprClass: { 10836 // FIXME: This code shouldn't be necessary! We should catch the implicit 10837 // promotion of register arrays earlier. 10838 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 10839 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 10840 if (ICE->getSubExpr()->getType()->isArrayType()) 10841 return getPrimaryDecl(ICE->getSubExpr()); 10842 } 10843 return nullptr; 10844 } 10845 case Stmt::UnaryOperatorClass: { 10846 UnaryOperator *UO = cast<UnaryOperator>(E); 10847 10848 switch(UO->getOpcode()) { 10849 case UO_Real: 10850 case UO_Imag: 10851 case UO_Extension: 10852 return getPrimaryDecl(UO->getSubExpr()); 10853 default: 10854 return nullptr; 10855 } 10856 } 10857 case Stmt::ParenExprClass: 10858 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 10859 case Stmt::ImplicitCastExprClass: 10860 // If the result of an implicit cast is an l-value, we care about 10861 // the sub-expression; otherwise, the result here doesn't matter. 10862 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 10863 default: 10864 return nullptr; 10865 } 10866 } 10867 10868 namespace { 10869 enum { 10870 AO_Bit_Field = 0, 10871 AO_Vector_Element = 1, 10872 AO_Property_Expansion = 2, 10873 AO_Register_Variable = 3, 10874 AO_No_Error = 4 10875 }; 10876 } 10877 /// \brief Diagnose invalid operand for address of operations. 10878 /// 10879 /// \param Type The type of operand which cannot have its address taken. 10880 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 10881 Expr *E, unsigned Type) { 10882 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 10883 } 10884 10885 /// CheckAddressOfOperand - The operand of & must be either a function 10886 /// designator or an lvalue designating an object. If it is an lvalue, the 10887 /// object cannot be declared with storage class register or be a bit field. 10888 /// Note: The usual conversions are *not* applied to the operand of the & 10889 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 10890 /// In C++, the operand might be an overloaded function name, in which case 10891 /// we allow the '&' but retain the overloaded-function type. 10892 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 10893 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 10894 if (PTy->getKind() == BuiltinType::Overload) { 10895 Expr *E = OrigOp.get()->IgnoreParens(); 10896 if (!isa<OverloadExpr>(E)) { 10897 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 10898 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 10899 << OrigOp.get()->getSourceRange(); 10900 return QualType(); 10901 } 10902 10903 OverloadExpr *Ovl = cast<OverloadExpr>(E); 10904 if (isa<UnresolvedMemberExpr>(Ovl)) 10905 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 10906 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10907 << OrigOp.get()->getSourceRange(); 10908 return QualType(); 10909 } 10910 10911 return Context.OverloadTy; 10912 } 10913 10914 if (PTy->getKind() == BuiltinType::UnknownAny) 10915 return Context.UnknownAnyTy; 10916 10917 if (PTy->getKind() == BuiltinType::BoundMember) { 10918 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10919 << OrigOp.get()->getSourceRange(); 10920 return QualType(); 10921 } 10922 10923 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 10924 if (OrigOp.isInvalid()) return QualType(); 10925 } 10926 10927 if (OrigOp.get()->isTypeDependent()) 10928 return Context.DependentTy; 10929 10930 assert(!OrigOp.get()->getType()->isPlaceholderType()); 10931 10932 // Make sure to ignore parentheses in subsequent checks 10933 Expr *op = OrigOp.get()->IgnoreParens(); 10934 10935 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 10936 if (LangOpts.OpenCL && op->getType()->isFunctionType()) { 10937 Diag(op->getExprLoc(), diag::err_opencl_taking_function_address); 10938 return QualType(); 10939 } 10940 10941 if (getLangOpts().C99) { 10942 // Implement C99-only parts of addressof rules. 10943 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 10944 if (uOp->getOpcode() == UO_Deref) 10945 // Per C99 6.5.3.2, the address of a deref always returns a valid result 10946 // (assuming the deref expression is valid). 10947 return uOp->getSubExpr()->getType(); 10948 } 10949 // Technically, there should be a check for array subscript 10950 // expressions here, but the result of one is always an lvalue anyway. 10951 } 10952 ValueDecl *dcl = getPrimaryDecl(op); 10953 10954 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 10955 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 10956 op->getLocStart())) 10957 return QualType(); 10958 10959 Expr::LValueClassification lval = op->ClassifyLValue(Context); 10960 unsigned AddressOfError = AO_No_Error; 10961 10962 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 10963 bool sfinae = (bool)isSFINAEContext(); 10964 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 10965 : diag::ext_typecheck_addrof_temporary) 10966 << op->getType() << op->getSourceRange(); 10967 if (sfinae) 10968 return QualType(); 10969 // Materialize the temporary as an lvalue so that we can take its address. 10970 OrigOp = op = 10971 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 10972 } else if (isa<ObjCSelectorExpr>(op)) { 10973 return Context.getPointerType(op->getType()); 10974 } else if (lval == Expr::LV_MemberFunction) { 10975 // If it's an instance method, make a member pointer. 10976 // The expression must have exactly the form &A::foo. 10977 10978 // If the underlying expression isn't a decl ref, give up. 10979 if (!isa<DeclRefExpr>(op)) { 10980 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10981 << OrigOp.get()->getSourceRange(); 10982 return QualType(); 10983 } 10984 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 10985 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 10986 10987 // The id-expression was parenthesized. 10988 if (OrigOp.get() != DRE) { 10989 Diag(OpLoc, diag::err_parens_pointer_member_function) 10990 << OrigOp.get()->getSourceRange(); 10991 10992 // The method was named without a qualifier. 10993 } else if (!DRE->getQualifier()) { 10994 if (MD->getParent()->getName().empty()) 10995 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 10996 << op->getSourceRange(); 10997 else { 10998 SmallString<32> Str; 10999 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 11000 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 11001 << op->getSourceRange() 11002 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 11003 } 11004 } 11005 11006 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 11007 if (isa<CXXDestructorDecl>(MD)) 11008 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 11009 11010 QualType MPTy = Context.getMemberPointerType( 11011 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 11012 // Under the MS ABI, lock down the inheritance model now. 11013 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11014 (void)isCompleteType(OpLoc, MPTy); 11015 return MPTy; 11016 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 11017 // C99 6.5.3.2p1 11018 // The operand must be either an l-value or a function designator 11019 if (!op->getType()->isFunctionType()) { 11020 // Use a special diagnostic for loads from property references. 11021 if (isa<PseudoObjectExpr>(op)) { 11022 AddressOfError = AO_Property_Expansion; 11023 } else { 11024 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 11025 << op->getType() << op->getSourceRange(); 11026 return QualType(); 11027 } 11028 } 11029 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 11030 // The operand cannot be a bit-field 11031 AddressOfError = AO_Bit_Field; 11032 } else if (op->getObjectKind() == OK_VectorComponent) { 11033 // The operand cannot be an element of a vector 11034 AddressOfError = AO_Vector_Element; 11035 } else if (dcl) { // C99 6.5.3.2p1 11036 // We have an lvalue with a decl. Make sure the decl is not declared 11037 // with the register storage-class specifier. 11038 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 11039 // in C++ it is not error to take address of a register 11040 // variable (c++03 7.1.1P3) 11041 if (vd->getStorageClass() == SC_Register && 11042 !getLangOpts().CPlusPlus) { 11043 AddressOfError = AO_Register_Variable; 11044 } 11045 } else if (isa<MSPropertyDecl>(dcl)) { 11046 AddressOfError = AO_Property_Expansion; 11047 } else if (isa<FunctionTemplateDecl>(dcl)) { 11048 return Context.OverloadTy; 11049 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 11050 // Okay: we can take the address of a field. 11051 // Could be a pointer to member, though, if there is an explicit 11052 // scope qualifier for the class. 11053 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 11054 DeclContext *Ctx = dcl->getDeclContext(); 11055 if (Ctx && Ctx->isRecord()) { 11056 if (dcl->getType()->isReferenceType()) { 11057 Diag(OpLoc, 11058 diag::err_cannot_form_pointer_to_member_of_reference_type) 11059 << dcl->getDeclName() << dcl->getType(); 11060 return QualType(); 11061 } 11062 11063 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 11064 Ctx = Ctx->getParent(); 11065 11066 QualType MPTy = Context.getMemberPointerType( 11067 op->getType(), 11068 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 11069 // Under the MS ABI, lock down the inheritance model now. 11070 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11071 (void)isCompleteType(OpLoc, MPTy); 11072 return MPTy; 11073 } 11074 } 11075 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 11076 !isa<BindingDecl>(dcl)) 11077 llvm_unreachable("Unknown/unexpected decl type"); 11078 } 11079 11080 if (AddressOfError != AO_No_Error) { 11081 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 11082 return QualType(); 11083 } 11084 11085 if (lval == Expr::LV_IncompleteVoidType) { 11086 // Taking the address of a void variable is technically illegal, but we 11087 // allow it in cases which are otherwise valid. 11088 // Example: "extern void x; void* y = &x;". 11089 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 11090 } 11091 11092 // If the operand has type "type", the result has type "pointer to type". 11093 if (op->getType()->isObjCObjectType()) 11094 return Context.getObjCObjectPointerType(op->getType()); 11095 11096 CheckAddressOfPackedMember(op); 11097 11098 return Context.getPointerType(op->getType()); 11099 } 11100 11101 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 11102 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 11103 if (!DRE) 11104 return; 11105 const Decl *D = DRE->getDecl(); 11106 if (!D) 11107 return; 11108 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 11109 if (!Param) 11110 return; 11111 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 11112 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 11113 return; 11114 if (FunctionScopeInfo *FD = S.getCurFunction()) 11115 if (!FD->ModifiedNonNullParams.count(Param)) 11116 FD->ModifiedNonNullParams.insert(Param); 11117 } 11118 11119 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 11120 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 11121 SourceLocation OpLoc) { 11122 if (Op->isTypeDependent()) 11123 return S.Context.DependentTy; 11124 11125 ExprResult ConvResult = S.UsualUnaryConversions(Op); 11126 if (ConvResult.isInvalid()) 11127 return QualType(); 11128 Op = ConvResult.get(); 11129 QualType OpTy = Op->getType(); 11130 QualType Result; 11131 11132 if (isa<CXXReinterpretCastExpr>(Op)) { 11133 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 11134 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 11135 Op->getSourceRange()); 11136 } 11137 11138 if (const PointerType *PT = OpTy->getAs<PointerType>()) 11139 { 11140 Result = PT->getPointeeType(); 11141 } 11142 else if (const ObjCObjectPointerType *OPT = 11143 OpTy->getAs<ObjCObjectPointerType>()) 11144 Result = OPT->getPointeeType(); 11145 else { 11146 ExprResult PR = S.CheckPlaceholderExpr(Op); 11147 if (PR.isInvalid()) return QualType(); 11148 if (PR.get() != Op) 11149 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 11150 } 11151 11152 if (Result.isNull()) { 11153 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 11154 << OpTy << Op->getSourceRange(); 11155 return QualType(); 11156 } 11157 11158 // Note that per both C89 and C99, indirection is always legal, even if Result 11159 // is an incomplete type or void. It would be possible to warn about 11160 // dereferencing a void pointer, but it's completely well-defined, and such a 11161 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 11162 // for pointers to 'void' but is fine for any other pointer type: 11163 // 11164 // C++ [expr.unary.op]p1: 11165 // [...] the expression to which [the unary * operator] is applied shall 11166 // be a pointer to an object type, or a pointer to a function type 11167 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 11168 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 11169 << OpTy << Op->getSourceRange(); 11170 11171 // Dereferences are usually l-values... 11172 VK = VK_LValue; 11173 11174 // ...except that certain expressions are never l-values in C. 11175 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 11176 VK = VK_RValue; 11177 11178 return Result; 11179 } 11180 11181 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 11182 BinaryOperatorKind Opc; 11183 switch (Kind) { 11184 default: llvm_unreachable("Unknown binop!"); 11185 case tok::periodstar: Opc = BO_PtrMemD; break; 11186 case tok::arrowstar: Opc = BO_PtrMemI; break; 11187 case tok::star: Opc = BO_Mul; break; 11188 case tok::slash: Opc = BO_Div; break; 11189 case tok::percent: Opc = BO_Rem; break; 11190 case tok::plus: Opc = BO_Add; break; 11191 case tok::minus: Opc = BO_Sub; break; 11192 case tok::lessless: Opc = BO_Shl; break; 11193 case tok::greatergreater: Opc = BO_Shr; break; 11194 case tok::lessequal: Opc = BO_LE; break; 11195 case tok::less: Opc = BO_LT; break; 11196 case tok::greaterequal: Opc = BO_GE; break; 11197 case tok::greater: Opc = BO_GT; break; 11198 case tok::exclaimequal: Opc = BO_NE; break; 11199 case tok::equalequal: Opc = BO_EQ; break; 11200 case tok::amp: Opc = BO_And; break; 11201 case tok::caret: Opc = BO_Xor; break; 11202 case tok::pipe: Opc = BO_Or; break; 11203 case tok::ampamp: Opc = BO_LAnd; break; 11204 case tok::pipepipe: Opc = BO_LOr; break; 11205 case tok::equal: Opc = BO_Assign; break; 11206 case tok::starequal: Opc = BO_MulAssign; break; 11207 case tok::slashequal: Opc = BO_DivAssign; break; 11208 case tok::percentequal: Opc = BO_RemAssign; break; 11209 case tok::plusequal: Opc = BO_AddAssign; break; 11210 case tok::minusequal: Opc = BO_SubAssign; break; 11211 case tok::lesslessequal: Opc = BO_ShlAssign; break; 11212 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 11213 case tok::ampequal: Opc = BO_AndAssign; break; 11214 case tok::caretequal: Opc = BO_XorAssign; break; 11215 case tok::pipeequal: Opc = BO_OrAssign; break; 11216 case tok::comma: Opc = BO_Comma; break; 11217 } 11218 return Opc; 11219 } 11220 11221 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 11222 tok::TokenKind Kind) { 11223 UnaryOperatorKind Opc; 11224 switch (Kind) { 11225 default: llvm_unreachable("Unknown unary op!"); 11226 case tok::plusplus: Opc = UO_PreInc; break; 11227 case tok::minusminus: Opc = UO_PreDec; break; 11228 case tok::amp: Opc = UO_AddrOf; break; 11229 case tok::star: Opc = UO_Deref; break; 11230 case tok::plus: Opc = UO_Plus; break; 11231 case tok::minus: Opc = UO_Minus; break; 11232 case tok::tilde: Opc = UO_Not; break; 11233 case tok::exclaim: Opc = UO_LNot; break; 11234 case tok::kw___real: Opc = UO_Real; break; 11235 case tok::kw___imag: Opc = UO_Imag; break; 11236 case tok::kw___extension__: Opc = UO_Extension; break; 11237 } 11238 return Opc; 11239 } 11240 11241 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 11242 /// This warning is only emitted for builtin assignment operations. It is also 11243 /// suppressed in the event of macro expansions. 11244 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 11245 SourceLocation OpLoc) { 11246 if (S.inTemplateInstantiation()) 11247 return; 11248 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 11249 return; 11250 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 11251 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 11252 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 11253 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 11254 if (!LHSDeclRef || !RHSDeclRef || 11255 LHSDeclRef->getLocation().isMacroID() || 11256 RHSDeclRef->getLocation().isMacroID()) 11257 return; 11258 const ValueDecl *LHSDecl = 11259 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 11260 const ValueDecl *RHSDecl = 11261 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 11262 if (LHSDecl != RHSDecl) 11263 return; 11264 if (LHSDecl->getType().isVolatileQualified()) 11265 return; 11266 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 11267 if (RefTy->getPointeeType().isVolatileQualified()) 11268 return; 11269 11270 S.Diag(OpLoc, diag::warn_self_assignment) 11271 << LHSDeclRef->getType() 11272 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 11273 } 11274 11275 /// Check if a bitwise-& is performed on an Objective-C pointer. This 11276 /// is usually indicative of introspection within the Objective-C pointer. 11277 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 11278 SourceLocation OpLoc) { 11279 if (!S.getLangOpts().ObjC1) 11280 return; 11281 11282 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 11283 const Expr *LHS = L.get(); 11284 const Expr *RHS = R.get(); 11285 11286 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 11287 ObjCPointerExpr = LHS; 11288 OtherExpr = RHS; 11289 } 11290 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 11291 ObjCPointerExpr = RHS; 11292 OtherExpr = LHS; 11293 } 11294 11295 // This warning is deliberately made very specific to reduce false 11296 // positives with logic that uses '&' for hashing. This logic mainly 11297 // looks for code trying to introspect into tagged pointers, which 11298 // code should generally never do. 11299 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 11300 unsigned Diag = diag::warn_objc_pointer_masking; 11301 // Determine if we are introspecting the result of performSelectorXXX. 11302 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 11303 // Special case messages to -performSelector and friends, which 11304 // can return non-pointer values boxed in a pointer value. 11305 // Some clients may wish to silence warnings in this subcase. 11306 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 11307 Selector S = ME->getSelector(); 11308 StringRef SelArg0 = S.getNameForSlot(0); 11309 if (SelArg0.startswith("performSelector")) 11310 Diag = diag::warn_objc_pointer_masking_performSelector; 11311 } 11312 11313 S.Diag(OpLoc, Diag) 11314 << ObjCPointerExpr->getSourceRange(); 11315 } 11316 } 11317 11318 static NamedDecl *getDeclFromExpr(Expr *E) { 11319 if (!E) 11320 return nullptr; 11321 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 11322 return DRE->getDecl(); 11323 if (auto *ME = dyn_cast<MemberExpr>(E)) 11324 return ME->getMemberDecl(); 11325 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 11326 return IRE->getDecl(); 11327 return nullptr; 11328 } 11329 11330 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 11331 /// operator @p Opc at location @c TokLoc. This routine only supports 11332 /// built-in operations; ActOnBinOp handles overloaded operators. 11333 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 11334 BinaryOperatorKind Opc, 11335 Expr *LHSExpr, Expr *RHSExpr) { 11336 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 11337 // The syntax only allows initializer lists on the RHS of assignment, 11338 // so we don't need to worry about accepting invalid code for 11339 // non-assignment operators. 11340 // C++11 5.17p9: 11341 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 11342 // of x = {} is x = T(). 11343 InitializationKind Kind = 11344 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 11345 InitializedEntity Entity = 11346 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 11347 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 11348 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 11349 if (Init.isInvalid()) 11350 return Init; 11351 RHSExpr = Init.get(); 11352 } 11353 11354 ExprResult LHS = LHSExpr, RHS = RHSExpr; 11355 QualType ResultTy; // Result type of the binary operator. 11356 // The following two variables are used for compound assignment operators 11357 QualType CompLHSTy; // Type of LHS after promotions for computation 11358 QualType CompResultTy; // Type of computation result 11359 ExprValueKind VK = VK_RValue; 11360 ExprObjectKind OK = OK_Ordinary; 11361 11362 if (!getLangOpts().CPlusPlus) { 11363 // C cannot handle TypoExpr nodes on either side of a binop because it 11364 // doesn't handle dependent types properly, so make sure any TypoExprs have 11365 // been dealt with before checking the operands. 11366 LHS = CorrectDelayedTyposInExpr(LHSExpr); 11367 RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) { 11368 if (Opc != BO_Assign) 11369 return ExprResult(E); 11370 // Avoid correcting the RHS to the same Expr as the LHS. 11371 Decl *D = getDeclFromExpr(E); 11372 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 11373 }); 11374 if (!LHS.isUsable() || !RHS.isUsable()) 11375 return ExprError(); 11376 } 11377 11378 if (getLangOpts().OpenCL) { 11379 QualType LHSTy = LHSExpr->getType(); 11380 QualType RHSTy = RHSExpr->getType(); 11381 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 11382 // the ATOMIC_VAR_INIT macro. 11383 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 11384 SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 11385 if (BO_Assign == Opc) 11386 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 11387 else 11388 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 11389 return ExprError(); 11390 } 11391 11392 // OpenCL special types - image, sampler, pipe, and blocks are to be used 11393 // only with a builtin functions and therefore should be disallowed here. 11394 if (LHSTy->isImageType() || RHSTy->isImageType() || 11395 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 11396 LHSTy->isPipeType() || RHSTy->isPipeType() || 11397 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 11398 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 11399 return ExprError(); 11400 } 11401 } 11402 11403 switch (Opc) { 11404 case BO_Assign: 11405 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 11406 if (getLangOpts().CPlusPlus && 11407 LHS.get()->getObjectKind() != OK_ObjCProperty) { 11408 VK = LHS.get()->getValueKind(); 11409 OK = LHS.get()->getObjectKind(); 11410 } 11411 if (!ResultTy.isNull()) { 11412 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 11413 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 11414 } 11415 RecordModifiableNonNullParam(*this, LHS.get()); 11416 break; 11417 case BO_PtrMemD: 11418 case BO_PtrMemI: 11419 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 11420 Opc == BO_PtrMemI); 11421 break; 11422 case BO_Mul: 11423 case BO_Div: 11424 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 11425 Opc == BO_Div); 11426 break; 11427 case BO_Rem: 11428 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 11429 break; 11430 case BO_Add: 11431 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 11432 break; 11433 case BO_Sub: 11434 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 11435 break; 11436 case BO_Shl: 11437 case BO_Shr: 11438 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 11439 break; 11440 case BO_LE: 11441 case BO_LT: 11442 case BO_GE: 11443 case BO_GT: 11444 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 11445 break; 11446 case BO_EQ: 11447 case BO_NE: 11448 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 11449 break; 11450 case BO_And: 11451 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 11452 case BO_Xor: 11453 case BO_Or: 11454 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 11455 break; 11456 case BO_LAnd: 11457 case BO_LOr: 11458 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 11459 break; 11460 case BO_MulAssign: 11461 case BO_DivAssign: 11462 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 11463 Opc == BO_DivAssign); 11464 CompLHSTy = CompResultTy; 11465 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11466 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11467 break; 11468 case BO_RemAssign: 11469 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 11470 CompLHSTy = CompResultTy; 11471 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11472 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11473 break; 11474 case BO_AddAssign: 11475 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 11476 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11477 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11478 break; 11479 case BO_SubAssign: 11480 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 11481 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11482 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11483 break; 11484 case BO_ShlAssign: 11485 case BO_ShrAssign: 11486 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 11487 CompLHSTy = CompResultTy; 11488 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11489 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11490 break; 11491 case BO_AndAssign: 11492 case BO_OrAssign: // fallthrough 11493 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 11494 case BO_XorAssign: 11495 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 11496 CompLHSTy = CompResultTy; 11497 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11498 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11499 break; 11500 case BO_Comma: 11501 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 11502 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 11503 VK = RHS.get()->getValueKind(); 11504 OK = RHS.get()->getObjectKind(); 11505 } 11506 break; 11507 } 11508 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 11509 return ExprError(); 11510 11511 // Check for array bounds violations for both sides of the BinaryOperator 11512 CheckArrayAccess(LHS.get()); 11513 CheckArrayAccess(RHS.get()); 11514 11515 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 11516 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 11517 &Context.Idents.get("object_setClass"), 11518 SourceLocation(), LookupOrdinaryName); 11519 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 11520 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd()); 11521 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 11522 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 11523 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 11524 FixItHint::CreateInsertion(RHSLocEnd, ")"); 11525 } 11526 else 11527 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 11528 } 11529 else if (const ObjCIvarRefExpr *OIRE = 11530 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 11531 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 11532 11533 if (CompResultTy.isNull()) 11534 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 11535 OK, OpLoc, FPFeatures); 11536 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 11537 OK_ObjCProperty) { 11538 VK = VK_LValue; 11539 OK = LHS.get()->getObjectKind(); 11540 } 11541 return new (Context) CompoundAssignOperator( 11542 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 11543 OpLoc, FPFeatures); 11544 } 11545 11546 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 11547 /// operators are mixed in a way that suggests that the programmer forgot that 11548 /// comparison operators have higher precedence. The most typical example of 11549 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 11550 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 11551 SourceLocation OpLoc, Expr *LHSExpr, 11552 Expr *RHSExpr) { 11553 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 11554 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 11555 11556 // Check that one of the sides is a comparison operator and the other isn't. 11557 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 11558 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 11559 if (isLeftComp == isRightComp) 11560 return; 11561 11562 // Bitwise operations are sometimes used as eager logical ops. 11563 // Don't diagnose this. 11564 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 11565 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 11566 if (isLeftBitwise || isRightBitwise) 11567 return; 11568 11569 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 11570 OpLoc) 11571 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 11572 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 11573 SourceRange ParensRange = isLeftComp ? 11574 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 11575 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd()); 11576 11577 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 11578 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 11579 SuggestParentheses(Self, OpLoc, 11580 Self.PDiag(diag::note_precedence_silence) << OpStr, 11581 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 11582 SuggestParentheses(Self, OpLoc, 11583 Self.PDiag(diag::note_precedence_bitwise_first) 11584 << BinaryOperator::getOpcodeStr(Opc), 11585 ParensRange); 11586 } 11587 11588 /// \brief It accepts a '&&' expr that is inside a '||' one. 11589 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 11590 /// in parentheses. 11591 static void 11592 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 11593 BinaryOperator *Bop) { 11594 assert(Bop->getOpcode() == BO_LAnd); 11595 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 11596 << Bop->getSourceRange() << OpLoc; 11597 SuggestParentheses(Self, Bop->getOperatorLoc(), 11598 Self.PDiag(diag::note_precedence_silence) 11599 << Bop->getOpcodeStr(), 11600 Bop->getSourceRange()); 11601 } 11602 11603 /// \brief Returns true if the given expression can be evaluated as a constant 11604 /// 'true'. 11605 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 11606 bool Res; 11607 return !E->isValueDependent() && 11608 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 11609 } 11610 11611 /// \brief Returns true if the given expression can be evaluated as a constant 11612 /// 'false'. 11613 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 11614 bool Res; 11615 return !E->isValueDependent() && 11616 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 11617 } 11618 11619 /// \brief Look for '&&' in the left hand of a '||' expr. 11620 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 11621 Expr *LHSExpr, Expr *RHSExpr) { 11622 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 11623 if (Bop->getOpcode() == BO_LAnd) { 11624 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 11625 if (EvaluatesAsFalse(S, RHSExpr)) 11626 return; 11627 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 11628 if (!EvaluatesAsTrue(S, Bop->getLHS())) 11629 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11630 } else if (Bop->getOpcode() == BO_LOr) { 11631 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 11632 // If it's "a || b && 1 || c" we didn't warn earlier for 11633 // "a || b && 1", but warn now. 11634 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 11635 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 11636 } 11637 } 11638 } 11639 } 11640 11641 /// \brief Look for '&&' in the right hand of a '||' expr. 11642 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 11643 Expr *LHSExpr, Expr *RHSExpr) { 11644 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 11645 if (Bop->getOpcode() == BO_LAnd) { 11646 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 11647 if (EvaluatesAsFalse(S, LHSExpr)) 11648 return; 11649 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 11650 if (!EvaluatesAsTrue(S, Bop->getRHS())) 11651 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11652 } 11653 } 11654 } 11655 11656 /// \brief Look for bitwise op in the left or right hand of a bitwise op with 11657 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 11658 /// the '&' expression in parentheses. 11659 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 11660 SourceLocation OpLoc, Expr *SubExpr) { 11661 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11662 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 11663 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 11664 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 11665 << Bop->getSourceRange() << OpLoc; 11666 SuggestParentheses(S, Bop->getOperatorLoc(), 11667 S.PDiag(diag::note_precedence_silence) 11668 << Bop->getOpcodeStr(), 11669 Bop->getSourceRange()); 11670 } 11671 } 11672 } 11673 11674 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 11675 Expr *SubExpr, StringRef Shift) { 11676 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11677 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 11678 StringRef Op = Bop->getOpcodeStr(); 11679 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 11680 << Bop->getSourceRange() << OpLoc << Shift << Op; 11681 SuggestParentheses(S, Bop->getOperatorLoc(), 11682 S.PDiag(diag::note_precedence_silence) << Op, 11683 Bop->getSourceRange()); 11684 } 11685 } 11686 } 11687 11688 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 11689 Expr *LHSExpr, Expr *RHSExpr) { 11690 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 11691 if (!OCE) 11692 return; 11693 11694 FunctionDecl *FD = OCE->getDirectCallee(); 11695 if (!FD || !FD->isOverloadedOperator()) 11696 return; 11697 11698 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 11699 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 11700 return; 11701 11702 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 11703 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 11704 << (Kind == OO_LessLess); 11705 SuggestParentheses(S, OCE->getOperatorLoc(), 11706 S.PDiag(diag::note_precedence_silence) 11707 << (Kind == OO_LessLess ? "<<" : ">>"), 11708 OCE->getSourceRange()); 11709 SuggestParentheses(S, OpLoc, 11710 S.PDiag(diag::note_evaluate_comparison_first), 11711 SourceRange(OCE->getArg(1)->getLocStart(), 11712 RHSExpr->getLocEnd())); 11713 } 11714 11715 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 11716 /// precedence. 11717 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 11718 SourceLocation OpLoc, Expr *LHSExpr, 11719 Expr *RHSExpr){ 11720 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 11721 if (BinaryOperator::isBitwiseOp(Opc)) 11722 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 11723 11724 // Diagnose "arg1 & arg2 | arg3" 11725 if ((Opc == BO_Or || Opc == BO_Xor) && 11726 !OpLoc.isMacroID()/* Don't warn in macros. */) { 11727 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 11728 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 11729 } 11730 11731 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 11732 // We don't warn for 'assert(a || b && "bad")' since this is safe. 11733 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 11734 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 11735 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 11736 } 11737 11738 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 11739 || Opc == BO_Shr) { 11740 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 11741 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 11742 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 11743 } 11744 11745 // Warn on overloaded shift operators and comparisons, such as: 11746 // cout << 5 == 4; 11747 if (BinaryOperator::isComparisonOp(Opc)) 11748 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 11749 } 11750 11751 // Binary Operators. 'Tok' is the token for the operator. 11752 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 11753 tok::TokenKind Kind, 11754 Expr *LHSExpr, Expr *RHSExpr) { 11755 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 11756 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 11757 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 11758 11759 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 11760 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 11761 11762 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 11763 } 11764 11765 /// Build an overloaded binary operator expression in the given scope. 11766 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 11767 BinaryOperatorKind Opc, 11768 Expr *LHS, Expr *RHS) { 11769 // Find all of the overloaded operators visible from this 11770 // point. We perform both an operator-name lookup from the local 11771 // scope and an argument-dependent lookup based on the types of 11772 // the arguments. 11773 UnresolvedSet<16> Functions; 11774 OverloadedOperatorKind OverOp 11775 = BinaryOperator::getOverloadedOperator(Opc); 11776 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 11777 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 11778 RHS->getType(), Functions); 11779 11780 // Build the (potentially-overloaded, potentially-dependent) 11781 // binary operation. 11782 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 11783 } 11784 11785 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 11786 BinaryOperatorKind Opc, 11787 Expr *LHSExpr, Expr *RHSExpr) { 11788 // We want to end up calling one of checkPseudoObjectAssignment 11789 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 11790 // both expressions are overloadable or either is type-dependent), 11791 // or CreateBuiltinBinOp (in any other case). We also want to get 11792 // any placeholder types out of the way. 11793 11794 // Handle pseudo-objects in the LHS. 11795 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 11796 // Assignments with a pseudo-object l-value need special analysis. 11797 if (pty->getKind() == BuiltinType::PseudoObject && 11798 BinaryOperator::isAssignmentOp(Opc)) 11799 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 11800 11801 // Don't resolve overloads if the other type is overloadable. 11802 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 11803 // We can't actually test that if we still have a placeholder, 11804 // though. Fortunately, none of the exceptions we see in that 11805 // code below are valid when the LHS is an overload set. Note 11806 // that an overload set can be dependently-typed, but it never 11807 // instantiates to having an overloadable type. 11808 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 11809 if (resolvedRHS.isInvalid()) return ExprError(); 11810 RHSExpr = resolvedRHS.get(); 11811 11812 if (RHSExpr->isTypeDependent() || 11813 RHSExpr->getType()->isOverloadableType()) 11814 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11815 } 11816 11817 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 11818 if (LHS.isInvalid()) return ExprError(); 11819 LHSExpr = LHS.get(); 11820 } 11821 11822 // Handle pseudo-objects in the RHS. 11823 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 11824 // An overload in the RHS can potentially be resolved by the type 11825 // being assigned to. 11826 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 11827 if (getLangOpts().CPlusPlus && 11828 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 11829 LHSExpr->getType()->isOverloadableType())) 11830 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11831 11832 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 11833 } 11834 11835 // Don't resolve overloads if the other type is overloadable. 11836 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 11837 LHSExpr->getType()->isOverloadableType()) 11838 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11839 11840 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 11841 if (!resolvedRHS.isUsable()) return ExprError(); 11842 RHSExpr = resolvedRHS.get(); 11843 } 11844 11845 if (getLangOpts().CPlusPlus) { 11846 // If either expression is type-dependent, always build an 11847 // overloaded op. 11848 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 11849 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11850 11851 // Otherwise, build an overloaded op if either expression has an 11852 // overloadable type. 11853 if (LHSExpr->getType()->isOverloadableType() || 11854 RHSExpr->getType()->isOverloadableType()) 11855 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11856 } 11857 11858 // Build a built-in binary operation. 11859 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 11860 } 11861 11862 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 11863 UnaryOperatorKind Opc, 11864 Expr *InputExpr) { 11865 ExprResult Input = InputExpr; 11866 ExprValueKind VK = VK_RValue; 11867 ExprObjectKind OK = OK_Ordinary; 11868 QualType resultType; 11869 if (getLangOpts().OpenCL) { 11870 QualType Ty = InputExpr->getType(); 11871 // The only legal unary operation for atomics is '&'. 11872 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 11873 // OpenCL special types - image, sampler, pipe, and blocks are to be used 11874 // only with a builtin functions and therefore should be disallowed here. 11875 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 11876 || Ty->isBlockPointerType())) { 11877 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11878 << InputExpr->getType() 11879 << Input.get()->getSourceRange()); 11880 } 11881 } 11882 switch (Opc) { 11883 case UO_PreInc: 11884 case UO_PreDec: 11885 case UO_PostInc: 11886 case UO_PostDec: 11887 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 11888 OpLoc, 11889 Opc == UO_PreInc || 11890 Opc == UO_PostInc, 11891 Opc == UO_PreInc || 11892 Opc == UO_PreDec); 11893 break; 11894 case UO_AddrOf: 11895 resultType = CheckAddressOfOperand(Input, OpLoc); 11896 RecordModifiableNonNullParam(*this, InputExpr); 11897 break; 11898 case UO_Deref: { 11899 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 11900 if (Input.isInvalid()) return ExprError(); 11901 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 11902 break; 11903 } 11904 case UO_Plus: 11905 case UO_Minus: 11906 Input = UsualUnaryConversions(Input.get()); 11907 if (Input.isInvalid()) return ExprError(); 11908 resultType = Input.get()->getType(); 11909 if (resultType->isDependentType()) 11910 break; 11911 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 11912 break; 11913 else if (resultType->isVectorType() && 11914 // The z vector extensions don't allow + or - with bool vectors. 11915 (!Context.getLangOpts().ZVector || 11916 resultType->getAs<VectorType>()->getVectorKind() != 11917 VectorType::AltiVecBool)) 11918 break; 11919 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 11920 Opc == UO_Plus && 11921 resultType->isPointerType()) 11922 break; 11923 11924 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11925 << resultType << Input.get()->getSourceRange()); 11926 11927 case UO_Not: // bitwise complement 11928 Input = UsualUnaryConversions(Input.get()); 11929 if (Input.isInvalid()) 11930 return ExprError(); 11931 resultType = Input.get()->getType(); 11932 if (resultType->isDependentType()) 11933 break; 11934 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 11935 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 11936 // C99 does not support '~' for complex conjugation. 11937 Diag(OpLoc, diag::ext_integer_complement_complex) 11938 << resultType << Input.get()->getSourceRange(); 11939 else if (resultType->hasIntegerRepresentation()) 11940 break; 11941 else if (resultType->isExtVectorType()) { 11942 if (Context.getLangOpts().OpenCL) { 11943 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 11944 // on vector float types. 11945 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 11946 if (!T->isIntegerType()) 11947 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11948 << resultType << Input.get()->getSourceRange()); 11949 } 11950 break; 11951 } else { 11952 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11953 << resultType << Input.get()->getSourceRange()); 11954 } 11955 break; 11956 11957 case UO_LNot: // logical negation 11958 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 11959 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 11960 if (Input.isInvalid()) return ExprError(); 11961 resultType = Input.get()->getType(); 11962 11963 // Though we still have to promote half FP to float... 11964 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 11965 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 11966 resultType = Context.FloatTy; 11967 } 11968 11969 if (resultType->isDependentType()) 11970 break; 11971 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 11972 // C99 6.5.3.3p1: ok, fallthrough; 11973 if (Context.getLangOpts().CPlusPlus) { 11974 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 11975 // operand contextually converted to bool. 11976 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 11977 ScalarTypeToBooleanCastKind(resultType)); 11978 } else if (Context.getLangOpts().OpenCL && 11979 Context.getLangOpts().OpenCLVersion < 120) { 11980 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 11981 // operate on scalar float types. 11982 if (!resultType->isIntegerType() && !resultType->isPointerType()) 11983 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11984 << resultType << Input.get()->getSourceRange()); 11985 } 11986 } else if (resultType->isExtVectorType()) { 11987 if (Context.getLangOpts().OpenCL && 11988 Context.getLangOpts().OpenCLVersion < 120) { 11989 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 11990 // operate on vector float types. 11991 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 11992 if (!T->isIntegerType()) 11993 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11994 << resultType << Input.get()->getSourceRange()); 11995 } 11996 // Vector logical not returns the signed variant of the operand type. 11997 resultType = GetSignedVectorType(resultType); 11998 break; 11999 } else { 12000 // FIXME: GCC's vector extension permits the usage of '!' with a vector 12001 // type in C++. We should allow that here too. 12002 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12003 << resultType << Input.get()->getSourceRange()); 12004 } 12005 12006 // LNot always has type int. C99 6.5.3.3p5. 12007 // In C++, it's bool. C++ 5.3.1p8 12008 resultType = Context.getLogicalOperationType(); 12009 break; 12010 case UO_Real: 12011 case UO_Imag: 12012 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 12013 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 12014 // complex l-values to ordinary l-values and all other values to r-values. 12015 if (Input.isInvalid()) return ExprError(); 12016 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 12017 if (Input.get()->getValueKind() != VK_RValue && 12018 Input.get()->getObjectKind() == OK_Ordinary) 12019 VK = Input.get()->getValueKind(); 12020 } else if (!getLangOpts().CPlusPlus) { 12021 // In C, a volatile scalar is read by __imag. In C++, it is not. 12022 Input = DefaultLvalueConversion(Input.get()); 12023 } 12024 break; 12025 case UO_Extension: 12026 case UO_Coawait: 12027 resultType = Input.get()->getType(); 12028 VK = Input.get()->getValueKind(); 12029 OK = Input.get()->getObjectKind(); 12030 break; 12031 } 12032 if (resultType.isNull() || Input.isInvalid()) 12033 return ExprError(); 12034 12035 // Check for array bounds violations in the operand of the UnaryOperator, 12036 // except for the '*' and '&' operators that have to be handled specially 12037 // by CheckArrayAccess (as there are special cases like &array[arraysize] 12038 // that are explicitly defined as valid by the standard). 12039 if (Opc != UO_AddrOf && Opc != UO_Deref) 12040 CheckArrayAccess(Input.get()); 12041 12042 return new (Context) 12043 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc); 12044 } 12045 12046 /// \brief Determine whether the given expression is a qualified member 12047 /// access expression, of a form that could be turned into a pointer to member 12048 /// with the address-of operator. 12049 static bool isQualifiedMemberAccess(Expr *E) { 12050 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12051 if (!DRE->getQualifier()) 12052 return false; 12053 12054 ValueDecl *VD = DRE->getDecl(); 12055 if (!VD->isCXXClassMember()) 12056 return false; 12057 12058 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 12059 return true; 12060 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 12061 return Method->isInstance(); 12062 12063 return false; 12064 } 12065 12066 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 12067 if (!ULE->getQualifier()) 12068 return false; 12069 12070 for (NamedDecl *D : ULE->decls()) { 12071 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 12072 if (Method->isInstance()) 12073 return true; 12074 } else { 12075 // Overload set does not contain methods. 12076 break; 12077 } 12078 } 12079 12080 return false; 12081 } 12082 12083 return false; 12084 } 12085 12086 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 12087 UnaryOperatorKind Opc, Expr *Input) { 12088 // First things first: handle placeholders so that the 12089 // overloaded-operator check considers the right type. 12090 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 12091 // Increment and decrement of pseudo-object references. 12092 if (pty->getKind() == BuiltinType::PseudoObject && 12093 UnaryOperator::isIncrementDecrementOp(Opc)) 12094 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 12095 12096 // extension is always a builtin operator. 12097 if (Opc == UO_Extension) 12098 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12099 12100 // & gets special logic for several kinds of placeholder. 12101 // The builtin code knows what to do. 12102 if (Opc == UO_AddrOf && 12103 (pty->getKind() == BuiltinType::Overload || 12104 pty->getKind() == BuiltinType::UnknownAny || 12105 pty->getKind() == BuiltinType::BoundMember)) 12106 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12107 12108 // Anything else needs to be handled now. 12109 ExprResult Result = CheckPlaceholderExpr(Input); 12110 if (Result.isInvalid()) return ExprError(); 12111 Input = Result.get(); 12112 } 12113 12114 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 12115 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 12116 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 12117 // Find all of the overloaded operators visible from this 12118 // point. We perform both an operator-name lookup from the local 12119 // scope and an argument-dependent lookup based on the types of 12120 // the arguments. 12121 UnresolvedSet<16> Functions; 12122 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 12123 if (S && OverOp != OO_None) 12124 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 12125 Functions); 12126 12127 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 12128 } 12129 12130 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12131 } 12132 12133 // Unary Operators. 'Tok' is the token for the operator. 12134 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 12135 tok::TokenKind Op, Expr *Input) { 12136 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 12137 } 12138 12139 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 12140 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 12141 LabelDecl *TheDecl) { 12142 TheDecl->markUsed(Context); 12143 // Create the AST node. The address of a label always has type 'void*'. 12144 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 12145 Context.getPointerType(Context.VoidTy)); 12146 } 12147 12148 /// Given the last statement in a statement-expression, check whether 12149 /// the result is a producing expression (like a call to an 12150 /// ns_returns_retained function) and, if so, rebuild it to hoist the 12151 /// release out of the full-expression. Otherwise, return null. 12152 /// Cannot fail. 12153 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 12154 // Should always be wrapped with one of these. 12155 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 12156 if (!cleanups) return nullptr; 12157 12158 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 12159 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 12160 return nullptr; 12161 12162 // Splice out the cast. This shouldn't modify any interesting 12163 // features of the statement. 12164 Expr *producer = cast->getSubExpr(); 12165 assert(producer->getType() == cast->getType()); 12166 assert(producer->getValueKind() == cast->getValueKind()); 12167 cleanups->setSubExpr(producer); 12168 return cleanups; 12169 } 12170 12171 void Sema::ActOnStartStmtExpr() { 12172 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 12173 } 12174 12175 void Sema::ActOnStmtExprError() { 12176 // Note that function is also called by TreeTransform when leaving a 12177 // StmtExpr scope without rebuilding anything. 12178 12179 DiscardCleanupsInEvaluationContext(); 12180 PopExpressionEvaluationContext(); 12181 } 12182 12183 ExprResult 12184 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 12185 SourceLocation RPLoc) { // "({..})" 12186 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 12187 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 12188 12189 if (hasAnyUnrecoverableErrorsInThisFunction()) 12190 DiscardCleanupsInEvaluationContext(); 12191 assert(!Cleanup.exprNeedsCleanups() && 12192 "cleanups within StmtExpr not correctly bound!"); 12193 PopExpressionEvaluationContext(); 12194 12195 // FIXME: there are a variety of strange constraints to enforce here, for 12196 // example, it is not possible to goto into a stmt expression apparently. 12197 // More semantic analysis is needed. 12198 12199 // If there are sub-stmts in the compound stmt, take the type of the last one 12200 // as the type of the stmtexpr. 12201 QualType Ty = Context.VoidTy; 12202 bool StmtExprMayBindToTemp = false; 12203 if (!Compound->body_empty()) { 12204 Stmt *LastStmt = Compound->body_back(); 12205 LabelStmt *LastLabelStmt = nullptr; 12206 // If LastStmt is a label, skip down through into the body. 12207 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 12208 LastLabelStmt = Label; 12209 LastStmt = Label->getSubStmt(); 12210 } 12211 12212 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 12213 // Do function/array conversion on the last expression, but not 12214 // lvalue-to-rvalue. However, initialize an unqualified type. 12215 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 12216 if (LastExpr.isInvalid()) 12217 return ExprError(); 12218 Ty = LastExpr.get()->getType().getUnqualifiedType(); 12219 12220 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 12221 // In ARC, if the final expression ends in a consume, splice 12222 // the consume out and bind it later. In the alternate case 12223 // (when dealing with a retainable type), the result 12224 // initialization will create a produce. In both cases the 12225 // result will be +1, and we'll need to balance that out with 12226 // a bind. 12227 if (Expr *rebuiltLastStmt 12228 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 12229 LastExpr = rebuiltLastStmt; 12230 } else { 12231 LastExpr = PerformCopyInitialization( 12232 InitializedEntity::InitializeResult(LPLoc, 12233 Ty, 12234 false), 12235 SourceLocation(), 12236 LastExpr); 12237 } 12238 12239 if (LastExpr.isInvalid()) 12240 return ExprError(); 12241 if (LastExpr.get() != nullptr) { 12242 if (!LastLabelStmt) 12243 Compound->setLastStmt(LastExpr.get()); 12244 else 12245 LastLabelStmt->setSubStmt(LastExpr.get()); 12246 StmtExprMayBindToTemp = true; 12247 } 12248 } 12249 } 12250 } 12251 12252 // FIXME: Check that expression type is complete/non-abstract; statement 12253 // expressions are not lvalues. 12254 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 12255 if (StmtExprMayBindToTemp) 12256 return MaybeBindToTemporary(ResStmtExpr); 12257 return ResStmtExpr; 12258 } 12259 12260 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 12261 TypeSourceInfo *TInfo, 12262 ArrayRef<OffsetOfComponent> Components, 12263 SourceLocation RParenLoc) { 12264 QualType ArgTy = TInfo->getType(); 12265 bool Dependent = ArgTy->isDependentType(); 12266 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 12267 12268 // We must have at least one component that refers to the type, and the first 12269 // one is known to be a field designator. Verify that the ArgTy represents 12270 // a struct/union/class. 12271 if (!Dependent && !ArgTy->isRecordType()) 12272 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 12273 << ArgTy << TypeRange); 12274 12275 // Type must be complete per C99 7.17p3 because a declaring a variable 12276 // with an incomplete type would be ill-formed. 12277 if (!Dependent 12278 && RequireCompleteType(BuiltinLoc, ArgTy, 12279 diag::err_offsetof_incomplete_type, TypeRange)) 12280 return ExprError(); 12281 12282 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 12283 // GCC extension, diagnose them. 12284 // FIXME: This diagnostic isn't actually visible because the location is in 12285 // a system header! 12286 if (Components.size() != 1) 12287 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 12288 << SourceRange(Components[1].LocStart, Components.back().LocEnd); 12289 12290 bool DidWarnAboutNonPOD = false; 12291 QualType CurrentType = ArgTy; 12292 SmallVector<OffsetOfNode, 4> Comps; 12293 SmallVector<Expr*, 4> Exprs; 12294 for (const OffsetOfComponent &OC : Components) { 12295 if (OC.isBrackets) { 12296 // Offset of an array sub-field. TODO: Should we allow vector elements? 12297 if (!CurrentType->isDependentType()) { 12298 const ArrayType *AT = Context.getAsArrayType(CurrentType); 12299 if(!AT) 12300 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 12301 << CurrentType); 12302 CurrentType = AT->getElementType(); 12303 } else 12304 CurrentType = Context.DependentTy; 12305 12306 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 12307 if (IdxRval.isInvalid()) 12308 return ExprError(); 12309 Expr *Idx = IdxRval.get(); 12310 12311 // The expression must be an integral expression. 12312 // FIXME: An integral constant expression? 12313 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 12314 !Idx->getType()->isIntegerType()) 12315 return ExprError(Diag(Idx->getLocStart(), 12316 diag::err_typecheck_subscript_not_integer) 12317 << Idx->getSourceRange()); 12318 12319 // Record this array index. 12320 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 12321 Exprs.push_back(Idx); 12322 continue; 12323 } 12324 12325 // Offset of a field. 12326 if (CurrentType->isDependentType()) { 12327 // We have the offset of a field, but we can't look into the dependent 12328 // type. Just record the identifier of the field. 12329 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 12330 CurrentType = Context.DependentTy; 12331 continue; 12332 } 12333 12334 // We need to have a complete type to look into. 12335 if (RequireCompleteType(OC.LocStart, CurrentType, 12336 diag::err_offsetof_incomplete_type)) 12337 return ExprError(); 12338 12339 // Look for the designated field. 12340 const RecordType *RC = CurrentType->getAs<RecordType>(); 12341 if (!RC) 12342 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 12343 << CurrentType); 12344 RecordDecl *RD = RC->getDecl(); 12345 12346 // C++ [lib.support.types]p5: 12347 // The macro offsetof accepts a restricted set of type arguments in this 12348 // International Standard. type shall be a POD structure or a POD union 12349 // (clause 9). 12350 // C++11 [support.types]p4: 12351 // If type is not a standard-layout class (Clause 9), the results are 12352 // undefined. 12353 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 12354 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 12355 unsigned DiagID = 12356 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 12357 : diag::ext_offsetof_non_pod_type; 12358 12359 if (!IsSafe && !DidWarnAboutNonPOD && 12360 DiagRuntimeBehavior(BuiltinLoc, nullptr, 12361 PDiag(DiagID) 12362 << SourceRange(Components[0].LocStart, OC.LocEnd) 12363 << CurrentType)) 12364 DidWarnAboutNonPOD = true; 12365 } 12366 12367 // Look for the field. 12368 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 12369 LookupQualifiedName(R, RD); 12370 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 12371 IndirectFieldDecl *IndirectMemberDecl = nullptr; 12372 if (!MemberDecl) { 12373 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 12374 MemberDecl = IndirectMemberDecl->getAnonField(); 12375 } 12376 12377 if (!MemberDecl) 12378 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 12379 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 12380 OC.LocEnd)); 12381 12382 // C99 7.17p3: 12383 // (If the specified member is a bit-field, the behavior is undefined.) 12384 // 12385 // We diagnose this as an error. 12386 if (MemberDecl->isBitField()) { 12387 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 12388 << MemberDecl->getDeclName() 12389 << SourceRange(BuiltinLoc, RParenLoc); 12390 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 12391 return ExprError(); 12392 } 12393 12394 RecordDecl *Parent = MemberDecl->getParent(); 12395 if (IndirectMemberDecl) 12396 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 12397 12398 // If the member was found in a base class, introduce OffsetOfNodes for 12399 // the base class indirections. 12400 CXXBasePaths Paths; 12401 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 12402 Paths)) { 12403 if (Paths.getDetectedVirtual()) { 12404 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 12405 << MemberDecl->getDeclName() 12406 << SourceRange(BuiltinLoc, RParenLoc); 12407 return ExprError(); 12408 } 12409 12410 CXXBasePath &Path = Paths.front(); 12411 for (const CXXBasePathElement &B : Path) 12412 Comps.push_back(OffsetOfNode(B.Base)); 12413 } 12414 12415 if (IndirectMemberDecl) { 12416 for (auto *FI : IndirectMemberDecl->chain()) { 12417 assert(isa<FieldDecl>(FI)); 12418 Comps.push_back(OffsetOfNode(OC.LocStart, 12419 cast<FieldDecl>(FI), OC.LocEnd)); 12420 } 12421 } else 12422 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 12423 12424 CurrentType = MemberDecl->getType().getNonReferenceType(); 12425 } 12426 12427 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 12428 Comps, Exprs, RParenLoc); 12429 } 12430 12431 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 12432 SourceLocation BuiltinLoc, 12433 SourceLocation TypeLoc, 12434 ParsedType ParsedArgTy, 12435 ArrayRef<OffsetOfComponent> Components, 12436 SourceLocation RParenLoc) { 12437 12438 TypeSourceInfo *ArgTInfo; 12439 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 12440 if (ArgTy.isNull()) 12441 return ExprError(); 12442 12443 if (!ArgTInfo) 12444 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 12445 12446 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 12447 } 12448 12449 12450 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 12451 Expr *CondExpr, 12452 Expr *LHSExpr, Expr *RHSExpr, 12453 SourceLocation RPLoc) { 12454 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 12455 12456 ExprValueKind VK = VK_RValue; 12457 ExprObjectKind OK = OK_Ordinary; 12458 QualType resType; 12459 bool ValueDependent = false; 12460 bool CondIsTrue = false; 12461 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 12462 resType = Context.DependentTy; 12463 ValueDependent = true; 12464 } else { 12465 // The conditional expression is required to be a constant expression. 12466 llvm::APSInt condEval(32); 12467 ExprResult CondICE 12468 = VerifyIntegerConstantExpression(CondExpr, &condEval, 12469 diag::err_typecheck_choose_expr_requires_constant, false); 12470 if (CondICE.isInvalid()) 12471 return ExprError(); 12472 CondExpr = CondICE.get(); 12473 CondIsTrue = condEval.getZExtValue(); 12474 12475 // If the condition is > zero, then the AST type is the same as the LSHExpr. 12476 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 12477 12478 resType = ActiveExpr->getType(); 12479 ValueDependent = ActiveExpr->isValueDependent(); 12480 VK = ActiveExpr->getValueKind(); 12481 OK = ActiveExpr->getObjectKind(); 12482 } 12483 12484 return new (Context) 12485 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 12486 CondIsTrue, resType->isDependentType(), ValueDependent); 12487 } 12488 12489 //===----------------------------------------------------------------------===// 12490 // Clang Extensions. 12491 //===----------------------------------------------------------------------===// 12492 12493 /// ActOnBlockStart - This callback is invoked when a block literal is started. 12494 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 12495 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 12496 12497 if (LangOpts.CPlusPlus) { 12498 Decl *ManglingContextDecl; 12499 if (MangleNumberingContext *MCtx = 12500 getCurrentMangleNumberContext(Block->getDeclContext(), 12501 ManglingContextDecl)) { 12502 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 12503 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 12504 } 12505 } 12506 12507 PushBlockScope(CurScope, Block); 12508 CurContext->addDecl(Block); 12509 if (CurScope) 12510 PushDeclContext(CurScope, Block); 12511 else 12512 CurContext = Block; 12513 12514 getCurBlock()->HasImplicitReturnType = true; 12515 12516 // Enter a new evaluation context to insulate the block from any 12517 // cleanups from the enclosing full-expression. 12518 PushExpressionEvaluationContext( 12519 ExpressionEvaluationContext::PotentiallyEvaluated); 12520 } 12521 12522 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 12523 Scope *CurScope) { 12524 assert(ParamInfo.getIdentifier() == nullptr && 12525 "block-id should have no identifier!"); 12526 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 12527 BlockScopeInfo *CurBlock = getCurBlock(); 12528 12529 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 12530 QualType T = Sig->getType(); 12531 12532 // FIXME: We should allow unexpanded parameter packs here, but that would, 12533 // in turn, make the block expression contain unexpanded parameter packs. 12534 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 12535 // Drop the parameters. 12536 FunctionProtoType::ExtProtoInfo EPI; 12537 EPI.HasTrailingReturn = false; 12538 EPI.TypeQuals |= DeclSpec::TQ_const; 12539 T = Context.getFunctionType(Context.DependentTy, None, EPI); 12540 Sig = Context.getTrivialTypeSourceInfo(T); 12541 } 12542 12543 // GetTypeForDeclarator always produces a function type for a block 12544 // literal signature. Furthermore, it is always a FunctionProtoType 12545 // unless the function was written with a typedef. 12546 assert(T->isFunctionType() && 12547 "GetTypeForDeclarator made a non-function block signature"); 12548 12549 // Look for an explicit signature in that function type. 12550 FunctionProtoTypeLoc ExplicitSignature; 12551 12552 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 12553 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) { 12554 12555 // Check whether that explicit signature was synthesized by 12556 // GetTypeForDeclarator. If so, don't save that as part of the 12557 // written signature. 12558 if (ExplicitSignature.getLocalRangeBegin() == 12559 ExplicitSignature.getLocalRangeEnd()) { 12560 // This would be much cheaper if we stored TypeLocs instead of 12561 // TypeSourceInfos. 12562 TypeLoc Result = ExplicitSignature.getReturnLoc(); 12563 unsigned Size = Result.getFullDataSize(); 12564 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 12565 Sig->getTypeLoc().initializeFullCopy(Result, Size); 12566 12567 ExplicitSignature = FunctionProtoTypeLoc(); 12568 } 12569 } 12570 12571 CurBlock->TheDecl->setSignatureAsWritten(Sig); 12572 CurBlock->FunctionType = T; 12573 12574 const FunctionType *Fn = T->getAs<FunctionType>(); 12575 QualType RetTy = Fn->getReturnType(); 12576 bool isVariadic = 12577 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 12578 12579 CurBlock->TheDecl->setIsVariadic(isVariadic); 12580 12581 // Context.DependentTy is used as a placeholder for a missing block 12582 // return type. TODO: what should we do with declarators like: 12583 // ^ * { ... } 12584 // If the answer is "apply template argument deduction".... 12585 if (RetTy != Context.DependentTy) { 12586 CurBlock->ReturnType = RetTy; 12587 CurBlock->TheDecl->setBlockMissingReturnType(false); 12588 CurBlock->HasImplicitReturnType = false; 12589 } 12590 12591 // Push block parameters from the declarator if we had them. 12592 SmallVector<ParmVarDecl*, 8> Params; 12593 if (ExplicitSignature) { 12594 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 12595 ParmVarDecl *Param = ExplicitSignature.getParam(I); 12596 if (Param->getIdentifier() == nullptr && 12597 !Param->isImplicit() && 12598 !Param->isInvalidDecl() && 12599 !getLangOpts().CPlusPlus) 12600 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 12601 Params.push_back(Param); 12602 } 12603 12604 // Fake up parameter variables if we have a typedef, like 12605 // ^ fntype { ... } 12606 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 12607 for (const auto &I : Fn->param_types()) { 12608 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 12609 CurBlock->TheDecl, ParamInfo.getLocStart(), I); 12610 Params.push_back(Param); 12611 } 12612 } 12613 12614 // Set the parameters on the block decl. 12615 if (!Params.empty()) { 12616 CurBlock->TheDecl->setParams(Params); 12617 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 12618 /*CheckParameterNames=*/false); 12619 } 12620 12621 // Finally we can process decl attributes. 12622 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 12623 12624 // Put the parameter variables in scope. 12625 for (auto AI : CurBlock->TheDecl->parameters()) { 12626 AI->setOwningFunction(CurBlock->TheDecl); 12627 12628 // If this has an identifier, add it to the scope stack. 12629 if (AI->getIdentifier()) { 12630 CheckShadow(CurBlock->TheScope, AI); 12631 12632 PushOnScopeChains(AI, CurBlock->TheScope); 12633 } 12634 } 12635 } 12636 12637 /// ActOnBlockError - If there is an error parsing a block, this callback 12638 /// is invoked to pop the information about the block from the action impl. 12639 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 12640 // Leave the expression-evaluation context. 12641 DiscardCleanupsInEvaluationContext(); 12642 PopExpressionEvaluationContext(); 12643 12644 // Pop off CurBlock, handle nested blocks. 12645 PopDeclContext(); 12646 PopFunctionScopeInfo(); 12647 } 12648 12649 /// ActOnBlockStmtExpr - This is called when the body of a block statement 12650 /// literal was successfully completed. ^(int x){...} 12651 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 12652 Stmt *Body, Scope *CurScope) { 12653 // If blocks are disabled, emit an error. 12654 if (!LangOpts.Blocks) 12655 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 12656 12657 // Leave the expression-evaluation context. 12658 if (hasAnyUnrecoverableErrorsInThisFunction()) 12659 DiscardCleanupsInEvaluationContext(); 12660 assert(!Cleanup.exprNeedsCleanups() && 12661 "cleanups within block not correctly bound!"); 12662 PopExpressionEvaluationContext(); 12663 12664 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 12665 12666 if (BSI->HasImplicitReturnType) 12667 deduceClosureReturnType(*BSI); 12668 12669 PopDeclContext(); 12670 12671 QualType RetTy = Context.VoidTy; 12672 if (!BSI->ReturnType.isNull()) 12673 RetTy = BSI->ReturnType; 12674 12675 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 12676 QualType BlockTy; 12677 12678 // Set the captured variables on the block. 12679 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 12680 SmallVector<BlockDecl::Capture, 4> Captures; 12681 for (CapturingScopeInfo::Capture &Cap : BSI->Captures) { 12682 if (Cap.isThisCapture()) 12683 continue; 12684 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 12685 Cap.isNested(), Cap.getInitExpr()); 12686 Captures.push_back(NewCap); 12687 } 12688 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 12689 12690 // If the user wrote a function type in some form, try to use that. 12691 if (!BSI->FunctionType.isNull()) { 12692 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 12693 12694 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 12695 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 12696 12697 // Turn protoless block types into nullary block types. 12698 if (isa<FunctionNoProtoType>(FTy)) { 12699 FunctionProtoType::ExtProtoInfo EPI; 12700 EPI.ExtInfo = Ext; 12701 BlockTy = Context.getFunctionType(RetTy, None, EPI); 12702 12703 // Otherwise, if we don't need to change anything about the function type, 12704 // preserve its sugar structure. 12705 } else if (FTy->getReturnType() == RetTy && 12706 (!NoReturn || FTy->getNoReturnAttr())) { 12707 BlockTy = BSI->FunctionType; 12708 12709 // Otherwise, make the minimal modifications to the function type. 12710 } else { 12711 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 12712 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 12713 EPI.TypeQuals = 0; // FIXME: silently? 12714 EPI.ExtInfo = Ext; 12715 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 12716 } 12717 12718 // If we don't have a function type, just build one from nothing. 12719 } else { 12720 FunctionProtoType::ExtProtoInfo EPI; 12721 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 12722 BlockTy = Context.getFunctionType(RetTy, None, EPI); 12723 } 12724 12725 DiagnoseUnusedParameters(BSI->TheDecl->parameters()); 12726 BlockTy = Context.getBlockPointerType(BlockTy); 12727 12728 // If needed, diagnose invalid gotos and switches in the block. 12729 if (getCurFunction()->NeedsScopeChecking() && 12730 !PP.isCodeCompletionEnabled()) 12731 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 12732 12733 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 12734 12735 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 12736 DiagnoseUnguardedAvailabilityViolations(BSI->TheDecl); 12737 12738 // Try to apply the named return value optimization. We have to check again 12739 // if we can do this, though, because blocks keep return statements around 12740 // to deduce an implicit return type. 12741 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 12742 !BSI->TheDecl->isDependentContext()) 12743 computeNRVO(Body, BSI); 12744 12745 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 12746 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 12747 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 12748 12749 // If the block isn't obviously global, i.e. it captures anything at 12750 // all, then we need to do a few things in the surrounding context: 12751 if (Result->getBlockDecl()->hasCaptures()) { 12752 // First, this expression has a new cleanup object. 12753 ExprCleanupObjects.push_back(Result->getBlockDecl()); 12754 Cleanup.setExprNeedsCleanups(true); 12755 12756 // It also gets a branch-protected scope if any of the captured 12757 // variables needs destruction. 12758 for (const auto &CI : Result->getBlockDecl()->captures()) { 12759 const VarDecl *var = CI.getVariable(); 12760 if (var->getType().isDestructedType() != QualType::DK_none) { 12761 getCurFunction()->setHasBranchProtectedScope(); 12762 break; 12763 } 12764 } 12765 } 12766 12767 return Result; 12768 } 12769 12770 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 12771 SourceLocation RPLoc) { 12772 TypeSourceInfo *TInfo; 12773 GetTypeFromParser(Ty, &TInfo); 12774 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 12775 } 12776 12777 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 12778 Expr *E, TypeSourceInfo *TInfo, 12779 SourceLocation RPLoc) { 12780 Expr *OrigExpr = E; 12781 bool IsMS = false; 12782 12783 // CUDA device code does not support varargs. 12784 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 12785 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 12786 CUDAFunctionTarget T = IdentifyCUDATarget(F); 12787 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 12788 return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device)); 12789 } 12790 } 12791 12792 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 12793 // as Microsoft ABI on an actual Microsoft platform, where 12794 // __builtin_ms_va_list and __builtin_va_list are the same.) 12795 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 12796 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 12797 QualType MSVaListType = Context.getBuiltinMSVaListType(); 12798 if (Context.hasSameType(MSVaListType, E->getType())) { 12799 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 12800 return ExprError(); 12801 IsMS = true; 12802 } 12803 } 12804 12805 // Get the va_list type 12806 QualType VaListType = Context.getBuiltinVaListType(); 12807 if (!IsMS) { 12808 if (VaListType->isArrayType()) { 12809 // Deal with implicit array decay; for example, on x86-64, 12810 // va_list is an array, but it's supposed to decay to 12811 // a pointer for va_arg. 12812 VaListType = Context.getArrayDecayedType(VaListType); 12813 // Make sure the input expression also decays appropriately. 12814 ExprResult Result = UsualUnaryConversions(E); 12815 if (Result.isInvalid()) 12816 return ExprError(); 12817 E = Result.get(); 12818 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 12819 // If va_list is a record type and we are compiling in C++ mode, 12820 // check the argument using reference binding. 12821 InitializedEntity Entity = InitializedEntity::InitializeParameter( 12822 Context, Context.getLValueReferenceType(VaListType), false); 12823 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 12824 if (Init.isInvalid()) 12825 return ExprError(); 12826 E = Init.getAs<Expr>(); 12827 } else { 12828 // Otherwise, the va_list argument must be an l-value because 12829 // it is modified by va_arg. 12830 if (!E->isTypeDependent() && 12831 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 12832 return ExprError(); 12833 } 12834 } 12835 12836 if (!IsMS && !E->isTypeDependent() && 12837 !Context.hasSameType(VaListType, E->getType())) 12838 return ExprError(Diag(E->getLocStart(), 12839 diag::err_first_argument_to_va_arg_not_of_type_va_list) 12840 << OrigExpr->getType() << E->getSourceRange()); 12841 12842 if (!TInfo->getType()->isDependentType()) { 12843 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 12844 diag::err_second_parameter_to_va_arg_incomplete, 12845 TInfo->getTypeLoc())) 12846 return ExprError(); 12847 12848 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 12849 TInfo->getType(), 12850 diag::err_second_parameter_to_va_arg_abstract, 12851 TInfo->getTypeLoc())) 12852 return ExprError(); 12853 12854 if (!TInfo->getType().isPODType(Context)) { 12855 Diag(TInfo->getTypeLoc().getBeginLoc(), 12856 TInfo->getType()->isObjCLifetimeType() 12857 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 12858 : diag::warn_second_parameter_to_va_arg_not_pod) 12859 << TInfo->getType() 12860 << TInfo->getTypeLoc().getSourceRange(); 12861 } 12862 12863 // Check for va_arg where arguments of the given type will be promoted 12864 // (i.e. this va_arg is guaranteed to have undefined behavior). 12865 QualType PromoteType; 12866 if (TInfo->getType()->isPromotableIntegerType()) { 12867 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 12868 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 12869 PromoteType = QualType(); 12870 } 12871 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 12872 PromoteType = Context.DoubleTy; 12873 if (!PromoteType.isNull()) 12874 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 12875 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 12876 << TInfo->getType() 12877 << PromoteType 12878 << TInfo->getTypeLoc().getSourceRange()); 12879 } 12880 12881 QualType T = TInfo->getType().getNonLValueExprType(Context); 12882 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 12883 } 12884 12885 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 12886 // The type of __null will be int or long, depending on the size of 12887 // pointers on the target. 12888 QualType Ty; 12889 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 12890 if (pw == Context.getTargetInfo().getIntWidth()) 12891 Ty = Context.IntTy; 12892 else if (pw == Context.getTargetInfo().getLongWidth()) 12893 Ty = Context.LongTy; 12894 else if (pw == Context.getTargetInfo().getLongLongWidth()) 12895 Ty = Context.LongLongTy; 12896 else { 12897 llvm_unreachable("I don't know size of pointer!"); 12898 } 12899 12900 return new (Context) GNUNullExpr(Ty, TokenLoc); 12901 } 12902 12903 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 12904 bool Diagnose) { 12905 if (!getLangOpts().ObjC1) 12906 return false; 12907 12908 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 12909 if (!PT) 12910 return false; 12911 12912 if (!PT->isObjCIdType()) { 12913 // Check if the destination is the 'NSString' interface. 12914 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 12915 if (!ID || !ID->getIdentifier()->isStr("NSString")) 12916 return false; 12917 } 12918 12919 // Ignore any parens, implicit casts (should only be 12920 // array-to-pointer decays), and not-so-opaque values. The last is 12921 // important for making this trigger for property assignments. 12922 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 12923 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 12924 if (OV->getSourceExpr()) 12925 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 12926 12927 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 12928 if (!SL || !SL->isAscii()) 12929 return false; 12930 if (Diagnose) { 12931 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix) 12932 << FixItHint::CreateInsertion(SL->getLocStart(), "@"); 12933 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get(); 12934 } 12935 return true; 12936 } 12937 12938 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 12939 const Expr *SrcExpr) { 12940 if (!DstType->isFunctionPointerType() || 12941 !SrcExpr->getType()->isFunctionType()) 12942 return false; 12943 12944 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 12945 if (!DRE) 12946 return false; 12947 12948 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 12949 if (!FD) 12950 return false; 12951 12952 return !S.checkAddressOfFunctionIsAvailable(FD, 12953 /*Complain=*/true, 12954 SrcExpr->getLocStart()); 12955 } 12956 12957 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 12958 SourceLocation Loc, 12959 QualType DstType, QualType SrcType, 12960 Expr *SrcExpr, AssignmentAction Action, 12961 bool *Complained) { 12962 if (Complained) 12963 *Complained = false; 12964 12965 // Decode the result (notice that AST's are still created for extensions). 12966 bool CheckInferredResultType = false; 12967 bool isInvalid = false; 12968 unsigned DiagKind = 0; 12969 FixItHint Hint; 12970 ConversionFixItGenerator ConvHints; 12971 bool MayHaveConvFixit = false; 12972 bool MayHaveFunctionDiff = false; 12973 const ObjCInterfaceDecl *IFace = nullptr; 12974 const ObjCProtocolDecl *PDecl = nullptr; 12975 12976 switch (ConvTy) { 12977 case Compatible: 12978 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 12979 return false; 12980 12981 case PointerToInt: 12982 DiagKind = diag::ext_typecheck_convert_pointer_int; 12983 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12984 MayHaveConvFixit = true; 12985 break; 12986 case IntToPointer: 12987 DiagKind = diag::ext_typecheck_convert_int_pointer; 12988 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12989 MayHaveConvFixit = true; 12990 break; 12991 case IncompatiblePointer: 12992 if (Action == AA_Passing_CFAudited) 12993 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 12994 else if (SrcType->isFunctionPointerType() && 12995 DstType->isFunctionPointerType()) 12996 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 12997 else 12998 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 12999 13000 CheckInferredResultType = DstType->isObjCObjectPointerType() && 13001 SrcType->isObjCObjectPointerType(); 13002 if (Hint.isNull() && !CheckInferredResultType) { 13003 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13004 } 13005 else if (CheckInferredResultType) { 13006 SrcType = SrcType.getUnqualifiedType(); 13007 DstType = DstType.getUnqualifiedType(); 13008 } 13009 MayHaveConvFixit = true; 13010 break; 13011 case IncompatiblePointerSign: 13012 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 13013 break; 13014 case FunctionVoidPointer: 13015 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 13016 break; 13017 case IncompatiblePointerDiscardsQualifiers: { 13018 // Perform array-to-pointer decay if necessary. 13019 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 13020 13021 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 13022 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 13023 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 13024 DiagKind = diag::err_typecheck_incompatible_address_space; 13025 break; 13026 13027 13028 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 13029 DiagKind = diag::err_typecheck_incompatible_ownership; 13030 break; 13031 } 13032 13033 llvm_unreachable("unknown error case for discarding qualifiers!"); 13034 // fallthrough 13035 } 13036 case CompatiblePointerDiscardsQualifiers: 13037 // If the qualifiers lost were because we were applying the 13038 // (deprecated) C++ conversion from a string literal to a char* 13039 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 13040 // Ideally, this check would be performed in 13041 // checkPointerTypesForAssignment. However, that would require a 13042 // bit of refactoring (so that the second argument is an 13043 // expression, rather than a type), which should be done as part 13044 // of a larger effort to fix checkPointerTypesForAssignment for 13045 // C++ semantics. 13046 if (getLangOpts().CPlusPlus && 13047 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 13048 return false; 13049 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 13050 break; 13051 case IncompatibleNestedPointerQualifiers: 13052 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 13053 break; 13054 case IntToBlockPointer: 13055 DiagKind = diag::err_int_to_block_pointer; 13056 break; 13057 case IncompatibleBlockPointer: 13058 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 13059 break; 13060 case IncompatibleObjCQualifiedId: { 13061 if (SrcType->isObjCQualifiedIdType()) { 13062 const ObjCObjectPointerType *srcOPT = 13063 SrcType->getAs<ObjCObjectPointerType>(); 13064 for (auto *srcProto : srcOPT->quals()) { 13065 PDecl = srcProto; 13066 break; 13067 } 13068 if (const ObjCInterfaceType *IFaceT = 13069 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 13070 IFace = IFaceT->getDecl(); 13071 } 13072 else if (DstType->isObjCQualifiedIdType()) { 13073 const ObjCObjectPointerType *dstOPT = 13074 DstType->getAs<ObjCObjectPointerType>(); 13075 for (auto *dstProto : dstOPT->quals()) { 13076 PDecl = dstProto; 13077 break; 13078 } 13079 if (const ObjCInterfaceType *IFaceT = 13080 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 13081 IFace = IFaceT->getDecl(); 13082 } 13083 DiagKind = diag::warn_incompatible_qualified_id; 13084 break; 13085 } 13086 case IncompatibleVectors: 13087 DiagKind = diag::warn_incompatible_vectors; 13088 break; 13089 case IncompatibleObjCWeakRef: 13090 DiagKind = diag::err_arc_weak_unavailable_assign; 13091 break; 13092 case Incompatible: 13093 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 13094 if (Complained) 13095 *Complained = true; 13096 return true; 13097 } 13098 13099 DiagKind = diag::err_typecheck_convert_incompatible; 13100 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13101 MayHaveConvFixit = true; 13102 isInvalid = true; 13103 MayHaveFunctionDiff = true; 13104 break; 13105 } 13106 13107 QualType FirstType, SecondType; 13108 switch (Action) { 13109 case AA_Assigning: 13110 case AA_Initializing: 13111 // The destination type comes first. 13112 FirstType = DstType; 13113 SecondType = SrcType; 13114 break; 13115 13116 case AA_Returning: 13117 case AA_Passing: 13118 case AA_Passing_CFAudited: 13119 case AA_Converting: 13120 case AA_Sending: 13121 case AA_Casting: 13122 // The source type comes first. 13123 FirstType = SrcType; 13124 SecondType = DstType; 13125 break; 13126 } 13127 13128 PartialDiagnostic FDiag = PDiag(DiagKind); 13129 if (Action == AA_Passing_CFAudited) 13130 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 13131 else 13132 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 13133 13134 // If we can fix the conversion, suggest the FixIts. 13135 assert(ConvHints.isNull() || Hint.isNull()); 13136 if (!ConvHints.isNull()) { 13137 for (FixItHint &H : ConvHints.Hints) 13138 FDiag << H; 13139 } else { 13140 FDiag << Hint; 13141 } 13142 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 13143 13144 if (MayHaveFunctionDiff) 13145 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 13146 13147 Diag(Loc, FDiag); 13148 if (DiagKind == diag::warn_incompatible_qualified_id && 13149 PDecl && IFace && !IFace->hasDefinition()) 13150 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 13151 << IFace->getName() << PDecl->getName(); 13152 13153 if (SecondType == Context.OverloadTy) 13154 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 13155 FirstType, /*TakingAddress=*/true); 13156 13157 if (CheckInferredResultType) 13158 EmitRelatedResultTypeNote(SrcExpr); 13159 13160 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 13161 EmitRelatedResultTypeNoteForReturn(DstType); 13162 13163 if (Complained) 13164 *Complained = true; 13165 return isInvalid; 13166 } 13167 13168 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 13169 llvm::APSInt *Result) { 13170 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 13171 public: 13172 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 13173 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 13174 } 13175 } Diagnoser; 13176 13177 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 13178 } 13179 13180 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 13181 llvm::APSInt *Result, 13182 unsigned DiagID, 13183 bool AllowFold) { 13184 class IDDiagnoser : public VerifyICEDiagnoser { 13185 unsigned DiagID; 13186 13187 public: 13188 IDDiagnoser(unsigned DiagID) 13189 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 13190 13191 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 13192 S.Diag(Loc, DiagID) << SR; 13193 } 13194 } Diagnoser(DiagID); 13195 13196 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 13197 } 13198 13199 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 13200 SourceRange SR) { 13201 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 13202 } 13203 13204 ExprResult 13205 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 13206 VerifyICEDiagnoser &Diagnoser, 13207 bool AllowFold) { 13208 SourceLocation DiagLoc = E->getLocStart(); 13209 13210 if (getLangOpts().CPlusPlus11) { 13211 // C++11 [expr.const]p5: 13212 // If an expression of literal class type is used in a context where an 13213 // integral constant expression is required, then that class type shall 13214 // have a single non-explicit conversion function to an integral or 13215 // unscoped enumeration type 13216 ExprResult Converted; 13217 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 13218 public: 13219 CXX11ConvertDiagnoser(bool Silent) 13220 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 13221 Silent, true) {} 13222 13223 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 13224 QualType T) override { 13225 return S.Diag(Loc, diag::err_ice_not_integral) << T; 13226 } 13227 13228 SemaDiagnosticBuilder diagnoseIncomplete( 13229 Sema &S, SourceLocation Loc, QualType T) override { 13230 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 13231 } 13232 13233 SemaDiagnosticBuilder diagnoseExplicitConv( 13234 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 13235 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 13236 } 13237 13238 SemaDiagnosticBuilder noteExplicitConv( 13239 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 13240 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 13241 << ConvTy->isEnumeralType() << ConvTy; 13242 } 13243 13244 SemaDiagnosticBuilder diagnoseAmbiguous( 13245 Sema &S, SourceLocation Loc, QualType T) override { 13246 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 13247 } 13248 13249 SemaDiagnosticBuilder noteAmbiguous( 13250 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 13251 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 13252 << ConvTy->isEnumeralType() << ConvTy; 13253 } 13254 13255 SemaDiagnosticBuilder diagnoseConversion( 13256 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 13257 llvm_unreachable("conversion functions are permitted"); 13258 } 13259 } ConvertDiagnoser(Diagnoser.Suppress); 13260 13261 Converted = PerformContextualImplicitConversion(DiagLoc, E, 13262 ConvertDiagnoser); 13263 if (Converted.isInvalid()) 13264 return Converted; 13265 E = Converted.get(); 13266 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 13267 return ExprError(); 13268 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 13269 // An ICE must be of integral or unscoped enumeration type. 13270 if (!Diagnoser.Suppress) 13271 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 13272 return ExprError(); 13273 } 13274 13275 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 13276 // in the non-ICE case. 13277 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 13278 if (Result) 13279 *Result = E->EvaluateKnownConstInt(Context); 13280 return E; 13281 } 13282 13283 Expr::EvalResult EvalResult; 13284 SmallVector<PartialDiagnosticAt, 8> Notes; 13285 EvalResult.Diag = &Notes; 13286 13287 // Try to evaluate the expression, and produce diagnostics explaining why it's 13288 // not a constant expression as a side-effect. 13289 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 13290 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 13291 13292 // In C++11, we can rely on diagnostics being produced for any expression 13293 // which is not a constant expression. If no diagnostics were produced, then 13294 // this is a constant expression. 13295 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 13296 if (Result) 13297 *Result = EvalResult.Val.getInt(); 13298 return E; 13299 } 13300 13301 // If our only note is the usual "invalid subexpression" note, just point 13302 // the caret at its location rather than producing an essentially 13303 // redundant note. 13304 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 13305 diag::note_invalid_subexpr_in_const_expr) { 13306 DiagLoc = Notes[0].first; 13307 Notes.clear(); 13308 } 13309 13310 if (!Folded || !AllowFold) { 13311 if (!Diagnoser.Suppress) { 13312 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 13313 for (const PartialDiagnosticAt &Note : Notes) 13314 Diag(Note.first, Note.second); 13315 } 13316 13317 return ExprError(); 13318 } 13319 13320 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 13321 for (const PartialDiagnosticAt &Note : Notes) 13322 Diag(Note.first, Note.second); 13323 13324 if (Result) 13325 *Result = EvalResult.Val.getInt(); 13326 return E; 13327 } 13328 13329 namespace { 13330 // Handle the case where we conclude a expression which we speculatively 13331 // considered to be unevaluated is actually evaluated. 13332 class TransformToPE : public TreeTransform<TransformToPE> { 13333 typedef TreeTransform<TransformToPE> BaseTransform; 13334 13335 public: 13336 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 13337 13338 // Make sure we redo semantic analysis 13339 bool AlwaysRebuild() { return true; } 13340 13341 // Make sure we handle LabelStmts correctly. 13342 // FIXME: This does the right thing, but maybe we need a more general 13343 // fix to TreeTransform? 13344 StmtResult TransformLabelStmt(LabelStmt *S) { 13345 S->getDecl()->setStmt(nullptr); 13346 return BaseTransform::TransformLabelStmt(S); 13347 } 13348 13349 // We need to special-case DeclRefExprs referring to FieldDecls which 13350 // are not part of a member pointer formation; normal TreeTransforming 13351 // doesn't catch this case because of the way we represent them in the AST. 13352 // FIXME: This is a bit ugly; is it really the best way to handle this 13353 // case? 13354 // 13355 // Error on DeclRefExprs referring to FieldDecls. 13356 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 13357 if (isa<FieldDecl>(E->getDecl()) && 13358 !SemaRef.isUnevaluatedContext()) 13359 return SemaRef.Diag(E->getLocation(), 13360 diag::err_invalid_non_static_member_use) 13361 << E->getDecl() << E->getSourceRange(); 13362 13363 return BaseTransform::TransformDeclRefExpr(E); 13364 } 13365 13366 // Exception: filter out member pointer formation 13367 ExprResult TransformUnaryOperator(UnaryOperator *E) { 13368 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 13369 return E; 13370 13371 return BaseTransform::TransformUnaryOperator(E); 13372 } 13373 13374 ExprResult TransformLambdaExpr(LambdaExpr *E) { 13375 // Lambdas never need to be transformed. 13376 return E; 13377 } 13378 }; 13379 } 13380 13381 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 13382 assert(isUnevaluatedContext() && 13383 "Should only transform unevaluated expressions"); 13384 ExprEvalContexts.back().Context = 13385 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 13386 if (isUnevaluatedContext()) 13387 return E; 13388 return TransformToPE(*this).TransformExpr(E); 13389 } 13390 13391 void 13392 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 13393 Decl *LambdaContextDecl, 13394 bool IsDecltype) { 13395 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 13396 LambdaContextDecl, IsDecltype); 13397 Cleanup.reset(); 13398 if (!MaybeODRUseExprs.empty()) 13399 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 13400 } 13401 13402 void 13403 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 13404 ReuseLambdaContextDecl_t, 13405 bool IsDecltype) { 13406 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 13407 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 13408 } 13409 13410 void Sema::PopExpressionEvaluationContext() { 13411 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 13412 unsigned NumTypos = Rec.NumTypos; 13413 13414 if (!Rec.Lambdas.empty()) { 13415 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 13416 unsigned D; 13417 if (Rec.isUnevaluated()) { 13418 // C++11 [expr.prim.lambda]p2: 13419 // A lambda-expression shall not appear in an unevaluated operand 13420 // (Clause 5). 13421 D = diag::err_lambda_unevaluated_operand; 13422 } else { 13423 // C++1y [expr.const]p2: 13424 // A conditional-expression e is a core constant expression unless the 13425 // evaluation of e, following the rules of the abstract machine, would 13426 // evaluate [...] a lambda-expression. 13427 D = diag::err_lambda_in_constant_expression; 13428 } 13429 13430 // C++1z allows lambda expressions as core constant expressions. 13431 // FIXME: In C++1z, reinstate the restrictions on lambda expressions (CWG 13432 // 1607) from appearing within template-arguments and array-bounds that 13433 // are part of function-signatures. Be mindful that P0315 (Lambdas in 13434 // unevaluated contexts) might lift some of these restrictions in a 13435 // future version. 13436 if (!Rec.isConstantEvaluated() || !getLangOpts().CPlusPlus1z) 13437 for (const auto *L : Rec.Lambdas) 13438 Diag(L->getLocStart(), D); 13439 } else { 13440 // Mark the capture expressions odr-used. This was deferred 13441 // during lambda expression creation. 13442 for (auto *Lambda : Rec.Lambdas) { 13443 for (auto *C : Lambda->capture_inits()) 13444 MarkDeclarationsReferencedInExpr(C); 13445 } 13446 } 13447 } 13448 13449 // When are coming out of an unevaluated context, clear out any 13450 // temporaries that we may have created as part of the evaluation of 13451 // the expression in that context: they aren't relevant because they 13452 // will never be constructed. 13453 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 13454 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 13455 ExprCleanupObjects.end()); 13456 Cleanup = Rec.ParentCleanup; 13457 CleanupVarDeclMarking(); 13458 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 13459 // Otherwise, merge the contexts together. 13460 } else { 13461 Cleanup.mergeFrom(Rec.ParentCleanup); 13462 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 13463 Rec.SavedMaybeODRUseExprs.end()); 13464 } 13465 13466 // Pop the current expression evaluation context off the stack. 13467 ExprEvalContexts.pop_back(); 13468 13469 if (!ExprEvalContexts.empty()) 13470 ExprEvalContexts.back().NumTypos += NumTypos; 13471 else 13472 assert(NumTypos == 0 && "There are outstanding typos after popping the " 13473 "last ExpressionEvaluationContextRecord"); 13474 } 13475 13476 void Sema::DiscardCleanupsInEvaluationContext() { 13477 ExprCleanupObjects.erase( 13478 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 13479 ExprCleanupObjects.end()); 13480 Cleanup.reset(); 13481 MaybeODRUseExprs.clear(); 13482 } 13483 13484 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 13485 if (!E->getType()->isVariablyModifiedType()) 13486 return E; 13487 return TransformToPotentiallyEvaluated(E); 13488 } 13489 13490 /// Are we within a context in which some evaluation could be performed (be it 13491 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite 13492 /// captured by C++'s idea of an "unevaluated context". 13493 static bool isEvaluatableContext(Sema &SemaRef) { 13494 switch (SemaRef.ExprEvalContexts.back().Context) { 13495 case Sema::ExpressionEvaluationContext::Unevaluated: 13496 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 13497 case Sema::ExpressionEvaluationContext::DiscardedStatement: 13498 // Expressions in this context are never evaluated. 13499 return false; 13500 13501 case Sema::ExpressionEvaluationContext::UnevaluatedList: 13502 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 13503 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 13504 // Expressions in this context could be evaluated. 13505 return true; 13506 13507 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 13508 // Referenced declarations will only be used if the construct in the 13509 // containing expression is used, at which point we'll be given another 13510 // turn to mark them. 13511 return false; 13512 } 13513 llvm_unreachable("Invalid context"); 13514 } 13515 13516 /// Are we within a context in which references to resolved functions or to 13517 /// variables result in odr-use? 13518 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) { 13519 // An expression in a template is not really an expression until it's been 13520 // instantiated, so it doesn't trigger odr-use. 13521 if (SkipDependentUses && SemaRef.CurContext->isDependentContext()) 13522 return false; 13523 13524 switch (SemaRef.ExprEvalContexts.back().Context) { 13525 case Sema::ExpressionEvaluationContext::Unevaluated: 13526 case Sema::ExpressionEvaluationContext::UnevaluatedList: 13527 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 13528 case Sema::ExpressionEvaluationContext::DiscardedStatement: 13529 return false; 13530 13531 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 13532 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 13533 return true; 13534 13535 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 13536 return false; 13537 } 13538 llvm_unreachable("Invalid context"); 13539 } 13540 13541 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 13542 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 13543 return Func->isConstexpr() && 13544 (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided())); 13545 } 13546 13547 /// \brief Mark a function referenced, and check whether it is odr-used 13548 /// (C++ [basic.def.odr]p2, C99 6.9p3) 13549 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 13550 bool MightBeOdrUse) { 13551 assert(Func && "No function?"); 13552 13553 Func->setReferenced(); 13554 13555 // C++11 [basic.def.odr]p3: 13556 // A function whose name appears as a potentially-evaluated expression is 13557 // odr-used if it is the unique lookup result or the selected member of a 13558 // set of overloaded functions [...]. 13559 // 13560 // We (incorrectly) mark overload resolution as an unevaluated context, so we 13561 // can just check that here. 13562 bool OdrUse = MightBeOdrUse && isOdrUseContext(*this); 13563 13564 // Determine whether we require a function definition to exist, per 13565 // C++11 [temp.inst]p3: 13566 // Unless a function template specialization has been explicitly 13567 // instantiated or explicitly specialized, the function template 13568 // specialization is implicitly instantiated when the specialization is 13569 // referenced in a context that requires a function definition to exist. 13570 // 13571 // That is either when this is an odr-use, or when a usage of a constexpr 13572 // function occurs within an evaluatable context. 13573 bool NeedDefinition = 13574 OdrUse || (isEvaluatableContext(*this) && 13575 isImplicitlyDefinableConstexprFunction(Func)); 13576 13577 // C++14 [temp.expl.spec]p6: 13578 // If a template [...] is explicitly specialized then that specialization 13579 // shall be declared before the first use of that specialization that would 13580 // cause an implicit instantiation to take place, in every translation unit 13581 // in which such a use occurs 13582 if (NeedDefinition && 13583 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 13584 Func->getMemberSpecializationInfo())) 13585 checkSpecializationVisibility(Loc, Func); 13586 13587 // C++14 [except.spec]p17: 13588 // An exception-specification is considered to be needed when: 13589 // - the function is odr-used or, if it appears in an unevaluated operand, 13590 // would be odr-used if the expression were potentially-evaluated; 13591 // 13592 // Note, we do this even if MightBeOdrUse is false. That indicates that the 13593 // function is a pure virtual function we're calling, and in that case the 13594 // function was selected by overload resolution and we need to resolve its 13595 // exception specification for a different reason. 13596 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 13597 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 13598 ResolveExceptionSpec(Loc, FPT); 13599 13600 // If we don't need to mark the function as used, and we don't need to 13601 // try to provide a definition, there's nothing more to do. 13602 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) && 13603 (!NeedDefinition || Func->getBody())) 13604 return; 13605 13606 // Note that this declaration has been used. 13607 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 13608 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 13609 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 13610 if (Constructor->isDefaultConstructor()) { 13611 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 13612 return; 13613 DefineImplicitDefaultConstructor(Loc, Constructor); 13614 } else if (Constructor->isCopyConstructor()) { 13615 DefineImplicitCopyConstructor(Loc, Constructor); 13616 } else if (Constructor->isMoveConstructor()) { 13617 DefineImplicitMoveConstructor(Loc, Constructor); 13618 } 13619 } else if (Constructor->getInheritedConstructor()) { 13620 DefineInheritingConstructor(Loc, Constructor); 13621 } 13622 } else if (CXXDestructorDecl *Destructor = 13623 dyn_cast<CXXDestructorDecl>(Func)) { 13624 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 13625 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 13626 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 13627 return; 13628 DefineImplicitDestructor(Loc, Destructor); 13629 } 13630 if (Destructor->isVirtual() && getLangOpts().AppleKext) 13631 MarkVTableUsed(Loc, Destructor->getParent()); 13632 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 13633 if (MethodDecl->isOverloadedOperator() && 13634 MethodDecl->getOverloadedOperator() == OO_Equal) { 13635 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 13636 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 13637 if (MethodDecl->isCopyAssignmentOperator()) 13638 DefineImplicitCopyAssignment(Loc, MethodDecl); 13639 else if (MethodDecl->isMoveAssignmentOperator()) 13640 DefineImplicitMoveAssignment(Loc, MethodDecl); 13641 } 13642 } else if (isa<CXXConversionDecl>(MethodDecl) && 13643 MethodDecl->getParent()->isLambda()) { 13644 CXXConversionDecl *Conversion = 13645 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 13646 if (Conversion->isLambdaToBlockPointerConversion()) 13647 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 13648 else 13649 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 13650 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 13651 MarkVTableUsed(Loc, MethodDecl->getParent()); 13652 } 13653 13654 // Recursive functions should be marked when used from another function. 13655 // FIXME: Is this really right? 13656 if (CurContext == Func) return; 13657 13658 // Implicit instantiation of function templates and member functions of 13659 // class templates. 13660 if (Func->isImplicitlyInstantiable()) { 13661 bool AlreadyInstantiated = false; 13662 SourceLocation PointOfInstantiation = Loc; 13663 if (FunctionTemplateSpecializationInfo *SpecInfo 13664 = Func->getTemplateSpecializationInfo()) { 13665 if (SpecInfo->getPointOfInstantiation().isInvalid()) 13666 SpecInfo->setPointOfInstantiation(Loc); 13667 else if (SpecInfo->getTemplateSpecializationKind() 13668 == TSK_ImplicitInstantiation) { 13669 AlreadyInstantiated = true; 13670 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 13671 } 13672 } else if (MemberSpecializationInfo *MSInfo 13673 = Func->getMemberSpecializationInfo()) { 13674 if (MSInfo->getPointOfInstantiation().isInvalid()) 13675 MSInfo->setPointOfInstantiation(Loc); 13676 else if (MSInfo->getTemplateSpecializationKind() 13677 == TSK_ImplicitInstantiation) { 13678 AlreadyInstantiated = true; 13679 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 13680 } 13681 } 13682 13683 if (!AlreadyInstantiated || Func->isConstexpr()) { 13684 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 13685 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 13686 CodeSynthesisContexts.size()) 13687 PendingLocalImplicitInstantiations.push_back( 13688 std::make_pair(Func, PointOfInstantiation)); 13689 else if (Func->isConstexpr()) 13690 // Do not defer instantiations of constexpr functions, to avoid the 13691 // expression evaluator needing to call back into Sema if it sees a 13692 // call to such a function. 13693 InstantiateFunctionDefinition(PointOfInstantiation, Func); 13694 else { 13695 PendingInstantiations.push_back(std::make_pair(Func, 13696 PointOfInstantiation)); 13697 // Notify the consumer that a function was implicitly instantiated. 13698 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 13699 } 13700 } 13701 } else { 13702 // Walk redefinitions, as some of them may be instantiable. 13703 for (auto i : Func->redecls()) { 13704 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 13705 MarkFunctionReferenced(Loc, i, OdrUse); 13706 } 13707 } 13708 13709 if (!OdrUse) return; 13710 13711 // Keep track of used but undefined functions. 13712 if (!Func->isDefined()) { 13713 if (mightHaveNonExternalLinkage(Func)) 13714 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 13715 else if (Func->getMostRecentDecl()->isInlined() && 13716 !LangOpts.GNUInline && 13717 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 13718 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 13719 } 13720 13721 Func->markUsed(Context); 13722 } 13723 13724 static void 13725 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 13726 ValueDecl *var, DeclContext *DC) { 13727 DeclContext *VarDC = var->getDeclContext(); 13728 13729 // If the parameter still belongs to the translation unit, then 13730 // we're actually just using one parameter in the declaration of 13731 // the next. 13732 if (isa<ParmVarDecl>(var) && 13733 isa<TranslationUnitDecl>(VarDC)) 13734 return; 13735 13736 // For C code, don't diagnose about capture if we're not actually in code 13737 // right now; it's impossible to write a non-constant expression outside of 13738 // function context, so we'll get other (more useful) diagnostics later. 13739 // 13740 // For C++, things get a bit more nasty... it would be nice to suppress this 13741 // diagnostic for certain cases like using a local variable in an array bound 13742 // for a member of a local class, but the correct predicate is not obvious. 13743 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 13744 return; 13745 13746 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 13747 unsigned ContextKind = 3; // unknown 13748 if (isa<CXXMethodDecl>(VarDC) && 13749 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 13750 ContextKind = 2; 13751 } else if (isa<FunctionDecl>(VarDC)) { 13752 ContextKind = 0; 13753 } else if (isa<BlockDecl>(VarDC)) { 13754 ContextKind = 1; 13755 } 13756 13757 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 13758 << var << ValueKind << ContextKind << VarDC; 13759 S.Diag(var->getLocation(), diag::note_entity_declared_at) 13760 << var; 13761 13762 // FIXME: Add additional diagnostic info about class etc. which prevents 13763 // capture. 13764 } 13765 13766 13767 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 13768 bool &SubCapturesAreNested, 13769 QualType &CaptureType, 13770 QualType &DeclRefType) { 13771 // Check whether we've already captured it. 13772 if (CSI->CaptureMap.count(Var)) { 13773 // If we found a capture, any subcaptures are nested. 13774 SubCapturesAreNested = true; 13775 13776 // Retrieve the capture type for this variable. 13777 CaptureType = CSI->getCapture(Var).getCaptureType(); 13778 13779 // Compute the type of an expression that refers to this variable. 13780 DeclRefType = CaptureType.getNonReferenceType(); 13781 13782 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 13783 // are mutable in the sense that user can change their value - they are 13784 // private instances of the captured declarations. 13785 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 13786 if (Cap.isCopyCapture() && 13787 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 13788 !(isa<CapturedRegionScopeInfo>(CSI) && 13789 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 13790 DeclRefType.addConst(); 13791 return true; 13792 } 13793 return false; 13794 } 13795 13796 // Only block literals, captured statements, and lambda expressions can 13797 // capture; other scopes don't work. 13798 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 13799 SourceLocation Loc, 13800 const bool Diagnose, Sema &S) { 13801 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 13802 return getLambdaAwareParentOfDeclContext(DC); 13803 else if (Var->hasLocalStorage()) { 13804 if (Diagnose) 13805 diagnoseUncapturableValueReference(S, Loc, Var, DC); 13806 } 13807 return nullptr; 13808 } 13809 13810 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 13811 // certain types of variables (unnamed, variably modified types etc.) 13812 // so check for eligibility. 13813 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 13814 SourceLocation Loc, 13815 const bool Diagnose, Sema &S) { 13816 13817 bool IsBlock = isa<BlockScopeInfo>(CSI); 13818 bool IsLambda = isa<LambdaScopeInfo>(CSI); 13819 13820 // Lambdas are not allowed to capture unnamed variables 13821 // (e.g. anonymous unions). 13822 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 13823 // assuming that's the intent. 13824 if (IsLambda && !Var->getDeclName()) { 13825 if (Diagnose) { 13826 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 13827 S.Diag(Var->getLocation(), diag::note_declared_at); 13828 } 13829 return false; 13830 } 13831 13832 // Prohibit variably-modified types in blocks; they're difficult to deal with. 13833 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 13834 if (Diagnose) { 13835 S.Diag(Loc, diag::err_ref_vm_type); 13836 S.Diag(Var->getLocation(), diag::note_previous_decl) 13837 << Var->getDeclName(); 13838 } 13839 return false; 13840 } 13841 // Prohibit structs with flexible array members too. 13842 // We cannot capture what is in the tail end of the struct. 13843 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 13844 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 13845 if (Diagnose) { 13846 if (IsBlock) 13847 S.Diag(Loc, diag::err_ref_flexarray_type); 13848 else 13849 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 13850 << Var->getDeclName(); 13851 S.Diag(Var->getLocation(), diag::note_previous_decl) 13852 << Var->getDeclName(); 13853 } 13854 return false; 13855 } 13856 } 13857 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 13858 // Lambdas and captured statements are not allowed to capture __block 13859 // variables; they don't support the expected semantics. 13860 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 13861 if (Diagnose) { 13862 S.Diag(Loc, diag::err_capture_block_variable) 13863 << Var->getDeclName() << !IsLambda; 13864 S.Diag(Var->getLocation(), diag::note_previous_decl) 13865 << Var->getDeclName(); 13866 } 13867 return false; 13868 } 13869 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 13870 if (S.getLangOpts().OpenCL && IsBlock && 13871 Var->getType()->isBlockPointerType()) { 13872 if (Diagnose) 13873 S.Diag(Loc, diag::err_opencl_block_ref_block); 13874 return false; 13875 } 13876 13877 return true; 13878 } 13879 13880 // Returns true if the capture by block was successful. 13881 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 13882 SourceLocation Loc, 13883 const bool BuildAndDiagnose, 13884 QualType &CaptureType, 13885 QualType &DeclRefType, 13886 const bool Nested, 13887 Sema &S) { 13888 Expr *CopyExpr = nullptr; 13889 bool ByRef = false; 13890 13891 // Blocks are not allowed to capture arrays. 13892 if (CaptureType->isArrayType()) { 13893 if (BuildAndDiagnose) { 13894 S.Diag(Loc, diag::err_ref_array_type); 13895 S.Diag(Var->getLocation(), diag::note_previous_decl) 13896 << Var->getDeclName(); 13897 } 13898 return false; 13899 } 13900 13901 // Forbid the block-capture of autoreleasing variables. 13902 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 13903 if (BuildAndDiagnose) { 13904 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 13905 << /*block*/ 0; 13906 S.Diag(Var->getLocation(), diag::note_previous_decl) 13907 << Var->getDeclName(); 13908 } 13909 return false; 13910 } 13911 13912 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 13913 if (const auto *PT = CaptureType->getAs<PointerType>()) { 13914 // This function finds out whether there is an AttributedType of kind 13915 // attr_objc_ownership in Ty. The existence of AttributedType of kind 13916 // attr_objc_ownership implies __autoreleasing was explicitly specified 13917 // rather than being added implicitly by the compiler. 13918 auto IsObjCOwnershipAttributedType = [](QualType Ty) { 13919 while (const auto *AttrTy = Ty->getAs<AttributedType>()) { 13920 if (AttrTy->getAttrKind() == AttributedType::attr_objc_ownership) 13921 return true; 13922 13923 // Peel off AttributedTypes that are not of kind objc_ownership. 13924 Ty = AttrTy->getModifiedType(); 13925 } 13926 13927 return false; 13928 }; 13929 13930 QualType PointeeTy = PT->getPointeeType(); 13931 13932 if (PointeeTy->getAs<ObjCObjectPointerType>() && 13933 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 13934 !IsObjCOwnershipAttributedType(PointeeTy)) { 13935 if (BuildAndDiagnose) { 13936 SourceLocation VarLoc = Var->getLocation(); 13937 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 13938 { 13939 auto AddAutoreleaseNote = 13940 S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing); 13941 // Provide a fix-it for the '__autoreleasing' keyword at the 13942 // appropriate location in the variable's type. 13943 if (const auto *TSI = Var->getTypeSourceInfo()) { 13944 PointerTypeLoc PTL = 13945 TSI->getTypeLoc().getAsAdjusted<PointerTypeLoc>(); 13946 if (PTL) { 13947 SourceLocation Loc = PTL.getPointeeLoc().getEndLoc(); 13948 Loc = Lexer::getLocForEndOfToken(Loc, 0, S.getSourceManager(), 13949 S.getLangOpts()); 13950 if (Loc.isValid()) { 13951 StringRef CharAtLoc = Lexer::getSourceText( 13952 CharSourceRange::getCharRange(Loc, Loc.getLocWithOffset(1)), 13953 S.getSourceManager(), S.getLangOpts()); 13954 AddAutoreleaseNote << FixItHint::CreateInsertion( 13955 Loc, CharAtLoc.empty() || !isWhitespace(CharAtLoc[0]) 13956 ? " __autoreleasing " 13957 : " __autoreleasing"); 13958 } 13959 } 13960 } 13961 } 13962 S.Diag(VarLoc, diag::note_declare_parameter_strong); 13963 } 13964 } 13965 } 13966 13967 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 13968 if (HasBlocksAttr || CaptureType->isReferenceType() || 13969 (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) { 13970 // Block capture by reference does not change the capture or 13971 // declaration reference types. 13972 ByRef = true; 13973 } else { 13974 // Block capture by copy introduces 'const'. 13975 CaptureType = CaptureType.getNonReferenceType().withConst(); 13976 DeclRefType = CaptureType; 13977 13978 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 13979 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 13980 // The capture logic needs the destructor, so make sure we mark it. 13981 // Usually this is unnecessary because most local variables have 13982 // their destructors marked at declaration time, but parameters are 13983 // an exception because it's technically only the call site that 13984 // actually requires the destructor. 13985 if (isa<ParmVarDecl>(Var)) 13986 S.FinalizeVarWithDestructor(Var, Record); 13987 13988 // Enter a new evaluation context to insulate the copy 13989 // full-expression. 13990 EnterExpressionEvaluationContext scope( 13991 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 13992 13993 // According to the blocks spec, the capture of a variable from 13994 // the stack requires a const copy constructor. This is not true 13995 // of the copy/move done to move a __block variable to the heap. 13996 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 13997 DeclRefType.withConst(), 13998 VK_LValue, Loc); 13999 14000 ExprResult Result 14001 = S.PerformCopyInitialization( 14002 InitializedEntity::InitializeBlock(Var->getLocation(), 14003 CaptureType, false), 14004 Loc, DeclRef); 14005 14006 // Build a full-expression copy expression if initialization 14007 // succeeded and used a non-trivial constructor. Recover from 14008 // errors by pretending that the copy isn't necessary. 14009 if (!Result.isInvalid() && 14010 !cast<CXXConstructExpr>(Result.get())->getConstructor() 14011 ->isTrivial()) { 14012 Result = S.MaybeCreateExprWithCleanups(Result); 14013 CopyExpr = Result.get(); 14014 } 14015 } 14016 } 14017 } 14018 14019 // Actually capture the variable. 14020 if (BuildAndDiagnose) 14021 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 14022 SourceLocation(), CaptureType, CopyExpr); 14023 14024 return true; 14025 14026 } 14027 14028 14029 /// \brief Capture the given variable in the captured region. 14030 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 14031 VarDecl *Var, 14032 SourceLocation Loc, 14033 const bool BuildAndDiagnose, 14034 QualType &CaptureType, 14035 QualType &DeclRefType, 14036 const bool RefersToCapturedVariable, 14037 Sema &S) { 14038 // By default, capture variables by reference. 14039 bool ByRef = true; 14040 // Using an LValue reference type is consistent with Lambdas (see below). 14041 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 14042 if (S.IsOpenMPCapturedDecl(Var)) 14043 DeclRefType = DeclRefType.getUnqualifiedType(); 14044 ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel); 14045 } 14046 14047 if (ByRef) 14048 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 14049 else 14050 CaptureType = DeclRefType; 14051 14052 Expr *CopyExpr = nullptr; 14053 if (BuildAndDiagnose) { 14054 // The current implementation assumes that all variables are captured 14055 // by references. Since there is no capture by copy, no expression 14056 // evaluation will be needed. 14057 RecordDecl *RD = RSI->TheRecordDecl; 14058 14059 FieldDecl *Field 14060 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 14061 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 14062 nullptr, false, ICIS_NoInit); 14063 Field->setImplicit(true); 14064 Field->setAccess(AS_private); 14065 RD->addDecl(Field); 14066 14067 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, 14068 DeclRefType, VK_LValue, Loc); 14069 Var->setReferenced(true); 14070 Var->markUsed(S.Context); 14071 } 14072 14073 // Actually capture the variable. 14074 if (BuildAndDiagnose) 14075 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 14076 SourceLocation(), CaptureType, CopyExpr); 14077 14078 14079 return true; 14080 } 14081 14082 /// \brief Create a field within the lambda class for the variable 14083 /// being captured. 14084 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, 14085 QualType FieldType, QualType DeclRefType, 14086 SourceLocation Loc, 14087 bool RefersToCapturedVariable) { 14088 CXXRecordDecl *Lambda = LSI->Lambda; 14089 14090 // Build the non-static data member. 14091 FieldDecl *Field 14092 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 14093 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 14094 nullptr, false, ICIS_NoInit); 14095 Field->setImplicit(true); 14096 Field->setAccess(AS_private); 14097 Lambda->addDecl(Field); 14098 } 14099 14100 /// \brief Capture the given variable in the lambda. 14101 static bool captureInLambda(LambdaScopeInfo *LSI, 14102 VarDecl *Var, 14103 SourceLocation Loc, 14104 const bool BuildAndDiagnose, 14105 QualType &CaptureType, 14106 QualType &DeclRefType, 14107 const bool RefersToCapturedVariable, 14108 const Sema::TryCaptureKind Kind, 14109 SourceLocation EllipsisLoc, 14110 const bool IsTopScope, 14111 Sema &S) { 14112 14113 // Determine whether we are capturing by reference or by value. 14114 bool ByRef = false; 14115 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 14116 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 14117 } else { 14118 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 14119 } 14120 14121 // Compute the type of the field that will capture this variable. 14122 if (ByRef) { 14123 // C++11 [expr.prim.lambda]p15: 14124 // An entity is captured by reference if it is implicitly or 14125 // explicitly captured but not captured by copy. It is 14126 // unspecified whether additional unnamed non-static data 14127 // members are declared in the closure type for entities 14128 // captured by reference. 14129 // 14130 // FIXME: It is not clear whether we want to build an lvalue reference 14131 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 14132 // to do the former, while EDG does the latter. Core issue 1249 will 14133 // clarify, but for now we follow GCC because it's a more permissive and 14134 // easily defensible position. 14135 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 14136 } else { 14137 // C++11 [expr.prim.lambda]p14: 14138 // For each entity captured by copy, an unnamed non-static 14139 // data member is declared in the closure type. The 14140 // declaration order of these members is unspecified. The type 14141 // of such a data member is the type of the corresponding 14142 // captured entity if the entity is not a reference to an 14143 // object, or the referenced type otherwise. [Note: If the 14144 // captured entity is a reference to a function, the 14145 // corresponding data member is also a reference to a 14146 // function. - end note ] 14147 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 14148 if (!RefType->getPointeeType()->isFunctionType()) 14149 CaptureType = RefType->getPointeeType(); 14150 } 14151 14152 // Forbid the lambda copy-capture of autoreleasing variables. 14153 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 14154 if (BuildAndDiagnose) { 14155 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 14156 S.Diag(Var->getLocation(), diag::note_previous_decl) 14157 << Var->getDeclName(); 14158 } 14159 return false; 14160 } 14161 14162 // Make sure that by-copy captures are of a complete and non-abstract type. 14163 if (BuildAndDiagnose) { 14164 if (!CaptureType->isDependentType() && 14165 S.RequireCompleteType(Loc, CaptureType, 14166 diag::err_capture_of_incomplete_type, 14167 Var->getDeclName())) 14168 return false; 14169 14170 if (S.RequireNonAbstractType(Loc, CaptureType, 14171 diag::err_capture_of_abstract_type)) 14172 return false; 14173 } 14174 } 14175 14176 // Capture this variable in the lambda. 14177 if (BuildAndDiagnose) 14178 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc, 14179 RefersToCapturedVariable); 14180 14181 // Compute the type of a reference to this captured variable. 14182 if (ByRef) 14183 DeclRefType = CaptureType.getNonReferenceType(); 14184 else { 14185 // C++ [expr.prim.lambda]p5: 14186 // The closure type for a lambda-expression has a public inline 14187 // function call operator [...]. This function call operator is 14188 // declared const (9.3.1) if and only if the lambda-expression's 14189 // parameter-declaration-clause is not followed by mutable. 14190 DeclRefType = CaptureType.getNonReferenceType(); 14191 if (!LSI->Mutable && !CaptureType->isReferenceType()) 14192 DeclRefType.addConst(); 14193 } 14194 14195 // Add the capture. 14196 if (BuildAndDiagnose) 14197 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 14198 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 14199 14200 return true; 14201 } 14202 14203 bool Sema::tryCaptureVariable( 14204 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 14205 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 14206 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 14207 // An init-capture is notionally from the context surrounding its 14208 // declaration, but its parent DC is the lambda class. 14209 DeclContext *VarDC = Var->getDeclContext(); 14210 if (Var->isInitCapture()) 14211 VarDC = VarDC->getParent(); 14212 14213 DeclContext *DC = CurContext; 14214 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 14215 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 14216 // We need to sync up the Declaration Context with the 14217 // FunctionScopeIndexToStopAt 14218 if (FunctionScopeIndexToStopAt) { 14219 unsigned FSIndex = FunctionScopes.size() - 1; 14220 while (FSIndex != MaxFunctionScopesIndex) { 14221 DC = getLambdaAwareParentOfDeclContext(DC); 14222 --FSIndex; 14223 } 14224 } 14225 14226 14227 // If the variable is declared in the current context, there is no need to 14228 // capture it. 14229 if (VarDC == DC) return true; 14230 14231 // Capture global variables if it is required to use private copy of this 14232 // variable. 14233 bool IsGlobal = !Var->hasLocalStorage(); 14234 if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var))) 14235 return true; 14236 14237 // Walk up the stack to determine whether we can capture the variable, 14238 // performing the "simple" checks that don't depend on type. We stop when 14239 // we've either hit the declared scope of the variable or find an existing 14240 // capture of that variable. We start from the innermost capturing-entity 14241 // (the DC) and ensure that all intervening capturing-entities 14242 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 14243 // declcontext can either capture the variable or have already captured 14244 // the variable. 14245 CaptureType = Var->getType(); 14246 DeclRefType = CaptureType.getNonReferenceType(); 14247 bool Nested = false; 14248 bool Explicit = (Kind != TryCapture_Implicit); 14249 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 14250 do { 14251 // Only block literals, captured statements, and lambda expressions can 14252 // capture; other scopes don't work. 14253 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 14254 ExprLoc, 14255 BuildAndDiagnose, 14256 *this); 14257 // We need to check for the parent *first* because, if we *have* 14258 // private-captured a global variable, we need to recursively capture it in 14259 // intermediate blocks, lambdas, etc. 14260 if (!ParentDC) { 14261 if (IsGlobal) { 14262 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 14263 break; 14264 } 14265 return true; 14266 } 14267 14268 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 14269 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 14270 14271 14272 // Check whether we've already captured it. 14273 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 14274 DeclRefType)) { 14275 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 14276 break; 14277 } 14278 // If we are instantiating a generic lambda call operator body, 14279 // we do not want to capture new variables. What was captured 14280 // during either a lambdas transformation or initial parsing 14281 // should be used. 14282 if (isGenericLambdaCallOperatorSpecialization(DC)) { 14283 if (BuildAndDiagnose) { 14284 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 14285 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 14286 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 14287 Diag(Var->getLocation(), diag::note_previous_decl) 14288 << Var->getDeclName(); 14289 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); 14290 } else 14291 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 14292 } 14293 return true; 14294 } 14295 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 14296 // certain types of variables (unnamed, variably modified types etc.) 14297 // so check for eligibility. 14298 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 14299 return true; 14300 14301 // Try to capture variable-length arrays types. 14302 if (Var->getType()->isVariablyModifiedType()) { 14303 // We're going to walk down into the type and look for VLA 14304 // expressions. 14305 QualType QTy = Var->getType(); 14306 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 14307 QTy = PVD->getOriginalType(); 14308 captureVariablyModifiedType(Context, QTy, CSI); 14309 } 14310 14311 if (getLangOpts().OpenMP) { 14312 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 14313 // OpenMP private variables should not be captured in outer scope, so 14314 // just break here. Similarly, global variables that are captured in a 14315 // target region should not be captured outside the scope of the region. 14316 if (RSI->CapRegionKind == CR_OpenMP) { 14317 auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 14318 // When we detect target captures we are looking from inside the 14319 // target region, therefore we need to propagate the capture from the 14320 // enclosing region. Therefore, the capture is not initially nested. 14321 if (IsTargetCap) 14322 FunctionScopesIndex--; 14323 14324 if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) { 14325 Nested = !IsTargetCap; 14326 DeclRefType = DeclRefType.getUnqualifiedType(); 14327 CaptureType = Context.getLValueReferenceType(DeclRefType); 14328 break; 14329 } 14330 } 14331 } 14332 } 14333 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 14334 // No capture-default, and this is not an explicit capture 14335 // so cannot capture this variable. 14336 if (BuildAndDiagnose) { 14337 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 14338 Diag(Var->getLocation(), diag::note_previous_decl) 14339 << Var->getDeclName(); 14340 if (cast<LambdaScopeInfo>(CSI)->Lambda) 14341 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 14342 diag::note_lambda_decl); 14343 // FIXME: If we error out because an outer lambda can not implicitly 14344 // capture a variable that an inner lambda explicitly captures, we 14345 // should have the inner lambda do the explicit capture - because 14346 // it makes for cleaner diagnostics later. This would purely be done 14347 // so that the diagnostic does not misleadingly claim that a variable 14348 // can not be captured by a lambda implicitly even though it is captured 14349 // explicitly. Suggestion: 14350 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 14351 // at the function head 14352 // - cache the StartingDeclContext - this must be a lambda 14353 // - captureInLambda in the innermost lambda the variable. 14354 } 14355 return true; 14356 } 14357 14358 FunctionScopesIndex--; 14359 DC = ParentDC; 14360 Explicit = false; 14361 } while (!VarDC->Equals(DC)); 14362 14363 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 14364 // computing the type of the capture at each step, checking type-specific 14365 // requirements, and adding captures if requested. 14366 // If the variable had already been captured previously, we start capturing 14367 // at the lambda nested within that one. 14368 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 14369 ++I) { 14370 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 14371 14372 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 14373 if (!captureInBlock(BSI, Var, ExprLoc, 14374 BuildAndDiagnose, CaptureType, 14375 DeclRefType, Nested, *this)) 14376 return true; 14377 Nested = true; 14378 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 14379 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 14380 BuildAndDiagnose, CaptureType, 14381 DeclRefType, Nested, *this)) 14382 return true; 14383 Nested = true; 14384 } else { 14385 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 14386 if (!captureInLambda(LSI, Var, ExprLoc, 14387 BuildAndDiagnose, CaptureType, 14388 DeclRefType, Nested, Kind, EllipsisLoc, 14389 /*IsTopScope*/I == N - 1, *this)) 14390 return true; 14391 Nested = true; 14392 } 14393 } 14394 return false; 14395 } 14396 14397 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 14398 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 14399 QualType CaptureType; 14400 QualType DeclRefType; 14401 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 14402 /*BuildAndDiagnose=*/true, CaptureType, 14403 DeclRefType, nullptr); 14404 } 14405 14406 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 14407 QualType CaptureType; 14408 QualType DeclRefType; 14409 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 14410 /*BuildAndDiagnose=*/false, CaptureType, 14411 DeclRefType, nullptr); 14412 } 14413 14414 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 14415 QualType CaptureType; 14416 QualType DeclRefType; 14417 14418 // Determine whether we can capture this variable. 14419 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 14420 /*BuildAndDiagnose=*/false, CaptureType, 14421 DeclRefType, nullptr)) 14422 return QualType(); 14423 14424 return DeclRefType; 14425 } 14426 14427 14428 14429 // If either the type of the variable or the initializer is dependent, 14430 // return false. Otherwise, determine whether the variable is a constant 14431 // expression. Use this if you need to know if a variable that might or 14432 // might not be dependent is truly a constant expression. 14433 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 14434 ASTContext &Context) { 14435 14436 if (Var->getType()->isDependentType()) 14437 return false; 14438 const VarDecl *DefVD = nullptr; 14439 Var->getAnyInitializer(DefVD); 14440 if (!DefVD) 14441 return false; 14442 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 14443 Expr *Init = cast<Expr>(Eval->Value); 14444 if (Init->isValueDependent()) 14445 return false; 14446 return IsVariableAConstantExpression(Var, Context); 14447 } 14448 14449 14450 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 14451 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 14452 // an object that satisfies the requirements for appearing in a 14453 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 14454 // is immediately applied." This function handles the lvalue-to-rvalue 14455 // conversion part. 14456 MaybeODRUseExprs.erase(E->IgnoreParens()); 14457 14458 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 14459 // to a variable that is a constant expression, and if so, identify it as 14460 // a reference to a variable that does not involve an odr-use of that 14461 // variable. 14462 if (LambdaScopeInfo *LSI = getCurLambda()) { 14463 Expr *SansParensExpr = E->IgnoreParens(); 14464 VarDecl *Var = nullptr; 14465 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 14466 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 14467 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 14468 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 14469 14470 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 14471 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 14472 } 14473 } 14474 14475 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 14476 Res = CorrectDelayedTyposInExpr(Res); 14477 14478 if (!Res.isUsable()) 14479 return Res; 14480 14481 // If a constant-expression is a reference to a variable where we delay 14482 // deciding whether it is an odr-use, just assume we will apply the 14483 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 14484 // (a non-type template argument), we have special handling anyway. 14485 UpdateMarkingForLValueToRValue(Res.get()); 14486 return Res; 14487 } 14488 14489 void Sema::CleanupVarDeclMarking() { 14490 for (Expr *E : MaybeODRUseExprs) { 14491 VarDecl *Var; 14492 SourceLocation Loc; 14493 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 14494 Var = cast<VarDecl>(DRE->getDecl()); 14495 Loc = DRE->getLocation(); 14496 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 14497 Var = cast<VarDecl>(ME->getMemberDecl()); 14498 Loc = ME->getMemberLoc(); 14499 } else { 14500 llvm_unreachable("Unexpected expression"); 14501 } 14502 14503 MarkVarDeclODRUsed(Var, Loc, *this, 14504 /*MaxFunctionScopeIndex Pointer*/ nullptr); 14505 } 14506 14507 MaybeODRUseExprs.clear(); 14508 } 14509 14510 14511 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 14512 VarDecl *Var, Expr *E) { 14513 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 14514 "Invalid Expr argument to DoMarkVarDeclReferenced"); 14515 Var->setReferenced(); 14516 14517 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 14518 14519 bool OdrUseContext = isOdrUseContext(SemaRef); 14520 bool NeedDefinition = 14521 OdrUseContext || (isEvaluatableContext(SemaRef) && 14522 Var->isUsableInConstantExpressions(SemaRef.Context)); 14523 14524 VarTemplateSpecializationDecl *VarSpec = 14525 dyn_cast<VarTemplateSpecializationDecl>(Var); 14526 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 14527 "Can't instantiate a partial template specialization."); 14528 14529 // If this might be a member specialization of a static data member, check 14530 // the specialization is visible. We already did the checks for variable 14531 // template specializations when we created them. 14532 if (NeedDefinition && TSK != TSK_Undeclared && 14533 !isa<VarTemplateSpecializationDecl>(Var)) 14534 SemaRef.checkSpecializationVisibility(Loc, Var); 14535 14536 // Perform implicit instantiation of static data members, static data member 14537 // templates of class templates, and variable template specializations. Delay 14538 // instantiations of variable templates, except for those that could be used 14539 // in a constant expression. 14540 if (NeedDefinition && isTemplateInstantiation(TSK)) { 14541 bool TryInstantiating = TSK == TSK_ImplicitInstantiation; 14542 14543 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) { 14544 if (Var->getPointOfInstantiation().isInvalid()) { 14545 // This is a modification of an existing AST node. Notify listeners. 14546 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 14547 L->StaticDataMemberInstantiated(Var); 14548 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context)) 14549 // Don't bother trying to instantiate it again, unless we might need 14550 // its initializer before we get to the end of the TU. 14551 TryInstantiating = false; 14552 } 14553 14554 if (Var->getPointOfInstantiation().isInvalid()) 14555 Var->setTemplateSpecializationKind(TSK, Loc); 14556 14557 if (TryInstantiating) { 14558 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 14559 bool InstantiationDependent = false; 14560 bool IsNonDependent = 14561 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 14562 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 14563 : true; 14564 14565 // Do not instantiate specializations that are still type-dependent. 14566 if (IsNonDependent) { 14567 if (Var->isUsableInConstantExpressions(SemaRef.Context)) { 14568 // Do not defer instantiations of variables which could be used in a 14569 // constant expression. 14570 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 14571 } else { 14572 SemaRef.PendingInstantiations 14573 .push_back(std::make_pair(Var, PointOfInstantiation)); 14574 } 14575 } 14576 } 14577 } 14578 14579 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 14580 // the requirements for appearing in a constant expression (5.19) and, if 14581 // it is an object, the lvalue-to-rvalue conversion (4.1) 14582 // is immediately applied." We check the first part here, and 14583 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 14584 // Note that we use the C++11 definition everywhere because nothing in 14585 // C++03 depends on whether we get the C++03 version correct. The second 14586 // part does not apply to references, since they are not objects. 14587 if (OdrUseContext && E && 14588 IsVariableAConstantExpression(Var, SemaRef.Context)) { 14589 // A reference initialized by a constant expression can never be 14590 // odr-used, so simply ignore it. 14591 if (!Var->getType()->isReferenceType()) 14592 SemaRef.MaybeODRUseExprs.insert(E); 14593 } else if (OdrUseContext) { 14594 MarkVarDeclODRUsed(Var, Loc, SemaRef, 14595 /*MaxFunctionScopeIndex ptr*/ nullptr); 14596 } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) { 14597 // If this is a dependent context, we don't need to mark variables as 14598 // odr-used, but we may still need to track them for lambda capture. 14599 // FIXME: Do we also need to do this inside dependent typeid expressions 14600 // (which are modeled as unevaluated at this point)? 14601 const bool RefersToEnclosingScope = 14602 (SemaRef.CurContext != Var->getDeclContext() && 14603 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 14604 if (RefersToEnclosingScope) { 14605 LambdaScopeInfo *const LSI = 14606 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 14607 if (LSI && !LSI->CallOperator->Encloses(Var->getDeclContext())) { 14608 // If a variable could potentially be odr-used, defer marking it so 14609 // until we finish analyzing the full expression for any 14610 // lvalue-to-rvalue 14611 // or discarded value conversions that would obviate odr-use. 14612 // Add it to the list of potential captures that will be analyzed 14613 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 14614 // unless the variable is a reference that was initialized by a constant 14615 // expression (this will never need to be captured or odr-used). 14616 assert(E && "Capture variable should be used in an expression."); 14617 if (!Var->getType()->isReferenceType() || 14618 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 14619 LSI->addPotentialCapture(E->IgnoreParens()); 14620 } 14621 } 14622 } 14623 } 14624 14625 /// \brief Mark a variable referenced, and check whether it is odr-used 14626 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 14627 /// used directly for normal expressions referring to VarDecl. 14628 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 14629 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 14630 } 14631 14632 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 14633 Decl *D, Expr *E, bool MightBeOdrUse) { 14634 if (SemaRef.isInOpenMPDeclareTargetContext()) 14635 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 14636 14637 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 14638 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 14639 return; 14640 } 14641 14642 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 14643 14644 // If this is a call to a method via a cast, also mark the method in the 14645 // derived class used in case codegen can devirtualize the call. 14646 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 14647 if (!ME) 14648 return; 14649 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 14650 if (!MD) 14651 return; 14652 // Only attempt to devirtualize if this is truly a virtual call. 14653 bool IsVirtualCall = MD->isVirtual() && 14654 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 14655 if (!IsVirtualCall) 14656 return; 14657 const Expr *Base = ME->getBase(); 14658 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType(); 14659 if (!MostDerivedClassDecl) 14660 return; 14661 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl); 14662 if (!DM || DM->isPure()) 14663 return; 14664 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 14665 } 14666 14667 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 14668 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) { 14669 // TODO: update this with DR# once a defect report is filed. 14670 // C++11 defect. The address of a pure member should not be an ODR use, even 14671 // if it's a qualified reference. 14672 bool OdrUse = true; 14673 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 14674 if (Method->isVirtual()) 14675 OdrUse = false; 14676 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 14677 } 14678 14679 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 14680 void Sema::MarkMemberReferenced(MemberExpr *E) { 14681 // C++11 [basic.def.odr]p2: 14682 // A non-overloaded function whose name appears as a potentially-evaluated 14683 // expression or a member of a set of candidate functions, if selected by 14684 // overload resolution when referred to from a potentially-evaluated 14685 // expression, is odr-used, unless it is a pure virtual function and its 14686 // name is not explicitly qualified. 14687 bool MightBeOdrUse = true; 14688 if (E->performsVirtualDispatch(getLangOpts())) { 14689 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 14690 if (Method->isPure()) 14691 MightBeOdrUse = false; 14692 } 14693 SourceLocation Loc = E->getMemberLoc().isValid() ? 14694 E->getMemberLoc() : E->getLocStart(); 14695 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 14696 } 14697 14698 /// \brief Perform marking for a reference to an arbitrary declaration. It 14699 /// marks the declaration referenced, and performs odr-use checking for 14700 /// functions and variables. This method should not be used when building a 14701 /// normal expression which refers to a variable. 14702 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 14703 bool MightBeOdrUse) { 14704 if (MightBeOdrUse) { 14705 if (auto *VD = dyn_cast<VarDecl>(D)) { 14706 MarkVariableReferenced(Loc, VD); 14707 return; 14708 } 14709 } 14710 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 14711 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 14712 return; 14713 } 14714 D->setReferenced(); 14715 } 14716 14717 namespace { 14718 // Mark all of the declarations used by a type as referenced. 14719 // FIXME: Not fully implemented yet! We need to have a better understanding 14720 // of when we're entering a context we should not recurse into. 14721 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 14722 // TreeTransforms rebuilding the type in a new context. Rather than 14723 // duplicating the TreeTransform logic, we should consider reusing it here. 14724 // Currently that causes problems when rebuilding LambdaExprs. 14725 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 14726 Sema &S; 14727 SourceLocation Loc; 14728 14729 public: 14730 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 14731 14732 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 14733 14734 bool TraverseTemplateArgument(const TemplateArgument &Arg); 14735 }; 14736 } 14737 14738 bool MarkReferencedDecls::TraverseTemplateArgument( 14739 const TemplateArgument &Arg) { 14740 { 14741 // A non-type template argument is a constant-evaluated context. 14742 EnterExpressionEvaluationContext Evaluated( 14743 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 14744 if (Arg.getKind() == TemplateArgument::Declaration) { 14745 if (Decl *D = Arg.getAsDecl()) 14746 S.MarkAnyDeclReferenced(Loc, D, true); 14747 } else if (Arg.getKind() == TemplateArgument::Expression) { 14748 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 14749 } 14750 } 14751 14752 return Inherited::TraverseTemplateArgument(Arg); 14753 } 14754 14755 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 14756 MarkReferencedDecls Marker(*this, Loc); 14757 Marker.TraverseType(T); 14758 } 14759 14760 namespace { 14761 /// \brief Helper class that marks all of the declarations referenced by 14762 /// potentially-evaluated subexpressions as "referenced". 14763 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 14764 Sema &S; 14765 bool SkipLocalVariables; 14766 14767 public: 14768 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 14769 14770 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 14771 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 14772 14773 void VisitDeclRefExpr(DeclRefExpr *E) { 14774 // If we were asked not to visit local variables, don't. 14775 if (SkipLocalVariables) { 14776 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 14777 if (VD->hasLocalStorage()) 14778 return; 14779 } 14780 14781 S.MarkDeclRefReferenced(E); 14782 } 14783 14784 void VisitMemberExpr(MemberExpr *E) { 14785 S.MarkMemberReferenced(E); 14786 Inherited::VisitMemberExpr(E); 14787 } 14788 14789 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 14790 S.MarkFunctionReferenced(E->getLocStart(), 14791 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 14792 Visit(E->getSubExpr()); 14793 } 14794 14795 void VisitCXXNewExpr(CXXNewExpr *E) { 14796 if (E->getOperatorNew()) 14797 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 14798 if (E->getOperatorDelete()) 14799 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 14800 Inherited::VisitCXXNewExpr(E); 14801 } 14802 14803 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 14804 if (E->getOperatorDelete()) 14805 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 14806 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 14807 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 14808 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 14809 S.MarkFunctionReferenced(E->getLocStart(), 14810 S.LookupDestructor(Record)); 14811 } 14812 14813 Inherited::VisitCXXDeleteExpr(E); 14814 } 14815 14816 void VisitCXXConstructExpr(CXXConstructExpr *E) { 14817 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 14818 Inherited::VisitCXXConstructExpr(E); 14819 } 14820 14821 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 14822 Visit(E->getExpr()); 14823 } 14824 14825 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 14826 Inherited::VisitImplicitCastExpr(E); 14827 14828 if (E->getCastKind() == CK_LValueToRValue) 14829 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 14830 } 14831 }; 14832 } 14833 14834 /// \brief Mark any declarations that appear within this expression or any 14835 /// potentially-evaluated subexpressions as "referenced". 14836 /// 14837 /// \param SkipLocalVariables If true, don't mark local variables as 14838 /// 'referenced'. 14839 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 14840 bool SkipLocalVariables) { 14841 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 14842 } 14843 14844 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 14845 /// of the program being compiled. 14846 /// 14847 /// This routine emits the given diagnostic when the code currently being 14848 /// type-checked is "potentially evaluated", meaning that there is a 14849 /// possibility that the code will actually be executable. Code in sizeof() 14850 /// expressions, code used only during overload resolution, etc., are not 14851 /// potentially evaluated. This routine will suppress such diagnostics or, 14852 /// in the absolutely nutty case of potentially potentially evaluated 14853 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 14854 /// later. 14855 /// 14856 /// This routine should be used for all diagnostics that describe the run-time 14857 /// behavior of a program, such as passing a non-POD value through an ellipsis. 14858 /// Failure to do so will likely result in spurious diagnostics or failures 14859 /// during overload resolution or within sizeof/alignof/typeof/typeid. 14860 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 14861 const PartialDiagnostic &PD) { 14862 switch (ExprEvalContexts.back().Context) { 14863 case ExpressionEvaluationContext::Unevaluated: 14864 case ExpressionEvaluationContext::UnevaluatedList: 14865 case ExpressionEvaluationContext::UnevaluatedAbstract: 14866 case ExpressionEvaluationContext::DiscardedStatement: 14867 // The argument will never be evaluated, so don't complain. 14868 break; 14869 14870 case ExpressionEvaluationContext::ConstantEvaluated: 14871 // Relevant diagnostics should be produced by constant evaluation. 14872 break; 14873 14874 case ExpressionEvaluationContext::PotentiallyEvaluated: 14875 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 14876 if (Statement && getCurFunctionOrMethodDecl()) { 14877 FunctionScopes.back()->PossiblyUnreachableDiags. 14878 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 14879 } 14880 else 14881 Diag(Loc, PD); 14882 14883 return true; 14884 } 14885 14886 return false; 14887 } 14888 14889 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 14890 CallExpr *CE, FunctionDecl *FD) { 14891 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 14892 return false; 14893 14894 // If we're inside a decltype's expression, don't check for a valid return 14895 // type or construct temporaries until we know whether this is the last call. 14896 if (ExprEvalContexts.back().IsDecltype) { 14897 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 14898 return false; 14899 } 14900 14901 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 14902 FunctionDecl *FD; 14903 CallExpr *CE; 14904 14905 public: 14906 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 14907 : FD(FD), CE(CE) { } 14908 14909 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 14910 if (!FD) { 14911 S.Diag(Loc, diag::err_call_incomplete_return) 14912 << T << CE->getSourceRange(); 14913 return; 14914 } 14915 14916 S.Diag(Loc, diag::err_call_function_incomplete_return) 14917 << CE->getSourceRange() << FD->getDeclName() << T; 14918 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 14919 << FD->getDeclName(); 14920 } 14921 } Diagnoser(FD, CE); 14922 14923 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 14924 return true; 14925 14926 return false; 14927 } 14928 14929 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 14930 // will prevent this condition from triggering, which is what we want. 14931 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 14932 SourceLocation Loc; 14933 14934 unsigned diagnostic = diag::warn_condition_is_assignment; 14935 bool IsOrAssign = false; 14936 14937 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 14938 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 14939 return; 14940 14941 IsOrAssign = Op->getOpcode() == BO_OrAssign; 14942 14943 // Greylist some idioms by putting them into a warning subcategory. 14944 if (ObjCMessageExpr *ME 14945 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 14946 Selector Sel = ME->getSelector(); 14947 14948 // self = [<foo> init...] 14949 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 14950 diagnostic = diag::warn_condition_is_idiomatic_assignment; 14951 14952 // <foo> = [<bar> nextObject] 14953 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 14954 diagnostic = diag::warn_condition_is_idiomatic_assignment; 14955 } 14956 14957 Loc = Op->getOperatorLoc(); 14958 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 14959 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 14960 return; 14961 14962 IsOrAssign = Op->getOperator() == OO_PipeEqual; 14963 Loc = Op->getOperatorLoc(); 14964 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 14965 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 14966 else { 14967 // Not an assignment. 14968 return; 14969 } 14970 14971 Diag(Loc, diagnostic) << E->getSourceRange(); 14972 14973 SourceLocation Open = E->getLocStart(); 14974 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 14975 Diag(Loc, diag::note_condition_assign_silence) 14976 << FixItHint::CreateInsertion(Open, "(") 14977 << FixItHint::CreateInsertion(Close, ")"); 14978 14979 if (IsOrAssign) 14980 Diag(Loc, diag::note_condition_or_assign_to_comparison) 14981 << FixItHint::CreateReplacement(Loc, "!="); 14982 else 14983 Diag(Loc, diag::note_condition_assign_to_comparison) 14984 << FixItHint::CreateReplacement(Loc, "=="); 14985 } 14986 14987 /// \brief Redundant parentheses over an equality comparison can indicate 14988 /// that the user intended an assignment used as condition. 14989 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 14990 // Don't warn if the parens came from a macro. 14991 SourceLocation parenLoc = ParenE->getLocStart(); 14992 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 14993 return; 14994 // Don't warn for dependent expressions. 14995 if (ParenE->isTypeDependent()) 14996 return; 14997 14998 Expr *E = ParenE->IgnoreParens(); 14999 15000 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 15001 if (opE->getOpcode() == BO_EQ && 15002 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 15003 == Expr::MLV_Valid) { 15004 SourceLocation Loc = opE->getOperatorLoc(); 15005 15006 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 15007 SourceRange ParenERange = ParenE->getSourceRange(); 15008 Diag(Loc, diag::note_equality_comparison_silence) 15009 << FixItHint::CreateRemoval(ParenERange.getBegin()) 15010 << FixItHint::CreateRemoval(ParenERange.getEnd()); 15011 Diag(Loc, diag::note_equality_comparison_to_assign) 15012 << FixItHint::CreateReplacement(Loc, "="); 15013 } 15014 } 15015 15016 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 15017 bool IsConstexpr) { 15018 DiagnoseAssignmentAsCondition(E); 15019 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 15020 DiagnoseEqualityWithExtraParens(parenE); 15021 15022 ExprResult result = CheckPlaceholderExpr(E); 15023 if (result.isInvalid()) return ExprError(); 15024 E = result.get(); 15025 15026 if (!E->isTypeDependent()) { 15027 if (getLangOpts().CPlusPlus) 15028 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 15029 15030 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 15031 if (ERes.isInvalid()) 15032 return ExprError(); 15033 E = ERes.get(); 15034 15035 QualType T = E->getType(); 15036 if (!T->isScalarType()) { // C99 6.8.4.1p1 15037 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 15038 << T << E->getSourceRange(); 15039 return ExprError(); 15040 } 15041 CheckBoolLikeConversion(E, Loc); 15042 } 15043 15044 return E; 15045 } 15046 15047 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 15048 Expr *SubExpr, ConditionKind CK) { 15049 // Empty conditions are valid in for-statements. 15050 if (!SubExpr) 15051 return ConditionResult(); 15052 15053 ExprResult Cond; 15054 switch (CK) { 15055 case ConditionKind::Boolean: 15056 Cond = CheckBooleanCondition(Loc, SubExpr); 15057 break; 15058 15059 case ConditionKind::ConstexprIf: 15060 Cond = CheckBooleanCondition(Loc, SubExpr, true); 15061 break; 15062 15063 case ConditionKind::Switch: 15064 Cond = CheckSwitchCondition(Loc, SubExpr); 15065 break; 15066 } 15067 if (Cond.isInvalid()) 15068 return ConditionError(); 15069 15070 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 15071 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 15072 if (!FullExpr.get()) 15073 return ConditionError(); 15074 15075 return ConditionResult(*this, nullptr, FullExpr, 15076 CK == ConditionKind::ConstexprIf); 15077 } 15078 15079 namespace { 15080 /// A visitor for rebuilding a call to an __unknown_any expression 15081 /// to have an appropriate type. 15082 struct RebuildUnknownAnyFunction 15083 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 15084 15085 Sema &S; 15086 15087 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 15088 15089 ExprResult VisitStmt(Stmt *S) { 15090 llvm_unreachable("unexpected statement!"); 15091 } 15092 15093 ExprResult VisitExpr(Expr *E) { 15094 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 15095 << E->getSourceRange(); 15096 return ExprError(); 15097 } 15098 15099 /// Rebuild an expression which simply semantically wraps another 15100 /// expression which it shares the type and value kind of. 15101 template <class T> ExprResult rebuildSugarExpr(T *E) { 15102 ExprResult SubResult = Visit(E->getSubExpr()); 15103 if (SubResult.isInvalid()) return ExprError(); 15104 15105 Expr *SubExpr = SubResult.get(); 15106 E->setSubExpr(SubExpr); 15107 E->setType(SubExpr->getType()); 15108 E->setValueKind(SubExpr->getValueKind()); 15109 assert(E->getObjectKind() == OK_Ordinary); 15110 return E; 15111 } 15112 15113 ExprResult VisitParenExpr(ParenExpr *E) { 15114 return rebuildSugarExpr(E); 15115 } 15116 15117 ExprResult VisitUnaryExtension(UnaryOperator *E) { 15118 return rebuildSugarExpr(E); 15119 } 15120 15121 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 15122 ExprResult SubResult = Visit(E->getSubExpr()); 15123 if (SubResult.isInvalid()) return ExprError(); 15124 15125 Expr *SubExpr = SubResult.get(); 15126 E->setSubExpr(SubExpr); 15127 E->setType(S.Context.getPointerType(SubExpr->getType())); 15128 assert(E->getValueKind() == VK_RValue); 15129 assert(E->getObjectKind() == OK_Ordinary); 15130 return E; 15131 } 15132 15133 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 15134 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 15135 15136 E->setType(VD->getType()); 15137 15138 assert(E->getValueKind() == VK_RValue); 15139 if (S.getLangOpts().CPlusPlus && 15140 !(isa<CXXMethodDecl>(VD) && 15141 cast<CXXMethodDecl>(VD)->isInstance())) 15142 E->setValueKind(VK_LValue); 15143 15144 return E; 15145 } 15146 15147 ExprResult VisitMemberExpr(MemberExpr *E) { 15148 return resolveDecl(E, E->getMemberDecl()); 15149 } 15150 15151 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 15152 return resolveDecl(E, E->getDecl()); 15153 } 15154 }; 15155 } 15156 15157 /// Given a function expression of unknown-any type, try to rebuild it 15158 /// to have a function type. 15159 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 15160 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 15161 if (Result.isInvalid()) return ExprError(); 15162 return S.DefaultFunctionArrayConversion(Result.get()); 15163 } 15164 15165 namespace { 15166 /// A visitor for rebuilding an expression of type __unknown_anytype 15167 /// into one which resolves the type directly on the referring 15168 /// expression. Strict preservation of the original source 15169 /// structure is not a goal. 15170 struct RebuildUnknownAnyExpr 15171 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 15172 15173 Sema &S; 15174 15175 /// The current destination type. 15176 QualType DestType; 15177 15178 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 15179 : S(S), DestType(CastType) {} 15180 15181 ExprResult VisitStmt(Stmt *S) { 15182 llvm_unreachable("unexpected statement!"); 15183 } 15184 15185 ExprResult VisitExpr(Expr *E) { 15186 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 15187 << E->getSourceRange(); 15188 return ExprError(); 15189 } 15190 15191 ExprResult VisitCallExpr(CallExpr *E); 15192 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 15193 15194 /// Rebuild an expression which simply semantically wraps another 15195 /// expression which it shares the type and value kind of. 15196 template <class T> ExprResult rebuildSugarExpr(T *E) { 15197 ExprResult SubResult = Visit(E->getSubExpr()); 15198 if (SubResult.isInvalid()) return ExprError(); 15199 Expr *SubExpr = SubResult.get(); 15200 E->setSubExpr(SubExpr); 15201 E->setType(SubExpr->getType()); 15202 E->setValueKind(SubExpr->getValueKind()); 15203 assert(E->getObjectKind() == OK_Ordinary); 15204 return E; 15205 } 15206 15207 ExprResult VisitParenExpr(ParenExpr *E) { 15208 return rebuildSugarExpr(E); 15209 } 15210 15211 ExprResult VisitUnaryExtension(UnaryOperator *E) { 15212 return rebuildSugarExpr(E); 15213 } 15214 15215 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 15216 const PointerType *Ptr = DestType->getAs<PointerType>(); 15217 if (!Ptr) { 15218 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 15219 << E->getSourceRange(); 15220 return ExprError(); 15221 } 15222 15223 if (isa<CallExpr>(E->getSubExpr())) { 15224 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 15225 << E->getSourceRange(); 15226 return ExprError(); 15227 } 15228 15229 assert(E->getValueKind() == VK_RValue); 15230 assert(E->getObjectKind() == OK_Ordinary); 15231 E->setType(DestType); 15232 15233 // Build the sub-expression as if it were an object of the pointee type. 15234 DestType = Ptr->getPointeeType(); 15235 ExprResult SubResult = Visit(E->getSubExpr()); 15236 if (SubResult.isInvalid()) return ExprError(); 15237 E->setSubExpr(SubResult.get()); 15238 return E; 15239 } 15240 15241 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 15242 15243 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 15244 15245 ExprResult VisitMemberExpr(MemberExpr *E) { 15246 return resolveDecl(E, E->getMemberDecl()); 15247 } 15248 15249 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 15250 return resolveDecl(E, E->getDecl()); 15251 } 15252 }; 15253 } 15254 15255 /// Rebuilds a call expression which yielded __unknown_anytype. 15256 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 15257 Expr *CalleeExpr = E->getCallee(); 15258 15259 enum FnKind { 15260 FK_MemberFunction, 15261 FK_FunctionPointer, 15262 FK_BlockPointer 15263 }; 15264 15265 FnKind Kind; 15266 QualType CalleeType = CalleeExpr->getType(); 15267 if (CalleeType == S.Context.BoundMemberTy) { 15268 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 15269 Kind = FK_MemberFunction; 15270 CalleeType = Expr::findBoundMemberType(CalleeExpr); 15271 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 15272 CalleeType = Ptr->getPointeeType(); 15273 Kind = FK_FunctionPointer; 15274 } else { 15275 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 15276 Kind = FK_BlockPointer; 15277 } 15278 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 15279 15280 // Verify that this is a legal result type of a function. 15281 if (DestType->isArrayType() || DestType->isFunctionType()) { 15282 unsigned diagID = diag::err_func_returning_array_function; 15283 if (Kind == FK_BlockPointer) 15284 diagID = diag::err_block_returning_array_function; 15285 15286 S.Diag(E->getExprLoc(), diagID) 15287 << DestType->isFunctionType() << DestType; 15288 return ExprError(); 15289 } 15290 15291 // Otherwise, go ahead and set DestType as the call's result. 15292 E->setType(DestType.getNonLValueExprType(S.Context)); 15293 E->setValueKind(Expr::getValueKindForType(DestType)); 15294 assert(E->getObjectKind() == OK_Ordinary); 15295 15296 // Rebuild the function type, replacing the result type with DestType. 15297 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 15298 if (Proto) { 15299 // __unknown_anytype(...) is a special case used by the debugger when 15300 // it has no idea what a function's signature is. 15301 // 15302 // We want to build this call essentially under the K&R 15303 // unprototyped rules, but making a FunctionNoProtoType in C++ 15304 // would foul up all sorts of assumptions. However, we cannot 15305 // simply pass all arguments as variadic arguments, nor can we 15306 // portably just call the function under a non-variadic type; see 15307 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 15308 // However, it turns out that in practice it is generally safe to 15309 // call a function declared as "A foo(B,C,D);" under the prototype 15310 // "A foo(B,C,D,...);". The only known exception is with the 15311 // Windows ABI, where any variadic function is implicitly cdecl 15312 // regardless of its normal CC. Therefore we change the parameter 15313 // types to match the types of the arguments. 15314 // 15315 // This is a hack, but it is far superior to moving the 15316 // corresponding target-specific code from IR-gen to Sema/AST. 15317 15318 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 15319 SmallVector<QualType, 8> ArgTypes; 15320 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 15321 ArgTypes.reserve(E->getNumArgs()); 15322 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 15323 Expr *Arg = E->getArg(i); 15324 QualType ArgType = Arg->getType(); 15325 if (E->isLValue()) { 15326 ArgType = S.Context.getLValueReferenceType(ArgType); 15327 } else if (E->isXValue()) { 15328 ArgType = S.Context.getRValueReferenceType(ArgType); 15329 } 15330 ArgTypes.push_back(ArgType); 15331 } 15332 ParamTypes = ArgTypes; 15333 } 15334 DestType = S.Context.getFunctionType(DestType, ParamTypes, 15335 Proto->getExtProtoInfo()); 15336 } else { 15337 DestType = S.Context.getFunctionNoProtoType(DestType, 15338 FnType->getExtInfo()); 15339 } 15340 15341 // Rebuild the appropriate pointer-to-function type. 15342 switch (Kind) { 15343 case FK_MemberFunction: 15344 // Nothing to do. 15345 break; 15346 15347 case FK_FunctionPointer: 15348 DestType = S.Context.getPointerType(DestType); 15349 break; 15350 15351 case FK_BlockPointer: 15352 DestType = S.Context.getBlockPointerType(DestType); 15353 break; 15354 } 15355 15356 // Finally, we can recurse. 15357 ExprResult CalleeResult = Visit(CalleeExpr); 15358 if (!CalleeResult.isUsable()) return ExprError(); 15359 E->setCallee(CalleeResult.get()); 15360 15361 // Bind a temporary if necessary. 15362 return S.MaybeBindToTemporary(E); 15363 } 15364 15365 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 15366 // Verify that this is a legal result type of a call. 15367 if (DestType->isArrayType() || DestType->isFunctionType()) { 15368 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 15369 << DestType->isFunctionType() << DestType; 15370 return ExprError(); 15371 } 15372 15373 // Rewrite the method result type if available. 15374 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 15375 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 15376 Method->setReturnType(DestType); 15377 } 15378 15379 // Change the type of the message. 15380 E->setType(DestType.getNonReferenceType()); 15381 E->setValueKind(Expr::getValueKindForType(DestType)); 15382 15383 return S.MaybeBindToTemporary(E); 15384 } 15385 15386 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 15387 // The only case we should ever see here is a function-to-pointer decay. 15388 if (E->getCastKind() == CK_FunctionToPointerDecay) { 15389 assert(E->getValueKind() == VK_RValue); 15390 assert(E->getObjectKind() == OK_Ordinary); 15391 15392 E->setType(DestType); 15393 15394 // Rebuild the sub-expression as the pointee (function) type. 15395 DestType = DestType->castAs<PointerType>()->getPointeeType(); 15396 15397 ExprResult Result = Visit(E->getSubExpr()); 15398 if (!Result.isUsable()) return ExprError(); 15399 15400 E->setSubExpr(Result.get()); 15401 return E; 15402 } else if (E->getCastKind() == CK_LValueToRValue) { 15403 assert(E->getValueKind() == VK_RValue); 15404 assert(E->getObjectKind() == OK_Ordinary); 15405 15406 assert(isa<BlockPointerType>(E->getType())); 15407 15408 E->setType(DestType); 15409 15410 // The sub-expression has to be a lvalue reference, so rebuild it as such. 15411 DestType = S.Context.getLValueReferenceType(DestType); 15412 15413 ExprResult Result = Visit(E->getSubExpr()); 15414 if (!Result.isUsable()) return ExprError(); 15415 15416 E->setSubExpr(Result.get()); 15417 return E; 15418 } else { 15419 llvm_unreachable("Unhandled cast type!"); 15420 } 15421 } 15422 15423 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 15424 ExprValueKind ValueKind = VK_LValue; 15425 QualType Type = DestType; 15426 15427 // We know how to make this work for certain kinds of decls: 15428 15429 // - functions 15430 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 15431 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 15432 DestType = Ptr->getPointeeType(); 15433 ExprResult Result = resolveDecl(E, VD); 15434 if (Result.isInvalid()) return ExprError(); 15435 return S.ImpCastExprToType(Result.get(), Type, 15436 CK_FunctionToPointerDecay, VK_RValue); 15437 } 15438 15439 if (!Type->isFunctionType()) { 15440 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 15441 << VD << E->getSourceRange(); 15442 return ExprError(); 15443 } 15444 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 15445 // We must match the FunctionDecl's type to the hack introduced in 15446 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 15447 // type. See the lengthy commentary in that routine. 15448 QualType FDT = FD->getType(); 15449 const FunctionType *FnType = FDT->castAs<FunctionType>(); 15450 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 15451 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 15452 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 15453 SourceLocation Loc = FD->getLocation(); 15454 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(), 15455 FD->getDeclContext(), 15456 Loc, Loc, FD->getNameInfo().getName(), 15457 DestType, FD->getTypeSourceInfo(), 15458 SC_None, false/*isInlineSpecified*/, 15459 FD->hasPrototype(), 15460 false/*isConstexprSpecified*/); 15461 15462 if (FD->getQualifier()) 15463 NewFD->setQualifierInfo(FD->getQualifierLoc()); 15464 15465 SmallVector<ParmVarDecl*, 16> Params; 15466 for (const auto &AI : FT->param_types()) { 15467 ParmVarDecl *Param = 15468 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 15469 Param->setScopeInfo(0, Params.size()); 15470 Params.push_back(Param); 15471 } 15472 NewFD->setParams(Params); 15473 DRE->setDecl(NewFD); 15474 VD = DRE->getDecl(); 15475 } 15476 } 15477 15478 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 15479 if (MD->isInstance()) { 15480 ValueKind = VK_RValue; 15481 Type = S.Context.BoundMemberTy; 15482 } 15483 15484 // Function references aren't l-values in C. 15485 if (!S.getLangOpts().CPlusPlus) 15486 ValueKind = VK_RValue; 15487 15488 // - variables 15489 } else if (isa<VarDecl>(VD)) { 15490 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 15491 Type = RefTy->getPointeeType(); 15492 } else if (Type->isFunctionType()) { 15493 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 15494 << VD << E->getSourceRange(); 15495 return ExprError(); 15496 } 15497 15498 // - nothing else 15499 } else { 15500 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 15501 << VD << E->getSourceRange(); 15502 return ExprError(); 15503 } 15504 15505 // Modifying the declaration like this is friendly to IR-gen but 15506 // also really dangerous. 15507 VD->setType(DestType); 15508 E->setType(Type); 15509 E->setValueKind(ValueKind); 15510 return E; 15511 } 15512 15513 /// Check a cast of an unknown-any type. We intentionally only 15514 /// trigger this for C-style casts. 15515 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 15516 Expr *CastExpr, CastKind &CastKind, 15517 ExprValueKind &VK, CXXCastPath &Path) { 15518 // The type we're casting to must be either void or complete. 15519 if (!CastType->isVoidType() && 15520 RequireCompleteType(TypeRange.getBegin(), CastType, 15521 diag::err_typecheck_cast_to_incomplete)) 15522 return ExprError(); 15523 15524 // Rewrite the casted expression from scratch. 15525 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 15526 if (!result.isUsable()) return ExprError(); 15527 15528 CastExpr = result.get(); 15529 VK = CastExpr->getValueKind(); 15530 CastKind = CK_NoOp; 15531 15532 return CastExpr; 15533 } 15534 15535 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 15536 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 15537 } 15538 15539 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 15540 Expr *arg, QualType ¶mType) { 15541 // If the syntactic form of the argument is not an explicit cast of 15542 // any sort, just do default argument promotion. 15543 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 15544 if (!castArg) { 15545 ExprResult result = DefaultArgumentPromotion(arg); 15546 if (result.isInvalid()) return ExprError(); 15547 paramType = result.get()->getType(); 15548 return result; 15549 } 15550 15551 // Otherwise, use the type that was written in the explicit cast. 15552 assert(!arg->hasPlaceholderType()); 15553 paramType = castArg->getTypeAsWritten(); 15554 15555 // Copy-initialize a parameter of that type. 15556 InitializedEntity entity = 15557 InitializedEntity::InitializeParameter(Context, paramType, 15558 /*consumed*/ false); 15559 return PerformCopyInitialization(entity, callLoc, arg); 15560 } 15561 15562 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 15563 Expr *orig = E; 15564 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 15565 while (true) { 15566 E = E->IgnoreParenImpCasts(); 15567 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 15568 E = call->getCallee(); 15569 diagID = diag::err_uncasted_call_of_unknown_any; 15570 } else { 15571 break; 15572 } 15573 } 15574 15575 SourceLocation loc; 15576 NamedDecl *d; 15577 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 15578 loc = ref->getLocation(); 15579 d = ref->getDecl(); 15580 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 15581 loc = mem->getMemberLoc(); 15582 d = mem->getMemberDecl(); 15583 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 15584 diagID = diag::err_uncasted_call_of_unknown_any; 15585 loc = msg->getSelectorStartLoc(); 15586 d = msg->getMethodDecl(); 15587 if (!d) { 15588 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 15589 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 15590 << orig->getSourceRange(); 15591 return ExprError(); 15592 } 15593 } else { 15594 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 15595 << E->getSourceRange(); 15596 return ExprError(); 15597 } 15598 15599 S.Diag(loc, diagID) << d << orig->getSourceRange(); 15600 15601 // Never recoverable. 15602 return ExprError(); 15603 } 15604 15605 /// Check for operands with placeholder types and complain if found. 15606 /// Returns ExprError() if there was an error and no recovery was possible. 15607 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 15608 if (!getLangOpts().CPlusPlus) { 15609 // C cannot handle TypoExpr nodes on either side of a binop because it 15610 // doesn't handle dependent types properly, so make sure any TypoExprs have 15611 // been dealt with before checking the operands. 15612 ExprResult Result = CorrectDelayedTyposInExpr(E); 15613 if (!Result.isUsable()) return ExprError(); 15614 E = Result.get(); 15615 } 15616 15617 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 15618 if (!placeholderType) return E; 15619 15620 switch (placeholderType->getKind()) { 15621 15622 // Overloaded expressions. 15623 case BuiltinType::Overload: { 15624 // Try to resolve a single function template specialization. 15625 // This is obligatory. 15626 ExprResult Result = E; 15627 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 15628 return Result; 15629 15630 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 15631 // leaves Result unchanged on failure. 15632 Result = E; 15633 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) 15634 return Result; 15635 15636 // If that failed, try to recover with a call. 15637 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 15638 /*complain*/ true); 15639 return Result; 15640 } 15641 15642 // Bound member functions. 15643 case BuiltinType::BoundMember: { 15644 ExprResult result = E; 15645 const Expr *BME = E->IgnoreParens(); 15646 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 15647 // Try to give a nicer diagnostic if it is a bound member that we recognize. 15648 if (isa<CXXPseudoDestructorExpr>(BME)) { 15649 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 15650 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 15651 if (ME->getMemberNameInfo().getName().getNameKind() == 15652 DeclarationName::CXXDestructorName) 15653 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 15654 } 15655 tryToRecoverWithCall(result, PD, 15656 /*complain*/ true); 15657 return result; 15658 } 15659 15660 // ARC unbridged casts. 15661 case BuiltinType::ARCUnbridgedCast: { 15662 Expr *realCast = stripARCUnbridgedCast(E); 15663 diagnoseARCUnbridgedCast(realCast); 15664 return realCast; 15665 } 15666 15667 // Expressions of unknown type. 15668 case BuiltinType::UnknownAny: 15669 return diagnoseUnknownAnyExpr(*this, E); 15670 15671 // Pseudo-objects. 15672 case BuiltinType::PseudoObject: 15673 return checkPseudoObjectRValue(E); 15674 15675 case BuiltinType::BuiltinFn: { 15676 // Accept __noop without parens by implicitly converting it to a call expr. 15677 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 15678 if (DRE) { 15679 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 15680 if (FD->getBuiltinID() == Builtin::BI__noop) { 15681 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 15682 CK_BuiltinFnToFnPtr).get(); 15683 return new (Context) CallExpr(Context, E, None, Context.IntTy, 15684 VK_RValue, SourceLocation()); 15685 } 15686 } 15687 15688 Diag(E->getLocStart(), diag::err_builtin_fn_use); 15689 return ExprError(); 15690 } 15691 15692 // Expressions of unknown type. 15693 case BuiltinType::OMPArraySection: 15694 Diag(E->getLocStart(), diag::err_omp_array_section_use); 15695 return ExprError(); 15696 15697 // Everything else should be impossible. 15698 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 15699 case BuiltinType::Id: 15700 #include "clang/Basic/OpenCLImageTypes.def" 15701 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 15702 #define PLACEHOLDER_TYPE(Id, SingletonId) 15703 #include "clang/AST/BuiltinTypes.def" 15704 break; 15705 } 15706 15707 llvm_unreachable("invalid placeholder type!"); 15708 } 15709 15710 bool Sema::CheckCaseExpression(Expr *E) { 15711 if (E->isTypeDependent()) 15712 return true; 15713 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 15714 return E->getType()->isIntegralOrEnumerationType(); 15715 return false; 15716 } 15717 15718 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 15719 ExprResult 15720 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 15721 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 15722 "Unknown Objective-C Boolean value!"); 15723 QualType BoolT = Context.ObjCBuiltinBoolTy; 15724 if (!Context.getBOOLDecl()) { 15725 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 15726 Sema::LookupOrdinaryName); 15727 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 15728 NamedDecl *ND = Result.getFoundDecl(); 15729 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 15730 Context.setBOOLDecl(TD); 15731 } 15732 } 15733 if (Context.getBOOLDecl()) 15734 BoolT = Context.getBOOLType(); 15735 return new (Context) 15736 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 15737 } 15738 15739 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 15740 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 15741 SourceLocation RParen) { 15742 15743 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 15744 15745 auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(), 15746 [&](const AvailabilitySpec &Spec) { 15747 return Spec.getPlatform() == Platform; 15748 }); 15749 15750 VersionTuple Version; 15751 if (Spec != AvailSpecs.end()) 15752 Version = Spec->getVersion(); 15753 15754 return new (Context) 15755 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 15756 } 15757