1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements semantic analysis for expressions. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "TreeTransform.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/ASTMutationListener.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/DeclObjC.h" 21 #include "clang/AST/DeclTemplate.h" 22 #include "clang/AST/EvaluatedExprVisitor.h" 23 #include "clang/AST/Expr.h" 24 #include "clang/AST/ExprCXX.h" 25 #include "clang/AST/ExprObjC.h" 26 #include "clang/AST/ExprOpenMP.h" 27 #include "clang/AST/RecursiveASTVisitor.h" 28 #include "clang/AST/TypeLoc.h" 29 #include "clang/Basic/PartialDiagnostic.h" 30 #include "clang/Basic/SourceManager.h" 31 #include "clang/Basic/TargetInfo.h" 32 #include "clang/Lex/LiteralSupport.h" 33 #include "clang/Lex/Preprocessor.h" 34 #include "clang/Sema/AnalysisBasedWarnings.h" 35 #include "clang/Sema/DeclSpec.h" 36 #include "clang/Sema/DelayedDiagnostic.h" 37 #include "clang/Sema/Designator.h" 38 #include "clang/Sema/Initialization.h" 39 #include "clang/Sema/Lookup.h" 40 #include "clang/Sema/ParsedTemplate.h" 41 #include "clang/Sema/Scope.h" 42 #include "clang/Sema/ScopeInfo.h" 43 #include "clang/Sema/SemaFixItUtils.h" 44 #include "clang/Sema/SemaInternal.h" 45 #include "clang/Sema/Template.h" 46 #include "llvm/Support/ConvertUTF.h" 47 using namespace clang; 48 using namespace sema; 49 50 /// \brief Determine whether the use of this declaration is valid, without 51 /// emitting diagnostics. 52 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 53 // See if this is an auto-typed variable whose initializer we are parsing. 54 if (ParsingInitForAutoVars.count(D)) 55 return false; 56 57 // See if this is a deleted function. 58 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 59 if (FD->isDeleted()) 60 return false; 61 62 // If the function has a deduced return type, and we can't deduce it, 63 // then we can't use it either. 64 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 65 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 66 return false; 67 } 68 69 // See if this function is unavailable. 70 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 71 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 72 return false; 73 74 return true; 75 } 76 77 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 78 // Warn if this is used but marked unused. 79 if (const auto *A = D->getAttr<UnusedAttr>()) { 80 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 81 // should diagnose them. 82 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused) { 83 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 84 if (DC && !DC->hasAttr<UnusedAttr>()) 85 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 86 } 87 } 88 } 89 90 static bool HasRedeclarationWithoutAvailabilityInCategory(const Decl *D) { 91 const auto *OMD = dyn_cast<ObjCMethodDecl>(D); 92 if (!OMD) 93 return false; 94 const ObjCInterfaceDecl *OID = OMD->getClassInterface(); 95 if (!OID) 96 return false; 97 98 for (const ObjCCategoryDecl *Cat : OID->visible_categories()) 99 if (ObjCMethodDecl *CatMeth = 100 Cat->getMethod(OMD->getSelector(), OMD->isInstanceMethod())) 101 if (!CatMeth->hasAttr<AvailabilityAttr>()) 102 return true; 103 return false; 104 } 105 106 AvailabilityResult 107 Sema::ShouldDiagnoseAvailabilityOfDecl(NamedDecl *&D, std::string *Message) { 108 AvailabilityResult Result = D->getAvailability(Message); 109 110 // For typedefs, if the typedef declaration appears available look 111 // to the underlying type to see if it is more restrictive. 112 while (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) { 113 if (Result == AR_Available) { 114 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 115 D = TT->getDecl(); 116 Result = D->getAvailability(Message); 117 continue; 118 } 119 } 120 break; 121 } 122 123 // Forward class declarations get their attributes from their definition. 124 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) { 125 if (IDecl->getDefinition()) { 126 D = IDecl->getDefinition(); 127 Result = D->getAvailability(Message); 128 } 129 } 130 131 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) 132 if (Result == AR_Available) { 133 const DeclContext *DC = ECD->getDeclContext(); 134 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC)) 135 Result = TheEnumDecl->getAvailability(Message); 136 } 137 138 if (Result == AR_NotYetIntroduced) { 139 // Don't do this for enums, they can't be redeclared. 140 if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D)) 141 return AR_Available; 142 143 bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited(); 144 // Objective-C method declarations in categories are not modelled as 145 // redeclarations, so manually look for a redeclaration in a category 146 // if necessary. 147 if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D)) 148 Warn = false; 149 // In general, D will point to the most recent redeclaration. However, 150 // for `@class A;` decls, this isn't true -- manually go through the 151 // redecl chain in that case. 152 if (Warn && isa<ObjCInterfaceDecl>(D)) 153 for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn; 154 Redecl = Redecl->getPreviousDecl()) 155 if (!Redecl->hasAttr<AvailabilityAttr>() || 156 Redecl->getAttr<AvailabilityAttr>()->isInherited()) 157 Warn = false; 158 159 return Warn ? AR_NotYetIntroduced : AR_Available; 160 } 161 162 return Result; 163 } 164 165 static void 166 DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc, 167 const ObjCInterfaceDecl *UnknownObjCClass, 168 bool ObjCPropertyAccess) { 169 std::string Message; 170 // See if this declaration is unavailable, deprecated, or partial. 171 if (AvailabilityResult Result = 172 S.ShouldDiagnoseAvailabilityOfDecl(D, &Message)) { 173 174 if (Result == AR_NotYetIntroduced && S.getCurFunctionOrMethodDecl()) { 175 S.getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 176 return; 177 } 178 179 const ObjCPropertyDecl *ObjCPDecl = nullptr; 180 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 181 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) { 182 AvailabilityResult PDeclResult = PD->getAvailability(nullptr); 183 if (PDeclResult == Result) 184 ObjCPDecl = PD; 185 } 186 } 187 188 S.EmitAvailabilityWarning(Result, D, Message, Loc, UnknownObjCClass, 189 ObjCPDecl, ObjCPropertyAccess); 190 } 191 } 192 193 /// \brief Emit a note explaining that this function is deleted. 194 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 195 assert(Decl->isDeleted()); 196 197 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 198 199 if (Method && Method->isDeleted() && Method->isDefaulted()) { 200 // If the method was explicitly defaulted, point at that declaration. 201 if (!Method->isImplicit()) 202 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 203 204 // Try to diagnose why this special member function was implicitly 205 // deleted. This might fail, if that reason no longer applies. 206 CXXSpecialMember CSM = getSpecialMember(Method); 207 if (CSM != CXXInvalid) 208 ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true); 209 210 return; 211 } 212 213 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 214 if (Ctor && Ctor->isInheritingConstructor()) 215 return NoteDeletedInheritingConstructor(Ctor); 216 217 Diag(Decl->getLocation(), diag::note_availability_specified_here) 218 << Decl << true; 219 } 220 221 /// \brief Determine whether a FunctionDecl was ever declared with an 222 /// explicit storage class. 223 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 224 for (auto I : D->redecls()) { 225 if (I->getStorageClass() != SC_None) 226 return true; 227 } 228 return false; 229 } 230 231 /// \brief Check whether we're in an extern inline function and referring to a 232 /// variable or function with internal linkage (C11 6.7.4p3). 233 /// 234 /// This is only a warning because we used to silently accept this code, but 235 /// in many cases it will not behave correctly. This is not enabled in C++ mode 236 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 237 /// and so while there may still be user mistakes, most of the time we can't 238 /// prove that there are errors. 239 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 240 const NamedDecl *D, 241 SourceLocation Loc) { 242 // This is disabled under C++; there are too many ways for this to fire in 243 // contexts where the warning is a false positive, or where it is technically 244 // correct but benign. 245 if (S.getLangOpts().CPlusPlus) 246 return; 247 248 // Check if this is an inlined function or method. 249 FunctionDecl *Current = S.getCurFunctionDecl(); 250 if (!Current) 251 return; 252 if (!Current->isInlined()) 253 return; 254 if (!Current->isExternallyVisible()) 255 return; 256 257 // Check if the decl has internal linkage. 258 if (D->getFormalLinkage() != InternalLinkage) 259 return; 260 261 // Downgrade from ExtWarn to Extension if 262 // (1) the supposedly external inline function is in the main file, 263 // and probably won't be included anywhere else. 264 // (2) the thing we're referencing is a pure function. 265 // (3) the thing we're referencing is another inline function. 266 // This last can give us false negatives, but it's better than warning on 267 // wrappers for simple C library functions. 268 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 269 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 270 if (!DowngradeWarning && UsedFn) 271 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 272 273 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 274 : diag::ext_internal_in_extern_inline) 275 << /*IsVar=*/!UsedFn << D; 276 277 S.MaybeSuggestAddingStaticToDecl(Current); 278 279 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 280 << D; 281 } 282 283 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 284 const FunctionDecl *First = Cur->getFirstDecl(); 285 286 // Suggest "static" on the function, if possible. 287 if (!hasAnyExplicitStorageClass(First)) { 288 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 289 Diag(DeclBegin, diag::note_convert_inline_to_static) 290 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 291 } 292 } 293 294 /// \brief Determine whether the use of this declaration is valid, and 295 /// emit any corresponding diagnostics. 296 /// 297 /// This routine diagnoses various problems with referencing 298 /// declarations that can occur when using a declaration. For example, 299 /// it might warn if a deprecated or unavailable declaration is being 300 /// used, or produce an error (and return true) if a C++0x deleted 301 /// function is being used. 302 /// 303 /// \returns true if there was an error (this declaration cannot be 304 /// referenced), false otherwise. 305 /// 306 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 307 const ObjCInterfaceDecl *UnknownObjCClass, 308 bool ObjCPropertyAccess) { 309 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 310 // If there were any diagnostics suppressed by template argument deduction, 311 // emit them now. 312 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 313 if (Pos != SuppressedDiagnostics.end()) { 314 for (const PartialDiagnosticAt &Suppressed : Pos->second) 315 Diag(Suppressed.first, Suppressed.second); 316 317 // Clear out the list of suppressed diagnostics, so that we don't emit 318 // them again for this specialization. However, we don't obsolete this 319 // entry from the table, because we want to avoid ever emitting these 320 // diagnostics again. 321 Pos->second.clear(); 322 } 323 324 // C++ [basic.start.main]p3: 325 // The function 'main' shall not be used within a program. 326 if (cast<FunctionDecl>(D)->isMain()) 327 Diag(Loc, diag::ext_main_used); 328 } 329 330 // See if this is an auto-typed variable whose initializer we are parsing. 331 if (ParsingInitForAutoVars.count(D)) { 332 if (isa<BindingDecl>(D)) { 333 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 334 << D->getDeclName(); 335 } else { 336 const AutoType *AT = cast<VarDecl>(D)->getType()->getContainedAutoType(); 337 338 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 339 << D->getDeclName() << (unsigned)AT->getKeyword(); 340 } 341 return true; 342 } 343 344 // See if this is a deleted function. 345 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 346 if (FD->isDeleted()) { 347 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 348 if (Ctor && Ctor->isInheritingConstructor()) 349 Diag(Loc, diag::err_deleted_inherited_ctor_use) 350 << Ctor->getParent() 351 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 352 else 353 Diag(Loc, diag::err_deleted_function_use); 354 NoteDeletedFunction(FD); 355 return true; 356 } 357 358 // If the function has a deduced return type, and we can't deduce it, 359 // then we can't use it either. 360 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 361 DeduceReturnType(FD, Loc)) 362 return true; 363 364 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 365 return true; 366 } 367 368 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 369 // Only the variables omp_in and omp_out are allowed in the combiner. 370 // Only the variables omp_priv and omp_orig are allowed in the 371 // initializer-clause. 372 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 373 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 374 isa<VarDecl>(D)) { 375 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 376 << getCurFunction()->HasOMPDeclareReductionCombiner; 377 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 378 return true; 379 } 380 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass, 381 ObjCPropertyAccess); 382 383 DiagnoseUnusedOfDecl(*this, D, Loc); 384 385 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 386 387 return false; 388 } 389 390 /// \brief Retrieve the message suffix that should be added to a 391 /// diagnostic complaining about the given function being deleted or 392 /// unavailable. 393 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 394 std::string Message; 395 if (FD->getAvailability(&Message)) 396 return ": " + Message; 397 398 return std::string(); 399 } 400 401 /// DiagnoseSentinelCalls - This routine checks whether a call or 402 /// message-send is to a declaration with the sentinel attribute, and 403 /// if so, it checks that the requirements of the sentinel are 404 /// satisfied. 405 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 406 ArrayRef<Expr *> Args) { 407 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 408 if (!attr) 409 return; 410 411 // The number of formal parameters of the declaration. 412 unsigned numFormalParams; 413 414 // The kind of declaration. This is also an index into a %select in 415 // the diagnostic. 416 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 417 418 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 419 numFormalParams = MD->param_size(); 420 calleeType = CT_Method; 421 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 422 numFormalParams = FD->param_size(); 423 calleeType = CT_Function; 424 } else if (isa<VarDecl>(D)) { 425 QualType type = cast<ValueDecl>(D)->getType(); 426 const FunctionType *fn = nullptr; 427 if (const PointerType *ptr = type->getAs<PointerType>()) { 428 fn = ptr->getPointeeType()->getAs<FunctionType>(); 429 if (!fn) return; 430 calleeType = CT_Function; 431 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 432 fn = ptr->getPointeeType()->castAs<FunctionType>(); 433 calleeType = CT_Block; 434 } else { 435 return; 436 } 437 438 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 439 numFormalParams = proto->getNumParams(); 440 } else { 441 numFormalParams = 0; 442 } 443 } else { 444 return; 445 } 446 447 // "nullPos" is the number of formal parameters at the end which 448 // effectively count as part of the variadic arguments. This is 449 // useful if you would prefer to not have *any* formal parameters, 450 // but the language forces you to have at least one. 451 unsigned nullPos = attr->getNullPos(); 452 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 453 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 454 455 // The number of arguments which should follow the sentinel. 456 unsigned numArgsAfterSentinel = attr->getSentinel(); 457 458 // If there aren't enough arguments for all the formal parameters, 459 // the sentinel, and the args after the sentinel, complain. 460 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 461 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 462 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 463 return; 464 } 465 466 // Otherwise, find the sentinel expression. 467 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 468 if (!sentinelExpr) return; 469 if (sentinelExpr->isValueDependent()) return; 470 if (Context.isSentinelNullExpr(sentinelExpr)) return; 471 472 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 473 // or 'NULL' if those are actually defined in the context. Only use 474 // 'nil' for ObjC methods, where it's much more likely that the 475 // variadic arguments form a list of object pointers. 476 SourceLocation MissingNilLoc 477 = getLocForEndOfToken(sentinelExpr->getLocEnd()); 478 std::string NullValue; 479 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 480 NullValue = "nil"; 481 else if (getLangOpts().CPlusPlus11) 482 NullValue = "nullptr"; 483 else if (PP.isMacroDefined("NULL")) 484 NullValue = "NULL"; 485 else 486 NullValue = "(void*) 0"; 487 488 if (MissingNilLoc.isInvalid()) 489 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 490 else 491 Diag(MissingNilLoc, diag::warn_missing_sentinel) 492 << int(calleeType) 493 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 494 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 495 } 496 497 SourceRange Sema::getExprRange(Expr *E) const { 498 return E ? E->getSourceRange() : SourceRange(); 499 } 500 501 //===----------------------------------------------------------------------===// 502 // Standard Promotions and Conversions 503 //===----------------------------------------------------------------------===// 504 505 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 506 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 507 // Handle any placeholder expressions which made it here. 508 if (E->getType()->isPlaceholderType()) { 509 ExprResult result = CheckPlaceholderExpr(E); 510 if (result.isInvalid()) return ExprError(); 511 E = result.get(); 512 } 513 514 QualType Ty = E->getType(); 515 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 516 517 if (Ty->isFunctionType()) { 518 // If we are here, we are not calling a function but taking 519 // its address (which is not allowed in OpenCL v1.0 s6.8.a.3). 520 if (getLangOpts().OpenCL) { 521 if (Diagnose) 522 Diag(E->getExprLoc(), diag::err_opencl_taking_function_address); 523 return ExprError(); 524 } 525 526 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 527 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 528 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 529 return ExprError(); 530 531 E = ImpCastExprToType(E, Context.getPointerType(Ty), 532 CK_FunctionToPointerDecay).get(); 533 } else if (Ty->isArrayType()) { 534 // In C90 mode, arrays only promote to pointers if the array expression is 535 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 536 // type 'array of type' is converted to an expression that has type 'pointer 537 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 538 // that has type 'array of type' ...". The relevant change is "an lvalue" 539 // (C90) to "an expression" (C99). 540 // 541 // C++ 4.2p1: 542 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 543 // T" can be converted to an rvalue of type "pointer to T". 544 // 545 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 546 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 547 CK_ArrayToPointerDecay).get(); 548 } 549 return E; 550 } 551 552 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 553 // Check to see if we are dereferencing a null pointer. If so, 554 // and if not volatile-qualified, this is undefined behavior that the 555 // optimizer will delete, so warn about it. People sometimes try to use this 556 // to get a deterministic trap and are surprised by clang's behavior. This 557 // only handles the pattern "*null", which is a very syntactic check. 558 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 559 if (UO->getOpcode() == UO_Deref && 560 UO->getSubExpr()->IgnoreParenCasts()-> 561 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 562 !UO->getType().isVolatileQualified()) { 563 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 564 S.PDiag(diag::warn_indirection_through_null) 565 << UO->getSubExpr()->getSourceRange()); 566 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 567 S.PDiag(diag::note_indirection_through_null)); 568 } 569 } 570 571 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 572 SourceLocation AssignLoc, 573 const Expr* RHS) { 574 const ObjCIvarDecl *IV = OIRE->getDecl(); 575 if (!IV) 576 return; 577 578 DeclarationName MemberName = IV->getDeclName(); 579 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 580 if (!Member || !Member->isStr("isa")) 581 return; 582 583 const Expr *Base = OIRE->getBase(); 584 QualType BaseType = Base->getType(); 585 if (OIRE->isArrow()) 586 BaseType = BaseType->getPointeeType(); 587 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 588 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 589 ObjCInterfaceDecl *ClassDeclared = nullptr; 590 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 591 if (!ClassDeclared->getSuperClass() 592 && (*ClassDeclared->ivar_begin()) == IV) { 593 if (RHS) { 594 NamedDecl *ObjectSetClass = 595 S.LookupSingleName(S.TUScope, 596 &S.Context.Idents.get("object_setClass"), 597 SourceLocation(), S.LookupOrdinaryName); 598 if (ObjectSetClass) { 599 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd()); 600 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 601 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 602 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 603 AssignLoc), ",") << 604 FixItHint::CreateInsertion(RHSLocEnd, ")"); 605 } 606 else 607 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 608 } else { 609 NamedDecl *ObjectGetClass = 610 S.LookupSingleName(S.TUScope, 611 &S.Context.Idents.get("object_getClass"), 612 SourceLocation(), S.LookupOrdinaryName); 613 if (ObjectGetClass) 614 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 615 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 616 FixItHint::CreateReplacement( 617 SourceRange(OIRE->getOpLoc(), 618 OIRE->getLocEnd()), ")"); 619 else 620 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 621 } 622 S.Diag(IV->getLocation(), diag::note_ivar_decl); 623 } 624 } 625 } 626 627 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 628 // Handle any placeholder expressions which made it here. 629 if (E->getType()->isPlaceholderType()) { 630 ExprResult result = CheckPlaceholderExpr(E); 631 if (result.isInvalid()) return ExprError(); 632 E = result.get(); 633 } 634 635 // C++ [conv.lval]p1: 636 // A glvalue of a non-function, non-array type T can be 637 // converted to a prvalue. 638 if (!E->isGLValue()) return E; 639 640 QualType T = E->getType(); 641 assert(!T.isNull() && "r-value conversion on typeless expression?"); 642 643 // We don't want to throw lvalue-to-rvalue casts on top of 644 // expressions of certain types in C++. 645 if (getLangOpts().CPlusPlus && 646 (E->getType() == Context.OverloadTy || 647 T->isDependentType() || 648 T->isRecordType())) 649 return E; 650 651 // The C standard is actually really unclear on this point, and 652 // DR106 tells us what the result should be but not why. It's 653 // generally best to say that void types just doesn't undergo 654 // lvalue-to-rvalue at all. Note that expressions of unqualified 655 // 'void' type are never l-values, but qualified void can be. 656 if (T->isVoidType()) 657 return E; 658 659 // OpenCL usually rejects direct accesses to values of 'half' type. 660 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 661 T->isHalfType()) { 662 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 663 << 0 << T; 664 return ExprError(); 665 } 666 667 CheckForNullPointerDereference(*this, E); 668 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 669 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 670 &Context.Idents.get("object_getClass"), 671 SourceLocation(), LookupOrdinaryName); 672 if (ObjectGetClass) 673 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 674 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 675 FixItHint::CreateReplacement( 676 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 677 else 678 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 679 } 680 else if (const ObjCIvarRefExpr *OIRE = 681 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 682 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 683 684 // C++ [conv.lval]p1: 685 // [...] If T is a non-class type, the type of the prvalue is the 686 // cv-unqualified version of T. Otherwise, the type of the 687 // rvalue is T. 688 // 689 // C99 6.3.2.1p2: 690 // If the lvalue has qualified type, the value has the unqualified 691 // version of the type of the lvalue; otherwise, the value has the 692 // type of the lvalue. 693 if (T.hasQualifiers()) 694 T = T.getUnqualifiedType(); 695 696 // Under the MS ABI, lock down the inheritance model now. 697 if (T->isMemberPointerType() && 698 Context.getTargetInfo().getCXXABI().isMicrosoft()) 699 (void)isCompleteType(E->getExprLoc(), T); 700 701 UpdateMarkingForLValueToRValue(E); 702 703 // Loading a __weak object implicitly retains the value, so we need a cleanup to 704 // balance that. 705 if (getLangOpts().ObjCAutoRefCount && 706 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 707 Cleanup.setExprNeedsCleanups(true); 708 709 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 710 nullptr, VK_RValue); 711 712 // C11 6.3.2.1p2: 713 // ... if the lvalue has atomic type, the value has the non-atomic version 714 // of the type of the lvalue ... 715 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 716 T = Atomic->getValueType().getUnqualifiedType(); 717 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 718 nullptr, VK_RValue); 719 } 720 721 return Res; 722 } 723 724 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 725 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 726 if (Res.isInvalid()) 727 return ExprError(); 728 Res = DefaultLvalueConversion(Res.get()); 729 if (Res.isInvalid()) 730 return ExprError(); 731 return Res; 732 } 733 734 /// CallExprUnaryConversions - a special case of an unary conversion 735 /// performed on a function designator of a call expression. 736 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 737 QualType Ty = E->getType(); 738 ExprResult Res = E; 739 // Only do implicit cast for a function type, but not for a pointer 740 // to function type. 741 if (Ty->isFunctionType()) { 742 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 743 CK_FunctionToPointerDecay).get(); 744 if (Res.isInvalid()) 745 return ExprError(); 746 } 747 Res = DefaultLvalueConversion(Res.get()); 748 if (Res.isInvalid()) 749 return ExprError(); 750 return Res.get(); 751 } 752 753 /// UsualUnaryConversions - Performs various conversions that are common to most 754 /// operators (C99 6.3). The conversions of array and function types are 755 /// sometimes suppressed. For example, the array->pointer conversion doesn't 756 /// apply if the array is an argument to the sizeof or address (&) operators. 757 /// In these instances, this routine should *not* be called. 758 ExprResult Sema::UsualUnaryConversions(Expr *E) { 759 // First, convert to an r-value. 760 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 761 if (Res.isInvalid()) 762 return ExprError(); 763 E = Res.get(); 764 765 QualType Ty = E->getType(); 766 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 767 768 // Half FP have to be promoted to float unless it is natively supported 769 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 770 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 771 772 // Try to perform integral promotions if the object has a theoretically 773 // promotable type. 774 if (Ty->isIntegralOrUnscopedEnumerationType()) { 775 // C99 6.3.1.1p2: 776 // 777 // The following may be used in an expression wherever an int or 778 // unsigned int may be used: 779 // - an object or expression with an integer type whose integer 780 // conversion rank is less than or equal to the rank of int 781 // and unsigned int. 782 // - A bit-field of type _Bool, int, signed int, or unsigned int. 783 // 784 // If an int can represent all values of the original type, the 785 // value is converted to an int; otherwise, it is converted to an 786 // unsigned int. These are called the integer promotions. All 787 // other types are unchanged by the integer promotions. 788 789 QualType PTy = Context.isPromotableBitField(E); 790 if (!PTy.isNull()) { 791 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 792 return E; 793 } 794 if (Ty->isPromotableIntegerType()) { 795 QualType PT = Context.getPromotedIntegerType(Ty); 796 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 797 return E; 798 } 799 } 800 return E; 801 } 802 803 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 804 /// do not have a prototype. Arguments that have type float or __fp16 805 /// are promoted to double. All other argument types are converted by 806 /// UsualUnaryConversions(). 807 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 808 QualType Ty = E->getType(); 809 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 810 811 ExprResult Res = UsualUnaryConversions(E); 812 if (Res.isInvalid()) 813 return ExprError(); 814 E = Res.get(); 815 816 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to 817 // double. 818 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 819 if (BTy && (BTy->getKind() == BuiltinType::Half || 820 BTy->getKind() == BuiltinType::Float)) { 821 if (getLangOpts().OpenCL && 822 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 823 if (BTy->getKind() == BuiltinType::Half) { 824 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 825 } 826 } else { 827 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 828 } 829 } 830 831 // C++ performs lvalue-to-rvalue conversion as a default argument 832 // promotion, even on class types, but note: 833 // C++11 [conv.lval]p2: 834 // When an lvalue-to-rvalue conversion occurs in an unevaluated 835 // operand or a subexpression thereof the value contained in the 836 // referenced object is not accessed. Otherwise, if the glvalue 837 // has a class type, the conversion copy-initializes a temporary 838 // of type T from the glvalue and the result of the conversion 839 // is a prvalue for the temporary. 840 // FIXME: add some way to gate this entire thing for correctness in 841 // potentially potentially evaluated contexts. 842 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 843 ExprResult Temp = PerformCopyInitialization( 844 InitializedEntity::InitializeTemporary(E->getType()), 845 E->getExprLoc(), E); 846 if (Temp.isInvalid()) 847 return ExprError(); 848 E = Temp.get(); 849 } 850 851 return E; 852 } 853 854 /// Determine the degree of POD-ness for an expression. 855 /// Incomplete types are considered POD, since this check can be performed 856 /// when we're in an unevaluated context. 857 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 858 if (Ty->isIncompleteType()) { 859 // C++11 [expr.call]p7: 860 // After these conversions, if the argument does not have arithmetic, 861 // enumeration, pointer, pointer to member, or class type, the program 862 // is ill-formed. 863 // 864 // Since we've already performed array-to-pointer and function-to-pointer 865 // decay, the only such type in C++ is cv void. This also handles 866 // initializer lists as variadic arguments. 867 if (Ty->isVoidType()) 868 return VAK_Invalid; 869 870 if (Ty->isObjCObjectType()) 871 return VAK_Invalid; 872 return VAK_Valid; 873 } 874 875 if (Ty.isCXX98PODType(Context)) 876 return VAK_Valid; 877 878 // C++11 [expr.call]p7: 879 // Passing a potentially-evaluated argument of class type (Clause 9) 880 // having a non-trivial copy constructor, a non-trivial move constructor, 881 // or a non-trivial destructor, with no corresponding parameter, 882 // is conditionally-supported with implementation-defined semantics. 883 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 884 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 885 if (!Record->hasNonTrivialCopyConstructor() && 886 !Record->hasNonTrivialMoveConstructor() && 887 !Record->hasNonTrivialDestructor()) 888 return VAK_ValidInCXX11; 889 890 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 891 return VAK_Valid; 892 893 if (Ty->isObjCObjectType()) 894 return VAK_Invalid; 895 896 if (getLangOpts().MSVCCompat) 897 return VAK_MSVCUndefined; 898 899 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 900 // permitted to reject them. We should consider doing so. 901 return VAK_Undefined; 902 } 903 904 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 905 // Don't allow one to pass an Objective-C interface to a vararg. 906 const QualType &Ty = E->getType(); 907 VarArgKind VAK = isValidVarArgType(Ty); 908 909 // Complain about passing non-POD types through varargs. 910 switch (VAK) { 911 case VAK_ValidInCXX11: 912 DiagRuntimeBehavior( 913 E->getLocStart(), nullptr, 914 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 915 << Ty << CT); 916 // Fall through. 917 case VAK_Valid: 918 if (Ty->isRecordType()) { 919 // This is unlikely to be what the user intended. If the class has a 920 // 'c_str' member function, the user probably meant to call that. 921 DiagRuntimeBehavior(E->getLocStart(), nullptr, 922 PDiag(diag::warn_pass_class_arg_to_vararg) 923 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 924 } 925 break; 926 927 case VAK_Undefined: 928 case VAK_MSVCUndefined: 929 DiagRuntimeBehavior( 930 E->getLocStart(), nullptr, 931 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 932 << getLangOpts().CPlusPlus11 << Ty << CT); 933 break; 934 935 case VAK_Invalid: 936 if (Ty->isObjCObjectType()) 937 DiagRuntimeBehavior( 938 E->getLocStart(), nullptr, 939 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 940 << Ty << CT); 941 else 942 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg) 943 << isa<InitListExpr>(E) << Ty << CT; 944 break; 945 } 946 } 947 948 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 949 /// will create a trap if the resulting type is not a POD type. 950 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 951 FunctionDecl *FDecl) { 952 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 953 // Strip the unbridged-cast placeholder expression off, if applicable. 954 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 955 (CT == VariadicMethod || 956 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 957 E = stripARCUnbridgedCast(E); 958 959 // Otherwise, do normal placeholder checking. 960 } else { 961 ExprResult ExprRes = CheckPlaceholderExpr(E); 962 if (ExprRes.isInvalid()) 963 return ExprError(); 964 E = ExprRes.get(); 965 } 966 } 967 968 ExprResult ExprRes = DefaultArgumentPromotion(E); 969 if (ExprRes.isInvalid()) 970 return ExprError(); 971 E = ExprRes.get(); 972 973 // Diagnostics regarding non-POD argument types are 974 // emitted along with format string checking in Sema::CheckFunctionCall(). 975 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 976 // Turn this into a trap. 977 CXXScopeSpec SS; 978 SourceLocation TemplateKWLoc; 979 UnqualifiedId Name; 980 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 981 E->getLocStart()); 982 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 983 Name, true, false); 984 if (TrapFn.isInvalid()) 985 return ExprError(); 986 987 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 988 E->getLocStart(), None, 989 E->getLocEnd()); 990 if (Call.isInvalid()) 991 return ExprError(); 992 993 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 994 Call.get(), E); 995 if (Comma.isInvalid()) 996 return ExprError(); 997 return Comma.get(); 998 } 999 1000 if (!getLangOpts().CPlusPlus && 1001 RequireCompleteType(E->getExprLoc(), E->getType(), 1002 diag::err_call_incomplete_argument)) 1003 return ExprError(); 1004 1005 return E; 1006 } 1007 1008 /// \brief Converts an integer to complex float type. Helper function of 1009 /// UsualArithmeticConversions() 1010 /// 1011 /// \return false if the integer expression is an integer type and is 1012 /// successfully converted to the complex type. 1013 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1014 ExprResult &ComplexExpr, 1015 QualType IntTy, 1016 QualType ComplexTy, 1017 bool SkipCast) { 1018 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1019 if (SkipCast) return false; 1020 if (IntTy->isIntegerType()) { 1021 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1022 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1023 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1024 CK_FloatingRealToComplex); 1025 } else { 1026 assert(IntTy->isComplexIntegerType()); 1027 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1028 CK_IntegralComplexToFloatingComplex); 1029 } 1030 return false; 1031 } 1032 1033 /// \brief Handle arithmetic conversion with complex types. Helper function of 1034 /// UsualArithmeticConversions() 1035 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1036 ExprResult &RHS, QualType LHSType, 1037 QualType RHSType, 1038 bool IsCompAssign) { 1039 // if we have an integer operand, the result is the complex type. 1040 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1041 /*skipCast*/false)) 1042 return LHSType; 1043 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1044 /*skipCast*/IsCompAssign)) 1045 return RHSType; 1046 1047 // This handles complex/complex, complex/float, or float/complex. 1048 // When both operands are complex, the shorter operand is converted to the 1049 // type of the longer, and that is the type of the result. This corresponds 1050 // to what is done when combining two real floating-point operands. 1051 // The fun begins when size promotion occur across type domains. 1052 // From H&S 6.3.4: When one operand is complex and the other is a real 1053 // floating-point type, the less precise type is converted, within it's 1054 // real or complex domain, to the precision of the other type. For example, 1055 // when combining a "long double" with a "double _Complex", the 1056 // "double _Complex" is promoted to "long double _Complex". 1057 1058 // Compute the rank of the two types, regardless of whether they are complex. 1059 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1060 1061 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1062 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1063 QualType LHSElementType = 1064 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1065 QualType RHSElementType = 1066 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1067 1068 QualType ResultType = S.Context.getComplexType(LHSElementType); 1069 if (Order < 0) { 1070 // Promote the precision of the LHS if not an assignment. 1071 ResultType = S.Context.getComplexType(RHSElementType); 1072 if (!IsCompAssign) { 1073 if (LHSComplexType) 1074 LHS = 1075 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1076 else 1077 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1078 } 1079 } else if (Order > 0) { 1080 // Promote the precision of the RHS. 1081 if (RHSComplexType) 1082 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1083 else 1084 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1085 } 1086 return ResultType; 1087 } 1088 1089 /// \brief Hande arithmetic conversion from integer to float. Helper function 1090 /// of UsualArithmeticConversions() 1091 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1092 ExprResult &IntExpr, 1093 QualType FloatTy, QualType IntTy, 1094 bool ConvertFloat, bool ConvertInt) { 1095 if (IntTy->isIntegerType()) { 1096 if (ConvertInt) 1097 // Convert intExpr to the lhs floating point type. 1098 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1099 CK_IntegralToFloating); 1100 return FloatTy; 1101 } 1102 1103 // Convert both sides to the appropriate complex float. 1104 assert(IntTy->isComplexIntegerType()); 1105 QualType result = S.Context.getComplexType(FloatTy); 1106 1107 // _Complex int -> _Complex float 1108 if (ConvertInt) 1109 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1110 CK_IntegralComplexToFloatingComplex); 1111 1112 // float -> _Complex float 1113 if (ConvertFloat) 1114 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1115 CK_FloatingRealToComplex); 1116 1117 return result; 1118 } 1119 1120 /// \brief Handle arithmethic conversion with floating point types. Helper 1121 /// function of UsualArithmeticConversions() 1122 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1123 ExprResult &RHS, QualType LHSType, 1124 QualType RHSType, bool IsCompAssign) { 1125 bool LHSFloat = LHSType->isRealFloatingType(); 1126 bool RHSFloat = RHSType->isRealFloatingType(); 1127 1128 // If we have two real floating types, convert the smaller operand 1129 // to the bigger result. 1130 if (LHSFloat && RHSFloat) { 1131 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1132 if (order > 0) { 1133 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1134 return LHSType; 1135 } 1136 1137 assert(order < 0 && "illegal float comparison"); 1138 if (!IsCompAssign) 1139 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1140 return RHSType; 1141 } 1142 1143 if (LHSFloat) { 1144 // Half FP has to be promoted to float unless it is natively supported 1145 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1146 LHSType = S.Context.FloatTy; 1147 1148 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1149 /*convertFloat=*/!IsCompAssign, 1150 /*convertInt=*/ true); 1151 } 1152 assert(RHSFloat); 1153 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1154 /*convertInt=*/ true, 1155 /*convertFloat=*/!IsCompAssign); 1156 } 1157 1158 /// \brief Diagnose attempts to convert between __float128 and long double if 1159 /// there is no support for such conversion. Helper function of 1160 /// UsualArithmeticConversions(). 1161 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1162 QualType RHSType) { 1163 /* No issue converting if at least one of the types is not a floating point 1164 type or the two types have the same rank. 1165 */ 1166 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1167 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1168 return false; 1169 1170 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1171 "The remaining types must be floating point types."); 1172 1173 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1174 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1175 1176 QualType LHSElemType = LHSComplex ? 1177 LHSComplex->getElementType() : LHSType; 1178 QualType RHSElemType = RHSComplex ? 1179 RHSComplex->getElementType() : RHSType; 1180 1181 // No issue if the two types have the same representation 1182 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1183 &S.Context.getFloatTypeSemantics(RHSElemType)) 1184 return false; 1185 1186 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1187 RHSElemType == S.Context.LongDoubleTy); 1188 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1189 RHSElemType == S.Context.Float128Ty); 1190 1191 /* We've handled the situation where __float128 and long double have the same 1192 representation. The only other allowable conversion is if long double is 1193 really just double. 1194 */ 1195 return Float128AndLongDouble && 1196 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) != 1197 &llvm::APFloat::IEEEdouble()); 1198 } 1199 1200 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1201 1202 namespace { 1203 /// These helper callbacks are placed in an anonymous namespace to 1204 /// permit their use as function template parameters. 1205 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1206 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1207 } 1208 1209 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1210 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1211 CK_IntegralComplexCast); 1212 } 1213 } 1214 1215 /// \brief Handle integer arithmetic conversions. Helper function of 1216 /// UsualArithmeticConversions() 1217 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1218 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1219 ExprResult &RHS, QualType LHSType, 1220 QualType RHSType, bool IsCompAssign) { 1221 // The rules for this case are in C99 6.3.1.8 1222 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1223 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1224 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1225 if (LHSSigned == RHSSigned) { 1226 // Same signedness; use the higher-ranked type 1227 if (order >= 0) { 1228 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1229 return LHSType; 1230 } else if (!IsCompAssign) 1231 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1232 return RHSType; 1233 } else if (order != (LHSSigned ? 1 : -1)) { 1234 // The unsigned type has greater than or equal rank to the 1235 // signed type, so use the unsigned type 1236 if (RHSSigned) { 1237 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1238 return LHSType; 1239 } else if (!IsCompAssign) 1240 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1241 return RHSType; 1242 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1243 // The two types are different widths; if we are here, that 1244 // means the signed type is larger than the unsigned type, so 1245 // use the signed type. 1246 if (LHSSigned) { 1247 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1248 return LHSType; 1249 } else if (!IsCompAssign) 1250 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1251 return RHSType; 1252 } else { 1253 // The signed type is higher-ranked than the unsigned type, 1254 // but isn't actually any bigger (like unsigned int and long 1255 // on most 32-bit systems). Use the unsigned type corresponding 1256 // to the signed type. 1257 QualType result = 1258 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1259 RHS = (*doRHSCast)(S, RHS.get(), result); 1260 if (!IsCompAssign) 1261 LHS = (*doLHSCast)(S, LHS.get(), result); 1262 return result; 1263 } 1264 } 1265 1266 /// \brief Handle conversions with GCC complex int extension. Helper function 1267 /// of UsualArithmeticConversions() 1268 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1269 ExprResult &RHS, QualType LHSType, 1270 QualType RHSType, 1271 bool IsCompAssign) { 1272 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1273 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1274 1275 if (LHSComplexInt && RHSComplexInt) { 1276 QualType LHSEltType = LHSComplexInt->getElementType(); 1277 QualType RHSEltType = RHSComplexInt->getElementType(); 1278 QualType ScalarType = 1279 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1280 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1281 1282 return S.Context.getComplexType(ScalarType); 1283 } 1284 1285 if (LHSComplexInt) { 1286 QualType LHSEltType = LHSComplexInt->getElementType(); 1287 QualType ScalarType = 1288 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1289 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1290 QualType ComplexType = S.Context.getComplexType(ScalarType); 1291 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1292 CK_IntegralRealToComplex); 1293 1294 return ComplexType; 1295 } 1296 1297 assert(RHSComplexInt); 1298 1299 QualType RHSEltType = RHSComplexInt->getElementType(); 1300 QualType ScalarType = 1301 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1302 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1303 QualType ComplexType = S.Context.getComplexType(ScalarType); 1304 1305 if (!IsCompAssign) 1306 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1307 CK_IntegralRealToComplex); 1308 return ComplexType; 1309 } 1310 1311 /// UsualArithmeticConversions - Performs various conversions that are common to 1312 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1313 /// routine returns the first non-arithmetic type found. The client is 1314 /// responsible for emitting appropriate error diagnostics. 1315 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1316 bool IsCompAssign) { 1317 if (!IsCompAssign) { 1318 LHS = UsualUnaryConversions(LHS.get()); 1319 if (LHS.isInvalid()) 1320 return QualType(); 1321 } 1322 1323 RHS = UsualUnaryConversions(RHS.get()); 1324 if (RHS.isInvalid()) 1325 return QualType(); 1326 1327 // For conversion purposes, we ignore any qualifiers. 1328 // For example, "const float" and "float" are equivalent. 1329 QualType LHSType = 1330 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1331 QualType RHSType = 1332 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1333 1334 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1335 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1336 LHSType = AtomicLHS->getValueType(); 1337 1338 // If both types are identical, no conversion is needed. 1339 if (LHSType == RHSType) 1340 return LHSType; 1341 1342 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1343 // The caller can deal with this (e.g. pointer + int). 1344 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1345 return QualType(); 1346 1347 // Apply unary and bitfield promotions to the LHS's type. 1348 QualType LHSUnpromotedType = LHSType; 1349 if (LHSType->isPromotableIntegerType()) 1350 LHSType = Context.getPromotedIntegerType(LHSType); 1351 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1352 if (!LHSBitfieldPromoteTy.isNull()) 1353 LHSType = LHSBitfieldPromoteTy; 1354 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1355 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1356 1357 // If both types are identical, no conversion is needed. 1358 if (LHSType == RHSType) 1359 return LHSType; 1360 1361 // At this point, we have two different arithmetic types. 1362 1363 // Diagnose attempts to convert between __float128 and long double where 1364 // such conversions currently can't be handled. 1365 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1366 return QualType(); 1367 1368 // Handle complex types first (C99 6.3.1.8p1). 1369 if (LHSType->isComplexType() || RHSType->isComplexType()) 1370 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1371 IsCompAssign); 1372 1373 // Now handle "real" floating types (i.e. float, double, long double). 1374 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1375 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1376 IsCompAssign); 1377 1378 // Handle GCC complex int extension. 1379 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1380 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1381 IsCompAssign); 1382 1383 // Finally, we have two differing integer types. 1384 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1385 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1386 } 1387 1388 1389 //===----------------------------------------------------------------------===// 1390 // Semantic Analysis for various Expression Types 1391 //===----------------------------------------------------------------------===// 1392 1393 1394 ExprResult 1395 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1396 SourceLocation DefaultLoc, 1397 SourceLocation RParenLoc, 1398 Expr *ControllingExpr, 1399 ArrayRef<ParsedType> ArgTypes, 1400 ArrayRef<Expr *> ArgExprs) { 1401 unsigned NumAssocs = ArgTypes.size(); 1402 assert(NumAssocs == ArgExprs.size()); 1403 1404 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1405 for (unsigned i = 0; i < NumAssocs; ++i) { 1406 if (ArgTypes[i]) 1407 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1408 else 1409 Types[i] = nullptr; 1410 } 1411 1412 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1413 ControllingExpr, 1414 llvm::makeArrayRef(Types, NumAssocs), 1415 ArgExprs); 1416 delete [] Types; 1417 return ER; 1418 } 1419 1420 ExprResult 1421 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1422 SourceLocation DefaultLoc, 1423 SourceLocation RParenLoc, 1424 Expr *ControllingExpr, 1425 ArrayRef<TypeSourceInfo *> Types, 1426 ArrayRef<Expr *> Exprs) { 1427 unsigned NumAssocs = Types.size(); 1428 assert(NumAssocs == Exprs.size()); 1429 1430 // Decay and strip qualifiers for the controlling expression type, and handle 1431 // placeholder type replacement. See committee discussion from WG14 DR423. 1432 { 1433 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 1434 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1435 if (R.isInvalid()) 1436 return ExprError(); 1437 ControllingExpr = R.get(); 1438 } 1439 1440 // The controlling expression is an unevaluated operand, so side effects are 1441 // likely unintended. 1442 if (ActiveTemplateInstantiations.empty() && 1443 ControllingExpr->HasSideEffects(Context, false)) 1444 Diag(ControllingExpr->getExprLoc(), 1445 diag::warn_side_effects_unevaluated_context); 1446 1447 bool TypeErrorFound = false, 1448 IsResultDependent = ControllingExpr->isTypeDependent(), 1449 ContainsUnexpandedParameterPack 1450 = ControllingExpr->containsUnexpandedParameterPack(); 1451 1452 for (unsigned i = 0; i < NumAssocs; ++i) { 1453 if (Exprs[i]->containsUnexpandedParameterPack()) 1454 ContainsUnexpandedParameterPack = true; 1455 1456 if (Types[i]) { 1457 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1458 ContainsUnexpandedParameterPack = true; 1459 1460 if (Types[i]->getType()->isDependentType()) { 1461 IsResultDependent = true; 1462 } else { 1463 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1464 // complete object type other than a variably modified type." 1465 unsigned D = 0; 1466 if (Types[i]->getType()->isIncompleteType()) 1467 D = diag::err_assoc_type_incomplete; 1468 else if (!Types[i]->getType()->isObjectType()) 1469 D = diag::err_assoc_type_nonobject; 1470 else if (Types[i]->getType()->isVariablyModifiedType()) 1471 D = diag::err_assoc_type_variably_modified; 1472 1473 if (D != 0) { 1474 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1475 << Types[i]->getTypeLoc().getSourceRange() 1476 << Types[i]->getType(); 1477 TypeErrorFound = true; 1478 } 1479 1480 // C11 6.5.1.1p2 "No two generic associations in the same generic 1481 // selection shall specify compatible types." 1482 for (unsigned j = i+1; j < NumAssocs; ++j) 1483 if (Types[j] && !Types[j]->getType()->isDependentType() && 1484 Context.typesAreCompatible(Types[i]->getType(), 1485 Types[j]->getType())) { 1486 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1487 diag::err_assoc_compatible_types) 1488 << Types[j]->getTypeLoc().getSourceRange() 1489 << Types[j]->getType() 1490 << Types[i]->getType(); 1491 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1492 diag::note_compat_assoc) 1493 << Types[i]->getTypeLoc().getSourceRange() 1494 << Types[i]->getType(); 1495 TypeErrorFound = true; 1496 } 1497 } 1498 } 1499 } 1500 if (TypeErrorFound) 1501 return ExprError(); 1502 1503 // If we determined that the generic selection is result-dependent, don't 1504 // try to compute the result expression. 1505 if (IsResultDependent) 1506 return new (Context) GenericSelectionExpr( 1507 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1508 ContainsUnexpandedParameterPack); 1509 1510 SmallVector<unsigned, 1> CompatIndices; 1511 unsigned DefaultIndex = -1U; 1512 for (unsigned i = 0; i < NumAssocs; ++i) { 1513 if (!Types[i]) 1514 DefaultIndex = i; 1515 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1516 Types[i]->getType())) 1517 CompatIndices.push_back(i); 1518 } 1519 1520 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1521 // type compatible with at most one of the types named in its generic 1522 // association list." 1523 if (CompatIndices.size() > 1) { 1524 // We strip parens here because the controlling expression is typically 1525 // parenthesized in macro definitions. 1526 ControllingExpr = ControllingExpr->IgnoreParens(); 1527 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1528 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1529 << (unsigned) CompatIndices.size(); 1530 for (unsigned I : CompatIndices) { 1531 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1532 diag::note_compat_assoc) 1533 << Types[I]->getTypeLoc().getSourceRange() 1534 << Types[I]->getType(); 1535 } 1536 return ExprError(); 1537 } 1538 1539 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1540 // its controlling expression shall have type compatible with exactly one of 1541 // the types named in its generic association list." 1542 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1543 // We strip parens here because the controlling expression is typically 1544 // parenthesized in macro definitions. 1545 ControllingExpr = ControllingExpr->IgnoreParens(); 1546 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1547 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1548 return ExprError(); 1549 } 1550 1551 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1552 // type name that is compatible with the type of the controlling expression, 1553 // then the result expression of the generic selection is the expression 1554 // in that generic association. Otherwise, the result expression of the 1555 // generic selection is the expression in the default generic association." 1556 unsigned ResultIndex = 1557 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1558 1559 return new (Context) GenericSelectionExpr( 1560 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1561 ContainsUnexpandedParameterPack, ResultIndex); 1562 } 1563 1564 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1565 /// location of the token and the offset of the ud-suffix within it. 1566 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1567 unsigned Offset) { 1568 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1569 S.getLangOpts()); 1570 } 1571 1572 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1573 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1574 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1575 IdentifierInfo *UDSuffix, 1576 SourceLocation UDSuffixLoc, 1577 ArrayRef<Expr*> Args, 1578 SourceLocation LitEndLoc) { 1579 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1580 1581 QualType ArgTy[2]; 1582 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1583 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1584 if (ArgTy[ArgIdx]->isArrayType()) 1585 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1586 } 1587 1588 DeclarationName OpName = 1589 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1590 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1591 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1592 1593 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1594 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1595 /*AllowRaw*/false, /*AllowTemplate*/false, 1596 /*AllowStringTemplate*/false) == Sema::LOLR_Error) 1597 return ExprError(); 1598 1599 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1600 } 1601 1602 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1603 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1604 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1605 /// multiple tokens. However, the common case is that StringToks points to one 1606 /// string. 1607 /// 1608 ExprResult 1609 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1610 assert(!StringToks.empty() && "Must have at least one string!"); 1611 1612 StringLiteralParser Literal(StringToks, PP); 1613 if (Literal.hadError) 1614 return ExprError(); 1615 1616 SmallVector<SourceLocation, 4> StringTokLocs; 1617 for (const Token &Tok : StringToks) 1618 StringTokLocs.push_back(Tok.getLocation()); 1619 1620 QualType CharTy = Context.CharTy; 1621 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1622 if (Literal.isWide()) { 1623 CharTy = Context.getWideCharType(); 1624 Kind = StringLiteral::Wide; 1625 } else if (Literal.isUTF8()) { 1626 Kind = StringLiteral::UTF8; 1627 } else if (Literal.isUTF16()) { 1628 CharTy = Context.Char16Ty; 1629 Kind = StringLiteral::UTF16; 1630 } else if (Literal.isUTF32()) { 1631 CharTy = Context.Char32Ty; 1632 Kind = StringLiteral::UTF32; 1633 } else if (Literal.isPascal()) { 1634 CharTy = Context.UnsignedCharTy; 1635 } 1636 1637 QualType CharTyConst = CharTy; 1638 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1639 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1640 CharTyConst.addConst(); 1641 1642 // Get an array type for the string, according to C99 6.4.5. This includes 1643 // the nul terminator character as well as the string length for pascal 1644 // strings. 1645 QualType StrTy = Context.getConstantArrayType(CharTyConst, 1646 llvm::APInt(32, Literal.GetNumStringChars()+1), 1647 ArrayType::Normal, 0); 1648 1649 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 1650 if (getLangOpts().OpenCL) { 1651 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant); 1652 } 1653 1654 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1655 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1656 Kind, Literal.Pascal, StrTy, 1657 &StringTokLocs[0], 1658 StringTokLocs.size()); 1659 if (Literal.getUDSuffix().empty()) 1660 return Lit; 1661 1662 // We're building a user-defined literal. 1663 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1664 SourceLocation UDSuffixLoc = 1665 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1666 Literal.getUDSuffixOffset()); 1667 1668 // Make sure we're allowed user-defined literals here. 1669 if (!UDLScope) 1670 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1671 1672 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1673 // operator "" X (str, len) 1674 QualType SizeType = Context.getSizeType(); 1675 1676 DeclarationName OpName = 1677 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1678 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1679 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1680 1681 QualType ArgTy[] = { 1682 Context.getArrayDecayedType(StrTy), SizeType 1683 }; 1684 1685 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1686 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1687 /*AllowRaw*/false, /*AllowTemplate*/false, 1688 /*AllowStringTemplate*/true)) { 1689 1690 case LOLR_Cooked: { 1691 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1692 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1693 StringTokLocs[0]); 1694 Expr *Args[] = { Lit, LenArg }; 1695 1696 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1697 } 1698 1699 case LOLR_StringTemplate: { 1700 TemplateArgumentListInfo ExplicitArgs; 1701 1702 unsigned CharBits = Context.getIntWidth(CharTy); 1703 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1704 llvm::APSInt Value(CharBits, CharIsUnsigned); 1705 1706 TemplateArgument TypeArg(CharTy); 1707 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1708 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1709 1710 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1711 Value = Lit->getCodeUnit(I); 1712 TemplateArgument Arg(Context, Value, CharTy); 1713 TemplateArgumentLocInfo ArgInfo; 1714 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1715 } 1716 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1717 &ExplicitArgs); 1718 } 1719 case LOLR_Raw: 1720 case LOLR_Template: 1721 llvm_unreachable("unexpected literal operator lookup result"); 1722 case LOLR_Error: 1723 return ExprError(); 1724 } 1725 llvm_unreachable("unexpected literal operator lookup result"); 1726 } 1727 1728 ExprResult 1729 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1730 SourceLocation Loc, 1731 const CXXScopeSpec *SS) { 1732 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1733 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1734 } 1735 1736 /// BuildDeclRefExpr - Build an expression that references a 1737 /// declaration that does not require a closure capture. 1738 ExprResult 1739 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1740 const DeclarationNameInfo &NameInfo, 1741 const CXXScopeSpec *SS, NamedDecl *FoundD, 1742 const TemplateArgumentListInfo *TemplateArgs) { 1743 bool RefersToCapturedVariable = 1744 isa<VarDecl>(D) && 1745 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1746 1747 DeclRefExpr *E; 1748 if (isa<VarTemplateSpecializationDecl>(D)) { 1749 VarTemplateSpecializationDecl *VarSpec = 1750 cast<VarTemplateSpecializationDecl>(D); 1751 1752 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1753 : NestedNameSpecifierLoc(), 1754 VarSpec->getTemplateKeywordLoc(), D, 1755 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK, 1756 FoundD, TemplateArgs); 1757 } else { 1758 assert(!TemplateArgs && "No template arguments for non-variable" 1759 " template specialization references"); 1760 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1761 : NestedNameSpecifierLoc(), 1762 SourceLocation(), D, RefersToCapturedVariable, 1763 NameInfo, Ty, VK, FoundD); 1764 } 1765 1766 MarkDeclRefReferenced(E); 1767 1768 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1769 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && 1770 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart())) 1771 recordUseOfEvaluatedWeak(E); 1772 1773 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 1774 UnusedPrivateFields.remove(FD); 1775 // Just in case we're building an illegal pointer-to-member. 1776 if (FD->isBitField()) 1777 E->setObjectKind(OK_BitField); 1778 } 1779 1780 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1781 // designates a bit-field. 1782 if (auto *BD = dyn_cast<BindingDecl>(D)) 1783 if (auto *BE = BD->getBinding()) 1784 E->setObjectKind(BE->getObjectKind()); 1785 1786 return E; 1787 } 1788 1789 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1790 /// possibly a list of template arguments. 1791 /// 1792 /// If this produces template arguments, it is permitted to call 1793 /// DecomposeTemplateName. 1794 /// 1795 /// This actually loses a lot of source location information for 1796 /// non-standard name kinds; we should consider preserving that in 1797 /// some way. 1798 void 1799 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1800 TemplateArgumentListInfo &Buffer, 1801 DeclarationNameInfo &NameInfo, 1802 const TemplateArgumentListInfo *&TemplateArgs) { 1803 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1804 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1805 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1806 1807 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1808 Id.TemplateId->NumArgs); 1809 translateTemplateArguments(TemplateArgsPtr, Buffer); 1810 1811 TemplateName TName = Id.TemplateId->Template.get(); 1812 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1813 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1814 TemplateArgs = &Buffer; 1815 } else { 1816 NameInfo = GetNameFromUnqualifiedId(Id); 1817 TemplateArgs = nullptr; 1818 } 1819 } 1820 1821 static void emitEmptyLookupTypoDiagnostic( 1822 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1823 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1824 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1825 DeclContext *Ctx = 1826 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1827 if (!TC) { 1828 // Emit a special diagnostic for failed member lookups. 1829 // FIXME: computing the declaration context might fail here (?) 1830 if (Ctx) 1831 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1832 << SS.getRange(); 1833 else 1834 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1835 return; 1836 } 1837 1838 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1839 bool DroppedSpecifier = 1840 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1841 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1842 ? diag::note_implicit_param_decl 1843 : diag::note_previous_decl; 1844 if (!Ctx) 1845 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1846 SemaRef.PDiag(NoteID)); 1847 else 1848 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1849 << Typo << Ctx << DroppedSpecifier 1850 << SS.getRange(), 1851 SemaRef.PDiag(NoteID)); 1852 } 1853 1854 /// Diagnose an empty lookup. 1855 /// 1856 /// \return false if new lookup candidates were found 1857 bool 1858 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1859 std::unique_ptr<CorrectionCandidateCallback> CCC, 1860 TemplateArgumentListInfo *ExplicitTemplateArgs, 1861 ArrayRef<Expr *> Args, TypoExpr **Out) { 1862 DeclarationName Name = R.getLookupName(); 1863 1864 unsigned diagnostic = diag::err_undeclared_var_use; 1865 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1866 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1867 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1868 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1869 diagnostic = diag::err_undeclared_use; 1870 diagnostic_suggest = diag::err_undeclared_use_suggest; 1871 } 1872 1873 // If the original lookup was an unqualified lookup, fake an 1874 // unqualified lookup. This is useful when (for example) the 1875 // original lookup would not have found something because it was a 1876 // dependent name. 1877 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1878 while (DC) { 1879 if (isa<CXXRecordDecl>(DC)) { 1880 LookupQualifiedName(R, DC); 1881 1882 if (!R.empty()) { 1883 // Don't give errors about ambiguities in this lookup. 1884 R.suppressDiagnostics(); 1885 1886 // During a default argument instantiation the CurContext points 1887 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1888 // function parameter list, hence add an explicit check. 1889 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() && 1890 ActiveTemplateInstantiations.back().Kind == 1891 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation; 1892 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1893 bool isInstance = CurMethod && 1894 CurMethod->isInstance() && 1895 DC == CurMethod->getParent() && !isDefaultArgument; 1896 1897 // Give a code modification hint to insert 'this->'. 1898 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1899 // Actually quite difficult! 1900 if (getLangOpts().MSVCCompat) 1901 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1902 if (isInstance) { 1903 Diag(R.getNameLoc(), diagnostic) << Name 1904 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1905 CheckCXXThisCapture(R.getNameLoc()); 1906 } else { 1907 Diag(R.getNameLoc(), diagnostic) << Name; 1908 } 1909 1910 // Do we really want to note all of these? 1911 for (NamedDecl *D : R) 1912 Diag(D->getLocation(), diag::note_dependent_var_use); 1913 1914 // Return true if we are inside a default argument instantiation 1915 // and the found name refers to an instance member function, otherwise 1916 // the function calling DiagnoseEmptyLookup will try to create an 1917 // implicit member call and this is wrong for default argument. 1918 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1919 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1920 return true; 1921 } 1922 1923 // Tell the callee to try to recover. 1924 return false; 1925 } 1926 1927 R.clear(); 1928 } 1929 1930 // In Microsoft mode, if we are performing lookup from within a friend 1931 // function definition declared at class scope then we must set 1932 // DC to the lexical parent to be able to search into the parent 1933 // class. 1934 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1935 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1936 DC->getLexicalParent()->isRecord()) 1937 DC = DC->getLexicalParent(); 1938 else 1939 DC = DC->getParent(); 1940 } 1941 1942 // We didn't find anything, so try to correct for a typo. 1943 TypoCorrection Corrected; 1944 if (S && Out) { 1945 SourceLocation TypoLoc = R.getNameLoc(); 1946 assert(!ExplicitTemplateArgs && 1947 "Diagnosing an empty lookup with explicit template args!"); 1948 *Out = CorrectTypoDelayed( 1949 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC), 1950 [=](const TypoCorrection &TC) { 1951 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 1952 diagnostic, diagnostic_suggest); 1953 }, 1954 nullptr, CTK_ErrorRecovery); 1955 if (*Out) 1956 return true; 1957 } else if (S && (Corrected = 1958 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, 1959 &SS, std::move(CCC), CTK_ErrorRecovery))) { 1960 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1961 bool DroppedSpecifier = 1962 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1963 R.setLookupName(Corrected.getCorrection()); 1964 1965 bool AcceptableWithRecovery = false; 1966 bool AcceptableWithoutRecovery = false; 1967 NamedDecl *ND = Corrected.getFoundDecl(); 1968 if (ND) { 1969 if (Corrected.isOverloaded()) { 1970 OverloadCandidateSet OCS(R.getNameLoc(), 1971 OverloadCandidateSet::CSK_Normal); 1972 OverloadCandidateSet::iterator Best; 1973 for (NamedDecl *CD : Corrected) { 1974 if (FunctionTemplateDecl *FTD = 1975 dyn_cast<FunctionTemplateDecl>(CD)) 1976 AddTemplateOverloadCandidate( 1977 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1978 Args, OCS); 1979 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 1980 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1981 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1982 Args, OCS); 1983 } 1984 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1985 case OR_Success: 1986 ND = Best->FoundDecl; 1987 Corrected.setCorrectionDecl(ND); 1988 break; 1989 default: 1990 // FIXME: Arbitrarily pick the first declaration for the note. 1991 Corrected.setCorrectionDecl(ND); 1992 break; 1993 } 1994 } 1995 R.addDecl(ND); 1996 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 1997 CXXRecordDecl *Record = nullptr; 1998 if (Corrected.getCorrectionSpecifier()) { 1999 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2000 Record = Ty->getAsCXXRecordDecl(); 2001 } 2002 if (!Record) 2003 Record = cast<CXXRecordDecl>( 2004 ND->getDeclContext()->getRedeclContext()); 2005 R.setNamingClass(Record); 2006 } 2007 2008 auto *UnderlyingND = ND->getUnderlyingDecl(); 2009 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2010 isa<FunctionTemplateDecl>(UnderlyingND); 2011 // FIXME: If we ended up with a typo for a type name or 2012 // Objective-C class name, we're in trouble because the parser 2013 // is in the wrong place to recover. Suggest the typo 2014 // correction, but don't make it a fix-it since we're not going 2015 // to recover well anyway. 2016 AcceptableWithoutRecovery = 2017 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND); 2018 } else { 2019 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2020 // because we aren't able to recover. 2021 AcceptableWithoutRecovery = true; 2022 } 2023 2024 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2025 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2026 ? diag::note_implicit_param_decl 2027 : diag::note_previous_decl; 2028 if (SS.isEmpty()) 2029 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2030 PDiag(NoteID), AcceptableWithRecovery); 2031 else 2032 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2033 << Name << computeDeclContext(SS, false) 2034 << DroppedSpecifier << SS.getRange(), 2035 PDiag(NoteID), AcceptableWithRecovery); 2036 2037 // Tell the callee whether to try to recover. 2038 return !AcceptableWithRecovery; 2039 } 2040 } 2041 R.clear(); 2042 2043 // Emit a special diagnostic for failed member lookups. 2044 // FIXME: computing the declaration context might fail here (?) 2045 if (!SS.isEmpty()) { 2046 Diag(R.getNameLoc(), diag::err_no_member) 2047 << Name << computeDeclContext(SS, false) 2048 << SS.getRange(); 2049 return true; 2050 } 2051 2052 // Give up, we can't recover. 2053 Diag(R.getNameLoc(), diagnostic) << Name; 2054 return true; 2055 } 2056 2057 /// In Microsoft mode, if we are inside a template class whose parent class has 2058 /// dependent base classes, and we can't resolve an unqualified identifier, then 2059 /// assume the identifier is a member of a dependent base class. We can only 2060 /// recover successfully in static methods, instance methods, and other contexts 2061 /// where 'this' is available. This doesn't precisely match MSVC's 2062 /// instantiation model, but it's close enough. 2063 static Expr * 2064 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2065 DeclarationNameInfo &NameInfo, 2066 SourceLocation TemplateKWLoc, 2067 const TemplateArgumentListInfo *TemplateArgs) { 2068 // Only try to recover from lookup into dependent bases in static methods or 2069 // contexts where 'this' is available. 2070 QualType ThisType = S.getCurrentThisType(); 2071 const CXXRecordDecl *RD = nullptr; 2072 if (!ThisType.isNull()) 2073 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2074 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2075 RD = MD->getParent(); 2076 if (!RD || !RD->hasAnyDependentBases()) 2077 return nullptr; 2078 2079 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2080 // is available, suggest inserting 'this->' as a fixit. 2081 SourceLocation Loc = NameInfo.getLoc(); 2082 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2083 DB << NameInfo.getName() << RD; 2084 2085 if (!ThisType.isNull()) { 2086 DB << FixItHint::CreateInsertion(Loc, "this->"); 2087 return CXXDependentScopeMemberExpr::Create( 2088 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2089 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2090 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 2091 } 2092 2093 // Synthesize a fake NNS that points to the derived class. This will 2094 // perform name lookup during template instantiation. 2095 CXXScopeSpec SS; 2096 auto *NNS = 2097 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2098 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2099 return DependentScopeDeclRefExpr::Create( 2100 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2101 TemplateArgs); 2102 } 2103 2104 ExprResult 2105 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2106 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2107 bool HasTrailingLParen, bool IsAddressOfOperand, 2108 std::unique_ptr<CorrectionCandidateCallback> CCC, 2109 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2110 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2111 "cannot be direct & operand and have a trailing lparen"); 2112 if (SS.isInvalid()) 2113 return ExprError(); 2114 2115 TemplateArgumentListInfo TemplateArgsBuffer; 2116 2117 // Decompose the UnqualifiedId into the following data. 2118 DeclarationNameInfo NameInfo; 2119 const TemplateArgumentListInfo *TemplateArgs; 2120 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2121 2122 DeclarationName Name = NameInfo.getName(); 2123 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2124 SourceLocation NameLoc = NameInfo.getLoc(); 2125 2126 // C++ [temp.dep.expr]p3: 2127 // An id-expression is type-dependent if it contains: 2128 // -- an identifier that was declared with a dependent type, 2129 // (note: handled after lookup) 2130 // -- a template-id that is dependent, 2131 // (note: handled in BuildTemplateIdExpr) 2132 // -- a conversion-function-id that specifies a dependent type, 2133 // -- a nested-name-specifier that contains a class-name that 2134 // names a dependent type. 2135 // Determine whether this is a member of an unknown specialization; 2136 // we need to handle these differently. 2137 bool DependentID = false; 2138 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2139 Name.getCXXNameType()->isDependentType()) { 2140 DependentID = true; 2141 } else if (SS.isSet()) { 2142 if (DeclContext *DC = computeDeclContext(SS, false)) { 2143 if (RequireCompleteDeclContext(SS, DC)) 2144 return ExprError(); 2145 } else { 2146 DependentID = true; 2147 } 2148 } 2149 2150 if (DependentID) 2151 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2152 IsAddressOfOperand, TemplateArgs); 2153 2154 // Perform the required lookup. 2155 LookupResult R(*this, NameInfo, 2156 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 2157 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 2158 if (TemplateArgs) { 2159 // Lookup the template name again to correctly establish the context in 2160 // which it was found. This is really unfortunate as we already did the 2161 // lookup to determine that it was a template name in the first place. If 2162 // this becomes a performance hit, we can work harder to preserve those 2163 // results until we get here but it's likely not worth it. 2164 bool MemberOfUnknownSpecialization; 2165 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2166 MemberOfUnknownSpecialization); 2167 2168 if (MemberOfUnknownSpecialization || 2169 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2170 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2171 IsAddressOfOperand, TemplateArgs); 2172 } else { 2173 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2174 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2175 2176 // If the result might be in a dependent base class, this is a dependent 2177 // id-expression. 2178 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2179 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2180 IsAddressOfOperand, TemplateArgs); 2181 2182 // If this reference is in an Objective-C method, then we need to do 2183 // some special Objective-C lookup, too. 2184 if (IvarLookupFollowUp) { 2185 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2186 if (E.isInvalid()) 2187 return ExprError(); 2188 2189 if (Expr *Ex = E.getAs<Expr>()) 2190 return Ex; 2191 } 2192 } 2193 2194 if (R.isAmbiguous()) 2195 return ExprError(); 2196 2197 // This could be an implicitly declared function reference (legal in C90, 2198 // extension in C99, forbidden in C++). 2199 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2200 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2201 if (D) R.addDecl(D); 2202 } 2203 2204 // Determine whether this name might be a candidate for 2205 // argument-dependent lookup. 2206 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2207 2208 if (R.empty() && !ADL) { 2209 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2210 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2211 TemplateKWLoc, TemplateArgs)) 2212 return E; 2213 } 2214 2215 // Don't diagnose an empty lookup for inline assembly. 2216 if (IsInlineAsmIdentifier) 2217 return ExprError(); 2218 2219 // If this name wasn't predeclared and if this is not a function 2220 // call, diagnose the problem. 2221 TypoExpr *TE = nullptr; 2222 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2223 II, SS.isValid() ? SS.getScopeRep() : nullptr); 2224 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; 2225 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2226 "Typo correction callback misconfigured"); 2227 if (CCC) { 2228 // Make sure the callback knows what the typo being diagnosed is. 2229 CCC->setTypoName(II); 2230 if (SS.isValid()) 2231 CCC->setTypoNNS(SS.getScopeRep()); 2232 } 2233 if (DiagnoseEmptyLookup(S, SS, R, 2234 CCC ? std::move(CCC) : std::move(DefaultValidator), 2235 nullptr, None, &TE)) { 2236 if (TE && KeywordReplacement) { 2237 auto &State = getTypoExprState(TE); 2238 auto BestTC = State.Consumer->getNextCorrection(); 2239 if (BestTC.isKeyword()) { 2240 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2241 if (State.DiagHandler) 2242 State.DiagHandler(BestTC); 2243 KeywordReplacement->startToken(); 2244 KeywordReplacement->setKind(II->getTokenID()); 2245 KeywordReplacement->setIdentifierInfo(II); 2246 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2247 // Clean up the state associated with the TypoExpr, since it has 2248 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2249 clearDelayedTypo(TE); 2250 // Signal that a correction to a keyword was performed by returning a 2251 // valid-but-null ExprResult. 2252 return (Expr*)nullptr; 2253 } 2254 State.Consumer->resetCorrectionStream(); 2255 } 2256 return TE ? TE : ExprError(); 2257 } 2258 2259 assert(!R.empty() && 2260 "DiagnoseEmptyLookup returned false but added no results"); 2261 2262 // If we found an Objective-C instance variable, let 2263 // LookupInObjCMethod build the appropriate expression to 2264 // reference the ivar. 2265 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2266 R.clear(); 2267 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2268 // In a hopelessly buggy code, Objective-C instance variable 2269 // lookup fails and no expression will be built to reference it. 2270 if (!E.isInvalid() && !E.get()) 2271 return ExprError(); 2272 return E; 2273 } 2274 } 2275 2276 // This is guaranteed from this point on. 2277 assert(!R.empty() || ADL); 2278 2279 // Check whether this might be a C++ implicit instance member access. 2280 // C++ [class.mfct.non-static]p3: 2281 // When an id-expression that is not part of a class member access 2282 // syntax and not used to form a pointer to member is used in the 2283 // body of a non-static member function of class X, if name lookup 2284 // resolves the name in the id-expression to a non-static non-type 2285 // member of some class C, the id-expression is transformed into a 2286 // class member access expression using (*this) as the 2287 // postfix-expression to the left of the . operator. 2288 // 2289 // But we don't actually need to do this for '&' operands if R 2290 // resolved to a function or overloaded function set, because the 2291 // expression is ill-formed if it actually works out to be a 2292 // non-static member function: 2293 // 2294 // C++ [expr.ref]p4: 2295 // Otherwise, if E1.E2 refers to a non-static member function. . . 2296 // [t]he expression can be used only as the left-hand operand of a 2297 // member function call. 2298 // 2299 // There are other safeguards against such uses, but it's important 2300 // to get this right here so that we don't end up making a 2301 // spuriously dependent expression if we're inside a dependent 2302 // instance method. 2303 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2304 bool MightBeImplicitMember; 2305 if (!IsAddressOfOperand) 2306 MightBeImplicitMember = true; 2307 else if (!SS.isEmpty()) 2308 MightBeImplicitMember = false; 2309 else if (R.isOverloadedResult()) 2310 MightBeImplicitMember = false; 2311 else if (R.isUnresolvableResult()) 2312 MightBeImplicitMember = true; 2313 else 2314 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2315 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2316 isa<MSPropertyDecl>(R.getFoundDecl()); 2317 2318 if (MightBeImplicitMember) 2319 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2320 R, TemplateArgs, S); 2321 } 2322 2323 if (TemplateArgs || TemplateKWLoc.isValid()) { 2324 2325 // In C++1y, if this is a variable template id, then check it 2326 // in BuildTemplateIdExpr(). 2327 // The single lookup result must be a variable template declaration. 2328 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId && 2329 Id.TemplateId->Kind == TNK_Var_template) { 2330 assert(R.getAsSingle<VarTemplateDecl>() && 2331 "There should only be one declaration found."); 2332 } 2333 2334 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2335 } 2336 2337 return BuildDeclarationNameExpr(SS, R, ADL); 2338 } 2339 2340 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2341 /// declaration name, generally during template instantiation. 2342 /// There's a large number of things which don't need to be done along 2343 /// this path. 2344 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2345 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2346 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2347 DeclContext *DC = computeDeclContext(SS, false); 2348 if (!DC) 2349 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2350 NameInfo, /*TemplateArgs=*/nullptr); 2351 2352 if (RequireCompleteDeclContext(SS, DC)) 2353 return ExprError(); 2354 2355 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2356 LookupQualifiedName(R, DC); 2357 2358 if (R.isAmbiguous()) 2359 return ExprError(); 2360 2361 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2362 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2363 NameInfo, /*TemplateArgs=*/nullptr); 2364 2365 if (R.empty()) { 2366 Diag(NameInfo.getLoc(), diag::err_no_member) 2367 << NameInfo.getName() << DC << SS.getRange(); 2368 return ExprError(); 2369 } 2370 2371 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2372 // Diagnose a missing typename if this resolved unambiguously to a type in 2373 // a dependent context. If we can recover with a type, downgrade this to 2374 // a warning in Microsoft compatibility mode. 2375 unsigned DiagID = diag::err_typename_missing; 2376 if (RecoveryTSI && getLangOpts().MSVCCompat) 2377 DiagID = diag::ext_typename_missing; 2378 SourceLocation Loc = SS.getBeginLoc(); 2379 auto D = Diag(Loc, DiagID); 2380 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2381 << SourceRange(Loc, NameInfo.getEndLoc()); 2382 2383 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2384 // context. 2385 if (!RecoveryTSI) 2386 return ExprError(); 2387 2388 // Only issue the fixit if we're prepared to recover. 2389 D << FixItHint::CreateInsertion(Loc, "typename "); 2390 2391 // Recover by pretending this was an elaborated type. 2392 QualType Ty = Context.getTypeDeclType(TD); 2393 TypeLocBuilder TLB; 2394 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2395 2396 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2397 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2398 QTL.setElaboratedKeywordLoc(SourceLocation()); 2399 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2400 2401 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2402 2403 return ExprEmpty(); 2404 } 2405 2406 // Defend against this resolving to an implicit member access. We usually 2407 // won't get here if this might be a legitimate a class member (we end up in 2408 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2409 // a pointer-to-member or in an unevaluated context in C++11. 2410 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2411 return BuildPossibleImplicitMemberExpr(SS, 2412 /*TemplateKWLoc=*/SourceLocation(), 2413 R, /*TemplateArgs=*/nullptr, S); 2414 2415 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2416 } 2417 2418 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2419 /// detected that we're currently inside an ObjC method. Perform some 2420 /// additional lookup. 2421 /// 2422 /// Ideally, most of this would be done by lookup, but there's 2423 /// actually quite a lot of extra work involved. 2424 /// 2425 /// Returns a null sentinel to indicate trivial success. 2426 ExprResult 2427 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2428 IdentifierInfo *II, bool AllowBuiltinCreation) { 2429 SourceLocation Loc = Lookup.getNameLoc(); 2430 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2431 2432 // Check for error condition which is already reported. 2433 if (!CurMethod) 2434 return ExprError(); 2435 2436 // There are two cases to handle here. 1) scoped lookup could have failed, 2437 // in which case we should look for an ivar. 2) scoped lookup could have 2438 // found a decl, but that decl is outside the current instance method (i.e. 2439 // a global variable). In these two cases, we do a lookup for an ivar with 2440 // this name, if the lookup sucedes, we replace it our current decl. 2441 2442 // If we're in a class method, we don't normally want to look for 2443 // ivars. But if we don't find anything else, and there's an 2444 // ivar, that's an error. 2445 bool IsClassMethod = CurMethod->isClassMethod(); 2446 2447 bool LookForIvars; 2448 if (Lookup.empty()) 2449 LookForIvars = true; 2450 else if (IsClassMethod) 2451 LookForIvars = false; 2452 else 2453 LookForIvars = (Lookup.isSingleResult() && 2454 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2455 ObjCInterfaceDecl *IFace = nullptr; 2456 if (LookForIvars) { 2457 IFace = CurMethod->getClassInterface(); 2458 ObjCInterfaceDecl *ClassDeclared; 2459 ObjCIvarDecl *IV = nullptr; 2460 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2461 // Diagnose using an ivar in a class method. 2462 if (IsClassMethod) 2463 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2464 << IV->getDeclName()); 2465 2466 // If we're referencing an invalid decl, just return this as a silent 2467 // error node. The error diagnostic was already emitted on the decl. 2468 if (IV->isInvalidDecl()) 2469 return ExprError(); 2470 2471 // Check if referencing a field with __attribute__((deprecated)). 2472 if (DiagnoseUseOfDecl(IV, Loc)) 2473 return ExprError(); 2474 2475 // Diagnose the use of an ivar outside of the declaring class. 2476 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2477 !declaresSameEntity(ClassDeclared, IFace) && 2478 !getLangOpts().DebuggerSupport) 2479 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2480 2481 // FIXME: This should use a new expr for a direct reference, don't 2482 // turn this into Self->ivar, just return a BareIVarExpr or something. 2483 IdentifierInfo &II = Context.Idents.get("self"); 2484 UnqualifiedId SelfName; 2485 SelfName.setIdentifier(&II, SourceLocation()); 2486 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2487 CXXScopeSpec SelfScopeSpec; 2488 SourceLocation TemplateKWLoc; 2489 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2490 SelfName, false, false); 2491 if (SelfExpr.isInvalid()) 2492 return ExprError(); 2493 2494 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2495 if (SelfExpr.isInvalid()) 2496 return ExprError(); 2497 2498 MarkAnyDeclReferenced(Loc, IV, true); 2499 2500 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2501 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2502 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2503 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2504 2505 ObjCIvarRefExpr *Result = new (Context) 2506 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2507 IV->getLocation(), SelfExpr.get(), true, true); 2508 2509 if (getLangOpts().ObjCAutoRefCount) { 2510 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2511 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2512 recordUseOfEvaluatedWeak(Result); 2513 } 2514 if (CurContext->isClosure()) 2515 Diag(Loc, diag::warn_implicitly_retains_self) 2516 << FixItHint::CreateInsertion(Loc, "self->"); 2517 } 2518 2519 return Result; 2520 } 2521 } else if (CurMethod->isInstanceMethod()) { 2522 // We should warn if a local variable hides an ivar. 2523 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2524 ObjCInterfaceDecl *ClassDeclared; 2525 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2526 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2527 declaresSameEntity(IFace, ClassDeclared)) 2528 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2529 } 2530 } 2531 } else if (Lookup.isSingleResult() && 2532 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2533 // If accessing a stand-alone ivar in a class method, this is an error. 2534 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2535 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2536 << IV->getDeclName()); 2537 } 2538 2539 if (Lookup.empty() && II && AllowBuiltinCreation) { 2540 // FIXME. Consolidate this with similar code in LookupName. 2541 if (unsigned BuiltinID = II->getBuiltinID()) { 2542 if (!(getLangOpts().CPlusPlus && 2543 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2544 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2545 S, Lookup.isForRedeclaration(), 2546 Lookup.getNameLoc()); 2547 if (D) Lookup.addDecl(D); 2548 } 2549 } 2550 } 2551 // Sentinel value saying that we didn't do anything special. 2552 return ExprResult((Expr *)nullptr); 2553 } 2554 2555 /// \brief Cast a base object to a member's actual type. 2556 /// 2557 /// Logically this happens in three phases: 2558 /// 2559 /// * First we cast from the base type to the naming class. 2560 /// The naming class is the class into which we were looking 2561 /// when we found the member; it's the qualifier type if a 2562 /// qualifier was provided, and otherwise it's the base type. 2563 /// 2564 /// * Next we cast from the naming class to the declaring class. 2565 /// If the member we found was brought into a class's scope by 2566 /// a using declaration, this is that class; otherwise it's 2567 /// the class declaring the member. 2568 /// 2569 /// * Finally we cast from the declaring class to the "true" 2570 /// declaring class of the member. This conversion does not 2571 /// obey access control. 2572 ExprResult 2573 Sema::PerformObjectMemberConversion(Expr *From, 2574 NestedNameSpecifier *Qualifier, 2575 NamedDecl *FoundDecl, 2576 NamedDecl *Member) { 2577 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2578 if (!RD) 2579 return From; 2580 2581 QualType DestRecordType; 2582 QualType DestType; 2583 QualType FromRecordType; 2584 QualType FromType = From->getType(); 2585 bool PointerConversions = false; 2586 if (isa<FieldDecl>(Member)) { 2587 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2588 2589 if (FromType->getAs<PointerType>()) { 2590 DestType = Context.getPointerType(DestRecordType); 2591 FromRecordType = FromType->getPointeeType(); 2592 PointerConversions = true; 2593 } else { 2594 DestType = DestRecordType; 2595 FromRecordType = FromType; 2596 } 2597 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2598 if (Method->isStatic()) 2599 return From; 2600 2601 DestType = Method->getThisType(Context); 2602 DestRecordType = DestType->getPointeeType(); 2603 2604 if (FromType->getAs<PointerType>()) { 2605 FromRecordType = FromType->getPointeeType(); 2606 PointerConversions = true; 2607 } else { 2608 FromRecordType = FromType; 2609 DestType = DestRecordType; 2610 } 2611 } else { 2612 // No conversion necessary. 2613 return From; 2614 } 2615 2616 if (DestType->isDependentType() || FromType->isDependentType()) 2617 return From; 2618 2619 // If the unqualified types are the same, no conversion is necessary. 2620 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2621 return From; 2622 2623 SourceRange FromRange = From->getSourceRange(); 2624 SourceLocation FromLoc = FromRange.getBegin(); 2625 2626 ExprValueKind VK = From->getValueKind(); 2627 2628 // C++ [class.member.lookup]p8: 2629 // [...] Ambiguities can often be resolved by qualifying a name with its 2630 // class name. 2631 // 2632 // If the member was a qualified name and the qualified referred to a 2633 // specific base subobject type, we'll cast to that intermediate type 2634 // first and then to the object in which the member is declared. That allows 2635 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2636 // 2637 // class Base { public: int x; }; 2638 // class Derived1 : public Base { }; 2639 // class Derived2 : public Base { }; 2640 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2641 // 2642 // void VeryDerived::f() { 2643 // x = 17; // error: ambiguous base subobjects 2644 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2645 // } 2646 if (Qualifier && Qualifier->getAsType()) { 2647 QualType QType = QualType(Qualifier->getAsType(), 0); 2648 assert(QType->isRecordType() && "lookup done with non-record type"); 2649 2650 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2651 2652 // In C++98, the qualifier type doesn't actually have to be a base 2653 // type of the object type, in which case we just ignore it. 2654 // Otherwise build the appropriate casts. 2655 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2656 CXXCastPath BasePath; 2657 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2658 FromLoc, FromRange, &BasePath)) 2659 return ExprError(); 2660 2661 if (PointerConversions) 2662 QType = Context.getPointerType(QType); 2663 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2664 VK, &BasePath).get(); 2665 2666 FromType = QType; 2667 FromRecordType = QRecordType; 2668 2669 // If the qualifier type was the same as the destination type, 2670 // we're done. 2671 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2672 return From; 2673 } 2674 } 2675 2676 bool IgnoreAccess = false; 2677 2678 // If we actually found the member through a using declaration, cast 2679 // down to the using declaration's type. 2680 // 2681 // Pointer equality is fine here because only one declaration of a 2682 // class ever has member declarations. 2683 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2684 assert(isa<UsingShadowDecl>(FoundDecl)); 2685 QualType URecordType = Context.getTypeDeclType( 2686 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2687 2688 // We only need to do this if the naming-class to declaring-class 2689 // conversion is non-trivial. 2690 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2691 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2692 CXXCastPath BasePath; 2693 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2694 FromLoc, FromRange, &BasePath)) 2695 return ExprError(); 2696 2697 QualType UType = URecordType; 2698 if (PointerConversions) 2699 UType = Context.getPointerType(UType); 2700 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2701 VK, &BasePath).get(); 2702 FromType = UType; 2703 FromRecordType = URecordType; 2704 } 2705 2706 // We don't do access control for the conversion from the 2707 // declaring class to the true declaring class. 2708 IgnoreAccess = true; 2709 } 2710 2711 CXXCastPath BasePath; 2712 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2713 FromLoc, FromRange, &BasePath, 2714 IgnoreAccess)) 2715 return ExprError(); 2716 2717 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2718 VK, &BasePath); 2719 } 2720 2721 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2722 const LookupResult &R, 2723 bool HasTrailingLParen) { 2724 // Only when used directly as the postfix-expression of a call. 2725 if (!HasTrailingLParen) 2726 return false; 2727 2728 // Never if a scope specifier was provided. 2729 if (SS.isSet()) 2730 return false; 2731 2732 // Only in C++ or ObjC++. 2733 if (!getLangOpts().CPlusPlus) 2734 return false; 2735 2736 // Turn off ADL when we find certain kinds of declarations during 2737 // normal lookup: 2738 for (NamedDecl *D : R) { 2739 // C++0x [basic.lookup.argdep]p3: 2740 // -- a declaration of a class member 2741 // Since using decls preserve this property, we check this on the 2742 // original decl. 2743 if (D->isCXXClassMember()) 2744 return false; 2745 2746 // C++0x [basic.lookup.argdep]p3: 2747 // -- a block-scope function declaration that is not a 2748 // using-declaration 2749 // NOTE: we also trigger this for function templates (in fact, we 2750 // don't check the decl type at all, since all other decl types 2751 // turn off ADL anyway). 2752 if (isa<UsingShadowDecl>(D)) 2753 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2754 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2755 return false; 2756 2757 // C++0x [basic.lookup.argdep]p3: 2758 // -- a declaration that is neither a function or a function 2759 // template 2760 // And also for builtin functions. 2761 if (isa<FunctionDecl>(D)) { 2762 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2763 2764 // But also builtin functions. 2765 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2766 return false; 2767 } else if (!isa<FunctionTemplateDecl>(D)) 2768 return false; 2769 } 2770 2771 return true; 2772 } 2773 2774 2775 /// Diagnoses obvious problems with the use of the given declaration 2776 /// as an expression. This is only actually called for lookups that 2777 /// were not overloaded, and it doesn't promise that the declaration 2778 /// will in fact be used. 2779 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2780 if (isa<TypedefNameDecl>(D)) { 2781 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2782 return true; 2783 } 2784 2785 if (isa<ObjCInterfaceDecl>(D)) { 2786 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2787 return true; 2788 } 2789 2790 if (isa<NamespaceDecl>(D)) { 2791 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2792 return true; 2793 } 2794 2795 return false; 2796 } 2797 2798 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2799 LookupResult &R, bool NeedsADL, 2800 bool AcceptInvalidDecl) { 2801 // If this is a single, fully-resolved result and we don't need ADL, 2802 // just build an ordinary singleton decl ref. 2803 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2804 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2805 R.getRepresentativeDecl(), nullptr, 2806 AcceptInvalidDecl); 2807 2808 // We only need to check the declaration if there's exactly one 2809 // result, because in the overloaded case the results can only be 2810 // functions and function templates. 2811 if (R.isSingleResult() && 2812 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2813 return ExprError(); 2814 2815 // Otherwise, just build an unresolved lookup expression. Suppress 2816 // any lookup-related diagnostics; we'll hash these out later, when 2817 // we've picked a target. 2818 R.suppressDiagnostics(); 2819 2820 UnresolvedLookupExpr *ULE 2821 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2822 SS.getWithLocInContext(Context), 2823 R.getLookupNameInfo(), 2824 NeedsADL, R.isOverloadedResult(), 2825 R.begin(), R.end()); 2826 2827 return ULE; 2828 } 2829 2830 static void 2831 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 2832 ValueDecl *var, DeclContext *DC); 2833 2834 /// \brief Complete semantic analysis for a reference to the given declaration. 2835 ExprResult Sema::BuildDeclarationNameExpr( 2836 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2837 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2838 bool AcceptInvalidDecl) { 2839 assert(D && "Cannot refer to a NULL declaration"); 2840 assert(!isa<FunctionTemplateDecl>(D) && 2841 "Cannot refer unambiguously to a function template"); 2842 2843 SourceLocation Loc = NameInfo.getLoc(); 2844 if (CheckDeclInExpr(*this, Loc, D)) 2845 return ExprError(); 2846 2847 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2848 // Specifically diagnose references to class templates that are missing 2849 // a template argument list. 2850 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2851 << Template << SS.getRange(); 2852 Diag(Template->getLocation(), diag::note_template_decl_here); 2853 return ExprError(); 2854 } 2855 2856 // Make sure that we're referring to a value. 2857 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2858 if (!VD) { 2859 Diag(Loc, diag::err_ref_non_value) 2860 << D << SS.getRange(); 2861 Diag(D->getLocation(), diag::note_declared_at); 2862 return ExprError(); 2863 } 2864 2865 // Check whether this declaration can be used. Note that we suppress 2866 // this check when we're going to perform argument-dependent lookup 2867 // on this function name, because this might not be the function 2868 // that overload resolution actually selects. 2869 if (DiagnoseUseOfDecl(VD, Loc)) 2870 return ExprError(); 2871 2872 // Only create DeclRefExpr's for valid Decl's. 2873 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2874 return ExprError(); 2875 2876 // Handle members of anonymous structs and unions. If we got here, 2877 // and the reference is to a class member indirect field, then this 2878 // must be the subject of a pointer-to-member expression. 2879 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2880 if (!indirectField->isCXXClassMember()) 2881 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2882 indirectField); 2883 2884 { 2885 QualType type = VD->getType(); 2886 if (auto *FPT = type->getAs<FunctionProtoType>()) { 2887 // C++ [except.spec]p17: 2888 // An exception-specification is considered to be needed when: 2889 // - in an expression, the function is the unique lookup result or 2890 // the selected member of a set of overloaded functions. 2891 ResolveExceptionSpec(Loc, FPT); 2892 type = VD->getType(); 2893 } 2894 ExprValueKind valueKind = VK_RValue; 2895 2896 switch (D->getKind()) { 2897 // Ignore all the non-ValueDecl kinds. 2898 #define ABSTRACT_DECL(kind) 2899 #define VALUE(type, base) 2900 #define DECL(type, base) \ 2901 case Decl::type: 2902 #include "clang/AST/DeclNodes.inc" 2903 llvm_unreachable("invalid value decl kind"); 2904 2905 // These shouldn't make it here. 2906 case Decl::ObjCAtDefsField: 2907 case Decl::ObjCIvar: 2908 llvm_unreachable("forming non-member reference to ivar?"); 2909 2910 // Enum constants are always r-values and never references. 2911 // Unresolved using declarations are dependent. 2912 case Decl::EnumConstant: 2913 case Decl::UnresolvedUsingValue: 2914 case Decl::OMPDeclareReduction: 2915 valueKind = VK_RValue; 2916 break; 2917 2918 // Fields and indirect fields that got here must be for 2919 // pointer-to-member expressions; we just call them l-values for 2920 // internal consistency, because this subexpression doesn't really 2921 // exist in the high-level semantics. 2922 case Decl::Field: 2923 case Decl::IndirectField: 2924 assert(getLangOpts().CPlusPlus && 2925 "building reference to field in C?"); 2926 2927 // These can't have reference type in well-formed programs, but 2928 // for internal consistency we do this anyway. 2929 type = type.getNonReferenceType(); 2930 valueKind = VK_LValue; 2931 break; 2932 2933 // Non-type template parameters are either l-values or r-values 2934 // depending on the type. 2935 case Decl::NonTypeTemplateParm: { 2936 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2937 type = reftype->getPointeeType(); 2938 valueKind = VK_LValue; // even if the parameter is an r-value reference 2939 break; 2940 } 2941 2942 // For non-references, we need to strip qualifiers just in case 2943 // the template parameter was declared as 'const int' or whatever. 2944 valueKind = VK_RValue; 2945 type = type.getUnqualifiedType(); 2946 break; 2947 } 2948 2949 case Decl::Var: 2950 case Decl::VarTemplateSpecialization: 2951 case Decl::VarTemplatePartialSpecialization: 2952 case Decl::Decomposition: 2953 case Decl::OMPCapturedExpr: 2954 // In C, "extern void blah;" is valid and is an r-value. 2955 if (!getLangOpts().CPlusPlus && 2956 !type.hasQualifiers() && 2957 type->isVoidType()) { 2958 valueKind = VK_RValue; 2959 break; 2960 } 2961 // fallthrough 2962 2963 case Decl::ImplicitParam: 2964 case Decl::ParmVar: { 2965 // These are always l-values. 2966 valueKind = VK_LValue; 2967 type = type.getNonReferenceType(); 2968 2969 // FIXME: Does the addition of const really only apply in 2970 // potentially-evaluated contexts? Since the variable isn't actually 2971 // captured in an unevaluated context, it seems that the answer is no. 2972 if (!isUnevaluatedContext()) { 2973 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2974 if (!CapturedType.isNull()) 2975 type = CapturedType; 2976 } 2977 2978 break; 2979 } 2980 2981 case Decl::Binding: { 2982 // These are always lvalues. 2983 valueKind = VK_LValue; 2984 type = type.getNonReferenceType(); 2985 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 2986 // decides how that's supposed to work. 2987 auto *BD = cast<BindingDecl>(VD); 2988 if (BD->getDeclContext()->isFunctionOrMethod() && 2989 BD->getDeclContext() != CurContext) 2990 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 2991 break; 2992 } 2993 2994 case Decl::Function: { 2995 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2996 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2997 type = Context.BuiltinFnTy; 2998 valueKind = VK_RValue; 2999 break; 3000 } 3001 } 3002 3003 const FunctionType *fty = type->castAs<FunctionType>(); 3004 3005 // If we're referring to a function with an __unknown_anytype 3006 // result type, make the entire expression __unknown_anytype. 3007 if (fty->getReturnType() == Context.UnknownAnyTy) { 3008 type = Context.UnknownAnyTy; 3009 valueKind = VK_RValue; 3010 break; 3011 } 3012 3013 // Functions are l-values in C++. 3014 if (getLangOpts().CPlusPlus) { 3015 valueKind = VK_LValue; 3016 break; 3017 } 3018 3019 // C99 DR 316 says that, if a function type comes from a 3020 // function definition (without a prototype), that type is only 3021 // used for checking compatibility. Therefore, when referencing 3022 // the function, we pretend that we don't have the full function 3023 // type. 3024 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3025 isa<FunctionProtoType>(fty)) 3026 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3027 fty->getExtInfo()); 3028 3029 // Functions are r-values in C. 3030 valueKind = VK_RValue; 3031 break; 3032 } 3033 3034 case Decl::MSProperty: 3035 valueKind = VK_LValue; 3036 break; 3037 3038 case Decl::CXXMethod: 3039 // If we're referring to a method with an __unknown_anytype 3040 // result type, make the entire expression __unknown_anytype. 3041 // This should only be possible with a type written directly. 3042 if (const FunctionProtoType *proto 3043 = dyn_cast<FunctionProtoType>(VD->getType())) 3044 if (proto->getReturnType() == Context.UnknownAnyTy) { 3045 type = Context.UnknownAnyTy; 3046 valueKind = VK_RValue; 3047 break; 3048 } 3049 3050 // C++ methods are l-values if static, r-values if non-static. 3051 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3052 valueKind = VK_LValue; 3053 break; 3054 } 3055 // fallthrough 3056 3057 case Decl::CXXConversion: 3058 case Decl::CXXDestructor: 3059 case Decl::CXXConstructor: 3060 valueKind = VK_RValue; 3061 break; 3062 } 3063 3064 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3065 TemplateArgs); 3066 } 3067 } 3068 3069 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3070 SmallString<32> &Target) { 3071 Target.resize(CharByteWidth * (Source.size() + 1)); 3072 char *ResultPtr = &Target[0]; 3073 const llvm::UTF8 *ErrorPtr; 3074 bool success = 3075 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3076 (void)success; 3077 assert(success); 3078 Target.resize(ResultPtr - &Target[0]); 3079 } 3080 3081 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3082 PredefinedExpr::IdentType IT) { 3083 // Pick the current block, lambda, captured statement or function. 3084 Decl *currentDecl = nullptr; 3085 if (const BlockScopeInfo *BSI = getCurBlock()) 3086 currentDecl = BSI->TheDecl; 3087 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3088 currentDecl = LSI->CallOperator; 3089 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3090 currentDecl = CSI->TheCapturedDecl; 3091 else 3092 currentDecl = getCurFunctionOrMethodDecl(); 3093 3094 if (!currentDecl) { 3095 Diag(Loc, diag::ext_predef_outside_function); 3096 currentDecl = Context.getTranslationUnitDecl(); 3097 } 3098 3099 QualType ResTy; 3100 StringLiteral *SL = nullptr; 3101 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3102 ResTy = Context.DependentTy; 3103 else { 3104 // Pre-defined identifiers are of type char[x], where x is the length of 3105 // the string. 3106 auto Str = PredefinedExpr::ComputeName(IT, currentDecl); 3107 unsigned Length = Str.length(); 3108 3109 llvm::APInt LengthI(32, Length + 1); 3110 if (IT == PredefinedExpr::LFunction) { 3111 ResTy = Context.WideCharTy.withConst(); 3112 SmallString<32> RawChars; 3113 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3114 Str, RawChars); 3115 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3116 /*IndexTypeQuals*/ 0); 3117 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3118 /*Pascal*/ false, ResTy, Loc); 3119 } else { 3120 ResTy = Context.CharTy.withConst(); 3121 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3122 /*IndexTypeQuals*/ 0); 3123 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3124 /*Pascal*/ false, ResTy, Loc); 3125 } 3126 } 3127 3128 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL); 3129 } 3130 3131 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3132 PredefinedExpr::IdentType IT; 3133 3134 switch (Kind) { 3135 default: llvm_unreachable("Unknown simple primary expr!"); 3136 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3137 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 3138 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 3139 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS] 3140 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 3141 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 3142 } 3143 3144 return BuildPredefinedExpr(Loc, IT); 3145 } 3146 3147 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3148 SmallString<16> CharBuffer; 3149 bool Invalid = false; 3150 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3151 if (Invalid) 3152 return ExprError(); 3153 3154 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3155 PP, Tok.getKind()); 3156 if (Literal.hadError()) 3157 return ExprError(); 3158 3159 QualType Ty; 3160 if (Literal.isWide()) 3161 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3162 else if (Literal.isUTF16()) 3163 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3164 else if (Literal.isUTF32()) 3165 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3166 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3167 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3168 else 3169 Ty = Context.CharTy; // 'x' -> char in C++ 3170 3171 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3172 if (Literal.isWide()) 3173 Kind = CharacterLiteral::Wide; 3174 else if (Literal.isUTF16()) 3175 Kind = CharacterLiteral::UTF16; 3176 else if (Literal.isUTF32()) 3177 Kind = CharacterLiteral::UTF32; 3178 else if (Literal.isUTF8()) 3179 Kind = CharacterLiteral::UTF8; 3180 3181 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3182 Tok.getLocation()); 3183 3184 if (Literal.getUDSuffix().empty()) 3185 return Lit; 3186 3187 // We're building a user-defined literal. 3188 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3189 SourceLocation UDSuffixLoc = 3190 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3191 3192 // Make sure we're allowed user-defined literals here. 3193 if (!UDLScope) 3194 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3195 3196 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3197 // operator "" X (ch) 3198 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3199 Lit, Tok.getLocation()); 3200 } 3201 3202 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3203 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3204 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3205 Context.IntTy, Loc); 3206 } 3207 3208 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3209 QualType Ty, SourceLocation Loc) { 3210 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3211 3212 using llvm::APFloat; 3213 APFloat Val(Format); 3214 3215 APFloat::opStatus result = Literal.GetFloatValue(Val); 3216 3217 // Overflow is always an error, but underflow is only an error if 3218 // we underflowed to zero (APFloat reports denormals as underflow). 3219 if ((result & APFloat::opOverflow) || 3220 ((result & APFloat::opUnderflow) && Val.isZero())) { 3221 unsigned diagnostic; 3222 SmallString<20> buffer; 3223 if (result & APFloat::opOverflow) { 3224 diagnostic = diag::warn_float_overflow; 3225 APFloat::getLargest(Format).toString(buffer); 3226 } else { 3227 diagnostic = diag::warn_float_underflow; 3228 APFloat::getSmallest(Format).toString(buffer); 3229 } 3230 3231 S.Diag(Loc, diagnostic) 3232 << Ty 3233 << StringRef(buffer.data(), buffer.size()); 3234 } 3235 3236 bool isExact = (result == APFloat::opOK); 3237 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3238 } 3239 3240 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3241 assert(E && "Invalid expression"); 3242 3243 if (E->isValueDependent()) 3244 return false; 3245 3246 QualType QT = E->getType(); 3247 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3248 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3249 return true; 3250 } 3251 3252 llvm::APSInt ValueAPS; 3253 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3254 3255 if (R.isInvalid()) 3256 return true; 3257 3258 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3259 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3260 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3261 << ValueAPS.toString(10) << ValueIsPositive; 3262 return true; 3263 } 3264 3265 return false; 3266 } 3267 3268 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3269 // Fast path for a single digit (which is quite common). A single digit 3270 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3271 if (Tok.getLength() == 1) { 3272 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3273 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3274 } 3275 3276 SmallString<128> SpellingBuffer; 3277 // NumericLiteralParser wants to overread by one character. Add padding to 3278 // the buffer in case the token is copied to the buffer. If getSpelling() 3279 // returns a StringRef to the memory buffer, it should have a null char at 3280 // the EOF, so it is also safe. 3281 SpellingBuffer.resize(Tok.getLength() + 1); 3282 3283 // Get the spelling of the token, which eliminates trigraphs, etc. 3284 bool Invalid = false; 3285 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3286 if (Invalid) 3287 return ExprError(); 3288 3289 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3290 if (Literal.hadError) 3291 return ExprError(); 3292 3293 if (Literal.hasUDSuffix()) { 3294 // We're building a user-defined literal. 3295 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3296 SourceLocation UDSuffixLoc = 3297 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3298 3299 // Make sure we're allowed user-defined literals here. 3300 if (!UDLScope) 3301 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3302 3303 QualType CookedTy; 3304 if (Literal.isFloatingLiteral()) { 3305 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3306 // long double, the literal is treated as a call of the form 3307 // operator "" X (f L) 3308 CookedTy = Context.LongDoubleTy; 3309 } else { 3310 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3311 // unsigned long long, the literal is treated as a call of the form 3312 // operator "" X (n ULL) 3313 CookedTy = Context.UnsignedLongLongTy; 3314 } 3315 3316 DeclarationName OpName = 3317 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3318 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3319 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3320 3321 SourceLocation TokLoc = Tok.getLocation(); 3322 3323 // Perform literal operator lookup to determine if we're building a raw 3324 // literal or a cooked one. 3325 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3326 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3327 /*AllowRaw*/true, /*AllowTemplate*/true, 3328 /*AllowStringTemplate*/false)) { 3329 case LOLR_Error: 3330 return ExprError(); 3331 3332 case LOLR_Cooked: { 3333 Expr *Lit; 3334 if (Literal.isFloatingLiteral()) { 3335 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3336 } else { 3337 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3338 if (Literal.GetIntegerValue(ResultVal)) 3339 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3340 << /* Unsigned */ 1; 3341 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3342 Tok.getLocation()); 3343 } 3344 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3345 } 3346 3347 case LOLR_Raw: { 3348 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3349 // literal is treated as a call of the form 3350 // operator "" X ("n") 3351 unsigned Length = Literal.getUDSuffixOffset(); 3352 QualType StrTy = Context.getConstantArrayType( 3353 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 3354 ArrayType::Normal, 0); 3355 Expr *Lit = StringLiteral::Create( 3356 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3357 /*Pascal*/false, StrTy, &TokLoc, 1); 3358 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3359 } 3360 3361 case LOLR_Template: { 3362 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3363 // template), L is treated as a call fo the form 3364 // operator "" X <'c1', 'c2', ... 'ck'>() 3365 // where n is the source character sequence c1 c2 ... ck. 3366 TemplateArgumentListInfo ExplicitArgs; 3367 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3368 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3369 llvm::APSInt Value(CharBits, CharIsUnsigned); 3370 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3371 Value = TokSpelling[I]; 3372 TemplateArgument Arg(Context, Value, Context.CharTy); 3373 TemplateArgumentLocInfo ArgInfo; 3374 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3375 } 3376 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3377 &ExplicitArgs); 3378 } 3379 case LOLR_StringTemplate: 3380 llvm_unreachable("unexpected literal operator lookup result"); 3381 } 3382 } 3383 3384 Expr *Res; 3385 3386 if (Literal.isFloatingLiteral()) { 3387 QualType Ty; 3388 if (Literal.isHalf){ 3389 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3390 Ty = Context.HalfTy; 3391 else { 3392 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3393 return ExprError(); 3394 } 3395 } else if (Literal.isFloat) 3396 Ty = Context.FloatTy; 3397 else if (Literal.isLong) 3398 Ty = Context.LongDoubleTy; 3399 else if (Literal.isFloat128) 3400 Ty = Context.Float128Ty; 3401 else 3402 Ty = Context.DoubleTy; 3403 3404 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3405 3406 if (Ty == Context.DoubleTy) { 3407 if (getLangOpts().SinglePrecisionConstants) { 3408 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3409 if (BTy->getKind() != BuiltinType::Float) { 3410 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3411 } 3412 } else if (getLangOpts().OpenCL && 3413 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3414 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3415 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3416 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3417 } 3418 } 3419 } else if (!Literal.isIntegerLiteral()) { 3420 return ExprError(); 3421 } else { 3422 QualType Ty; 3423 3424 // 'long long' is a C99 or C++11 feature. 3425 if (!getLangOpts().C99 && Literal.isLongLong) { 3426 if (getLangOpts().CPlusPlus) 3427 Diag(Tok.getLocation(), 3428 getLangOpts().CPlusPlus11 ? 3429 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3430 else 3431 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3432 } 3433 3434 // Get the value in the widest-possible width. 3435 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3436 llvm::APInt ResultVal(MaxWidth, 0); 3437 3438 if (Literal.GetIntegerValue(ResultVal)) { 3439 // If this value didn't fit into uintmax_t, error and force to ull. 3440 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3441 << /* Unsigned */ 1; 3442 Ty = Context.UnsignedLongLongTy; 3443 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3444 "long long is not intmax_t?"); 3445 } else { 3446 // If this value fits into a ULL, try to figure out what else it fits into 3447 // according to the rules of C99 6.4.4.1p5. 3448 3449 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3450 // be an unsigned int. 3451 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3452 3453 // Check from smallest to largest, picking the smallest type we can. 3454 unsigned Width = 0; 3455 3456 // Microsoft specific integer suffixes are explicitly sized. 3457 if (Literal.MicrosoftInteger) { 3458 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3459 Width = 8; 3460 Ty = Context.CharTy; 3461 } else { 3462 Width = Literal.MicrosoftInteger; 3463 Ty = Context.getIntTypeForBitwidth(Width, 3464 /*Signed=*/!Literal.isUnsigned); 3465 } 3466 } 3467 3468 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3469 // Are int/unsigned possibilities? 3470 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3471 3472 // Does it fit in a unsigned int? 3473 if (ResultVal.isIntN(IntSize)) { 3474 // Does it fit in a signed int? 3475 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3476 Ty = Context.IntTy; 3477 else if (AllowUnsigned) 3478 Ty = Context.UnsignedIntTy; 3479 Width = IntSize; 3480 } 3481 } 3482 3483 // Are long/unsigned long possibilities? 3484 if (Ty.isNull() && !Literal.isLongLong) { 3485 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3486 3487 // Does it fit in a unsigned long? 3488 if (ResultVal.isIntN(LongSize)) { 3489 // Does it fit in a signed long? 3490 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3491 Ty = Context.LongTy; 3492 else if (AllowUnsigned) 3493 Ty = Context.UnsignedLongTy; 3494 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3495 // is compatible. 3496 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3497 const unsigned LongLongSize = 3498 Context.getTargetInfo().getLongLongWidth(); 3499 Diag(Tok.getLocation(), 3500 getLangOpts().CPlusPlus 3501 ? Literal.isLong 3502 ? diag::warn_old_implicitly_unsigned_long_cxx 3503 : /*C++98 UB*/ diag:: 3504 ext_old_implicitly_unsigned_long_cxx 3505 : diag::warn_old_implicitly_unsigned_long) 3506 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3507 : /*will be ill-formed*/ 1); 3508 Ty = Context.UnsignedLongTy; 3509 } 3510 Width = LongSize; 3511 } 3512 } 3513 3514 // Check long long if needed. 3515 if (Ty.isNull()) { 3516 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3517 3518 // Does it fit in a unsigned long long? 3519 if (ResultVal.isIntN(LongLongSize)) { 3520 // Does it fit in a signed long long? 3521 // To be compatible with MSVC, hex integer literals ending with the 3522 // LL or i64 suffix are always signed in Microsoft mode. 3523 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3524 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3525 Ty = Context.LongLongTy; 3526 else if (AllowUnsigned) 3527 Ty = Context.UnsignedLongLongTy; 3528 Width = LongLongSize; 3529 } 3530 } 3531 3532 // If we still couldn't decide a type, we probably have something that 3533 // does not fit in a signed long long, but has no U suffix. 3534 if (Ty.isNull()) { 3535 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3536 Ty = Context.UnsignedLongLongTy; 3537 Width = Context.getTargetInfo().getLongLongWidth(); 3538 } 3539 3540 if (ResultVal.getBitWidth() != Width) 3541 ResultVal = ResultVal.trunc(Width); 3542 } 3543 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3544 } 3545 3546 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3547 if (Literal.isImaginary) 3548 Res = new (Context) ImaginaryLiteral(Res, 3549 Context.getComplexType(Res->getType())); 3550 3551 return Res; 3552 } 3553 3554 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3555 assert(E && "ActOnParenExpr() missing expr"); 3556 return new (Context) ParenExpr(L, R, E); 3557 } 3558 3559 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3560 SourceLocation Loc, 3561 SourceRange ArgRange) { 3562 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3563 // scalar or vector data type argument..." 3564 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3565 // type (C99 6.2.5p18) or void. 3566 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3567 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3568 << T << ArgRange; 3569 return true; 3570 } 3571 3572 assert((T->isVoidType() || !T->isIncompleteType()) && 3573 "Scalar types should always be complete"); 3574 return false; 3575 } 3576 3577 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3578 SourceLocation Loc, 3579 SourceRange ArgRange, 3580 UnaryExprOrTypeTrait TraitKind) { 3581 // Invalid types must be hard errors for SFINAE in C++. 3582 if (S.LangOpts.CPlusPlus) 3583 return true; 3584 3585 // C99 6.5.3.4p1: 3586 if (T->isFunctionType() && 3587 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3588 // sizeof(function)/alignof(function) is allowed as an extension. 3589 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3590 << TraitKind << ArgRange; 3591 return false; 3592 } 3593 3594 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3595 // this is an error (OpenCL v1.1 s6.3.k) 3596 if (T->isVoidType()) { 3597 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3598 : diag::ext_sizeof_alignof_void_type; 3599 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3600 return false; 3601 } 3602 3603 return true; 3604 } 3605 3606 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3607 SourceLocation Loc, 3608 SourceRange ArgRange, 3609 UnaryExprOrTypeTrait TraitKind) { 3610 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3611 // runtime doesn't allow it. 3612 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3613 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3614 << T << (TraitKind == UETT_SizeOf) 3615 << ArgRange; 3616 return true; 3617 } 3618 3619 return false; 3620 } 3621 3622 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3623 /// pointer type is equal to T) and emit a warning if it is. 3624 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3625 Expr *E) { 3626 // Don't warn if the operation changed the type. 3627 if (T != E->getType()) 3628 return; 3629 3630 // Now look for array decays. 3631 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3632 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3633 return; 3634 3635 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3636 << ICE->getType() 3637 << ICE->getSubExpr()->getType(); 3638 } 3639 3640 /// \brief Check the constraints on expression operands to unary type expression 3641 /// and type traits. 3642 /// 3643 /// Completes any types necessary and validates the constraints on the operand 3644 /// expression. The logic mostly mirrors the type-based overload, but may modify 3645 /// the expression as it completes the type for that expression through template 3646 /// instantiation, etc. 3647 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3648 UnaryExprOrTypeTrait ExprKind) { 3649 QualType ExprTy = E->getType(); 3650 assert(!ExprTy->isReferenceType()); 3651 3652 if (ExprKind == UETT_VecStep) 3653 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3654 E->getSourceRange()); 3655 3656 // Whitelist some types as extensions 3657 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3658 E->getSourceRange(), ExprKind)) 3659 return false; 3660 3661 // 'alignof' applied to an expression only requires the base element type of 3662 // the expression to be complete. 'sizeof' requires the expression's type to 3663 // be complete (and will attempt to complete it if it's an array of unknown 3664 // bound). 3665 if (ExprKind == UETT_AlignOf) { 3666 if (RequireCompleteType(E->getExprLoc(), 3667 Context.getBaseElementType(E->getType()), 3668 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3669 E->getSourceRange())) 3670 return true; 3671 } else { 3672 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3673 ExprKind, E->getSourceRange())) 3674 return true; 3675 } 3676 3677 // Completing the expression's type may have changed it. 3678 ExprTy = E->getType(); 3679 assert(!ExprTy->isReferenceType()); 3680 3681 if (ExprTy->isFunctionType()) { 3682 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3683 << ExprKind << E->getSourceRange(); 3684 return true; 3685 } 3686 3687 // The operand for sizeof and alignof is in an unevaluated expression context, 3688 // so side effects could result in unintended consequences. 3689 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) && 3690 ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false)) 3691 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3692 3693 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3694 E->getSourceRange(), ExprKind)) 3695 return true; 3696 3697 if (ExprKind == UETT_SizeOf) { 3698 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3699 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3700 QualType OType = PVD->getOriginalType(); 3701 QualType Type = PVD->getType(); 3702 if (Type->isPointerType() && OType->isArrayType()) { 3703 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3704 << Type << OType; 3705 Diag(PVD->getLocation(), diag::note_declared_at); 3706 } 3707 } 3708 } 3709 3710 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3711 // decays into a pointer and returns an unintended result. This is most 3712 // likely a typo for "sizeof(array) op x". 3713 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3714 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3715 BO->getLHS()); 3716 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3717 BO->getRHS()); 3718 } 3719 } 3720 3721 return false; 3722 } 3723 3724 /// \brief Check the constraints on operands to unary expression and type 3725 /// traits. 3726 /// 3727 /// This will complete any types necessary, and validate the various constraints 3728 /// on those operands. 3729 /// 3730 /// The UsualUnaryConversions() function is *not* called by this routine. 3731 /// C99 6.3.2.1p[2-4] all state: 3732 /// Except when it is the operand of the sizeof operator ... 3733 /// 3734 /// C++ [expr.sizeof]p4 3735 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3736 /// standard conversions are not applied to the operand of sizeof. 3737 /// 3738 /// This policy is followed for all of the unary trait expressions. 3739 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3740 SourceLocation OpLoc, 3741 SourceRange ExprRange, 3742 UnaryExprOrTypeTrait ExprKind) { 3743 if (ExprType->isDependentType()) 3744 return false; 3745 3746 // C++ [expr.sizeof]p2: 3747 // When applied to a reference or a reference type, the result 3748 // is the size of the referenced type. 3749 // C++11 [expr.alignof]p3: 3750 // When alignof is applied to a reference type, the result 3751 // shall be the alignment of the referenced type. 3752 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3753 ExprType = Ref->getPointeeType(); 3754 3755 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3756 // When alignof or _Alignof is applied to an array type, the result 3757 // is the alignment of the element type. 3758 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign) 3759 ExprType = Context.getBaseElementType(ExprType); 3760 3761 if (ExprKind == UETT_VecStep) 3762 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3763 3764 // Whitelist some types as extensions 3765 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3766 ExprKind)) 3767 return false; 3768 3769 if (RequireCompleteType(OpLoc, ExprType, 3770 diag::err_sizeof_alignof_incomplete_type, 3771 ExprKind, ExprRange)) 3772 return true; 3773 3774 if (ExprType->isFunctionType()) { 3775 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3776 << ExprKind << ExprRange; 3777 return true; 3778 } 3779 3780 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3781 ExprKind)) 3782 return true; 3783 3784 return false; 3785 } 3786 3787 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3788 E = E->IgnoreParens(); 3789 3790 // Cannot know anything else if the expression is dependent. 3791 if (E->isTypeDependent()) 3792 return false; 3793 3794 if (E->getObjectKind() == OK_BitField) { 3795 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3796 << 1 << E->getSourceRange(); 3797 return true; 3798 } 3799 3800 ValueDecl *D = nullptr; 3801 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3802 D = DRE->getDecl(); 3803 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3804 D = ME->getMemberDecl(); 3805 } 3806 3807 // If it's a field, require the containing struct to have a 3808 // complete definition so that we can compute the layout. 3809 // 3810 // This can happen in C++11 onwards, either by naming the member 3811 // in a way that is not transformed into a member access expression 3812 // (in an unevaluated operand, for instance), or by naming the member 3813 // in a trailing-return-type. 3814 // 3815 // For the record, since __alignof__ on expressions is a GCC 3816 // extension, GCC seems to permit this but always gives the 3817 // nonsensical answer 0. 3818 // 3819 // We don't really need the layout here --- we could instead just 3820 // directly check for all the appropriate alignment-lowing 3821 // attributes --- but that would require duplicating a lot of 3822 // logic that just isn't worth duplicating for such a marginal 3823 // use-case. 3824 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3825 // Fast path this check, since we at least know the record has a 3826 // definition if we can find a member of it. 3827 if (!FD->getParent()->isCompleteDefinition()) { 3828 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3829 << E->getSourceRange(); 3830 return true; 3831 } 3832 3833 // Otherwise, if it's a field, and the field doesn't have 3834 // reference type, then it must have a complete type (or be a 3835 // flexible array member, which we explicitly want to 3836 // white-list anyway), which makes the following checks trivial. 3837 if (!FD->getType()->isReferenceType()) 3838 return false; 3839 } 3840 3841 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3842 } 3843 3844 bool Sema::CheckVecStepExpr(Expr *E) { 3845 E = E->IgnoreParens(); 3846 3847 // Cannot know anything else if the expression is dependent. 3848 if (E->isTypeDependent()) 3849 return false; 3850 3851 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3852 } 3853 3854 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 3855 CapturingScopeInfo *CSI) { 3856 assert(T->isVariablyModifiedType()); 3857 assert(CSI != nullptr); 3858 3859 // We're going to walk down into the type and look for VLA expressions. 3860 do { 3861 const Type *Ty = T.getTypePtr(); 3862 switch (Ty->getTypeClass()) { 3863 #define TYPE(Class, Base) 3864 #define ABSTRACT_TYPE(Class, Base) 3865 #define NON_CANONICAL_TYPE(Class, Base) 3866 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 3867 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 3868 #include "clang/AST/TypeNodes.def" 3869 T = QualType(); 3870 break; 3871 // These types are never variably-modified. 3872 case Type::Builtin: 3873 case Type::Complex: 3874 case Type::Vector: 3875 case Type::ExtVector: 3876 case Type::Record: 3877 case Type::Enum: 3878 case Type::Elaborated: 3879 case Type::TemplateSpecialization: 3880 case Type::ObjCObject: 3881 case Type::ObjCInterface: 3882 case Type::ObjCObjectPointer: 3883 case Type::ObjCTypeParam: 3884 case Type::Pipe: 3885 llvm_unreachable("type class is never variably-modified!"); 3886 case Type::Adjusted: 3887 T = cast<AdjustedType>(Ty)->getOriginalType(); 3888 break; 3889 case Type::Decayed: 3890 T = cast<DecayedType>(Ty)->getPointeeType(); 3891 break; 3892 case Type::Pointer: 3893 T = cast<PointerType>(Ty)->getPointeeType(); 3894 break; 3895 case Type::BlockPointer: 3896 T = cast<BlockPointerType>(Ty)->getPointeeType(); 3897 break; 3898 case Type::LValueReference: 3899 case Type::RValueReference: 3900 T = cast<ReferenceType>(Ty)->getPointeeType(); 3901 break; 3902 case Type::MemberPointer: 3903 T = cast<MemberPointerType>(Ty)->getPointeeType(); 3904 break; 3905 case Type::ConstantArray: 3906 case Type::IncompleteArray: 3907 // Losing element qualification here is fine. 3908 T = cast<ArrayType>(Ty)->getElementType(); 3909 break; 3910 case Type::VariableArray: { 3911 // Losing element qualification here is fine. 3912 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 3913 3914 // Unknown size indication requires no size computation. 3915 // Otherwise, evaluate and record it. 3916 if (auto Size = VAT->getSizeExpr()) { 3917 if (!CSI->isVLATypeCaptured(VAT)) { 3918 RecordDecl *CapRecord = nullptr; 3919 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 3920 CapRecord = LSI->Lambda; 3921 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 3922 CapRecord = CRSI->TheRecordDecl; 3923 } 3924 if (CapRecord) { 3925 auto ExprLoc = Size->getExprLoc(); 3926 auto SizeType = Context.getSizeType(); 3927 // Build the non-static data member. 3928 auto Field = 3929 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc, 3930 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 3931 /*BW*/ nullptr, /*Mutable*/ false, 3932 /*InitStyle*/ ICIS_NoInit); 3933 Field->setImplicit(true); 3934 Field->setAccess(AS_private); 3935 Field->setCapturedVLAType(VAT); 3936 CapRecord->addDecl(Field); 3937 3938 CSI->addVLATypeCapture(ExprLoc, SizeType); 3939 } 3940 } 3941 } 3942 T = VAT->getElementType(); 3943 break; 3944 } 3945 case Type::FunctionProto: 3946 case Type::FunctionNoProto: 3947 T = cast<FunctionType>(Ty)->getReturnType(); 3948 break; 3949 case Type::Paren: 3950 case Type::TypeOf: 3951 case Type::UnaryTransform: 3952 case Type::Attributed: 3953 case Type::SubstTemplateTypeParm: 3954 case Type::PackExpansion: 3955 // Keep walking after single level desugaring. 3956 T = T.getSingleStepDesugaredType(Context); 3957 break; 3958 case Type::Typedef: 3959 T = cast<TypedefType>(Ty)->desugar(); 3960 break; 3961 case Type::Decltype: 3962 T = cast<DecltypeType>(Ty)->desugar(); 3963 break; 3964 case Type::Auto: 3965 T = cast<AutoType>(Ty)->getDeducedType(); 3966 break; 3967 case Type::TypeOfExpr: 3968 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 3969 break; 3970 case Type::Atomic: 3971 T = cast<AtomicType>(Ty)->getValueType(); 3972 break; 3973 } 3974 } while (!T.isNull() && T->isVariablyModifiedType()); 3975 } 3976 3977 /// \brief Build a sizeof or alignof expression given a type operand. 3978 ExprResult 3979 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3980 SourceLocation OpLoc, 3981 UnaryExprOrTypeTrait ExprKind, 3982 SourceRange R) { 3983 if (!TInfo) 3984 return ExprError(); 3985 3986 QualType T = TInfo->getType(); 3987 3988 if (!T->isDependentType() && 3989 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3990 return ExprError(); 3991 3992 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 3993 if (auto *TT = T->getAs<TypedefType>()) { 3994 for (auto I = FunctionScopes.rbegin(), 3995 E = std::prev(FunctionScopes.rend()); 3996 I != E; ++I) { 3997 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 3998 if (CSI == nullptr) 3999 break; 4000 DeclContext *DC = nullptr; 4001 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4002 DC = LSI->CallOperator; 4003 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4004 DC = CRSI->TheCapturedDecl; 4005 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4006 DC = BSI->TheDecl; 4007 if (DC) { 4008 if (DC->containsDecl(TT->getDecl())) 4009 break; 4010 captureVariablyModifiedType(Context, T, CSI); 4011 } 4012 } 4013 } 4014 } 4015 4016 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4017 return new (Context) UnaryExprOrTypeTraitExpr( 4018 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4019 } 4020 4021 /// \brief Build a sizeof or alignof expression given an expression 4022 /// operand. 4023 ExprResult 4024 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4025 UnaryExprOrTypeTrait ExprKind) { 4026 ExprResult PE = CheckPlaceholderExpr(E); 4027 if (PE.isInvalid()) 4028 return ExprError(); 4029 4030 E = PE.get(); 4031 4032 // Verify that the operand is valid. 4033 bool isInvalid = false; 4034 if (E->isTypeDependent()) { 4035 // Delay type-checking for type-dependent expressions. 4036 } else if (ExprKind == UETT_AlignOf) { 4037 isInvalid = CheckAlignOfExpr(*this, E); 4038 } else if (ExprKind == UETT_VecStep) { 4039 isInvalid = CheckVecStepExpr(E); 4040 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4041 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4042 isInvalid = true; 4043 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4044 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4045 isInvalid = true; 4046 } else { 4047 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4048 } 4049 4050 if (isInvalid) 4051 return ExprError(); 4052 4053 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4054 PE = TransformToPotentiallyEvaluated(E); 4055 if (PE.isInvalid()) return ExprError(); 4056 E = PE.get(); 4057 } 4058 4059 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4060 return new (Context) UnaryExprOrTypeTraitExpr( 4061 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4062 } 4063 4064 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4065 /// expr and the same for @c alignof and @c __alignof 4066 /// Note that the ArgRange is invalid if isType is false. 4067 ExprResult 4068 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4069 UnaryExprOrTypeTrait ExprKind, bool IsType, 4070 void *TyOrEx, SourceRange ArgRange) { 4071 // If error parsing type, ignore. 4072 if (!TyOrEx) return ExprError(); 4073 4074 if (IsType) { 4075 TypeSourceInfo *TInfo; 4076 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4077 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4078 } 4079 4080 Expr *ArgEx = (Expr *)TyOrEx; 4081 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4082 return Result; 4083 } 4084 4085 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4086 bool IsReal) { 4087 if (V.get()->isTypeDependent()) 4088 return S.Context.DependentTy; 4089 4090 // _Real and _Imag are only l-values for normal l-values. 4091 if (V.get()->getObjectKind() != OK_Ordinary) { 4092 V = S.DefaultLvalueConversion(V.get()); 4093 if (V.isInvalid()) 4094 return QualType(); 4095 } 4096 4097 // These operators return the element type of a complex type. 4098 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4099 return CT->getElementType(); 4100 4101 // Otherwise they pass through real integer and floating point types here. 4102 if (V.get()->getType()->isArithmeticType()) 4103 return V.get()->getType(); 4104 4105 // Test for placeholders. 4106 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4107 if (PR.isInvalid()) return QualType(); 4108 if (PR.get() != V.get()) { 4109 V = PR; 4110 return CheckRealImagOperand(S, V, Loc, IsReal); 4111 } 4112 4113 // Reject anything else. 4114 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4115 << (IsReal ? "__real" : "__imag"); 4116 return QualType(); 4117 } 4118 4119 4120 4121 ExprResult 4122 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4123 tok::TokenKind Kind, Expr *Input) { 4124 UnaryOperatorKind Opc; 4125 switch (Kind) { 4126 default: llvm_unreachable("Unknown unary op!"); 4127 case tok::plusplus: Opc = UO_PostInc; break; 4128 case tok::minusminus: Opc = UO_PostDec; break; 4129 } 4130 4131 // Since this might is a postfix expression, get rid of ParenListExprs. 4132 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4133 if (Result.isInvalid()) return ExprError(); 4134 Input = Result.get(); 4135 4136 return BuildUnaryOp(S, OpLoc, Opc, Input); 4137 } 4138 4139 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 4140 /// 4141 /// \return true on error 4142 static bool checkArithmeticOnObjCPointer(Sema &S, 4143 SourceLocation opLoc, 4144 Expr *op) { 4145 assert(op->getType()->isObjCObjectPointerType()); 4146 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4147 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4148 return false; 4149 4150 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4151 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4152 << op->getSourceRange(); 4153 return true; 4154 } 4155 4156 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4157 auto *BaseNoParens = Base->IgnoreParens(); 4158 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4159 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4160 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4161 } 4162 4163 ExprResult 4164 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4165 Expr *idx, SourceLocation rbLoc) { 4166 if (base && !base->getType().isNull() && 4167 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4168 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4169 /*Length=*/nullptr, rbLoc); 4170 4171 // Since this might be a postfix expression, get rid of ParenListExprs. 4172 if (isa<ParenListExpr>(base)) { 4173 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4174 if (result.isInvalid()) return ExprError(); 4175 base = result.get(); 4176 } 4177 4178 // Handle any non-overload placeholder types in the base and index 4179 // expressions. We can't handle overloads here because the other 4180 // operand might be an overloadable type, in which case the overload 4181 // resolution for the operator overload should get the first crack 4182 // at the overload. 4183 bool IsMSPropertySubscript = false; 4184 if (base->getType()->isNonOverloadPlaceholderType()) { 4185 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4186 if (!IsMSPropertySubscript) { 4187 ExprResult result = CheckPlaceholderExpr(base); 4188 if (result.isInvalid()) 4189 return ExprError(); 4190 base = result.get(); 4191 } 4192 } 4193 if (idx->getType()->isNonOverloadPlaceholderType()) { 4194 ExprResult result = CheckPlaceholderExpr(idx); 4195 if (result.isInvalid()) return ExprError(); 4196 idx = result.get(); 4197 } 4198 4199 // Build an unanalyzed expression if either operand is type-dependent. 4200 if (getLangOpts().CPlusPlus && 4201 (base->isTypeDependent() || idx->isTypeDependent())) { 4202 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4203 VK_LValue, OK_Ordinary, rbLoc); 4204 } 4205 4206 // MSDN, property (C++) 4207 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4208 // This attribute can also be used in the declaration of an empty array in a 4209 // class or structure definition. For example: 4210 // __declspec(property(get=GetX, put=PutX)) int x[]; 4211 // The above statement indicates that x[] can be used with one or more array 4212 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4213 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4214 if (IsMSPropertySubscript) { 4215 // Build MS property subscript expression if base is MS property reference 4216 // or MS property subscript. 4217 return new (Context) MSPropertySubscriptExpr( 4218 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4219 } 4220 4221 // Use C++ overloaded-operator rules if either operand has record 4222 // type. The spec says to do this if either type is *overloadable*, 4223 // but enum types can't declare subscript operators or conversion 4224 // operators, so there's nothing interesting for overload resolution 4225 // to do if there aren't any record types involved. 4226 // 4227 // ObjC pointers have their own subscripting logic that is not tied 4228 // to overload resolution and so should not take this path. 4229 if (getLangOpts().CPlusPlus && 4230 (base->getType()->isRecordType() || 4231 (!base->getType()->isObjCObjectPointerType() && 4232 idx->getType()->isRecordType()))) { 4233 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4234 } 4235 4236 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4237 } 4238 4239 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4240 Expr *LowerBound, 4241 SourceLocation ColonLoc, Expr *Length, 4242 SourceLocation RBLoc) { 4243 if (Base->getType()->isPlaceholderType() && 4244 !Base->getType()->isSpecificPlaceholderType( 4245 BuiltinType::OMPArraySection)) { 4246 ExprResult Result = CheckPlaceholderExpr(Base); 4247 if (Result.isInvalid()) 4248 return ExprError(); 4249 Base = Result.get(); 4250 } 4251 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4252 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4253 if (Result.isInvalid()) 4254 return ExprError(); 4255 Result = DefaultLvalueConversion(Result.get()); 4256 if (Result.isInvalid()) 4257 return ExprError(); 4258 LowerBound = Result.get(); 4259 } 4260 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4261 ExprResult Result = CheckPlaceholderExpr(Length); 4262 if (Result.isInvalid()) 4263 return ExprError(); 4264 Result = DefaultLvalueConversion(Result.get()); 4265 if (Result.isInvalid()) 4266 return ExprError(); 4267 Length = Result.get(); 4268 } 4269 4270 // Build an unanalyzed expression if either operand is type-dependent. 4271 if (Base->isTypeDependent() || 4272 (LowerBound && 4273 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4274 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4275 return new (Context) 4276 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4277 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4278 } 4279 4280 // Perform default conversions. 4281 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4282 QualType ResultTy; 4283 if (OriginalTy->isAnyPointerType()) { 4284 ResultTy = OriginalTy->getPointeeType(); 4285 } else if (OriginalTy->isArrayType()) { 4286 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4287 } else { 4288 return ExprError( 4289 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4290 << Base->getSourceRange()); 4291 } 4292 // C99 6.5.2.1p1 4293 if (LowerBound) { 4294 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4295 LowerBound); 4296 if (Res.isInvalid()) 4297 return ExprError(Diag(LowerBound->getExprLoc(), 4298 diag::err_omp_typecheck_section_not_integer) 4299 << 0 << LowerBound->getSourceRange()); 4300 LowerBound = Res.get(); 4301 4302 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4303 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4304 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4305 << 0 << LowerBound->getSourceRange(); 4306 } 4307 if (Length) { 4308 auto Res = 4309 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4310 if (Res.isInvalid()) 4311 return ExprError(Diag(Length->getExprLoc(), 4312 diag::err_omp_typecheck_section_not_integer) 4313 << 1 << Length->getSourceRange()); 4314 Length = Res.get(); 4315 4316 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4317 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4318 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4319 << 1 << Length->getSourceRange(); 4320 } 4321 4322 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4323 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4324 // type. Note that functions are not objects, and that (in C99 parlance) 4325 // incomplete types are not object types. 4326 if (ResultTy->isFunctionType()) { 4327 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4328 << ResultTy << Base->getSourceRange(); 4329 return ExprError(); 4330 } 4331 4332 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4333 diag::err_omp_section_incomplete_type, Base)) 4334 return ExprError(); 4335 4336 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4337 llvm::APSInt LowerBoundValue; 4338 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) { 4339 // OpenMP 4.5, [2.4 Array Sections] 4340 // The array section must be a subset of the original array. 4341 if (LowerBoundValue.isNegative()) { 4342 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4343 << LowerBound->getSourceRange(); 4344 return ExprError(); 4345 } 4346 } 4347 } 4348 4349 if (Length) { 4350 llvm::APSInt LengthValue; 4351 if (Length->EvaluateAsInt(LengthValue, Context)) { 4352 // OpenMP 4.5, [2.4 Array Sections] 4353 // The length must evaluate to non-negative integers. 4354 if (LengthValue.isNegative()) { 4355 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4356 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4357 << Length->getSourceRange(); 4358 return ExprError(); 4359 } 4360 } 4361 } else if (ColonLoc.isValid() && 4362 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4363 !OriginalTy->isVariableArrayType()))) { 4364 // OpenMP 4.5, [2.4 Array Sections] 4365 // When the size of the array dimension is not known, the length must be 4366 // specified explicitly. 4367 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4368 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4369 return ExprError(); 4370 } 4371 4372 if (!Base->getType()->isSpecificPlaceholderType( 4373 BuiltinType::OMPArraySection)) { 4374 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4375 if (Result.isInvalid()) 4376 return ExprError(); 4377 Base = Result.get(); 4378 } 4379 return new (Context) 4380 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4381 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4382 } 4383 4384 ExprResult 4385 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4386 Expr *Idx, SourceLocation RLoc) { 4387 Expr *LHSExp = Base; 4388 Expr *RHSExp = Idx; 4389 4390 ExprValueKind VK = VK_LValue; 4391 ExprObjectKind OK = OK_Ordinary; 4392 4393 // Per C++ core issue 1213, the result is an xvalue if either operand is 4394 // a non-lvalue array, and an lvalue otherwise. 4395 if (getLangOpts().CPlusPlus11 && 4396 ((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) || 4397 (RHSExp->getType()->isArrayType() && !RHSExp->isLValue()))) 4398 VK = VK_XValue; 4399 4400 // Perform default conversions. 4401 if (!LHSExp->getType()->getAs<VectorType>()) { 4402 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4403 if (Result.isInvalid()) 4404 return ExprError(); 4405 LHSExp = Result.get(); 4406 } 4407 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4408 if (Result.isInvalid()) 4409 return ExprError(); 4410 RHSExp = Result.get(); 4411 4412 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4413 4414 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4415 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4416 // in the subscript position. As a result, we need to derive the array base 4417 // and index from the expression types. 4418 Expr *BaseExpr, *IndexExpr; 4419 QualType ResultType; 4420 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4421 BaseExpr = LHSExp; 4422 IndexExpr = RHSExp; 4423 ResultType = Context.DependentTy; 4424 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4425 BaseExpr = LHSExp; 4426 IndexExpr = RHSExp; 4427 ResultType = PTy->getPointeeType(); 4428 } else if (const ObjCObjectPointerType *PTy = 4429 LHSTy->getAs<ObjCObjectPointerType>()) { 4430 BaseExpr = LHSExp; 4431 IndexExpr = RHSExp; 4432 4433 // Use custom logic if this should be the pseudo-object subscript 4434 // expression. 4435 if (!LangOpts.isSubscriptPointerArithmetic()) 4436 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4437 nullptr); 4438 4439 ResultType = PTy->getPointeeType(); 4440 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4441 // Handle the uncommon case of "123[Ptr]". 4442 BaseExpr = RHSExp; 4443 IndexExpr = LHSExp; 4444 ResultType = PTy->getPointeeType(); 4445 } else if (const ObjCObjectPointerType *PTy = 4446 RHSTy->getAs<ObjCObjectPointerType>()) { 4447 // Handle the uncommon case of "123[Ptr]". 4448 BaseExpr = RHSExp; 4449 IndexExpr = LHSExp; 4450 ResultType = PTy->getPointeeType(); 4451 if (!LangOpts.isSubscriptPointerArithmetic()) { 4452 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4453 << ResultType << BaseExpr->getSourceRange(); 4454 return ExprError(); 4455 } 4456 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4457 BaseExpr = LHSExp; // vectors: V[123] 4458 IndexExpr = RHSExp; 4459 VK = LHSExp->getValueKind(); 4460 if (VK != VK_RValue) 4461 OK = OK_VectorComponent; 4462 4463 // FIXME: need to deal with const... 4464 ResultType = VTy->getElementType(); 4465 } else if (LHSTy->isArrayType()) { 4466 // If we see an array that wasn't promoted by 4467 // DefaultFunctionArrayLvalueConversion, it must be an array that 4468 // wasn't promoted because of the C90 rule that doesn't 4469 // allow promoting non-lvalue arrays. Warn, then 4470 // force the promotion here. 4471 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4472 LHSExp->getSourceRange(); 4473 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4474 CK_ArrayToPointerDecay).get(); 4475 LHSTy = LHSExp->getType(); 4476 4477 BaseExpr = LHSExp; 4478 IndexExpr = RHSExp; 4479 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4480 } else if (RHSTy->isArrayType()) { 4481 // Same as previous, except for 123[f().a] case 4482 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4483 RHSExp->getSourceRange(); 4484 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4485 CK_ArrayToPointerDecay).get(); 4486 RHSTy = RHSExp->getType(); 4487 4488 BaseExpr = RHSExp; 4489 IndexExpr = LHSExp; 4490 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4491 } else { 4492 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4493 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4494 } 4495 // C99 6.5.2.1p1 4496 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4497 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4498 << IndexExpr->getSourceRange()); 4499 4500 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4501 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4502 && !IndexExpr->isTypeDependent()) 4503 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4504 4505 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4506 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4507 // type. Note that Functions are not objects, and that (in C99 parlance) 4508 // incomplete types are not object types. 4509 if (ResultType->isFunctionType()) { 4510 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 4511 << ResultType << BaseExpr->getSourceRange(); 4512 return ExprError(); 4513 } 4514 4515 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4516 // GNU extension: subscripting on pointer to void 4517 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4518 << BaseExpr->getSourceRange(); 4519 4520 // C forbids expressions of unqualified void type from being l-values. 4521 // See IsCForbiddenLValueType. 4522 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4523 } else if (!ResultType->isDependentType() && 4524 RequireCompleteType(LLoc, ResultType, 4525 diag::err_subscript_incomplete_type, BaseExpr)) 4526 return ExprError(); 4527 4528 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4529 !ResultType.isCForbiddenLValueType()); 4530 4531 return new (Context) 4532 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4533 } 4534 4535 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 4536 ParmVarDecl *Param) { 4537 if (Param->hasUnparsedDefaultArg()) { 4538 Diag(CallLoc, 4539 diag::err_use_of_default_argument_to_function_declared_later) << 4540 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4541 Diag(UnparsedDefaultArgLocs[Param], 4542 diag::note_default_argument_declared_here); 4543 return true; 4544 } 4545 4546 if (Param->hasUninstantiatedDefaultArg()) { 4547 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4548 4549 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated, 4550 Param); 4551 4552 // Instantiate the expression. 4553 MultiLevelTemplateArgumentList MutiLevelArgList 4554 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4555 4556 InstantiatingTemplate Inst(*this, CallLoc, Param, 4557 MutiLevelArgList.getInnermost()); 4558 if (Inst.isInvalid()) 4559 return true; 4560 if (Inst.isAlreadyInstantiating()) { 4561 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4562 Param->setInvalidDecl(); 4563 return true; 4564 } 4565 4566 ExprResult Result; 4567 { 4568 // C++ [dcl.fct.default]p5: 4569 // The names in the [default argument] expression are bound, and 4570 // the semantic constraints are checked, at the point where the 4571 // default argument expression appears. 4572 ContextRAII SavedContext(*this, FD); 4573 LocalInstantiationScope Local(*this); 4574 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 4575 /*DirectInit*/false); 4576 } 4577 if (Result.isInvalid()) 4578 return true; 4579 4580 // Check the expression as an initializer for the parameter. 4581 InitializedEntity Entity 4582 = InitializedEntity::InitializeParameter(Context, Param); 4583 InitializationKind Kind 4584 = InitializationKind::CreateCopy(Param->getLocation(), 4585 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 4586 Expr *ResultE = Result.getAs<Expr>(); 4587 4588 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4589 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4590 if (Result.isInvalid()) 4591 return true; 4592 4593 Result = ActOnFinishFullExpr(Result.getAs<Expr>(), 4594 Param->getOuterLocStart()); 4595 if (Result.isInvalid()) 4596 return true; 4597 4598 // Remember the instantiated default argument. 4599 Param->setDefaultArg(Result.getAs<Expr>()); 4600 if (ASTMutationListener *L = getASTMutationListener()) { 4601 L->DefaultArgumentInstantiated(Param); 4602 } 4603 } 4604 4605 // If the default argument expression is not set yet, we are building it now. 4606 if (!Param->hasInit()) { 4607 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4608 Param->setInvalidDecl(); 4609 return true; 4610 } 4611 4612 // If the default expression creates temporaries, we need to 4613 // push them to the current stack of expression temporaries so they'll 4614 // be properly destroyed. 4615 // FIXME: We should really be rebuilding the default argument with new 4616 // bound temporaries; see the comment in PR5810. 4617 // We don't need to do that with block decls, though, because 4618 // blocks in default argument expression can never capture anything. 4619 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 4620 // Set the "needs cleanups" bit regardless of whether there are 4621 // any explicit objects. 4622 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 4623 4624 // Append all the objects to the cleanup list. Right now, this 4625 // should always be a no-op, because blocks in default argument 4626 // expressions should never be able to capture anything. 4627 assert(!Init->getNumObjects() && 4628 "default argument expression has capturing blocks?"); 4629 } 4630 4631 // We already type-checked the argument, so we know it works. 4632 // Just mark all of the declarations in this potentially-evaluated expression 4633 // as being "referenced". 4634 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4635 /*SkipLocalVariables=*/true); 4636 return false; 4637 } 4638 4639 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4640 FunctionDecl *FD, ParmVarDecl *Param) { 4641 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 4642 return ExprError(); 4643 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4644 } 4645 4646 Sema::VariadicCallType 4647 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4648 Expr *Fn) { 4649 if (Proto && Proto->isVariadic()) { 4650 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4651 return VariadicConstructor; 4652 else if (Fn && Fn->getType()->isBlockPointerType()) 4653 return VariadicBlock; 4654 else if (FDecl) { 4655 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4656 if (Method->isInstance()) 4657 return VariadicMethod; 4658 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4659 return VariadicMethod; 4660 return VariadicFunction; 4661 } 4662 return VariadicDoesNotApply; 4663 } 4664 4665 namespace { 4666 class FunctionCallCCC : public FunctionCallFilterCCC { 4667 public: 4668 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4669 unsigned NumArgs, MemberExpr *ME) 4670 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4671 FunctionName(FuncName) {} 4672 4673 bool ValidateCandidate(const TypoCorrection &candidate) override { 4674 if (!candidate.getCorrectionSpecifier() || 4675 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4676 return false; 4677 } 4678 4679 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4680 } 4681 4682 private: 4683 const IdentifierInfo *const FunctionName; 4684 }; 4685 } 4686 4687 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4688 FunctionDecl *FDecl, 4689 ArrayRef<Expr *> Args) { 4690 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4691 DeclarationName FuncName = FDecl->getDeclName(); 4692 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart(); 4693 4694 if (TypoCorrection Corrected = S.CorrectTypo( 4695 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4696 S.getScopeForContext(S.CurContext), nullptr, 4697 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4698 Args.size(), ME), 4699 Sema::CTK_ErrorRecovery)) { 4700 if (NamedDecl *ND = Corrected.getFoundDecl()) { 4701 if (Corrected.isOverloaded()) { 4702 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4703 OverloadCandidateSet::iterator Best; 4704 for (NamedDecl *CD : Corrected) { 4705 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 4706 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4707 OCS); 4708 } 4709 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4710 case OR_Success: 4711 ND = Best->FoundDecl; 4712 Corrected.setCorrectionDecl(ND); 4713 break; 4714 default: 4715 break; 4716 } 4717 } 4718 ND = ND->getUnderlyingDecl(); 4719 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 4720 return Corrected; 4721 } 4722 } 4723 return TypoCorrection(); 4724 } 4725 4726 /// ConvertArgumentsForCall - Converts the arguments specified in 4727 /// Args/NumArgs to the parameter types of the function FDecl with 4728 /// function prototype Proto. Call is the call expression itself, and 4729 /// Fn is the function expression. For a C++ member function, this 4730 /// routine does not attempt to convert the object argument. Returns 4731 /// true if the call is ill-formed. 4732 bool 4733 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4734 FunctionDecl *FDecl, 4735 const FunctionProtoType *Proto, 4736 ArrayRef<Expr *> Args, 4737 SourceLocation RParenLoc, 4738 bool IsExecConfig) { 4739 // Bail out early if calling a builtin with custom typechecking. 4740 if (FDecl) 4741 if (unsigned ID = FDecl->getBuiltinID()) 4742 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4743 return false; 4744 4745 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4746 // assignment, to the types of the corresponding parameter, ... 4747 unsigned NumParams = Proto->getNumParams(); 4748 bool Invalid = false; 4749 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4750 unsigned FnKind = Fn->getType()->isBlockPointerType() 4751 ? 1 /* block */ 4752 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4753 : 0 /* function */); 4754 4755 // If too few arguments are available (and we don't have default 4756 // arguments for the remaining parameters), don't make the call. 4757 if (Args.size() < NumParams) { 4758 if (Args.size() < MinArgs) { 4759 TypoCorrection TC; 4760 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4761 unsigned diag_id = 4762 MinArgs == NumParams && !Proto->isVariadic() 4763 ? diag::err_typecheck_call_too_few_args_suggest 4764 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4765 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4766 << static_cast<unsigned>(Args.size()) 4767 << TC.getCorrectionRange()); 4768 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4769 Diag(RParenLoc, 4770 MinArgs == NumParams && !Proto->isVariadic() 4771 ? diag::err_typecheck_call_too_few_args_one 4772 : diag::err_typecheck_call_too_few_args_at_least_one) 4773 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4774 else 4775 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4776 ? diag::err_typecheck_call_too_few_args 4777 : diag::err_typecheck_call_too_few_args_at_least) 4778 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4779 << Fn->getSourceRange(); 4780 4781 // Emit the location of the prototype. 4782 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4783 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4784 << FDecl; 4785 4786 return true; 4787 } 4788 Call->setNumArgs(Context, NumParams); 4789 } 4790 4791 // If too many are passed and not variadic, error on the extras and drop 4792 // them. 4793 if (Args.size() > NumParams) { 4794 if (!Proto->isVariadic()) { 4795 TypoCorrection TC; 4796 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4797 unsigned diag_id = 4798 MinArgs == NumParams && !Proto->isVariadic() 4799 ? diag::err_typecheck_call_too_many_args_suggest 4800 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4801 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4802 << static_cast<unsigned>(Args.size()) 4803 << TC.getCorrectionRange()); 4804 } else if (NumParams == 1 && FDecl && 4805 FDecl->getParamDecl(0)->getDeclName()) 4806 Diag(Args[NumParams]->getLocStart(), 4807 MinArgs == NumParams 4808 ? diag::err_typecheck_call_too_many_args_one 4809 : diag::err_typecheck_call_too_many_args_at_most_one) 4810 << FnKind << FDecl->getParamDecl(0) 4811 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4812 << SourceRange(Args[NumParams]->getLocStart(), 4813 Args.back()->getLocEnd()); 4814 else 4815 Diag(Args[NumParams]->getLocStart(), 4816 MinArgs == NumParams 4817 ? diag::err_typecheck_call_too_many_args 4818 : diag::err_typecheck_call_too_many_args_at_most) 4819 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4820 << Fn->getSourceRange() 4821 << SourceRange(Args[NumParams]->getLocStart(), 4822 Args.back()->getLocEnd()); 4823 4824 // Emit the location of the prototype. 4825 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4826 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4827 << FDecl; 4828 4829 // This deletes the extra arguments. 4830 Call->setNumArgs(Context, NumParams); 4831 return true; 4832 } 4833 } 4834 SmallVector<Expr *, 8> AllArgs; 4835 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4836 4837 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4838 Proto, 0, Args, AllArgs, CallType); 4839 if (Invalid) 4840 return true; 4841 unsigned TotalNumArgs = AllArgs.size(); 4842 for (unsigned i = 0; i < TotalNumArgs; ++i) 4843 Call->setArg(i, AllArgs[i]); 4844 4845 return false; 4846 } 4847 4848 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4849 const FunctionProtoType *Proto, 4850 unsigned FirstParam, ArrayRef<Expr *> Args, 4851 SmallVectorImpl<Expr *> &AllArgs, 4852 VariadicCallType CallType, bool AllowExplicit, 4853 bool IsListInitialization) { 4854 unsigned NumParams = Proto->getNumParams(); 4855 bool Invalid = false; 4856 size_t ArgIx = 0; 4857 // Continue to check argument types (even if we have too few/many args). 4858 for (unsigned i = FirstParam; i < NumParams; i++) { 4859 QualType ProtoArgType = Proto->getParamType(i); 4860 4861 Expr *Arg; 4862 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4863 if (ArgIx < Args.size()) { 4864 Arg = Args[ArgIx++]; 4865 4866 if (RequireCompleteType(Arg->getLocStart(), 4867 ProtoArgType, 4868 diag::err_call_incomplete_argument, Arg)) 4869 return true; 4870 4871 // Strip the unbridged-cast placeholder expression off, if applicable. 4872 bool CFAudited = false; 4873 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4874 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4875 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4876 Arg = stripARCUnbridgedCast(Arg); 4877 else if (getLangOpts().ObjCAutoRefCount && 4878 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4879 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4880 CFAudited = true; 4881 4882 InitializedEntity Entity = 4883 Param ? InitializedEntity::InitializeParameter(Context, Param, 4884 ProtoArgType) 4885 : InitializedEntity::InitializeParameter( 4886 Context, ProtoArgType, Proto->isParamConsumed(i)); 4887 4888 // Remember that parameter belongs to a CF audited API. 4889 if (CFAudited) 4890 Entity.setParameterCFAudited(); 4891 4892 ExprResult ArgE = PerformCopyInitialization( 4893 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 4894 if (ArgE.isInvalid()) 4895 return true; 4896 4897 Arg = ArgE.getAs<Expr>(); 4898 } else { 4899 assert(Param && "can't use default arguments without a known callee"); 4900 4901 ExprResult ArgExpr = 4902 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4903 if (ArgExpr.isInvalid()) 4904 return true; 4905 4906 Arg = ArgExpr.getAs<Expr>(); 4907 } 4908 4909 // Check for array bounds violations for each argument to the call. This 4910 // check only triggers warnings when the argument isn't a more complex Expr 4911 // with its own checking, such as a BinaryOperator. 4912 CheckArrayAccess(Arg); 4913 4914 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4915 CheckStaticArrayArgument(CallLoc, Param, Arg); 4916 4917 AllArgs.push_back(Arg); 4918 } 4919 4920 // If this is a variadic call, handle args passed through "...". 4921 if (CallType != VariadicDoesNotApply) { 4922 // Assume that extern "C" functions with variadic arguments that 4923 // return __unknown_anytype aren't *really* variadic. 4924 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4925 FDecl->isExternC()) { 4926 for (Expr *A : Args.slice(ArgIx)) { 4927 QualType paramType; // ignored 4928 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 4929 Invalid |= arg.isInvalid(); 4930 AllArgs.push_back(arg.get()); 4931 } 4932 4933 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4934 } else { 4935 for (Expr *A : Args.slice(ArgIx)) { 4936 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 4937 Invalid |= Arg.isInvalid(); 4938 AllArgs.push_back(Arg.get()); 4939 } 4940 } 4941 4942 // Check for array bounds violations. 4943 for (Expr *A : Args.slice(ArgIx)) 4944 CheckArrayAccess(A); 4945 } 4946 return Invalid; 4947 } 4948 4949 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4950 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4951 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4952 TL = DTL.getOriginalLoc(); 4953 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4954 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4955 << ATL.getLocalSourceRange(); 4956 } 4957 4958 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4959 /// array parameter, check that it is non-null, and that if it is formed by 4960 /// array-to-pointer decay, the underlying array is sufficiently large. 4961 /// 4962 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4963 /// array type derivation, then for each call to the function, the value of the 4964 /// corresponding actual argument shall provide access to the first element of 4965 /// an array with at least as many elements as specified by the size expression. 4966 void 4967 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4968 ParmVarDecl *Param, 4969 const Expr *ArgExpr) { 4970 // Static array parameters are not supported in C++. 4971 if (!Param || getLangOpts().CPlusPlus) 4972 return; 4973 4974 QualType OrigTy = Param->getOriginalType(); 4975 4976 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4977 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4978 return; 4979 4980 if (ArgExpr->isNullPointerConstant(Context, 4981 Expr::NPC_NeverValueDependent)) { 4982 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4983 DiagnoseCalleeStaticArrayParam(*this, Param); 4984 return; 4985 } 4986 4987 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 4988 if (!CAT) 4989 return; 4990 4991 const ConstantArrayType *ArgCAT = 4992 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 4993 if (!ArgCAT) 4994 return; 4995 4996 if (ArgCAT->getSize().ult(CAT->getSize())) { 4997 Diag(CallLoc, diag::warn_static_array_too_small) 4998 << ArgExpr->getSourceRange() 4999 << (unsigned) ArgCAT->getSize().getZExtValue() 5000 << (unsigned) CAT->getSize().getZExtValue(); 5001 DiagnoseCalleeStaticArrayParam(*this, Param); 5002 } 5003 } 5004 5005 /// Given a function expression of unknown-any type, try to rebuild it 5006 /// to have a function type. 5007 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 5008 5009 /// Is the given type a placeholder that we need to lower out 5010 /// immediately during argument processing? 5011 static bool isPlaceholderToRemoveAsArg(QualType type) { 5012 // Placeholders are never sugared. 5013 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 5014 if (!placeholder) return false; 5015 5016 switch (placeholder->getKind()) { 5017 // Ignore all the non-placeholder types. 5018 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 5019 case BuiltinType::Id: 5020 #include "clang/Basic/OpenCLImageTypes.def" 5021 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 5022 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 5023 #include "clang/AST/BuiltinTypes.def" 5024 return false; 5025 5026 // We cannot lower out overload sets; they might validly be resolved 5027 // by the call machinery. 5028 case BuiltinType::Overload: 5029 return false; 5030 5031 // Unbridged casts in ARC can be handled in some call positions and 5032 // should be left in place. 5033 case BuiltinType::ARCUnbridgedCast: 5034 return false; 5035 5036 // Pseudo-objects should be converted as soon as possible. 5037 case BuiltinType::PseudoObject: 5038 return true; 5039 5040 // The debugger mode could theoretically but currently does not try 5041 // to resolve unknown-typed arguments based on known parameter types. 5042 case BuiltinType::UnknownAny: 5043 return true; 5044 5045 // These are always invalid as call arguments and should be reported. 5046 case BuiltinType::BoundMember: 5047 case BuiltinType::BuiltinFn: 5048 case BuiltinType::OMPArraySection: 5049 return true; 5050 5051 } 5052 llvm_unreachable("bad builtin type kind"); 5053 } 5054 5055 /// Check an argument list for placeholders that we won't try to 5056 /// handle later. 5057 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5058 // Apply this processing to all the arguments at once instead of 5059 // dying at the first failure. 5060 bool hasInvalid = false; 5061 for (size_t i = 0, e = args.size(); i != e; i++) { 5062 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5063 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5064 if (result.isInvalid()) hasInvalid = true; 5065 else args[i] = result.get(); 5066 } else if (hasInvalid) { 5067 (void)S.CorrectDelayedTyposInExpr(args[i]); 5068 } 5069 } 5070 return hasInvalid; 5071 } 5072 5073 /// If a builtin function has a pointer argument with no explicit address 5074 /// space, then it should be able to accept a pointer to any address 5075 /// space as input. In order to do this, we need to replace the 5076 /// standard builtin declaration with one that uses the same address space 5077 /// as the call. 5078 /// 5079 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5080 /// it does not contain any pointer arguments without 5081 /// an address space qualifer. Otherwise the rewritten 5082 /// FunctionDecl is returned. 5083 /// TODO: Handle pointer return types. 5084 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5085 const FunctionDecl *FDecl, 5086 MultiExprArg ArgExprs) { 5087 5088 QualType DeclType = FDecl->getType(); 5089 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5090 5091 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 5092 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 5093 return nullptr; 5094 5095 bool NeedsNewDecl = false; 5096 unsigned i = 0; 5097 SmallVector<QualType, 8> OverloadParams; 5098 5099 for (QualType ParamType : FT->param_types()) { 5100 5101 // Convert array arguments to pointer to simplify type lookup. 5102 ExprResult ArgRes = 5103 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5104 if (ArgRes.isInvalid()) 5105 return nullptr; 5106 Expr *Arg = ArgRes.get(); 5107 QualType ArgType = Arg->getType(); 5108 if (!ParamType->isPointerType() || 5109 ParamType.getQualifiers().hasAddressSpace() || 5110 !ArgType->isPointerType() || 5111 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 5112 OverloadParams.push_back(ParamType); 5113 continue; 5114 } 5115 5116 NeedsNewDecl = true; 5117 unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace(); 5118 5119 QualType PointeeType = ParamType->getPointeeType(); 5120 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5121 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5122 } 5123 5124 if (!NeedsNewDecl) 5125 return nullptr; 5126 5127 FunctionProtoType::ExtProtoInfo EPI; 5128 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5129 OverloadParams, EPI); 5130 DeclContext *Parent = Context.getTranslationUnitDecl(); 5131 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5132 FDecl->getLocation(), 5133 FDecl->getLocation(), 5134 FDecl->getIdentifier(), 5135 OverloadTy, 5136 /*TInfo=*/nullptr, 5137 SC_Extern, false, 5138 /*hasPrototype=*/true); 5139 SmallVector<ParmVarDecl*, 16> Params; 5140 FT = cast<FunctionProtoType>(OverloadTy); 5141 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5142 QualType ParamType = FT->getParamType(i); 5143 ParmVarDecl *Parm = 5144 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5145 SourceLocation(), nullptr, ParamType, 5146 /*TInfo=*/nullptr, SC_None, nullptr); 5147 Parm->setScopeInfo(0, i); 5148 Params.push_back(Parm); 5149 } 5150 OverloadDecl->setParams(Params); 5151 return OverloadDecl; 5152 } 5153 5154 static bool isNumberOfArgsValidForCall(Sema &S, const FunctionDecl *Callee, 5155 std::size_t NumArgs) { 5156 if (S.TooManyArguments(Callee->getNumParams(), NumArgs, 5157 /*PartialOverloading=*/false)) 5158 return Callee->isVariadic(); 5159 return Callee->getMinRequiredArguments() <= NumArgs; 5160 } 5161 5162 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 5163 /// This provides the location of the left/right parens and a list of comma 5164 /// locations. 5165 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5166 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5167 Expr *ExecConfig, bool IsExecConfig) { 5168 // Since this might be a postfix expression, get rid of ParenListExprs. 5169 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 5170 if (Result.isInvalid()) return ExprError(); 5171 Fn = Result.get(); 5172 5173 if (checkArgsForPlaceholders(*this, ArgExprs)) 5174 return ExprError(); 5175 5176 if (getLangOpts().CPlusPlus) { 5177 // If this is a pseudo-destructor expression, build the call immediately. 5178 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5179 if (!ArgExprs.empty()) { 5180 // Pseudo-destructor calls should not have any arguments. 5181 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 5182 << FixItHint::CreateRemoval( 5183 SourceRange(ArgExprs.front()->getLocStart(), 5184 ArgExprs.back()->getLocEnd())); 5185 } 5186 5187 return new (Context) 5188 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc); 5189 } 5190 if (Fn->getType() == Context.PseudoObjectTy) { 5191 ExprResult result = CheckPlaceholderExpr(Fn); 5192 if (result.isInvalid()) return ExprError(); 5193 Fn = result.get(); 5194 } 5195 5196 // Determine whether this is a dependent call inside a C++ template, 5197 // in which case we won't do any semantic analysis now. 5198 bool Dependent = false; 5199 if (Fn->isTypeDependent()) 5200 Dependent = true; 5201 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5202 Dependent = true; 5203 5204 if (Dependent) { 5205 if (ExecConfig) { 5206 return new (Context) CUDAKernelCallExpr( 5207 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5208 Context.DependentTy, VK_RValue, RParenLoc); 5209 } else { 5210 return new (Context) CallExpr( 5211 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5212 } 5213 } 5214 5215 // Determine whether this is a call to an object (C++ [over.call.object]). 5216 if (Fn->getType()->isRecordType()) 5217 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 5218 RParenLoc); 5219 5220 if (Fn->getType() == Context.UnknownAnyTy) { 5221 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5222 if (result.isInvalid()) return ExprError(); 5223 Fn = result.get(); 5224 } 5225 5226 if (Fn->getType() == Context.BoundMemberTy) { 5227 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5228 RParenLoc); 5229 } 5230 } 5231 5232 // Check for overloaded calls. This can happen even in C due to extensions. 5233 if (Fn->getType() == Context.OverloadTy) { 5234 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5235 5236 // We aren't supposed to apply this logic for if there'Scope an '&' 5237 // involved. 5238 if (!find.HasFormOfMemberPointer) { 5239 OverloadExpr *ovl = find.Expression; 5240 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5241 return BuildOverloadedCallExpr( 5242 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 5243 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 5244 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5245 RParenLoc); 5246 } 5247 } 5248 5249 // If we're directly calling a function, get the appropriate declaration. 5250 if (Fn->getType() == Context.UnknownAnyTy) { 5251 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5252 if (result.isInvalid()) return ExprError(); 5253 Fn = result.get(); 5254 } 5255 5256 Expr *NakedFn = Fn->IgnoreParens(); 5257 5258 bool CallingNDeclIndirectly = false; 5259 NamedDecl *NDecl = nullptr; 5260 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5261 if (UnOp->getOpcode() == UO_AddrOf) { 5262 CallingNDeclIndirectly = true; 5263 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5264 } 5265 } 5266 5267 if (isa<DeclRefExpr>(NakedFn)) { 5268 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 5269 5270 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5271 if (FDecl && FDecl->getBuiltinID()) { 5272 // Rewrite the function decl for this builtin by replacing parameters 5273 // with no explicit address space with the address space of the arguments 5274 // in ArgExprs. 5275 if ((FDecl = 5276 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5277 NDecl = FDecl; 5278 Fn = DeclRefExpr::Create( 5279 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 5280 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl); 5281 } 5282 } 5283 } else if (isa<MemberExpr>(NakedFn)) 5284 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5285 5286 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5287 if (CallingNDeclIndirectly && 5288 !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 5289 Fn->getLocStart())) 5290 return ExprError(); 5291 5292 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 5293 return ExprError(); 5294 5295 // CheckEnableIf assumes that the we're passing in a sane number of args for 5296 // FD, but that doesn't always hold true here. This is because, in some 5297 // cases, we'll emit a diag about an ill-formed function call, but then 5298 // we'll continue on as if the function call wasn't ill-formed. So, if the 5299 // number of args looks incorrect, don't do enable_if checks; we should've 5300 // already emitted an error about the bad call. 5301 if (FD->hasAttr<EnableIfAttr>() && 5302 isNumberOfArgsValidForCall(*this, FD, ArgExprs.size())) { 5303 if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) { 5304 Diag(Fn->getLocStart(), 5305 isa<CXXMethodDecl>(FD) 5306 ? diag::err_ovl_no_viable_member_function_in_call 5307 : diag::err_ovl_no_viable_function_in_call) 5308 << FD << FD->getSourceRange(); 5309 Diag(FD->getLocation(), 5310 diag::note_ovl_candidate_disabled_by_enable_if_attr) 5311 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5312 } 5313 } 5314 } 5315 5316 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5317 ExecConfig, IsExecConfig); 5318 } 5319 5320 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5321 /// 5322 /// __builtin_astype( value, dst type ) 5323 /// 5324 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5325 SourceLocation BuiltinLoc, 5326 SourceLocation RParenLoc) { 5327 ExprValueKind VK = VK_RValue; 5328 ExprObjectKind OK = OK_Ordinary; 5329 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5330 QualType SrcTy = E->getType(); 5331 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5332 return ExprError(Diag(BuiltinLoc, 5333 diag::err_invalid_astype_of_different_size) 5334 << DstTy 5335 << SrcTy 5336 << E->getSourceRange()); 5337 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5338 } 5339 5340 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5341 /// provided arguments. 5342 /// 5343 /// __builtin_convertvector( value, dst type ) 5344 /// 5345 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5346 SourceLocation BuiltinLoc, 5347 SourceLocation RParenLoc) { 5348 TypeSourceInfo *TInfo; 5349 GetTypeFromParser(ParsedDestTy, &TInfo); 5350 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5351 } 5352 5353 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5354 /// i.e. an expression not of \p OverloadTy. The expression should 5355 /// unary-convert to an expression of function-pointer or 5356 /// block-pointer type. 5357 /// 5358 /// \param NDecl the declaration being called, if available 5359 ExprResult 5360 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5361 SourceLocation LParenLoc, 5362 ArrayRef<Expr *> Args, 5363 SourceLocation RParenLoc, 5364 Expr *Config, bool IsExecConfig) { 5365 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5366 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5367 5368 // Functions with 'interrupt' attribute cannot be called directly. 5369 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5370 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5371 return ExprError(); 5372 } 5373 5374 // Promote the function operand. 5375 // We special-case function promotion here because we only allow promoting 5376 // builtin functions to function pointers in the callee of a call. 5377 ExprResult Result; 5378 if (BuiltinID && 5379 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5380 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 5381 CK_BuiltinFnToFnPtr).get(); 5382 } else { 5383 Result = CallExprUnaryConversions(Fn); 5384 } 5385 if (Result.isInvalid()) 5386 return ExprError(); 5387 Fn = Result.get(); 5388 5389 // Make the call expr early, before semantic checks. This guarantees cleanup 5390 // of arguments and function on error. 5391 CallExpr *TheCall; 5392 if (Config) 5393 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 5394 cast<CallExpr>(Config), Args, 5395 Context.BoolTy, VK_RValue, 5396 RParenLoc); 5397 else 5398 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 5399 VK_RValue, RParenLoc); 5400 5401 if (!getLangOpts().CPlusPlus) { 5402 // C cannot always handle TypoExpr nodes in builtin calls and direct 5403 // function calls as their argument checking don't necessarily handle 5404 // dependent types properly, so make sure any TypoExprs have been 5405 // dealt with. 5406 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5407 if (!Result.isUsable()) return ExprError(); 5408 TheCall = dyn_cast<CallExpr>(Result.get()); 5409 if (!TheCall) return Result; 5410 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5411 } 5412 5413 // Bail out early if calling a builtin with custom typechecking. 5414 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5415 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5416 5417 retry: 5418 const FunctionType *FuncT; 5419 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5420 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5421 // have type pointer to function". 5422 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5423 if (!FuncT) 5424 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5425 << Fn->getType() << Fn->getSourceRange()); 5426 } else if (const BlockPointerType *BPT = 5427 Fn->getType()->getAs<BlockPointerType>()) { 5428 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5429 } else { 5430 // Handle calls to expressions of unknown-any type. 5431 if (Fn->getType() == Context.UnknownAnyTy) { 5432 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5433 if (rewrite.isInvalid()) return ExprError(); 5434 Fn = rewrite.get(); 5435 TheCall->setCallee(Fn); 5436 goto retry; 5437 } 5438 5439 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5440 << Fn->getType() << Fn->getSourceRange()); 5441 } 5442 5443 if (getLangOpts().CUDA) { 5444 if (Config) { 5445 // CUDA: Kernel calls must be to global functions 5446 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5447 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5448 << FDecl->getName() << Fn->getSourceRange()); 5449 5450 // CUDA: Kernel function must have 'void' return type 5451 if (!FuncT->getReturnType()->isVoidType()) 5452 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5453 << Fn->getType() << Fn->getSourceRange()); 5454 } else { 5455 // CUDA: Calls to global functions must be configured 5456 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5457 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5458 << FDecl->getName() << Fn->getSourceRange()); 5459 } 5460 } 5461 5462 // Check for a valid return type 5463 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall, 5464 FDecl)) 5465 return ExprError(); 5466 5467 // We know the result type of the call, set it. 5468 TheCall->setType(FuncT->getCallResultType(Context)); 5469 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5470 5471 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 5472 if (Proto) { 5473 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5474 IsExecConfig)) 5475 return ExprError(); 5476 } else { 5477 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5478 5479 if (FDecl) { 5480 // Check if we have too few/too many template arguments, based 5481 // on our knowledge of the function definition. 5482 const FunctionDecl *Def = nullptr; 5483 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5484 Proto = Def->getType()->getAs<FunctionProtoType>(); 5485 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5486 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5487 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5488 } 5489 5490 // If the function we're calling isn't a function prototype, but we have 5491 // a function prototype from a prior declaratiom, use that prototype. 5492 if (!FDecl->hasPrototype()) 5493 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5494 } 5495 5496 // Promote the arguments (C99 6.5.2.2p6). 5497 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5498 Expr *Arg = Args[i]; 5499 5500 if (Proto && i < Proto->getNumParams()) { 5501 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5502 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5503 ExprResult ArgE = 5504 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5505 if (ArgE.isInvalid()) 5506 return true; 5507 5508 Arg = ArgE.getAs<Expr>(); 5509 5510 } else { 5511 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5512 5513 if (ArgE.isInvalid()) 5514 return true; 5515 5516 Arg = ArgE.getAs<Expr>(); 5517 } 5518 5519 if (RequireCompleteType(Arg->getLocStart(), 5520 Arg->getType(), 5521 diag::err_call_incomplete_argument, Arg)) 5522 return ExprError(); 5523 5524 TheCall->setArg(i, Arg); 5525 } 5526 } 5527 5528 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5529 if (!Method->isStatic()) 5530 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5531 << Fn->getSourceRange()); 5532 5533 // Check for sentinels 5534 if (NDecl) 5535 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5536 5537 // Do special checking on direct calls to functions. 5538 if (FDecl) { 5539 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5540 return ExprError(); 5541 5542 if (BuiltinID) 5543 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5544 } else if (NDecl) { 5545 if (CheckPointerCall(NDecl, TheCall, Proto)) 5546 return ExprError(); 5547 } else { 5548 if (CheckOtherCall(TheCall, Proto)) 5549 return ExprError(); 5550 } 5551 5552 return MaybeBindToTemporary(TheCall); 5553 } 5554 5555 ExprResult 5556 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5557 SourceLocation RParenLoc, Expr *InitExpr) { 5558 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5559 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 5560 5561 TypeSourceInfo *TInfo; 5562 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5563 if (!TInfo) 5564 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5565 5566 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5567 } 5568 5569 ExprResult 5570 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5571 SourceLocation RParenLoc, Expr *LiteralExpr) { 5572 QualType literalType = TInfo->getType(); 5573 5574 if (literalType->isArrayType()) { 5575 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5576 diag::err_illegal_decl_array_incomplete_type, 5577 SourceRange(LParenLoc, 5578 LiteralExpr->getSourceRange().getEnd()))) 5579 return ExprError(); 5580 if (literalType->isVariableArrayType()) 5581 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5582 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5583 } else if (!literalType->isDependentType() && 5584 RequireCompleteType(LParenLoc, literalType, 5585 diag::err_typecheck_decl_incomplete_type, 5586 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5587 return ExprError(); 5588 5589 InitializedEntity Entity 5590 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5591 InitializationKind Kind 5592 = InitializationKind::CreateCStyleCast(LParenLoc, 5593 SourceRange(LParenLoc, RParenLoc), 5594 /*InitList=*/true); 5595 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5596 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5597 &literalType); 5598 if (Result.isInvalid()) 5599 return ExprError(); 5600 LiteralExpr = Result.get(); 5601 5602 bool isFileScope = !CurContext->isFunctionOrMethod(); 5603 if (isFileScope && 5604 !LiteralExpr->isTypeDependent() && 5605 !LiteralExpr->isValueDependent() && 5606 !literalType->isDependentType()) { // 6.5.2.5p3 5607 if (CheckForConstantInitializer(LiteralExpr, literalType)) 5608 return ExprError(); 5609 } 5610 5611 // In C, compound literals are l-values for some reason. 5612 // For GCC compatibility, in C++, file-scope array compound literals with 5613 // constant initializers are also l-values, and compound literals are 5614 // otherwise prvalues. 5615 // 5616 // (GCC also treats C++ list-initialized file-scope array prvalues with 5617 // constant initializers as l-values, but that's non-conforming, so we don't 5618 // follow it there.) 5619 // 5620 // FIXME: It would be better to handle the lvalue cases as materializing and 5621 // lifetime-extending a temporary object, but our materialized temporaries 5622 // representation only supports lifetime extension from a variable, not "out 5623 // of thin air". 5624 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 5625 // is bound to the result of applying array-to-pointer decay to the compound 5626 // literal. 5627 // FIXME: GCC supports compound literals of reference type, which should 5628 // obviously have a value kind derived from the kind of reference involved. 5629 ExprValueKind VK = 5630 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 5631 ? VK_RValue 5632 : VK_LValue; 5633 5634 return MaybeBindToTemporary( 5635 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 5636 VK, LiteralExpr, isFileScope)); 5637 } 5638 5639 ExprResult 5640 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 5641 SourceLocation RBraceLoc) { 5642 // Immediately handle non-overload placeholders. Overloads can be 5643 // resolved contextually, but everything else here can't. 5644 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 5645 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 5646 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 5647 5648 // Ignore failures; dropping the entire initializer list because 5649 // of one failure would be terrible for indexing/etc. 5650 if (result.isInvalid()) continue; 5651 5652 InitArgList[I] = result.get(); 5653 } 5654 } 5655 5656 // Semantic analysis for initializers is done by ActOnDeclarator() and 5657 // CheckInitializer() - it requires knowledge of the object being intialized. 5658 5659 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 5660 RBraceLoc); 5661 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 5662 return E; 5663 } 5664 5665 /// Do an explicit extend of the given block pointer if we're in ARC. 5666 void Sema::maybeExtendBlockObject(ExprResult &E) { 5667 assert(E.get()->getType()->isBlockPointerType()); 5668 assert(E.get()->isRValue()); 5669 5670 // Only do this in an r-value context. 5671 if (!getLangOpts().ObjCAutoRefCount) return; 5672 5673 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 5674 CK_ARCExtendBlockObject, E.get(), 5675 /*base path*/ nullptr, VK_RValue); 5676 Cleanup.setExprNeedsCleanups(true); 5677 } 5678 5679 /// Prepare a conversion of the given expression to an ObjC object 5680 /// pointer type. 5681 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 5682 QualType type = E.get()->getType(); 5683 if (type->isObjCObjectPointerType()) { 5684 return CK_BitCast; 5685 } else if (type->isBlockPointerType()) { 5686 maybeExtendBlockObject(E); 5687 return CK_BlockPointerToObjCPointerCast; 5688 } else { 5689 assert(type->isPointerType()); 5690 return CK_CPointerToObjCPointerCast; 5691 } 5692 } 5693 5694 /// Prepares for a scalar cast, performing all the necessary stages 5695 /// except the final cast and returning the kind required. 5696 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 5697 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 5698 // Also, callers should have filtered out the invalid cases with 5699 // pointers. Everything else should be possible. 5700 5701 QualType SrcTy = Src.get()->getType(); 5702 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 5703 return CK_NoOp; 5704 5705 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 5706 case Type::STK_MemberPointer: 5707 llvm_unreachable("member pointer type in C"); 5708 5709 case Type::STK_CPointer: 5710 case Type::STK_BlockPointer: 5711 case Type::STK_ObjCObjectPointer: 5712 switch (DestTy->getScalarTypeKind()) { 5713 case Type::STK_CPointer: { 5714 unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace(); 5715 unsigned DestAS = DestTy->getPointeeType().getAddressSpace(); 5716 if (SrcAS != DestAS) 5717 return CK_AddressSpaceConversion; 5718 return CK_BitCast; 5719 } 5720 case Type::STK_BlockPointer: 5721 return (SrcKind == Type::STK_BlockPointer 5722 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 5723 case Type::STK_ObjCObjectPointer: 5724 if (SrcKind == Type::STK_ObjCObjectPointer) 5725 return CK_BitCast; 5726 if (SrcKind == Type::STK_CPointer) 5727 return CK_CPointerToObjCPointerCast; 5728 maybeExtendBlockObject(Src); 5729 return CK_BlockPointerToObjCPointerCast; 5730 case Type::STK_Bool: 5731 return CK_PointerToBoolean; 5732 case Type::STK_Integral: 5733 return CK_PointerToIntegral; 5734 case Type::STK_Floating: 5735 case Type::STK_FloatingComplex: 5736 case Type::STK_IntegralComplex: 5737 case Type::STK_MemberPointer: 5738 llvm_unreachable("illegal cast from pointer"); 5739 } 5740 llvm_unreachable("Should have returned before this"); 5741 5742 case Type::STK_Bool: // casting from bool is like casting from an integer 5743 case Type::STK_Integral: 5744 switch (DestTy->getScalarTypeKind()) { 5745 case Type::STK_CPointer: 5746 case Type::STK_ObjCObjectPointer: 5747 case Type::STK_BlockPointer: 5748 if (Src.get()->isNullPointerConstant(Context, 5749 Expr::NPC_ValueDependentIsNull)) 5750 return CK_NullToPointer; 5751 return CK_IntegralToPointer; 5752 case Type::STK_Bool: 5753 return CK_IntegralToBoolean; 5754 case Type::STK_Integral: 5755 return CK_IntegralCast; 5756 case Type::STK_Floating: 5757 return CK_IntegralToFloating; 5758 case Type::STK_IntegralComplex: 5759 Src = ImpCastExprToType(Src.get(), 5760 DestTy->castAs<ComplexType>()->getElementType(), 5761 CK_IntegralCast); 5762 return CK_IntegralRealToComplex; 5763 case Type::STK_FloatingComplex: 5764 Src = ImpCastExprToType(Src.get(), 5765 DestTy->castAs<ComplexType>()->getElementType(), 5766 CK_IntegralToFloating); 5767 return CK_FloatingRealToComplex; 5768 case Type::STK_MemberPointer: 5769 llvm_unreachable("member pointer type in C"); 5770 } 5771 llvm_unreachable("Should have returned before this"); 5772 5773 case Type::STK_Floating: 5774 switch (DestTy->getScalarTypeKind()) { 5775 case Type::STK_Floating: 5776 return CK_FloatingCast; 5777 case Type::STK_Bool: 5778 return CK_FloatingToBoolean; 5779 case Type::STK_Integral: 5780 return CK_FloatingToIntegral; 5781 case Type::STK_FloatingComplex: 5782 Src = ImpCastExprToType(Src.get(), 5783 DestTy->castAs<ComplexType>()->getElementType(), 5784 CK_FloatingCast); 5785 return CK_FloatingRealToComplex; 5786 case Type::STK_IntegralComplex: 5787 Src = ImpCastExprToType(Src.get(), 5788 DestTy->castAs<ComplexType>()->getElementType(), 5789 CK_FloatingToIntegral); 5790 return CK_IntegralRealToComplex; 5791 case Type::STK_CPointer: 5792 case Type::STK_ObjCObjectPointer: 5793 case Type::STK_BlockPointer: 5794 llvm_unreachable("valid float->pointer cast?"); 5795 case Type::STK_MemberPointer: 5796 llvm_unreachable("member pointer type in C"); 5797 } 5798 llvm_unreachable("Should have returned before this"); 5799 5800 case Type::STK_FloatingComplex: 5801 switch (DestTy->getScalarTypeKind()) { 5802 case Type::STK_FloatingComplex: 5803 return CK_FloatingComplexCast; 5804 case Type::STK_IntegralComplex: 5805 return CK_FloatingComplexToIntegralComplex; 5806 case Type::STK_Floating: { 5807 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5808 if (Context.hasSameType(ET, DestTy)) 5809 return CK_FloatingComplexToReal; 5810 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 5811 return CK_FloatingCast; 5812 } 5813 case Type::STK_Bool: 5814 return CK_FloatingComplexToBoolean; 5815 case Type::STK_Integral: 5816 Src = ImpCastExprToType(Src.get(), 5817 SrcTy->castAs<ComplexType>()->getElementType(), 5818 CK_FloatingComplexToReal); 5819 return CK_FloatingToIntegral; 5820 case Type::STK_CPointer: 5821 case Type::STK_ObjCObjectPointer: 5822 case Type::STK_BlockPointer: 5823 llvm_unreachable("valid complex float->pointer cast?"); 5824 case Type::STK_MemberPointer: 5825 llvm_unreachable("member pointer type in C"); 5826 } 5827 llvm_unreachable("Should have returned before this"); 5828 5829 case Type::STK_IntegralComplex: 5830 switch (DestTy->getScalarTypeKind()) { 5831 case Type::STK_FloatingComplex: 5832 return CK_IntegralComplexToFloatingComplex; 5833 case Type::STK_IntegralComplex: 5834 return CK_IntegralComplexCast; 5835 case Type::STK_Integral: { 5836 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5837 if (Context.hasSameType(ET, DestTy)) 5838 return CK_IntegralComplexToReal; 5839 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 5840 return CK_IntegralCast; 5841 } 5842 case Type::STK_Bool: 5843 return CK_IntegralComplexToBoolean; 5844 case Type::STK_Floating: 5845 Src = ImpCastExprToType(Src.get(), 5846 SrcTy->castAs<ComplexType>()->getElementType(), 5847 CK_IntegralComplexToReal); 5848 return CK_IntegralToFloating; 5849 case Type::STK_CPointer: 5850 case Type::STK_ObjCObjectPointer: 5851 case Type::STK_BlockPointer: 5852 llvm_unreachable("valid complex int->pointer cast?"); 5853 case Type::STK_MemberPointer: 5854 llvm_unreachable("member pointer type in C"); 5855 } 5856 llvm_unreachable("Should have returned before this"); 5857 } 5858 5859 llvm_unreachable("Unhandled scalar cast"); 5860 } 5861 5862 static bool breakDownVectorType(QualType type, uint64_t &len, 5863 QualType &eltType) { 5864 // Vectors are simple. 5865 if (const VectorType *vecType = type->getAs<VectorType>()) { 5866 len = vecType->getNumElements(); 5867 eltType = vecType->getElementType(); 5868 assert(eltType->isScalarType()); 5869 return true; 5870 } 5871 5872 // We allow lax conversion to and from non-vector types, but only if 5873 // they're real types (i.e. non-complex, non-pointer scalar types). 5874 if (!type->isRealType()) return false; 5875 5876 len = 1; 5877 eltType = type; 5878 return true; 5879 } 5880 5881 /// Are the two types lax-compatible vector types? That is, given 5882 /// that one of them is a vector, do they have equal storage sizes, 5883 /// where the storage size is the number of elements times the element 5884 /// size? 5885 /// 5886 /// This will also return false if either of the types is neither a 5887 /// vector nor a real type. 5888 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 5889 assert(destTy->isVectorType() || srcTy->isVectorType()); 5890 5891 // Disallow lax conversions between scalars and ExtVectors (these 5892 // conversions are allowed for other vector types because common headers 5893 // depend on them). Most scalar OP ExtVector cases are handled by the 5894 // splat path anyway, which does what we want (convert, not bitcast). 5895 // What this rules out for ExtVectors is crazy things like char4*float. 5896 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 5897 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 5898 5899 uint64_t srcLen, destLen; 5900 QualType srcEltTy, destEltTy; 5901 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 5902 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 5903 5904 // ASTContext::getTypeSize will return the size rounded up to a 5905 // power of 2, so instead of using that, we need to use the raw 5906 // element size multiplied by the element count. 5907 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 5908 uint64_t destEltSize = Context.getTypeSize(destEltTy); 5909 5910 return (srcLen * srcEltSize == destLen * destEltSize); 5911 } 5912 5913 /// Is this a legal conversion between two types, one of which is 5914 /// known to be a vector type? 5915 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 5916 assert(destTy->isVectorType() || srcTy->isVectorType()); 5917 5918 if (!Context.getLangOpts().LaxVectorConversions) 5919 return false; 5920 return areLaxCompatibleVectorTypes(srcTy, destTy); 5921 } 5922 5923 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5924 CastKind &Kind) { 5925 assert(VectorTy->isVectorType() && "Not a vector type!"); 5926 5927 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 5928 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 5929 return Diag(R.getBegin(), 5930 Ty->isVectorType() ? 5931 diag::err_invalid_conversion_between_vectors : 5932 diag::err_invalid_conversion_between_vector_and_integer) 5933 << VectorTy << Ty << R; 5934 } else 5935 return Diag(R.getBegin(), 5936 diag::err_invalid_conversion_between_vector_and_scalar) 5937 << VectorTy << Ty << R; 5938 5939 Kind = CK_BitCast; 5940 return false; 5941 } 5942 5943 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 5944 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 5945 5946 if (DestElemTy == SplattedExpr->getType()) 5947 return SplattedExpr; 5948 5949 assert(DestElemTy->isFloatingType() || 5950 DestElemTy->isIntegralOrEnumerationType()); 5951 5952 CastKind CK; 5953 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 5954 // OpenCL requires that we convert `true` boolean expressions to -1, but 5955 // only when splatting vectors. 5956 if (DestElemTy->isFloatingType()) { 5957 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 5958 // in two steps: boolean to signed integral, then to floating. 5959 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 5960 CK_BooleanToSignedIntegral); 5961 SplattedExpr = CastExprRes.get(); 5962 CK = CK_IntegralToFloating; 5963 } else { 5964 CK = CK_BooleanToSignedIntegral; 5965 } 5966 } else { 5967 ExprResult CastExprRes = SplattedExpr; 5968 CK = PrepareScalarCast(CastExprRes, DestElemTy); 5969 if (CastExprRes.isInvalid()) 5970 return ExprError(); 5971 SplattedExpr = CastExprRes.get(); 5972 } 5973 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 5974 } 5975 5976 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 5977 Expr *CastExpr, CastKind &Kind) { 5978 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 5979 5980 QualType SrcTy = CastExpr->getType(); 5981 5982 // If SrcTy is a VectorType, the total size must match to explicitly cast to 5983 // an ExtVectorType. 5984 // In OpenCL, casts between vectors of different types are not allowed. 5985 // (See OpenCL 6.2). 5986 if (SrcTy->isVectorType()) { 5987 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) 5988 || (getLangOpts().OpenCL && 5989 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 5990 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 5991 << DestTy << SrcTy << R; 5992 return ExprError(); 5993 } 5994 Kind = CK_BitCast; 5995 return CastExpr; 5996 } 5997 5998 // All non-pointer scalars can be cast to ExtVector type. The appropriate 5999 // conversion will take place first from scalar to elt type, and then 6000 // splat from elt type to vector. 6001 if (SrcTy->isPointerType()) 6002 return Diag(R.getBegin(), 6003 diag::err_invalid_conversion_between_vector_and_scalar) 6004 << DestTy << SrcTy << R; 6005 6006 Kind = CK_VectorSplat; 6007 return prepareVectorSplat(DestTy, CastExpr); 6008 } 6009 6010 ExprResult 6011 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 6012 Declarator &D, ParsedType &Ty, 6013 SourceLocation RParenLoc, Expr *CastExpr) { 6014 assert(!D.isInvalidType() && (CastExpr != nullptr) && 6015 "ActOnCastExpr(): missing type or expr"); 6016 6017 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 6018 if (D.isInvalidType()) 6019 return ExprError(); 6020 6021 if (getLangOpts().CPlusPlus) { 6022 // Check that there are no default arguments (C++ only). 6023 CheckExtraCXXDefaultArguments(D); 6024 } else { 6025 // Make sure any TypoExprs have been dealt with. 6026 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 6027 if (!Res.isUsable()) 6028 return ExprError(); 6029 CastExpr = Res.get(); 6030 } 6031 6032 checkUnusedDeclAttributes(D); 6033 6034 QualType castType = castTInfo->getType(); 6035 Ty = CreateParsedType(castType, castTInfo); 6036 6037 bool isVectorLiteral = false; 6038 6039 // Check for an altivec or OpenCL literal, 6040 // i.e. all the elements are integer constants. 6041 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 6042 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 6043 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 6044 && castType->isVectorType() && (PE || PLE)) { 6045 if (PLE && PLE->getNumExprs() == 0) { 6046 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 6047 return ExprError(); 6048 } 6049 if (PE || PLE->getNumExprs() == 1) { 6050 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 6051 if (!E->getType()->isVectorType()) 6052 isVectorLiteral = true; 6053 } 6054 else 6055 isVectorLiteral = true; 6056 } 6057 6058 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 6059 // then handle it as such. 6060 if (isVectorLiteral) 6061 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 6062 6063 // If the Expr being casted is a ParenListExpr, handle it specially. 6064 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 6065 // sequence of BinOp comma operators. 6066 if (isa<ParenListExpr>(CastExpr)) { 6067 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 6068 if (Result.isInvalid()) return ExprError(); 6069 CastExpr = Result.get(); 6070 } 6071 6072 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6073 !getSourceManager().isInSystemMacro(LParenLoc)) 6074 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6075 6076 CheckTollFreeBridgeCast(castType, CastExpr); 6077 6078 CheckObjCBridgeRelatedCast(castType, CastExpr); 6079 6080 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 6081 6082 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6083 } 6084 6085 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6086 SourceLocation RParenLoc, Expr *E, 6087 TypeSourceInfo *TInfo) { 6088 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6089 "Expected paren or paren list expression"); 6090 6091 Expr **exprs; 6092 unsigned numExprs; 6093 Expr *subExpr; 6094 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6095 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6096 LiteralLParenLoc = PE->getLParenLoc(); 6097 LiteralRParenLoc = PE->getRParenLoc(); 6098 exprs = PE->getExprs(); 6099 numExprs = PE->getNumExprs(); 6100 } else { // isa<ParenExpr> by assertion at function entrance 6101 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6102 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6103 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6104 exprs = &subExpr; 6105 numExprs = 1; 6106 } 6107 6108 QualType Ty = TInfo->getType(); 6109 assert(Ty->isVectorType() && "Expected vector type"); 6110 6111 SmallVector<Expr *, 8> initExprs; 6112 const VectorType *VTy = Ty->getAs<VectorType>(); 6113 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 6114 6115 // '(...)' form of vector initialization in AltiVec: the number of 6116 // initializers must be one or must match the size of the vector. 6117 // If a single value is specified in the initializer then it will be 6118 // replicated to all the components of the vector 6119 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6120 // The number of initializers must be one or must match the size of the 6121 // vector. If a single value is specified in the initializer then it will 6122 // be replicated to all the components of the vector 6123 if (numExprs == 1) { 6124 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6125 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6126 if (Literal.isInvalid()) 6127 return ExprError(); 6128 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6129 PrepareScalarCast(Literal, ElemTy)); 6130 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6131 } 6132 else if (numExprs < numElems) { 6133 Diag(E->getExprLoc(), 6134 diag::err_incorrect_number_of_vector_initializers); 6135 return ExprError(); 6136 } 6137 else 6138 initExprs.append(exprs, exprs + numExprs); 6139 } 6140 else { 6141 // For OpenCL, when the number of initializers is a single value, 6142 // it will be replicated to all components of the vector. 6143 if (getLangOpts().OpenCL && 6144 VTy->getVectorKind() == VectorType::GenericVector && 6145 numExprs == 1) { 6146 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6147 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6148 if (Literal.isInvalid()) 6149 return ExprError(); 6150 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6151 PrepareScalarCast(Literal, ElemTy)); 6152 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6153 } 6154 6155 initExprs.append(exprs, exprs + numExprs); 6156 } 6157 // FIXME: This means that pretty-printing the final AST will produce curly 6158 // braces instead of the original commas. 6159 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6160 initExprs, LiteralRParenLoc); 6161 initE->setType(Ty); 6162 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6163 } 6164 6165 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6166 /// the ParenListExpr into a sequence of comma binary operators. 6167 ExprResult 6168 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6169 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6170 if (!E) 6171 return OrigExpr; 6172 6173 ExprResult Result(E->getExpr(0)); 6174 6175 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6176 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6177 E->getExpr(i)); 6178 6179 if (Result.isInvalid()) return ExprError(); 6180 6181 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6182 } 6183 6184 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6185 SourceLocation R, 6186 MultiExprArg Val) { 6187 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 6188 return expr; 6189 } 6190 6191 /// \brief Emit a specialized diagnostic when one expression is a null pointer 6192 /// constant and the other is not a pointer. Returns true if a diagnostic is 6193 /// emitted. 6194 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6195 SourceLocation QuestionLoc) { 6196 Expr *NullExpr = LHSExpr; 6197 Expr *NonPointerExpr = RHSExpr; 6198 Expr::NullPointerConstantKind NullKind = 6199 NullExpr->isNullPointerConstant(Context, 6200 Expr::NPC_ValueDependentIsNotNull); 6201 6202 if (NullKind == Expr::NPCK_NotNull) { 6203 NullExpr = RHSExpr; 6204 NonPointerExpr = LHSExpr; 6205 NullKind = 6206 NullExpr->isNullPointerConstant(Context, 6207 Expr::NPC_ValueDependentIsNotNull); 6208 } 6209 6210 if (NullKind == Expr::NPCK_NotNull) 6211 return false; 6212 6213 if (NullKind == Expr::NPCK_ZeroExpression) 6214 return false; 6215 6216 if (NullKind == Expr::NPCK_ZeroLiteral) { 6217 // In this case, check to make sure that we got here from a "NULL" 6218 // string in the source code. 6219 NullExpr = NullExpr->IgnoreParenImpCasts(); 6220 SourceLocation loc = NullExpr->getExprLoc(); 6221 if (!findMacroSpelling(loc, "NULL")) 6222 return false; 6223 } 6224 6225 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6226 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6227 << NonPointerExpr->getType() << DiagType 6228 << NonPointerExpr->getSourceRange(); 6229 return true; 6230 } 6231 6232 /// \brief Return false if the condition expression is valid, true otherwise. 6233 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6234 QualType CondTy = Cond->getType(); 6235 6236 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6237 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6238 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6239 << CondTy << Cond->getSourceRange(); 6240 return true; 6241 } 6242 6243 // C99 6.5.15p2 6244 if (CondTy->isScalarType()) return false; 6245 6246 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6247 << CondTy << Cond->getSourceRange(); 6248 return true; 6249 } 6250 6251 /// \brief Handle when one or both operands are void type. 6252 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6253 ExprResult &RHS) { 6254 Expr *LHSExpr = LHS.get(); 6255 Expr *RHSExpr = RHS.get(); 6256 6257 if (!LHSExpr->getType()->isVoidType()) 6258 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6259 << RHSExpr->getSourceRange(); 6260 if (!RHSExpr->getType()->isVoidType()) 6261 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6262 << LHSExpr->getSourceRange(); 6263 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6264 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6265 return S.Context.VoidTy; 6266 } 6267 6268 /// \brief Return false if the NullExpr can be promoted to PointerTy, 6269 /// true otherwise. 6270 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6271 QualType PointerTy) { 6272 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6273 !NullExpr.get()->isNullPointerConstant(S.Context, 6274 Expr::NPC_ValueDependentIsNull)) 6275 return true; 6276 6277 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6278 return false; 6279 } 6280 6281 /// \brief Checks compatibility between two pointers and return the resulting 6282 /// type. 6283 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6284 ExprResult &RHS, 6285 SourceLocation Loc) { 6286 QualType LHSTy = LHS.get()->getType(); 6287 QualType RHSTy = RHS.get()->getType(); 6288 6289 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6290 // Two identical pointers types are always compatible. 6291 return LHSTy; 6292 } 6293 6294 QualType lhptee, rhptee; 6295 6296 // Get the pointee types. 6297 bool IsBlockPointer = false; 6298 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6299 lhptee = LHSBTy->getPointeeType(); 6300 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6301 IsBlockPointer = true; 6302 } else { 6303 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6304 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6305 } 6306 6307 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6308 // differently qualified versions of compatible types, the result type is 6309 // a pointer to an appropriately qualified version of the composite 6310 // type. 6311 6312 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6313 // clause doesn't make sense for our extensions. E.g. address space 2 should 6314 // be incompatible with address space 3: they may live on different devices or 6315 // anything. 6316 Qualifiers lhQual = lhptee.getQualifiers(); 6317 Qualifiers rhQual = rhptee.getQualifiers(); 6318 6319 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6320 lhQual.removeCVRQualifiers(); 6321 rhQual.removeCVRQualifiers(); 6322 6323 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 6324 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 6325 6326 // For OpenCL: 6327 // 1. If LHS and RHS types match exactly and: 6328 // (a) AS match => use standard C rules, no bitcast or addrspacecast 6329 // (b) AS overlap => generate addrspacecast 6330 // (c) AS don't overlap => give an error 6331 // 2. if LHS and RHS types don't match: 6332 // (a) AS match => use standard C rules, generate bitcast 6333 // (b) AS overlap => generate addrspacecast instead of bitcast 6334 // (c) AS don't overlap => give an error 6335 6336 // For OpenCL, non-null composite type is returned only for cases 1a and 1b. 6337 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 6338 6339 // OpenCL cases 1c, 2a, 2b, and 2c. 6340 if (CompositeTy.isNull()) { 6341 // In this situation, we assume void* type. No especially good 6342 // reason, but this is what gcc does, and we do have to pick 6343 // to get a consistent AST. 6344 QualType incompatTy; 6345 if (S.getLangOpts().OpenCL) { 6346 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 6347 // spaces is disallowed. 6348 unsigned ResultAddrSpace; 6349 if (lhQual.isAddressSpaceSupersetOf(rhQual)) { 6350 // Cases 2a and 2b. 6351 ResultAddrSpace = lhQual.getAddressSpace(); 6352 } else if (rhQual.isAddressSpaceSupersetOf(lhQual)) { 6353 // Cases 2a and 2b. 6354 ResultAddrSpace = rhQual.getAddressSpace(); 6355 } else { 6356 // Cases 1c and 2c. 6357 S.Diag(Loc, 6358 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 6359 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 6360 << RHS.get()->getSourceRange(); 6361 return QualType(); 6362 } 6363 6364 // Continue handling cases 2a and 2b. 6365 incompatTy = S.Context.getPointerType( 6366 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 6367 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, 6368 (lhQual.getAddressSpace() != ResultAddrSpace) 6369 ? CK_AddressSpaceConversion /* 2b */ 6370 : CK_BitCast /* 2a */); 6371 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, 6372 (rhQual.getAddressSpace() != ResultAddrSpace) 6373 ? CK_AddressSpaceConversion /* 2b */ 6374 : CK_BitCast /* 2a */); 6375 } else { 6376 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 6377 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6378 << RHS.get()->getSourceRange(); 6379 incompatTy = S.Context.getPointerType(S.Context.VoidTy); 6380 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6381 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6382 } 6383 return incompatTy; 6384 } 6385 6386 // The pointer types are compatible. 6387 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual); 6388 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 6389 if (IsBlockPointer) 6390 ResultTy = S.Context.getBlockPointerType(ResultTy); 6391 else { 6392 // Cases 1a and 1b for OpenCL. 6393 auto ResultAddrSpace = ResultTy.getQualifiers().getAddressSpace(); 6394 LHSCastKind = lhQual.getAddressSpace() == ResultAddrSpace 6395 ? CK_BitCast /* 1a */ 6396 : CK_AddressSpaceConversion /* 1b */; 6397 RHSCastKind = rhQual.getAddressSpace() == ResultAddrSpace 6398 ? CK_BitCast /* 1a */ 6399 : CK_AddressSpaceConversion /* 1b */; 6400 ResultTy = S.Context.getPointerType(ResultTy); 6401 } 6402 6403 // For case 1a of OpenCL, S.ImpCastExprToType will not insert bitcast 6404 // if the target type does not change. 6405 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 6406 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 6407 return ResultTy; 6408 } 6409 6410 /// \brief Return the resulting type when the operands are both block pointers. 6411 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 6412 ExprResult &LHS, 6413 ExprResult &RHS, 6414 SourceLocation Loc) { 6415 QualType LHSTy = LHS.get()->getType(); 6416 QualType RHSTy = RHS.get()->getType(); 6417 6418 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 6419 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 6420 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 6421 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6422 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6423 return destType; 6424 } 6425 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 6426 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6427 << RHS.get()->getSourceRange(); 6428 return QualType(); 6429 } 6430 6431 // We have 2 block pointer types. 6432 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6433 } 6434 6435 /// \brief Return the resulting type when the operands are both pointers. 6436 static QualType 6437 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 6438 ExprResult &RHS, 6439 SourceLocation Loc) { 6440 // get the pointer types 6441 QualType LHSTy = LHS.get()->getType(); 6442 QualType RHSTy = RHS.get()->getType(); 6443 6444 // get the "pointed to" types 6445 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6446 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6447 6448 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 6449 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 6450 // Figure out necessary qualifiers (C99 6.5.15p6) 6451 QualType destPointee 6452 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6453 QualType destType = S.Context.getPointerType(destPointee); 6454 // Add qualifiers if necessary. 6455 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6456 // Promote to void*. 6457 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6458 return destType; 6459 } 6460 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 6461 QualType destPointee 6462 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6463 QualType destType = S.Context.getPointerType(destPointee); 6464 // Add qualifiers if necessary. 6465 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6466 // Promote to void*. 6467 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6468 return destType; 6469 } 6470 6471 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6472 } 6473 6474 /// \brief Return false if the first expression is not an integer and the second 6475 /// expression is not a pointer, true otherwise. 6476 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 6477 Expr* PointerExpr, SourceLocation Loc, 6478 bool IsIntFirstExpr) { 6479 if (!PointerExpr->getType()->isPointerType() || 6480 !Int.get()->getType()->isIntegerType()) 6481 return false; 6482 6483 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 6484 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 6485 6486 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 6487 << Expr1->getType() << Expr2->getType() 6488 << Expr1->getSourceRange() << Expr2->getSourceRange(); 6489 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 6490 CK_IntegralToPointer); 6491 return true; 6492 } 6493 6494 /// \brief Simple conversion between integer and floating point types. 6495 /// 6496 /// Used when handling the OpenCL conditional operator where the 6497 /// condition is a vector while the other operands are scalar. 6498 /// 6499 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 6500 /// types are either integer or floating type. Between the two 6501 /// operands, the type with the higher rank is defined as the "result 6502 /// type". The other operand needs to be promoted to the same type. No 6503 /// other type promotion is allowed. We cannot use 6504 /// UsualArithmeticConversions() for this purpose, since it always 6505 /// promotes promotable types. 6506 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 6507 ExprResult &RHS, 6508 SourceLocation QuestionLoc) { 6509 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 6510 if (LHS.isInvalid()) 6511 return QualType(); 6512 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 6513 if (RHS.isInvalid()) 6514 return QualType(); 6515 6516 // For conversion purposes, we ignore any qualifiers. 6517 // For example, "const float" and "float" are equivalent. 6518 QualType LHSType = 6519 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6520 QualType RHSType = 6521 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6522 6523 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 6524 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6525 << LHSType << LHS.get()->getSourceRange(); 6526 return QualType(); 6527 } 6528 6529 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 6530 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6531 << RHSType << RHS.get()->getSourceRange(); 6532 return QualType(); 6533 } 6534 6535 // If both types are identical, no conversion is needed. 6536 if (LHSType == RHSType) 6537 return LHSType; 6538 6539 // Now handle "real" floating types (i.e. float, double, long double). 6540 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 6541 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 6542 /*IsCompAssign = */ false); 6543 6544 // Finally, we have two differing integer types. 6545 return handleIntegerConversion<doIntegralCast, doIntegralCast> 6546 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 6547 } 6548 6549 /// \brief Convert scalar operands to a vector that matches the 6550 /// condition in length. 6551 /// 6552 /// Used when handling the OpenCL conditional operator where the 6553 /// condition is a vector while the other operands are scalar. 6554 /// 6555 /// We first compute the "result type" for the scalar operands 6556 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 6557 /// into a vector of that type where the length matches the condition 6558 /// vector type. s6.11.6 requires that the element types of the result 6559 /// and the condition must have the same number of bits. 6560 static QualType 6561 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 6562 QualType CondTy, SourceLocation QuestionLoc) { 6563 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 6564 if (ResTy.isNull()) return QualType(); 6565 6566 const VectorType *CV = CondTy->getAs<VectorType>(); 6567 assert(CV); 6568 6569 // Determine the vector result type 6570 unsigned NumElements = CV->getNumElements(); 6571 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 6572 6573 // Ensure that all types have the same number of bits 6574 if (S.Context.getTypeSize(CV->getElementType()) 6575 != S.Context.getTypeSize(ResTy)) { 6576 // Since VectorTy is created internally, it does not pretty print 6577 // with an OpenCL name. Instead, we just print a description. 6578 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 6579 SmallString<64> Str; 6580 llvm::raw_svector_ostream OS(Str); 6581 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 6582 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6583 << CondTy << OS.str(); 6584 return QualType(); 6585 } 6586 6587 // Convert operands to the vector result type 6588 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 6589 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 6590 6591 return VectorTy; 6592 } 6593 6594 /// \brief Return false if this is a valid OpenCL condition vector 6595 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 6596 SourceLocation QuestionLoc) { 6597 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 6598 // integral type. 6599 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 6600 assert(CondTy); 6601 QualType EleTy = CondTy->getElementType(); 6602 if (EleTy->isIntegerType()) return false; 6603 6604 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6605 << Cond->getType() << Cond->getSourceRange(); 6606 return true; 6607 } 6608 6609 /// \brief Return false if the vector condition type and the vector 6610 /// result type are compatible. 6611 /// 6612 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 6613 /// number of elements, and their element types have the same number 6614 /// of bits. 6615 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 6616 SourceLocation QuestionLoc) { 6617 const VectorType *CV = CondTy->getAs<VectorType>(); 6618 const VectorType *RV = VecResTy->getAs<VectorType>(); 6619 assert(CV && RV); 6620 6621 if (CV->getNumElements() != RV->getNumElements()) { 6622 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 6623 << CondTy << VecResTy; 6624 return true; 6625 } 6626 6627 QualType CVE = CV->getElementType(); 6628 QualType RVE = RV->getElementType(); 6629 6630 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 6631 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6632 << CondTy << VecResTy; 6633 return true; 6634 } 6635 6636 return false; 6637 } 6638 6639 /// \brief Return the resulting type for the conditional operator in 6640 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 6641 /// s6.3.i) when the condition is a vector type. 6642 static QualType 6643 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 6644 ExprResult &LHS, ExprResult &RHS, 6645 SourceLocation QuestionLoc) { 6646 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 6647 if (Cond.isInvalid()) 6648 return QualType(); 6649 QualType CondTy = Cond.get()->getType(); 6650 6651 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 6652 return QualType(); 6653 6654 // If either operand is a vector then find the vector type of the 6655 // result as specified in OpenCL v1.1 s6.3.i. 6656 if (LHS.get()->getType()->isVectorType() || 6657 RHS.get()->getType()->isVectorType()) { 6658 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 6659 /*isCompAssign*/false, 6660 /*AllowBothBool*/true, 6661 /*AllowBoolConversions*/false); 6662 if (VecResTy.isNull()) return QualType(); 6663 // The result type must match the condition type as specified in 6664 // OpenCL v1.1 s6.11.6. 6665 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 6666 return QualType(); 6667 return VecResTy; 6668 } 6669 6670 // Both operands are scalar. 6671 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 6672 } 6673 6674 /// \brief Return true if the Expr is block type 6675 static bool checkBlockType(Sema &S, const Expr *E) { 6676 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 6677 QualType Ty = CE->getCallee()->getType(); 6678 if (Ty->isBlockPointerType()) { 6679 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 6680 return true; 6681 } 6682 } 6683 return false; 6684 } 6685 6686 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 6687 /// In that case, LHS = cond. 6688 /// C99 6.5.15 6689 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 6690 ExprResult &RHS, ExprValueKind &VK, 6691 ExprObjectKind &OK, 6692 SourceLocation QuestionLoc) { 6693 6694 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 6695 if (!LHSResult.isUsable()) return QualType(); 6696 LHS = LHSResult; 6697 6698 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 6699 if (!RHSResult.isUsable()) return QualType(); 6700 RHS = RHSResult; 6701 6702 // C++ is sufficiently different to merit its own checker. 6703 if (getLangOpts().CPlusPlus) 6704 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 6705 6706 VK = VK_RValue; 6707 OK = OK_Ordinary; 6708 6709 // The OpenCL operator with a vector condition is sufficiently 6710 // different to merit its own checker. 6711 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 6712 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 6713 6714 // First, check the condition. 6715 Cond = UsualUnaryConversions(Cond.get()); 6716 if (Cond.isInvalid()) 6717 return QualType(); 6718 if (checkCondition(*this, Cond.get(), QuestionLoc)) 6719 return QualType(); 6720 6721 // Now check the two expressions. 6722 if (LHS.get()->getType()->isVectorType() || 6723 RHS.get()->getType()->isVectorType()) 6724 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 6725 /*AllowBothBool*/true, 6726 /*AllowBoolConversions*/false); 6727 6728 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 6729 if (LHS.isInvalid() || RHS.isInvalid()) 6730 return QualType(); 6731 6732 QualType LHSTy = LHS.get()->getType(); 6733 QualType RHSTy = RHS.get()->getType(); 6734 6735 // Diagnose attempts to convert between __float128 and long double where 6736 // such conversions currently can't be handled. 6737 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 6738 Diag(QuestionLoc, 6739 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 6740 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6741 return QualType(); 6742 } 6743 6744 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 6745 // selection operator (?:). 6746 if (getLangOpts().OpenCL && 6747 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 6748 return QualType(); 6749 } 6750 6751 // If both operands have arithmetic type, do the usual arithmetic conversions 6752 // to find a common type: C99 6.5.15p3,5. 6753 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 6754 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 6755 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 6756 6757 return ResTy; 6758 } 6759 6760 // If both operands are the same structure or union type, the result is that 6761 // type. 6762 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 6763 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 6764 if (LHSRT->getDecl() == RHSRT->getDecl()) 6765 // "If both the operands have structure or union type, the result has 6766 // that type." This implies that CV qualifiers are dropped. 6767 return LHSTy.getUnqualifiedType(); 6768 // FIXME: Type of conditional expression must be complete in C mode. 6769 } 6770 6771 // C99 6.5.15p5: "If both operands have void type, the result has void type." 6772 // The following || allows only one side to be void (a GCC-ism). 6773 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 6774 return checkConditionalVoidType(*this, LHS, RHS); 6775 } 6776 6777 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 6778 // the type of the other operand." 6779 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 6780 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 6781 6782 // All objective-c pointer type analysis is done here. 6783 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 6784 QuestionLoc); 6785 if (LHS.isInvalid() || RHS.isInvalid()) 6786 return QualType(); 6787 if (!compositeType.isNull()) 6788 return compositeType; 6789 6790 6791 // Handle block pointer types. 6792 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 6793 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 6794 QuestionLoc); 6795 6796 // Check constraints for C object pointers types (C99 6.5.15p3,6). 6797 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 6798 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 6799 QuestionLoc); 6800 6801 // GCC compatibility: soften pointer/integer mismatch. Note that 6802 // null pointers have been filtered out by this point. 6803 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 6804 /*isIntFirstExpr=*/true)) 6805 return RHSTy; 6806 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 6807 /*isIntFirstExpr=*/false)) 6808 return LHSTy; 6809 6810 // Emit a better diagnostic if one of the expressions is a null pointer 6811 // constant and the other is not a pointer type. In this case, the user most 6812 // likely forgot to take the address of the other expression. 6813 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 6814 return QualType(); 6815 6816 // Otherwise, the operands are not compatible. 6817 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 6818 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6819 << RHS.get()->getSourceRange(); 6820 return QualType(); 6821 } 6822 6823 /// FindCompositeObjCPointerType - Helper method to find composite type of 6824 /// two objective-c pointer types of the two input expressions. 6825 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 6826 SourceLocation QuestionLoc) { 6827 QualType LHSTy = LHS.get()->getType(); 6828 QualType RHSTy = RHS.get()->getType(); 6829 6830 // Handle things like Class and struct objc_class*. Here we case the result 6831 // to the pseudo-builtin, because that will be implicitly cast back to the 6832 // redefinition type if an attempt is made to access its fields. 6833 if (LHSTy->isObjCClassType() && 6834 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 6835 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6836 return LHSTy; 6837 } 6838 if (RHSTy->isObjCClassType() && 6839 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 6840 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6841 return RHSTy; 6842 } 6843 // And the same for struct objc_object* / id 6844 if (LHSTy->isObjCIdType() && 6845 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 6846 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6847 return LHSTy; 6848 } 6849 if (RHSTy->isObjCIdType() && 6850 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 6851 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6852 return RHSTy; 6853 } 6854 // And the same for struct objc_selector* / SEL 6855 if (Context.isObjCSelType(LHSTy) && 6856 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 6857 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 6858 return LHSTy; 6859 } 6860 if (Context.isObjCSelType(RHSTy) && 6861 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 6862 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 6863 return RHSTy; 6864 } 6865 // Check constraints for Objective-C object pointers types. 6866 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 6867 6868 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 6869 // Two identical object pointer types are always compatible. 6870 return LHSTy; 6871 } 6872 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 6873 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 6874 QualType compositeType = LHSTy; 6875 6876 // If both operands are interfaces and either operand can be 6877 // assigned to the other, use that type as the composite 6878 // type. This allows 6879 // xxx ? (A*) a : (B*) b 6880 // where B is a subclass of A. 6881 // 6882 // Additionally, as for assignment, if either type is 'id' 6883 // allow silent coercion. Finally, if the types are 6884 // incompatible then make sure to use 'id' as the composite 6885 // type so the result is acceptable for sending messages to. 6886 6887 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 6888 // It could return the composite type. 6889 if (!(compositeType = 6890 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 6891 // Nothing more to do. 6892 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 6893 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 6894 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 6895 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 6896 } else if ((LHSTy->isObjCQualifiedIdType() || 6897 RHSTy->isObjCQualifiedIdType()) && 6898 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 6899 // Need to handle "id<xx>" explicitly. 6900 // GCC allows qualified id and any Objective-C type to devolve to 6901 // id. Currently localizing to here until clear this should be 6902 // part of ObjCQualifiedIdTypesAreCompatible. 6903 compositeType = Context.getObjCIdType(); 6904 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 6905 compositeType = Context.getObjCIdType(); 6906 } else { 6907 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 6908 << LHSTy << RHSTy 6909 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6910 QualType incompatTy = Context.getObjCIdType(); 6911 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6912 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6913 return incompatTy; 6914 } 6915 // The object pointer types are compatible. 6916 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 6917 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 6918 return compositeType; 6919 } 6920 // Check Objective-C object pointer types and 'void *' 6921 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 6922 if (getLangOpts().ObjCAutoRefCount) { 6923 // ARC forbids the implicit conversion of object pointers to 'void *', 6924 // so these types are not compatible. 6925 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6926 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6927 LHS = RHS = true; 6928 return QualType(); 6929 } 6930 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6931 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6932 QualType destPointee 6933 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6934 QualType destType = Context.getPointerType(destPointee); 6935 // Add qualifiers if necessary. 6936 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6937 // Promote to void*. 6938 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6939 return destType; 6940 } 6941 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 6942 if (getLangOpts().ObjCAutoRefCount) { 6943 // ARC forbids the implicit conversion of object pointers to 'void *', 6944 // so these types are not compatible. 6945 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6946 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6947 LHS = RHS = true; 6948 return QualType(); 6949 } 6950 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6951 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6952 QualType destPointee 6953 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6954 QualType destType = Context.getPointerType(destPointee); 6955 // Add qualifiers if necessary. 6956 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6957 // Promote to void*. 6958 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6959 return destType; 6960 } 6961 return QualType(); 6962 } 6963 6964 /// SuggestParentheses - Emit a note with a fixit hint that wraps 6965 /// ParenRange in parentheses. 6966 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 6967 const PartialDiagnostic &Note, 6968 SourceRange ParenRange) { 6969 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 6970 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 6971 EndLoc.isValid()) { 6972 Self.Diag(Loc, Note) 6973 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 6974 << FixItHint::CreateInsertion(EndLoc, ")"); 6975 } else { 6976 // We can't display the parentheses, so just show the bare note. 6977 Self.Diag(Loc, Note) << ParenRange; 6978 } 6979 } 6980 6981 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 6982 return BinaryOperator::isAdditiveOp(Opc) || 6983 BinaryOperator::isMultiplicativeOp(Opc) || 6984 BinaryOperator::isShiftOp(Opc); 6985 } 6986 6987 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 6988 /// expression, either using a built-in or overloaded operator, 6989 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 6990 /// expression. 6991 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 6992 Expr **RHSExprs) { 6993 // Don't strip parenthesis: we should not warn if E is in parenthesis. 6994 E = E->IgnoreImpCasts(); 6995 E = E->IgnoreConversionOperator(); 6996 E = E->IgnoreImpCasts(); 6997 6998 // Built-in binary operator. 6999 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 7000 if (IsArithmeticOp(OP->getOpcode())) { 7001 *Opcode = OP->getOpcode(); 7002 *RHSExprs = OP->getRHS(); 7003 return true; 7004 } 7005 } 7006 7007 // Overloaded operator. 7008 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 7009 if (Call->getNumArgs() != 2) 7010 return false; 7011 7012 // Make sure this is really a binary operator that is safe to pass into 7013 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 7014 OverloadedOperatorKind OO = Call->getOperator(); 7015 if (OO < OO_Plus || OO > OO_Arrow || 7016 OO == OO_PlusPlus || OO == OO_MinusMinus) 7017 return false; 7018 7019 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 7020 if (IsArithmeticOp(OpKind)) { 7021 *Opcode = OpKind; 7022 *RHSExprs = Call->getArg(1); 7023 return true; 7024 } 7025 } 7026 7027 return false; 7028 } 7029 7030 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 7031 /// or is a logical expression such as (x==y) which has int type, but is 7032 /// commonly interpreted as boolean. 7033 static bool ExprLooksBoolean(Expr *E) { 7034 E = E->IgnoreParenImpCasts(); 7035 7036 if (E->getType()->isBooleanType()) 7037 return true; 7038 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 7039 return OP->isComparisonOp() || OP->isLogicalOp(); 7040 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 7041 return OP->getOpcode() == UO_LNot; 7042 if (E->getType()->isPointerType()) 7043 return true; 7044 7045 return false; 7046 } 7047 7048 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 7049 /// and binary operator are mixed in a way that suggests the programmer assumed 7050 /// the conditional operator has higher precedence, for example: 7051 /// "int x = a + someBinaryCondition ? 1 : 2". 7052 static void DiagnoseConditionalPrecedence(Sema &Self, 7053 SourceLocation OpLoc, 7054 Expr *Condition, 7055 Expr *LHSExpr, 7056 Expr *RHSExpr) { 7057 BinaryOperatorKind CondOpcode; 7058 Expr *CondRHS; 7059 7060 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 7061 return; 7062 if (!ExprLooksBoolean(CondRHS)) 7063 return; 7064 7065 // The condition is an arithmetic binary expression, with a right- 7066 // hand side that looks boolean, so warn. 7067 7068 Self.Diag(OpLoc, diag::warn_precedence_conditional) 7069 << Condition->getSourceRange() 7070 << BinaryOperator::getOpcodeStr(CondOpcode); 7071 7072 SuggestParentheses(Self, OpLoc, 7073 Self.PDiag(diag::note_precedence_silence) 7074 << BinaryOperator::getOpcodeStr(CondOpcode), 7075 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 7076 7077 SuggestParentheses(Self, OpLoc, 7078 Self.PDiag(diag::note_precedence_conditional_first), 7079 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 7080 } 7081 7082 /// Compute the nullability of a conditional expression. 7083 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 7084 QualType LHSTy, QualType RHSTy, 7085 ASTContext &Ctx) { 7086 if (!ResTy->isAnyPointerType()) 7087 return ResTy; 7088 7089 auto GetNullability = [&Ctx](QualType Ty) { 7090 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 7091 if (Kind) 7092 return *Kind; 7093 return NullabilityKind::Unspecified; 7094 }; 7095 7096 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 7097 NullabilityKind MergedKind; 7098 7099 // Compute nullability of a binary conditional expression. 7100 if (IsBin) { 7101 if (LHSKind == NullabilityKind::NonNull) 7102 MergedKind = NullabilityKind::NonNull; 7103 else 7104 MergedKind = RHSKind; 7105 // Compute nullability of a normal conditional expression. 7106 } else { 7107 if (LHSKind == NullabilityKind::Nullable || 7108 RHSKind == NullabilityKind::Nullable) 7109 MergedKind = NullabilityKind::Nullable; 7110 else if (LHSKind == NullabilityKind::NonNull) 7111 MergedKind = RHSKind; 7112 else if (RHSKind == NullabilityKind::NonNull) 7113 MergedKind = LHSKind; 7114 else 7115 MergedKind = NullabilityKind::Unspecified; 7116 } 7117 7118 // Return if ResTy already has the correct nullability. 7119 if (GetNullability(ResTy) == MergedKind) 7120 return ResTy; 7121 7122 // Strip all nullability from ResTy. 7123 while (ResTy->getNullability(Ctx)) 7124 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 7125 7126 // Create a new AttributedType with the new nullability kind. 7127 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 7128 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 7129 } 7130 7131 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7132 /// in the case of a the GNU conditional expr extension. 7133 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7134 SourceLocation ColonLoc, 7135 Expr *CondExpr, Expr *LHSExpr, 7136 Expr *RHSExpr) { 7137 if (!getLangOpts().CPlusPlus) { 7138 // C cannot handle TypoExpr nodes in the condition because it 7139 // doesn't handle dependent types properly, so make sure any TypoExprs have 7140 // been dealt with before checking the operands. 7141 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7142 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7143 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7144 7145 if (!CondResult.isUsable()) 7146 return ExprError(); 7147 7148 if (LHSExpr) { 7149 if (!LHSResult.isUsable()) 7150 return ExprError(); 7151 } 7152 7153 if (!RHSResult.isUsable()) 7154 return ExprError(); 7155 7156 CondExpr = CondResult.get(); 7157 LHSExpr = LHSResult.get(); 7158 RHSExpr = RHSResult.get(); 7159 } 7160 7161 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7162 // was the condition. 7163 OpaqueValueExpr *opaqueValue = nullptr; 7164 Expr *commonExpr = nullptr; 7165 if (!LHSExpr) { 7166 commonExpr = CondExpr; 7167 // Lower out placeholder types first. This is important so that we don't 7168 // try to capture a placeholder. This happens in few cases in C++; such 7169 // as Objective-C++'s dictionary subscripting syntax. 7170 if (commonExpr->hasPlaceholderType()) { 7171 ExprResult result = CheckPlaceholderExpr(commonExpr); 7172 if (!result.isUsable()) return ExprError(); 7173 commonExpr = result.get(); 7174 } 7175 // We usually want to apply unary conversions *before* saving, except 7176 // in the special case of a C++ l-value conditional. 7177 if (!(getLangOpts().CPlusPlus 7178 && !commonExpr->isTypeDependent() 7179 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7180 && commonExpr->isGLValue() 7181 && commonExpr->isOrdinaryOrBitFieldObject() 7182 && RHSExpr->isOrdinaryOrBitFieldObject() 7183 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7184 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7185 if (commonRes.isInvalid()) 7186 return ExprError(); 7187 commonExpr = commonRes.get(); 7188 } 7189 7190 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7191 commonExpr->getType(), 7192 commonExpr->getValueKind(), 7193 commonExpr->getObjectKind(), 7194 commonExpr); 7195 LHSExpr = CondExpr = opaqueValue; 7196 } 7197 7198 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 7199 ExprValueKind VK = VK_RValue; 7200 ExprObjectKind OK = OK_Ordinary; 7201 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7202 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7203 VK, OK, QuestionLoc); 7204 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7205 RHS.isInvalid()) 7206 return ExprError(); 7207 7208 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7209 RHS.get()); 7210 7211 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 7212 7213 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 7214 Context); 7215 7216 if (!commonExpr) 7217 return new (Context) 7218 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 7219 RHS.get(), result, VK, OK); 7220 7221 return new (Context) BinaryConditionalOperator( 7222 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 7223 ColonLoc, result, VK, OK); 7224 } 7225 7226 // checkPointerTypesForAssignment - This is a very tricky routine (despite 7227 // being closely modeled after the C99 spec:-). The odd characteristic of this 7228 // routine is it effectively iqnores the qualifiers on the top level pointee. 7229 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 7230 // FIXME: add a couple examples in this comment. 7231 static Sema::AssignConvertType 7232 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 7233 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7234 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7235 7236 // get the "pointed to" type (ignoring qualifiers at the top level) 7237 const Type *lhptee, *rhptee; 7238 Qualifiers lhq, rhq; 7239 std::tie(lhptee, lhq) = 7240 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 7241 std::tie(rhptee, rhq) = 7242 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 7243 7244 Sema::AssignConvertType ConvTy = Sema::Compatible; 7245 7246 // C99 6.5.16.1p1: This following citation is common to constraints 7247 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 7248 // qualifiers of the type *pointed to* by the right; 7249 7250 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 7251 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 7252 lhq.compatiblyIncludesObjCLifetime(rhq)) { 7253 // Ignore lifetime for further calculation. 7254 lhq.removeObjCLifetime(); 7255 rhq.removeObjCLifetime(); 7256 } 7257 7258 if (!lhq.compatiblyIncludes(rhq)) { 7259 // Treat address-space mismatches as fatal. TODO: address subspaces 7260 if (!lhq.isAddressSpaceSupersetOf(rhq)) 7261 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7262 7263 // It's okay to add or remove GC or lifetime qualifiers when converting to 7264 // and from void*. 7265 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 7266 .compatiblyIncludes( 7267 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 7268 && (lhptee->isVoidType() || rhptee->isVoidType())) 7269 ; // keep old 7270 7271 // Treat lifetime mismatches as fatal. 7272 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 7273 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7274 7275 // For GCC/MS compatibility, other qualifier mismatches are treated 7276 // as still compatible in C. 7277 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7278 } 7279 7280 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 7281 // incomplete type and the other is a pointer to a qualified or unqualified 7282 // version of void... 7283 if (lhptee->isVoidType()) { 7284 if (rhptee->isIncompleteOrObjectType()) 7285 return ConvTy; 7286 7287 // As an extension, we allow cast to/from void* to function pointer. 7288 assert(rhptee->isFunctionType()); 7289 return Sema::FunctionVoidPointer; 7290 } 7291 7292 if (rhptee->isVoidType()) { 7293 if (lhptee->isIncompleteOrObjectType()) 7294 return ConvTy; 7295 7296 // As an extension, we allow cast to/from void* to function pointer. 7297 assert(lhptee->isFunctionType()); 7298 return Sema::FunctionVoidPointer; 7299 } 7300 7301 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7302 // unqualified versions of compatible types, ... 7303 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7304 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7305 // Check if the pointee types are compatible ignoring the sign. 7306 // We explicitly check for char so that we catch "char" vs 7307 // "unsigned char" on systems where "char" is unsigned. 7308 if (lhptee->isCharType()) 7309 ltrans = S.Context.UnsignedCharTy; 7310 else if (lhptee->hasSignedIntegerRepresentation()) 7311 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7312 7313 if (rhptee->isCharType()) 7314 rtrans = S.Context.UnsignedCharTy; 7315 else if (rhptee->hasSignedIntegerRepresentation()) 7316 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 7317 7318 if (ltrans == rtrans) { 7319 // Types are compatible ignoring the sign. Qualifier incompatibility 7320 // takes priority over sign incompatibility because the sign 7321 // warning can be disabled. 7322 if (ConvTy != Sema::Compatible) 7323 return ConvTy; 7324 7325 return Sema::IncompatiblePointerSign; 7326 } 7327 7328 // If we are a multi-level pointer, it's possible that our issue is simply 7329 // one of qualification - e.g. char ** -> const char ** is not allowed. If 7330 // the eventual target type is the same and the pointers have the same 7331 // level of indirection, this must be the issue. 7332 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 7333 do { 7334 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 7335 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 7336 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 7337 7338 if (lhptee == rhptee) 7339 return Sema::IncompatibleNestedPointerQualifiers; 7340 } 7341 7342 // General pointer incompatibility takes priority over qualifiers. 7343 return Sema::IncompatiblePointer; 7344 } 7345 if (!S.getLangOpts().CPlusPlus && 7346 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 7347 return Sema::IncompatiblePointer; 7348 return ConvTy; 7349 } 7350 7351 /// checkBlockPointerTypesForAssignment - This routine determines whether two 7352 /// block pointer types are compatible or whether a block and normal pointer 7353 /// are compatible. It is more restrict than comparing two function pointer 7354 // types. 7355 static Sema::AssignConvertType 7356 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 7357 QualType RHSType) { 7358 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7359 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7360 7361 QualType lhptee, rhptee; 7362 7363 // get the "pointed to" type (ignoring qualifiers at the top level) 7364 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 7365 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 7366 7367 // In C++, the types have to match exactly. 7368 if (S.getLangOpts().CPlusPlus) 7369 return Sema::IncompatibleBlockPointer; 7370 7371 Sema::AssignConvertType ConvTy = Sema::Compatible; 7372 7373 // For blocks we enforce that qualifiers are identical. 7374 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers()) 7375 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7376 7377 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 7378 return Sema::IncompatibleBlockPointer; 7379 7380 return ConvTy; 7381 } 7382 7383 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 7384 /// for assignment compatibility. 7385 static Sema::AssignConvertType 7386 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 7387 QualType RHSType) { 7388 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 7389 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 7390 7391 if (LHSType->isObjCBuiltinType()) { 7392 // Class is not compatible with ObjC object pointers. 7393 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 7394 !RHSType->isObjCQualifiedClassType()) 7395 return Sema::IncompatiblePointer; 7396 return Sema::Compatible; 7397 } 7398 if (RHSType->isObjCBuiltinType()) { 7399 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 7400 !LHSType->isObjCQualifiedClassType()) 7401 return Sema::IncompatiblePointer; 7402 return Sema::Compatible; 7403 } 7404 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7405 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7406 7407 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 7408 // make an exception for id<P> 7409 !LHSType->isObjCQualifiedIdType()) 7410 return Sema::CompatiblePointerDiscardsQualifiers; 7411 7412 if (S.Context.typesAreCompatible(LHSType, RHSType)) 7413 return Sema::Compatible; 7414 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 7415 return Sema::IncompatibleObjCQualifiedId; 7416 return Sema::IncompatiblePointer; 7417 } 7418 7419 Sema::AssignConvertType 7420 Sema::CheckAssignmentConstraints(SourceLocation Loc, 7421 QualType LHSType, QualType RHSType) { 7422 // Fake up an opaque expression. We don't actually care about what 7423 // cast operations are required, so if CheckAssignmentConstraints 7424 // adds casts to this they'll be wasted, but fortunately that doesn't 7425 // usually happen on valid code. 7426 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 7427 ExprResult RHSPtr = &RHSExpr; 7428 CastKind K = CK_Invalid; 7429 7430 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 7431 } 7432 7433 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 7434 /// has code to accommodate several GCC extensions when type checking 7435 /// pointers. Here are some objectionable examples that GCC considers warnings: 7436 /// 7437 /// int a, *pint; 7438 /// short *pshort; 7439 /// struct foo *pfoo; 7440 /// 7441 /// pint = pshort; // warning: assignment from incompatible pointer type 7442 /// a = pint; // warning: assignment makes integer from pointer without a cast 7443 /// pint = a; // warning: assignment makes pointer from integer without a cast 7444 /// pint = pfoo; // warning: assignment from incompatible pointer type 7445 /// 7446 /// As a result, the code for dealing with pointers is more complex than the 7447 /// C99 spec dictates. 7448 /// 7449 /// Sets 'Kind' for any result kind except Incompatible. 7450 Sema::AssignConvertType 7451 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 7452 CastKind &Kind, bool ConvertRHS) { 7453 QualType RHSType = RHS.get()->getType(); 7454 QualType OrigLHSType = LHSType; 7455 7456 // Get canonical types. We're not formatting these types, just comparing 7457 // them. 7458 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 7459 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 7460 7461 // Common case: no conversion required. 7462 if (LHSType == RHSType) { 7463 Kind = CK_NoOp; 7464 return Compatible; 7465 } 7466 7467 // If we have an atomic type, try a non-atomic assignment, then just add an 7468 // atomic qualification step. 7469 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 7470 Sema::AssignConvertType result = 7471 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 7472 if (result != Compatible) 7473 return result; 7474 if (Kind != CK_NoOp && ConvertRHS) 7475 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 7476 Kind = CK_NonAtomicToAtomic; 7477 return Compatible; 7478 } 7479 7480 // If the left-hand side is a reference type, then we are in a 7481 // (rare!) case where we've allowed the use of references in C, 7482 // e.g., as a parameter type in a built-in function. In this case, 7483 // just make sure that the type referenced is compatible with the 7484 // right-hand side type. The caller is responsible for adjusting 7485 // LHSType so that the resulting expression does not have reference 7486 // type. 7487 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 7488 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 7489 Kind = CK_LValueBitCast; 7490 return Compatible; 7491 } 7492 return Incompatible; 7493 } 7494 7495 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 7496 // to the same ExtVector type. 7497 if (LHSType->isExtVectorType()) { 7498 if (RHSType->isExtVectorType()) 7499 return Incompatible; 7500 if (RHSType->isArithmeticType()) { 7501 // CK_VectorSplat does T -> vector T, so first cast to the element type. 7502 if (ConvertRHS) 7503 RHS = prepareVectorSplat(LHSType, RHS.get()); 7504 Kind = CK_VectorSplat; 7505 return Compatible; 7506 } 7507 } 7508 7509 // Conversions to or from vector type. 7510 if (LHSType->isVectorType() || RHSType->isVectorType()) { 7511 if (LHSType->isVectorType() && RHSType->isVectorType()) { 7512 // Allow assignments of an AltiVec vector type to an equivalent GCC 7513 // vector type and vice versa 7514 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7515 Kind = CK_BitCast; 7516 return Compatible; 7517 } 7518 7519 // If we are allowing lax vector conversions, and LHS and RHS are both 7520 // vectors, the total size only needs to be the same. This is a bitcast; 7521 // no bits are changed but the result type is different. 7522 if (isLaxVectorConversion(RHSType, LHSType)) { 7523 Kind = CK_BitCast; 7524 return IncompatibleVectors; 7525 } 7526 } 7527 7528 // When the RHS comes from another lax conversion (e.g. binops between 7529 // scalars and vectors) the result is canonicalized as a vector. When the 7530 // LHS is also a vector, the lax is allowed by the condition above. Handle 7531 // the case where LHS is a scalar. 7532 if (LHSType->isScalarType()) { 7533 const VectorType *VecType = RHSType->getAs<VectorType>(); 7534 if (VecType && VecType->getNumElements() == 1 && 7535 isLaxVectorConversion(RHSType, LHSType)) { 7536 ExprResult *VecExpr = &RHS; 7537 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 7538 Kind = CK_BitCast; 7539 return Compatible; 7540 } 7541 } 7542 7543 return Incompatible; 7544 } 7545 7546 // Diagnose attempts to convert between __float128 and long double where 7547 // such conversions currently can't be handled. 7548 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 7549 return Incompatible; 7550 7551 // Arithmetic conversions. 7552 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 7553 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 7554 if (ConvertRHS) 7555 Kind = PrepareScalarCast(RHS, LHSType); 7556 return Compatible; 7557 } 7558 7559 // Conversions to normal pointers. 7560 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 7561 // U* -> T* 7562 if (isa<PointerType>(RHSType)) { 7563 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7564 unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 7565 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7566 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 7567 } 7568 7569 // int -> T* 7570 if (RHSType->isIntegerType()) { 7571 Kind = CK_IntegralToPointer; // FIXME: null? 7572 return IntToPointer; 7573 } 7574 7575 // C pointers are not compatible with ObjC object pointers, 7576 // with two exceptions: 7577 if (isa<ObjCObjectPointerType>(RHSType)) { 7578 // - conversions to void* 7579 if (LHSPointer->getPointeeType()->isVoidType()) { 7580 Kind = CK_BitCast; 7581 return Compatible; 7582 } 7583 7584 // - conversions from 'Class' to the redefinition type 7585 if (RHSType->isObjCClassType() && 7586 Context.hasSameType(LHSType, 7587 Context.getObjCClassRedefinitionType())) { 7588 Kind = CK_BitCast; 7589 return Compatible; 7590 } 7591 7592 Kind = CK_BitCast; 7593 return IncompatiblePointer; 7594 } 7595 7596 // U^ -> void* 7597 if (RHSType->getAs<BlockPointerType>()) { 7598 if (LHSPointer->getPointeeType()->isVoidType()) { 7599 Kind = CK_BitCast; 7600 return Compatible; 7601 } 7602 } 7603 7604 return Incompatible; 7605 } 7606 7607 // Conversions to block pointers. 7608 if (isa<BlockPointerType>(LHSType)) { 7609 // U^ -> T^ 7610 if (RHSType->isBlockPointerType()) { 7611 Kind = CK_BitCast; 7612 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 7613 } 7614 7615 // int or null -> T^ 7616 if (RHSType->isIntegerType()) { 7617 Kind = CK_IntegralToPointer; // FIXME: null 7618 return IntToBlockPointer; 7619 } 7620 7621 // id -> T^ 7622 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 7623 Kind = CK_AnyPointerToBlockPointerCast; 7624 return Compatible; 7625 } 7626 7627 // void* -> T^ 7628 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 7629 if (RHSPT->getPointeeType()->isVoidType()) { 7630 Kind = CK_AnyPointerToBlockPointerCast; 7631 return Compatible; 7632 } 7633 7634 return Incompatible; 7635 } 7636 7637 // Conversions to Objective-C pointers. 7638 if (isa<ObjCObjectPointerType>(LHSType)) { 7639 // A* -> B* 7640 if (RHSType->isObjCObjectPointerType()) { 7641 Kind = CK_BitCast; 7642 Sema::AssignConvertType result = 7643 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 7644 if (getLangOpts().ObjCAutoRefCount && 7645 result == Compatible && 7646 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 7647 result = IncompatibleObjCWeakRef; 7648 return result; 7649 } 7650 7651 // int or null -> A* 7652 if (RHSType->isIntegerType()) { 7653 Kind = CK_IntegralToPointer; // FIXME: null 7654 return IntToPointer; 7655 } 7656 7657 // In general, C pointers are not compatible with ObjC object pointers, 7658 // with two exceptions: 7659 if (isa<PointerType>(RHSType)) { 7660 Kind = CK_CPointerToObjCPointerCast; 7661 7662 // - conversions from 'void*' 7663 if (RHSType->isVoidPointerType()) { 7664 return Compatible; 7665 } 7666 7667 // - conversions to 'Class' from its redefinition type 7668 if (LHSType->isObjCClassType() && 7669 Context.hasSameType(RHSType, 7670 Context.getObjCClassRedefinitionType())) { 7671 return Compatible; 7672 } 7673 7674 return IncompatiblePointer; 7675 } 7676 7677 // Only under strict condition T^ is compatible with an Objective-C pointer. 7678 if (RHSType->isBlockPointerType() && 7679 LHSType->isBlockCompatibleObjCPointerType(Context)) { 7680 if (ConvertRHS) 7681 maybeExtendBlockObject(RHS); 7682 Kind = CK_BlockPointerToObjCPointerCast; 7683 return Compatible; 7684 } 7685 7686 return Incompatible; 7687 } 7688 7689 // Conversions from pointers that are not covered by the above. 7690 if (isa<PointerType>(RHSType)) { 7691 // T* -> _Bool 7692 if (LHSType == Context.BoolTy) { 7693 Kind = CK_PointerToBoolean; 7694 return Compatible; 7695 } 7696 7697 // T* -> int 7698 if (LHSType->isIntegerType()) { 7699 Kind = CK_PointerToIntegral; 7700 return PointerToInt; 7701 } 7702 7703 return Incompatible; 7704 } 7705 7706 // Conversions from Objective-C pointers that are not covered by the above. 7707 if (isa<ObjCObjectPointerType>(RHSType)) { 7708 // T* -> _Bool 7709 if (LHSType == Context.BoolTy) { 7710 Kind = CK_PointerToBoolean; 7711 return Compatible; 7712 } 7713 7714 // T* -> int 7715 if (LHSType->isIntegerType()) { 7716 Kind = CK_PointerToIntegral; 7717 return PointerToInt; 7718 } 7719 7720 return Incompatible; 7721 } 7722 7723 // struct A -> struct B 7724 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 7725 if (Context.typesAreCompatible(LHSType, RHSType)) { 7726 Kind = CK_NoOp; 7727 return Compatible; 7728 } 7729 } 7730 7731 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 7732 Kind = CK_IntToOCLSampler; 7733 return Compatible; 7734 } 7735 7736 return Incompatible; 7737 } 7738 7739 /// \brief Constructs a transparent union from an expression that is 7740 /// used to initialize the transparent union. 7741 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 7742 ExprResult &EResult, QualType UnionType, 7743 FieldDecl *Field) { 7744 // Build an initializer list that designates the appropriate member 7745 // of the transparent union. 7746 Expr *E = EResult.get(); 7747 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 7748 E, SourceLocation()); 7749 Initializer->setType(UnionType); 7750 Initializer->setInitializedFieldInUnion(Field); 7751 7752 // Build a compound literal constructing a value of the transparent 7753 // union type from this initializer list. 7754 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 7755 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 7756 VK_RValue, Initializer, false); 7757 } 7758 7759 Sema::AssignConvertType 7760 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 7761 ExprResult &RHS) { 7762 QualType RHSType = RHS.get()->getType(); 7763 7764 // If the ArgType is a Union type, we want to handle a potential 7765 // transparent_union GCC extension. 7766 const RecordType *UT = ArgType->getAsUnionType(); 7767 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 7768 return Incompatible; 7769 7770 // The field to initialize within the transparent union. 7771 RecordDecl *UD = UT->getDecl(); 7772 FieldDecl *InitField = nullptr; 7773 // It's compatible if the expression matches any of the fields. 7774 for (auto *it : UD->fields()) { 7775 if (it->getType()->isPointerType()) { 7776 // If the transparent union contains a pointer type, we allow: 7777 // 1) void pointer 7778 // 2) null pointer constant 7779 if (RHSType->isPointerType()) 7780 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 7781 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 7782 InitField = it; 7783 break; 7784 } 7785 7786 if (RHS.get()->isNullPointerConstant(Context, 7787 Expr::NPC_ValueDependentIsNull)) { 7788 RHS = ImpCastExprToType(RHS.get(), it->getType(), 7789 CK_NullToPointer); 7790 InitField = it; 7791 break; 7792 } 7793 } 7794 7795 CastKind Kind = CK_Invalid; 7796 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 7797 == Compatible) { 7798 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 7799 InitField = it; 7800 break; 7801 } 7802 } 7803 7804 if (!InitField) 7805 return Incompatible; 7806 7807 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 7808 return Compatible; 7809 } 7810 7811 Sema::AssignConvertType 7812 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 7813 bool Diagnose, 7814 bool DiagnoseCFAudited, 7815 bool ConvertRHS) { 7816 // We need to be able to tell the caller whether we diagnosed a problem, if 7817 // they ask us to issue diagnostics. 7818 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 7819 7820 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 7821 // we can't avoid *all* modifications at the moment, so we need some somewhere 7822 // to put the updated value. 7823 ExprResult LocalRHS = CallerRHS; 7824 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 7825 7826 if (getLangOpts().CPlusPlus) { 7827 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 7828 // C++ 5.17p3: If the left operand is not of class type, the 7829 // expression is implicitly converted (C++ 4) to the 7830 // cv-unqualified type of the left operand. 7831 QualType RHSType = RHS.get()->getType(); 7832 if (Diagnose) { 7833 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7834 AA_Assigning); 7835 } else { 7836 ImplicitConversionSequence ICS = 7837 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7838 /*SuppressUserConversions=*/false, 7839 /*AllowExplicit=*/false, 7840 /*InOverloadResolution=*/false, 7841 /*CStyle=*/false, 7842 /*AllowObjCWritebackConversion=*/false); 7843 if (ICS.isFailure()) 7844 return Incompatible; 7845 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7846 ICS, AA_Assigning); 7847 } 7848 if (RHS.isInvalid()) 7849 return Incompatible; 7850 Sema::AssignConvertType result = Compatible; 7851 if (getLangOpts().ObjCAutoRefCount && 7852 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 7853 result = IncompatibleObjCWeakRef; 7854 return result; 7855 } 7856 7857 // FIXME: Currently, we fall through and treat C++ classes like C 7858 // structures. 7859 // FIXME: We also fall through for atomics; not sure what should 7860 // happen there, though. 7861 } else if (RHS.get()->getType() == Context.OverloadTy) { 7862 // As a set of extensions to C, we support overloading on functions. These 7863 // functions need to be resolved here. 7864 DeclAccessPair DAP; 7865 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 7866 RHS.get(), LHSType, /*Complain=*/false, DAP)) 7867 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 7868 else 7869 return Incompatible; 7870 } 7871 7872 // C99 6.5.16.1p1: the left operand is a pointer and the right is 7873 // a null pointer constant. 7874 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 7875 LHSType->isBlockPointerType()) && 7876 RHS.get()->isNullPointerConstant(Context, 7877 Expr::NPC_ValueDependentIsNull)) { 7878 if (Diagnose || ConvertRHS) { 7879 CastKind Kind; 7880 CXXCastPath Path; 7881 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 7882 /*IgnoreBaseAccess=*/false, Diagnose); 7883 if (ConvertRHS) 7884 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 7885 } 7886 return Compatible; 7887 } 7888 7889 // This check seems unnatural, however it is necessary to ensure the proper 7890 // conversion of functions/arrays. If the conversion were done for all 7891 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 7892 // expressions that suppress this implicit conversion (&, sizeof). 7893 // 7894 // Suppress this for references: C++ 8.5.3p5. 7895 if (!LHSType->isReferenceType()) { 7896 // FIXME: We potentially allocate here even if ConvertRHS is false. 7897 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 7898 if (RHS.isInvalid()) 7899 return Incompatible; 7900 } 7901 7902 Expr *PRE = RHS.get()->IgnoreParenCasts(); 7903 if (Diagnose && isa<ObjCProtocolExpr>(PRE)) { 7904 ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol(); 7905 if (PDecl && !PDecl->hasDefinition()) { 7906 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName(); 7907 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl; 7908 } 7909 } 7910 7911 CastKind Kind = CK_Invalid; 7912 Sema::AssignConvertType result = 7913 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 7914 7915 // C99 6.5.16.1p2: The value of the right operand is converted to the 7916 // type of the assignment expression. 7917 // CheckAssignmentConstraints allows the left-hand side to be a reference, 7918 // so that we can use references in built-in functions even in C. 7919 // The getNonReferenceType() call makes sure that the resulting expression 7920 // does not have reference type. 7921 if (result != Incompatible && RHS.get()->getType() != LHSType) { 7922 QualType Ty = LHSType.getNonLValueExprType(Context); 7923 Expr *E = RHS.get(); 7924 7925 // Check for various Objective-C errors. If we are not reporting 7926 // diagnostics and just checking for errors, e.g., during overload 7927 // resolution, return Incompatible to indicate the failure. 7928 if (getLangOpts().ObjCAutoRefCount && 7929 CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 7930 Diagnose, DiagnoseCFAudited) != ACR_okay) { 7931 if (!Diagnose) 7932 return Incompatible; 7933 } 7934 if (getLangOpts().ObjC1 && 7935 (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType, 7936 E->getType(), E, Diagnose) || 7937 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 7938 if (!Diagnose) 7939 return Incompatible; 7940 // Replace the expression with a corrected version and continue so we 7941 // can find further errors. 7942 RHS = E; 7943 return Compatible; 7944 } 7945 7946 if (ConvertRHS) 7947 RHS = ImpCastExprToType(E, Ty, Kind); 7948 } 7949 return result; 7950 } 7951 7952 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 7953 ExprResult &RHS) { 7954 Diag(Loc, diag::err_typecheck_invalid_operands) 7955 << LHS.get()->getType() << RHS.get()->getType() 7956 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7957 return QualType(); 7958 } 7959 7960 /// Try to convert a value of non-vector type to a vector type by converting 7961 /// the type to the element type of the vector and then performing a splat. 7962 /// If the language is OpenCL, we only use conversions that promote scalar 7963 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 7964 /// for float->int. 7965 /// 7966 /// \param scalar - if non-null, actually perform the conversions 7967 /// \return true if the operation fails (but without diagnosing the failure) 7968 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 7969 QualType scalarTy, 7970 QualType vectorEltTy, 7971 QualType vectorTy) { 7972 // The conversion to apply to the scalar before splatting it, 7973 // if necessary. 7974 CastKind scalarCast = CK_Invalid; 7975 7976 if (vectorEltTy->isIntegralType(S.Context)) { 7977 if (!scalarTy->isIntegralType(S.Context)) 7978 return true; 7979 if (S.getLangOpts().OpenCL && 7980 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0) 7981 return true; 7982 scalarCast = CK_IntegralCast; 7983 } else if (vectorEltTy->isRealFloatingType()) { 7984 if (scalarTy->isRealFloatingType()) { 7985 if (S.getLangOpts().OpenCL && 7986 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) 7987 return true; 7988 scalarCast = CK_FloatingCast; 7989 } 7990 else if (scalarTy->isIntegralType(S.Context)) 7991 scalarCast = CK_IntegralToFloating; 7992 else 7993 return true; 7994 } else { 7995 return true; 7996 } 7997 7998 // Adjust scalar if desired. 7999 if (scalar) { 8000 if (scalarCast != CK_Invalid) 8001 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 8002 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 8003 } 8004 return false; 8005 } 8006 8007 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 8008 SourceLocation Loc, bool IsCompAssign, 8009 bool AllowBothBool, 8010 bool AllowBoolConversions) { 8011 if (!IsCompAssign) { 8012 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 8013 if (LHS.isInvalid()) 8014 return QualType(); 8015 } 8016 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 8017 if (RHS.isInvalid()) 8018 return QualType(); 8019 8020 // For conversion purposes, we ignore any qualifiers. 8021 // For example, "const float" and "float" are equivalent. 8022 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 8023 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 8024 8025 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 8026 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 8027 assert(LHSVecType || RHSVecType); 8028 8029 // AltiVec-style "vector bool op vector bool" combinations are allowed 8030 // for some operators but not others. 8031 if (!AllowBothBool && 8032 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8033 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8034 return InvalidOperands(Loc, LHS, RHS); 8035 8036 // If the vector types are identical, return. 8037 if (Context.hasSameType(LHSType, RHSType)) 8038 return LHSType; 8039 8040 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 8041 if (LHSVecType && RHSVecType && 8042 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8043 if (isa<ExtVectorType>(LHSVecType)) { 8044 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8045 return LHSType; 8046 } 8047 8048 if (!IsCompAssign) 8049 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8050 return RHSType; 8051 } 8052 8053 // AllowBoolConversions says that bool and non-bool AltiVec vectors 8054 // can be mixed, with the result being the non-bool type. The non-bool 8055 // operand must have integer element type. 8056 if (AllowBoolConversions && LHSVecType && RHSVecType && 8057 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 8058 (Context.getTypeSize(LHSVecType->getElementType()) == 8059 Context.getTypeSize(RHSVecType->getElementType()))) { 8060 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 8061 LHSVecType->getElementType()->isIntegerType() && 8062 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 8063 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8064 return LHSType; 8065 } 8066 if (!IsCompAssign && 8067 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8068 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 8069 RHSVecType->getElementType()->isIntegerType()) { 8070 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8071 return RHSType; 8072 } 8073 } 8074 8075 // If there's an ext-vector type and a scalar, try to convert the scalar to 8076 // the vector element type and splat. 8077 // FIXME: this should also work for regular vector types as supported in GCC. 8078 if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) { 8079 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 8080 LHSVecType->getElementType(), LHSType)) 8081 return LHSType; 8082 } 8083 if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) { 8084 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 8085 LHSType, RHSVecType->getElementType(), 8086 RHSType)) 8087 return RHSType; 8088 } 8089 8090 // FIXME: The code below also handles convertion between vectors and 8091 // non-scalars, we should break this down into fine grained specific checks 8092 // and emit proper diagnostics. 8093 QualType VecType = LHSVecType ? LHSType : RHSType; 8094 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 8095 QualType OtherType = LHSVecType ? RHSType : LHSType; 8096 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 8097 if (isLaxVectorConversion(OtherType, VecType)) { 8098 // If we're allowing lax vector conversions, only the total (data) size 8099 // needs to be the same. For non compound assignment, if one of the types is 8100 // scalar, the result is always the vector type. 8101 if (!IsCompAssign) { 8102 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 8103 return VecType; 8104 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 8105 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 8106 // type. Note that this is already done by non-compound assignments in 8107 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 8108 // <1 x T> -> T. The result is also a vector type. 8109 } else if (OtherType->isExtVectorType() || 8110 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 8111 ExprResult *RHSExpr = &RHS; 8112 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 8113 return VecType; 8114 } 8115 } 8116 8117 // Okay, the expression is invalid. 8118 8119 // If there's a non-vector, non-real operand, diagnose that. 8120 if ((!RHSVecType && !RHSType->isRealType()) || 8121 (!LHSVecType && !LHSType->isRealType())) { 8122 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 8123 << LHSType << RHSType 8124 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8125 return QualType(); 8126 } 8127 8128 // OpenCL V1.1 6.2.6.p1: 8129 // If the operands are of more than one vector type, then an error shall 8130 // occur. Implicit conversions between vector types are not permitted, per 8131 // section 6.2.1. 8132 if (getLangOpts().OpenCL && 8133 RHSVecType && isa<ExtVectorType>(RHSVecType) && 8134 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 8135 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 8136 << RHSType; 8137 return QualType(); 8138 } 8139 8140 // Otherwise, use the generic diagnostic. 8141 Diag(Loc, diag::err_typecheck_vector_not_convertable) 8142 << LHSType << RHSType 8143 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8144 return QualType(); 8145 } 8146 8147 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 8148 // expression. These are mainly cases where the null pointer is used as an 8149 // integer instead of a pointer. 8150 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 8151 SourceLocation Loc, bool IsCompare) { 8152 // The canonical way to check for a GNU null is with isNullPointerConstant, 8153 // but we use a bit of a hack here for speed; this is a relatively 8154 // hot path, and isNullPointerConstant is slow. 8155 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 8156 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 8157 8158 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 8159 8160 // Avoid analyzing cases where the result will either be invalid (and 8161 // diagnosed as such) or entirely valid and not something to warn about. 8162 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 8163 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 8164 return; 8165 8166 // Comparison operations would not make sense with a null pointer no matter 8167 // what the other expression is. 8168 if (!IsCompare) { 8169 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 8170 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 8171 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 8172 return; 8173 } 8174 8175 // The rest of the operations only make sense with a null pointer 8176 // if the other expression is a pointer. 8177 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 8178 NonNullType->canDecayToPointerType()) 8179 return; 8180 8181 S.Diag(Loc, diag::warn_null_in_comparison_operation) 8182 << LHSNull /* LHS is NULL */ << NonNullType 8183 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8184 } 8185 8186 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 8187 ExprResult &RHS, 8188 SourceLocation Loc, bool IsDiv) { 8189 // Check for division/remainder by zero. 8190 llvm::APSInt RHSValue; 8191 if (!RHS.get()->isValueDependent() && 8192 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0) 8193 S.DiagRuntimeBehavior(Loc, RHS.get(), 8194 S.PDiag(diag::warn_remainder_division_by_zero) 8195 << IsDiv << RHS.get()->getSourceRange()); 8196 } 8197 8198 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 8199 SourceLocation Loc, 8200 bool IsCompAssign, bool IsDiv) { 8201 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8202 8203 if (LHS.get()->getType()->isVectorType() || 8204 RHS.get()->getType()->isVectorType()) 8205 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8206 /*AllowBothBool*/getLangOpts().AltiVec, 8207 /*AllowBoolConversions*/false); 8208 8209 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8210 if (LHS.isInvalid() || RHS.isInvalid()) 8211 return QualType(); 8212 8213 8214 if (compType.isNull() || !compType->isArithmeticType()) 8215 return InvalidOperands(Loc, LHS, RHS); 8216 if (IsDiv) 8217 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 8218 return compType; 8219 } 8220 8221 QualType Sema::CheckRemainderOperands( 8222 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 8223 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8224 8225 if (LHS.get()->getType()->isVectorType() || 8226 RHS.get()->getType()->isVectorType()) { 8227 if (LHS.get()->getType()->hasIntegerRepresentation() && 8228 RHS.get()->getType()->hasIntegerRepresentation()) 8229 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8230 /*AllowBothBool*/getLangOpts().AltiVec, 8231 /*AllowBoolConversions*/false); 8232 return InvalidOperands(Loc, LHS, RHS); 8233 } 8234 8235 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8236 if (LHS.isInvalid() || RHS.isInvalid()) 8237 return QualType(); 8238 8239 if (compType.isNull() || !compType->isIntegerType()) 8240 return InvalidOperands(Loc, LHS, RHS); 8241 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 8242 return compType; 8243 } 8244 8245 /// \brief Diagnose invalid arithmetic on two void pointers. 8246 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 8247 Expr *LHSExpr, Expr *RHSExpr) { 8248 S.Diag(Loc, S.getLangOpts().CPlusPlus 8249 ? diag::err_typecheck_pointer_arith_void_type 8250 : diag::ext_gnu_void_ptr) 8251 << 1 /* two pointers */ << LHSExpr->getSourceRange() 8252 << RHSExpr->getSourceRange(); 8253 } 8254 8255 /// \brief Diagnose invalid arithmetic on a void pointer. 8256 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 8257 Expr *Pointer) { 8258 S.Diag(Loc, S.getLangOpts().CPlusPlus 8259 ? diag::err_typecheck_pointer_arith_void_type 8260 : diag::ext_gnu_void_ptr) 8261 << 0 /* one pointer */ << Pointer->getSourceRange(); 8262 } 8263 8264 /// \brief Diagnose invalid arithmetic on two function pointers. 8265 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 8266 Expr *LHS, Expr *RHS) { 8267 assert(LHS->getType()->isAnyPointerType()); 8268 assert(RHS->getType()->isAnyPointerType()); 8269 S.Diag(Loc, S.getLangOpts().CPlusPlus 8270 ? diag::err_typecheck_pointer_arith_function_type 8271 : diag::ext_gnu_ptr_func_arith) 8272 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 8273 // We only show the second type if it differs from the first. 8274 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 8275 RHS->getType()) 8276 << RHS->getType()->getPointeeType() 8277 << LHS->getSourceRange() << RHS->getSourceRange(); 8278 } 8279 8280 /// \brief Diagnose invalid arithmetic on a function pointer. 8281 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 8282 Expr *Pointer) { 8283 assert(Pointer->getType()->isAnyPointerType()); 8284 S.Diag(Loc, S.getLangOpts().CPlusPlus 8285 ? diag::err_typecheck_pointer_arith_function_type 8286 : diag::ext_gnu_ptr_func_arith) 8287 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 8288 << 0 /* one pointer, so only one type */ 8289 << Pointer->getSourceRange(); 8290 } 8291 8292 /// \brief Emit error if Operand is incomplete pointer type 8293 /// 8294 /// \returns True if pointer has incomplete type 8295 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 8296 Expr *Operand) { 8297 QualType ResType = Operand->getType(); 8298 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8299 ResType = ResAtomicType->getValueType(); 8300 8301 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 8302 QualType PointeeTy = ResType->getPointeeType(); 8303 return S.RequireCompleteType(Loc, PointeeTy, 8304 diag::err_typecheck_arithmetic_incomplete_type, 8305 PointeeTy, Operand->getSourceRange()); 8306 } 8307 8308 /// \brief Check the validity of an arithmetic pointer operand. 8309 /// 8310 /// If the operand has pointer type, this code will check for pointer types 8311 /// which are invalid in arithmetic operations. These will be diagnosed 8312 /// appropriately, including whether or not the use is supported as an 8313 /// extension. 8314 /// 8315 /// \returns True when the operand is valid to use (even if as an extension). 8316 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 8317 Expr *Operand) { 8318 QualType ResType = Operand->getType(); 8319 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8320 ResType = ResAtomicType->getValueType(); 8321 8322 if (!ResType->isAnyPointerType()) return true; 8323 8324 QualType PointeeTy = ResType->getPointeeType(); 8325 if (PointeeTy->isVoidType()) { 8326 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 8327 return !S.getLangOpts().CPlusPlus; 8328 } 8329 if (PointeeTy->isFunctionType()) { 8330 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 8331 return !S.getLangOpts().CPlusPlus; 8332 } 8333 8334 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 8335 8336 return true; 8337 } 8338 8339 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 8340 /// operands. 8341 /// 8342 /// This routine will diagnose any invalid arithmetic on pointer operands much 8343 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 8344 /// for emitting a single diagnostic even for operations where both LHS and RHS 8345 /// are (potentially problematic) pointers. 8346 /// 8347 /// \returns True when the operand is valid to use (even if as an extension). 8348 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 8349 Expr *LHSExpr, Expr *RHSExpr) { 8350 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 8351 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 8352 if (!isLHSPointer && !isRHSPointer) return true; 8353 8354 QualType LHSPointeeTy, RHSPointeeTy; 8355 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 8356 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 8357 8358 // if both are pointers check if operation is valid wrt address spaces 8359 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 8360 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 8361 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 8362 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 8363 S.Diag(Loc, 8364 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8365 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 8366 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 8367 return false; 8368 } 8369 } 8370 8371 // Check for arithmetic on pointers to incomplete types. 8372 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 8373 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 8374 if (isLHSVoidPtr || isRHSVoidPtr) { 8375 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 8376 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 8377 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 8378 8379 return !S.getLangOpts().CPlusPlus; 8380 } 8381 8382 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 8383 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 8384 if (isLHSFuncPtr || isRHSFuncPtr) { 8385 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 8386 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 8387 RHSExpr); 8388 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 8389 8390 return !S.getLangOpts().CPlusPlus; 8391 } 8392 8393 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 8394 return false; 8395 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 8396 return false; 8397 8398 return true; 8399 } 8400 8401 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 8402 /// literal. 8403 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 8404 Expr *LHSExpr, Expr *RHSExpr) { 8405 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 8406 Expr* IndexExpr = RHSExpr; 8407 if (!StrExpr) { 8408 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 8409 IndexExpr = LHSExpr; 8410 } 8411 8412 bool IsStringPlusInt = StrExpr && 8413 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 8414 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 8415 return; 8416 8417 llvm::APSInt index; 8418 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 8419 unsigned StrLenWithNull = StrExpr->getLength() + 1; 8420 if (index.isNonNegative() && 8421 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 8422 index.isUnsigned())) 8423 return; 8424 } 8425 8426 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8427 Self.Diag(OpLoc, diag::warn_string_plus_int) 8428 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 8429 8430 // Only print a fixit for "str" + int, not for int + "str". 8431 if (IndexExpr == RHSExpr) { 8432 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8433 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8434 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8435 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8436 << FixItHint::CreateInsertion(EndLoc, "]"); 8437 } else 8438 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8439 } 8440 8441 /// \brief Emit a warning when adding a char literal to a string. 8442 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 8443 Expr *LHSExpr, Expr *RHSExpr) { 8444 const Expr *StringRefExpr = LHSExpr; 8445 const CharacterLiteral *CharExpr = 8446 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 8447 8448 if (!CharExpr) { 8449 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 8450 StringRefExpr = RHSExpr; 8451 } 8452 8453 if (!CharExpr || !StringRefExpr) 8454 return; 8455 8456 const QualType StringType = StringRefExpr->getType(); 8457 8458 // Return if not a PointerType. 8459 if (!StringType->isAnyPointerType()) 8460 return; 8461 8462 // Return if not a CharacterType. 8463 if (!StringType->getPointeeType()->isAnyCharacterType()) 8464 return; 8465 8466 ASTContext &Ctx = Self.getASTContext(); 8467 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8468 8469 const QualType CharType = CharExpr->getType(); 8470 if (!CharType->isAnyCharacterType() && 8471 CharType->isIntegerType() && 8472 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 8473 Self.Diag(OpLoc, diag::warn_string_plus_char) 8474 << DiagRange << Ctx.CharTy; 8475 } else { 8476 Self.Diag(OpLoc, diag::warn_string_plus_char) 8477 << DiagRange << CharExpr->getType(); 8478 } 8479 8480 // Only print a fixit for str + char, not for char + str. 8481 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 8482 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8483 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8484 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8485 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8486 << FixItHint::CreateInsertion(EndLoc, "]"); 8487 } else { 8488 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8489 } 8490 } 8491 8492 /// \brief Emit error when two pointers are incompatible. 8493 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 8494 Expr *LHSExpr, Expr *RHSExpr) { 8495 assert(LHSExpr->getType()->isAnyPointerType()); 8496 assert(RHSExpr->getType()->isAnyPointerType()); 8497 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 8498 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 8499 << RHSExpr->getSourceRange(); 8500 } 8501 8502 // C99 6.5.6 8503 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 8504 SourceLocation Loc, BinaryOperatorKind Opc, 8505 QualType* CompLHSTy) { 8506 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8507 8508 if (LHS.get()->getType()->isVectorType() || 8509 RHS.get()->getType()->isVectorType()) { 8510 QualType compType = CheckVectorOperands( 8511 LHS, RHS, Loc, CompLHSTy, 8512 /*AllowBothBool*/getLangOpts().AltiVec, 8513 /*AllowBoolConversions*/getLangOpts().ZVector); 8514 if (CompLHSTy) *CompLHSTy = compType; 8515 return compType; 8516 } 8517 8518 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8519 if (LHS.isInvalid() || RHS.isInvalid()) 8520 return QualType(); 8521 8522 // Diagnose "string literal" '+' int and string '+' "char literal". 8523 if (Opc == BO_Add) { 8524 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 8525 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 8526 } 8527 8528 // handle the common case first (both operands are arithmetic). 8529 if (!compType.isNull() && compType->isArithmeticType()) { 8530 if (CompLHSTy) *CompLHSTy = compType; 8531 return compType; 8532 } 8533 8534 // Type-checking. Ultimately the pointer's going to be in PExp; 8535 // note that we bias towards the LHS being the pointer. 8536 Expr *PExp = LHS.get(), *IExp = RHS.get(); 8537 8538 bool isObjCPointer; 8539 if (PExp->getType()->isPointerType()) { 8540 isObjCPointer = false; 8541 } else if (PExp->getType()->isObjCObjectPointerType()) { 8542 isObjCPointer = true; 8543 } else { 8544 std::swap(PExp, IExp); 8545 if (PExp->getType()->isPointerType()) { 8546 isObjCPointer = false; 8547 } else if (PExp->getType()->isObjCObjectPointerType()) { 8548 isObjCPointer = true; 8549 } else { 8550 return InvalidOperands(Loc, LHS, RHS); 8551 } 8552 } 8553 assert(PExp->getType()->isAnyPointerType()); 8554 8555 if (!IExp->getType()->isIntegerType()) 8556 return InvalidOperands(Loc, LHS, RHS); 8557 8558 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 8559 return QualType(); 8560 8561 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 8562 return QualType(); 8563 8564 // Check array bounds for pointer arithemtic 8565 CheckArrayAccess(PExp, IExp); 8566 8567 if (CompLHSTy) { 8568 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 8569 if (LHSTy.isNull()) { 8570 LHSTy = LHS.get()->getType(); 8571 if (LHSTy->isPromotableIntegerType()) 8572 LHSTy = Context.getPromotedIntegerType(LHSTy); 8573 } 8574 *CompLHSTy = LHSTy; 8575 } 8576 8577 return PExp->getType(); 8578 } 8579 8580 // C99 6.5.6 8581 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 8582 SourceLocation Loc, 8583 QualType* CompLHSTy) { 8584 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8585 8586 if (LHS.get()->getType()->isVectorType() || 8587 RHS.get()->getType()->isVectorType()) { 8588 QualType compType = CheckVectorOperands( 8589 LHS, RHS, Loc, CompLHSTy, 8590 /*AllowBothBool*/getLangOpts().AltiVec, 8591 /*AllowBoolConversions*/getLangOpts().ZVector); 8592 if (CompLHSTy) *CompLHSTy = compType; 8593 return compType; 8594 } 8595 8596 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8597 if (LHS.isInvalid() || RHS.isInvalid()) 8598 return QualType(); 8599 8600 // Enforce type constraints: C99 6.5.6p3. 8601 8602 // Handle the common case first (both operands are arithmetic). 8603 if (!compType.isNull() && compType->isArithmeticType()) { 8604 if (CompLHSTy) *CompLHSTy = compType; 8605 return compType; 8606 } 8607 8608 // Either ptr - int or ptr - ptr. 8609 if (LHS.get()->getType()->isAnyPointerType()) { 8610 QualType lpointee = LHS.get()->getType()->getPointeeType(); 8611 8612 // Diagnose bad cases where we step over interface counts. 8613 if (LHS.get()->getType()->isObjCObjectPointerType() && 8614 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 8615 return QualType(); 8616 8617 // The result type of a pointer-int computation is the pointer type. 8618 if (RHS.get()->getType()->isIntegerType()) { 8619 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 8620 return QualType(); 8621 8622 // Check array bounds for pointer arithemtic 8623 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 8624 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 8625 8626 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8627 return LHS.get()->getType(); 8628 } 8629 8630 // Handle pointer-pointer subtractions. 8631 if (const PointerType *RHSPTy 8632 = RHS.get()->getType()->getAs<PointerType>()) { 8633 QualType rpointee = RHSPTy->getPointeeType(); 8634 8635 if (getLangOpts().CPlusPlus) { 8636 // Pointee types must be the same: C++ [expr.add] 8637 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 8638 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8639 } 8640 } else { 8641 // Pointee types must be compatible C99 6.5.6p3 8642 if (!Context.typesAreCompatible( 8643 Context.getCanonicalType(lpointee).getUnqualifiedType(), 8644 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 8645 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8646 return QualType(); 8647 } 8648 } 8649 8650 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 8651 LHS.get(), RHS.get())) 8652 return QualType(); 8653 8654 // The pointee type may have zero size. As an extension, a structure or 8655 // union may have zero size or an array may have zero length. In this 8656 // case subtraction does not make sense. 8657 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 8658 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 8659 if (ElementSize.isZero()) { 8660 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 8661 << rpointee.getUnqualifiedType() 8662 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8663 } 8664 } 8665 8666 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8667 return Context.getPointerDiffType(); 8668 } 8669 } 8670 8671 return InvalidOperands(Loc, LHS, RHS); 8672 } 8673 8674 static bool isScopedEnumerationType(QualType T) { 8675 if (const EnumType *ET = T->getAs<EnumType>()) 8676 return ET->getDecl()->isScoped(); 8677 return false; 8678 } 8679 8680 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 8681 SourceLocation Loc, BinaryOperatorKind Opc, 8682 QualType LHSType) { 8683 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 8684 // so skip remaining warnings as we don't want to modify values within Sema. 8685 if (S.getLangOpts().OpenCL) 8686 return; 8687 8688 llvm::APSInt Right; 8689 // Check right/shifter operand 8690 if (RHS.get()->isValueDependent() || 8691 !RHS.get()->EvaluateAsInt(Right, S.Context)) 8692 return; 8693 8694 if (Right.isNegative()) { 8695 S.DiagRuntimeBehavior(Loc, RHS.get(), 8696 S.PDiag(diag::warn_shift_negative) 8697 << RHS.get()->getSourceRange()); 8698 return; 8699 } 8700 llvm::APInt LeftBits(Right.getBitWidth(), 8701 S.Context.getTypeSize(LHS.get()->getType())); 8702 if (Right.uge(LeftBits)) { 8703 S.DiagRuntimeBehavior(Loc, RHS.get(), 8704 S.PDiag(diag::warn_shift_gt_typewidth) 8705 << RHS.get()->getSourceRange()); 8706 return; 8707 } 8708 if (Opc != BO_Shl) 8709 return; 8710 8711 // When left shifting an ICE which is signed, we can check for overflow which 8712 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 8713 // integers have defined behavior modulo one more than the maximum value 8714 // representable in the result type, so never warn for those. 8715 llvm::APSInt Left; 8716 if (LHS.get()->isValueDependent() || 8717 LHSType->hasUnsignedIntegerRepresentation() || 8718 !LHS.get()->EvaluateAsInt(Left, S.Context)) 8719 return; 8720 8721 // If LHS does not have a signed type and non-negative value 8722 // then, the behavior is undefined. Warn about it. 8723 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) { 8724 S.DiagRuntimeBehavior(Loc, LHS.get(), 8725 S.PDiag(diag::warn_shift_lhs_negative) 8726 << LHS.get()->getSourceRange()); 8727 return; 8728 } 8729 8730 llvm::APInt ResultBits = 8731 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 8732 if (LeftBits.uge(ResultBits)) 8733 return; 8734 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 8735 Result = Result.shl(Right); 8736 8737 // Print the bit representation of the signed integer as an unsigned 8738 // hexadecimal number. 8739 SmallString<40> HexResult; 8740 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 8741 8742 // If we are only missing a sign bit, this is less likely to result in actual 8743 // bugs -- if the result is cast back to an unsigned type, it will have the 8744 // expected value. Thus we place this behind a different warning that can be 8745 // turned off separately if needed. 8746 if (LeftBits == ResultBits - 1) { 8747 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 8748 << HexResult << LHSType 8749 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8750 return; 8751 } 8752 8753 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 8754 << HexResult.str() << Result.getMinSignedBits() << LHSType 8755 << Left.getBitWidth() << LHS.get()->getSourceRange() 8756 << RHS.get()->getSourceRange(); 8757 } 8758 8759 /// \brief Return the resulting type when a vector is shifted 8760 /// by a scalar or vector shift amount. 8761 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 8762 SourceLocation Loc, bool IsCompAssign) { 8763 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 8764 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 8765 !LHS.get()->getType()->isVectorType()) { 8766 S.Diag(Loc, diag::err_shift_rhs_only_vector) 8767 << RHS.get()->getType() << LHS.get()->getType() 8768 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8769 return QualType(); 8770 } 8771 8772 if (!IsCompAssign) { 8773 LHS = S.UsualUnaryConversions(LHS.get()); 8774 if (LHS.isInvalid()) return QualType(); 8775 } 8776 8777 RHS = S.UsualUnaryConversions(RHS.get()); 8778 if (RHS.isInvalid()) return QualType(); 8779 8780 QualType LHSType = LHS.get()->getType(); 8781 // Note that LHS might be a scalar because the routine calls not only in 8782 // OpenCL case. 8783 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 8784 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 8785 8786 // Note that RHS might not be a vector. 8787 QualType RHSType = RHS.get()->getType(); 8788 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 8789 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 8790 8791 // The operands need to be integers. 8792 if (!LHSEleType->isIntegerType()) { 8793 S.Diag(Loc, diag::err_typecheck_expect_int) 8794 << LHS.get()->getType() << LHS.get()->getSourceRange(); 8795 return QualType(); 8796 } 8797 8798 if (!RHSEleType->isIntegerType()) { 8799 S.Diag(Loc, diag::err_typecheck_expect_int) 8800 << RHS.get()->getType() << RHS.get()->getSourceRange(); 8801 return QualType(); 8802 } 8803 8804 if (!LHSVecTy) { 8805 assert(RHSVecTy); 8806 if (IsCompAssign) 8807 return RHSType; 8808 if (LHSEleType != RHSEleType) { 8809 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 8810 LHSEleType = RHSEleType; 8811 } 8812 QualType VecTy = 8813 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 8814 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 8815 LHSType = VecTy; 8816 } else if (RHSVecTy) { 8817 // OpenCL v1.1 s6.3.j says that for vector types, the operators 8818 // are applied component-wise. So if RHS is a vector, then ensure 8819 // that the number of elements is the same as LHS... 8820 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 8821 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 8822 << LHS.get()->getType() << RHS.get()->getType() 8823 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8824 return QualType(); 8825 } 8826 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 8827 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 8828 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 8829 if (LHSBT != RHSBT && 8830 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 8831 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 8832 << LHS.get()->getType() << RHS.get()->getType() 8833 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8834 } 8835 } 8836 } else { 8837 // ...else expand RHS to match the number of elements in LHS. 8838 QualType VecTy = 8839 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 8840 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 8841 } 8842 8843 return LHSType; 8844 } 8845 8846 // C99 6.5.7 8847 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 8848 SourceLocation Loc, BinaryOperatorKind Opc, 8849 bool IsCompAssign) { 8850 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8851 8852 // Vector shifts promote their scalar inputs to vector type. 8853 if (LHS.get()->getType()->isVectorType() || 8854 RHS.get()->getType()->isVectorType()) { 8855 if (LangOpts.ZVector) { 8856 // The shift operators for the z vector extensions work basically 8857 // like general shifts, except that neither the LHS nor the RHS is 8858 // allowed to be a "vector bool". 8859 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 8860 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 8861 return InvalidOperands(Loc, LHS, RHS); 8862 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 8863 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8864 return InvalidOperands(Loc, LHS, RHS); 8865 } 8866 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 8867 } 8868 8869 // Shifts don't perform usual arithmetic conversions, they just do integer 8870 // promotions on each operand. C99 6.5.7p3 8871 8872 // For the LHS, do usual unary conversions, but then reset them away 8873 // if this is a compound assignment. 8874 ExprResult OldLHS = LHS; 8875 LHS = UsualUnaryConversions(LHS.get()); 8876 if (LHS.isInvalid()) 8877 return QualType(); 8878 QualType LHSType = LHS.get()->getType(); 8879 if (IsCompAssign) LHS = OldLHS; 8880 8881 // The RHS is simpler. 8882 RHS = UsualUnaryConversions(RHS.get()); 8883 if (RHS.isInvalid()) 8884 return QualType(); 8885 QualType RHSType = RHS.get()->getType(); 8886 8887 // C99 6.5.7p2: Each of the operands shall have integer type. 8888 if (!LHSType->hasIntegerRepresentation() || 8889 !RHSType->hasIntegerRepresentation()) 8890 return InvalidOperands(Loc, LHS, RHS); 8891 8892 // C++0x: Don't allow scoped enums. FIXME: Use something better than 8893 // hasIntegerRepresentation() above instead of this. 8894 if (isScopedEnumerationType(LHSType) || 8895 isScopedEnumerationType(RHSType)) { 8896 return InvalidOperands(Loc, LHS, RHS); 8897 } 8898 // Sanity-check shift operands 8899 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 8900 8901 // "The type of the result is that of the promoted left operand." 8902 return LHSType; 8903 } 8904 8905 static bool IsWithinTemplateSpecialization(Decl *D) { 8906 if (DeclContext *DC = D->getDeclContext()) { 8907 if (isa<ClassTemplateSpecializationDecl>(DC)) 8908 return true; 8909 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 8910 return FD->isFunctionTemplateSpecialization(); 8911 } 8912 return false; 8913 } 8914 8915 /// If two different enums are compared, raise a warning. 8916 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 8917 Expr *RHS) { 8918 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 8919 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 8920 8921 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 8922 if (!LHSEnumType) 8923 return; 8924 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 8925 if (!RHSEnumType) 8926 return; 8927 8928 // Ignore anonymous enums. 8929 if (!LHSEnumType->getDecl()->getIdentifier()) 8930 return; 8931 if (!RHSEnumType->getDecl()->getIdentifier()) 8932 return; 8933 8934 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 8935 return; 8936 8937 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 8938 << LHSStrippedType << RHSStrippedType 8939 << LHS->getSourceRange() << RHS->getSourceRange(); 8940 } 8941 8942 /// \brief Diagnose bad pointer comparisons. 8943 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 8944 ExprResult &LHS, ExprResult &RHS, 8945 bool IsError) { 8946 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 8947 : diag::ext_typecheck_comparison_of_distinct_pointers) 8948 << LHS.get()->getType() << RHS.get()->getType() 8949 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8950 } 8951 8952 /// \brief Returns false if the pointers are converted to a composite type, 8953 /// true otherwise. 8954 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 8955 ExprResult &LHS, ExprResult &RHS) { 8956 // C++ [expr.rel]p2: 8957 // [...] Pointer conversions (4.10) and qualification 8958 // conversions (4.4) are performed on pointer operands (or on 8959 // a pointer operand and a null pointer constant) to bring 8960 // them to their composite pointer type. [...] 8961 // 8962 // C++ [expr.eq]p1 uses the same notion for (in)equality 8963 // comparisons of pointers. 8964 8965 QualType LHSType = LHS.get()->getType(); 8966 QualType RHSType = RHS.get()->getType(); 8967 assert(LHSType->isPointerType() || RHSType->isPointerType() || 8968 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 8969 8970 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 8971 if (T.isNull()) { 8972 if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) && 8973 (RHSType->isPointerType() || RHSType->isMemberPointerType())) 8974 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 8975 else 8976 S.InvalidOperands(Loc, LHS, RHS); 8977 return true; 8978 } 8979 8980 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 8981 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 8982 return false; 8983 } 8984 8985 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 8986 ExprResult &LHS, 8987 ExprResult &RHS, 8988 bool IsError) { 8989 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 8990 : diag::ext_typecheck_comparison_of_fptr_to_void) 8991 << LHS.get()->getType() << RHS.get()->getType() 8992 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8993 } 8994 8995 static bool isObjCObjectLiteral(ExprResult &E) { 8996 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 8997 case Stmt::ObjCArrayLiteralClass: 8998 case Stmt::ObjCDictionaryLiteralClass: 8999 case Stmt::ObjCStringLiteralClass: 9000 case Stmt::ObjCBoxedExprClass: 9001 return true; 9002 default: 9003 // Note that ObjCBoolLiteral is NOT an object literal! 9004 return false; 9005 } 9006 } 9007 9008 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 9009 const ObjCObjectPointerType *Type = 9010 LHS->getType()->getAs<ObjCObjectPointerType>(); 9011 9012 // If this is not actually an Objective-C object, bail out. 9013 if (!Type) 9014 return false; 9015 9016 // Get the LHS object's interface type. 9017 QualType InterfaceType = Type->getPointeeType(); 9018 9019 // If the RHS isn't an Objective-C object, bail out. 9020 if (!RHS->getType()->isObjCObjectPointerType()) 9021 return false; 9022 9023 // Try to find the -isEqual: method. 9024 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 9025 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 9026 InterfaceType, 9027 /*instance=*/true); 9028 if (!Method) { 9029 if (Type->isObjCIdType()) { 9030 // For 'id', just check the global pool. 9031 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 9032 /*receiverId=*/true); 9033 } else { 9034 // Check protocols. 9035 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 9036 /*instance=*/true); 9037 } 9038 } 9039 9040 if (!Method) 9041 return false; 9042 9043 QualType T = Method->parameters()[0]->getType(); 9044 if (!T->isObjCObjectPointerType()) 9045 return false; 9046 9047 QualType R = Method->getReturnType(); 9048 if (!R->isScalarType()) 9049 return false; 9050 9051 return true; 9052 } 9053 9054 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 9055 FromE = FromE->IgnoreParenImpCasts(); 9056 switch (FromE->getStmtClass()) { 9057 default: 9058 break; 9059 case Stmt::ObjCStringLiteralClass: 9060 // "string literal" 9061 return LK_String; 9062 case Stmt::ObjCArrayLiteralClass: 9063 // "array literal" 9064 return LK_Array; 9065 case Stmt::ObjCDictionaryLiteralClass: 9066 // "dictionary literal" 9067 return LK_Dictionary; 9068 case Stmt::BlockExprClass: 9069 return LK_Block; 9070 case Stmt::ObjCBoxedExprClass: { 9071 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 9072 switch (Inner->getStmtClass()) { 9073 case Stmt::IntegerLiteralClass: 9074 case Stmt::FloatingLiteralClass: 9075 case Stmt::CharacterLiteralClass: 9076 case Stmt::ObjCBoolLiteralExprClass: 9077 case Stmt::CXXBoolLiteralExprClass: 9078 // "numeric literal" 9079 return LK_Numeric; 9080 case Stmt::ImplicitCastExprClass: { 9081 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 9082 // Boolean literals can be represented by implicit casts. 9083 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 9084 return LK_Numeric; 9085 break; 9086 } 9087 default: 9088 break; 9089 } 9090 return LK_Boxed; 9091 } 9092 } 9093 return LK_None; 9094 } 9095 9096 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 9097 ExprResult &LHS, ExprResult &RHS, 9098 BinaryOperator::Opcode Opc){ 9099 Expr *Literal; 9100 Expr *Other; 9101 if (isObjCObjectLiteral(LHS)) { 9102 Literal = LHS.get(); 9103 Other = RHS.get(); 9104 } else { 9105 Literal = RHS.get(); 9106 Other = LHS.get(); 9107 } 9108 9109 // Don't warn on comparisons against nil. 9110 Other = Other->IgnoreParenCasts(); 9111 if (Other->isNullPointerConstant(S.getASTContext(), 9112 Expr::NPC_ValueDependentIsNotNull)) 9113 return; 9114 9115 // This should be kept in sync with warn_objc_literal_comparison. 9116 // LK_String should always be after the other literals, since it has its own 9117 // warning flag. 9118 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 9119 assert(LiteralKind != Sema::LK_Block); 9120 if (LiteralKind == Sema::LK_None) { 9121 llvm_unreachable("Unknown Objective-C object literal kind"); 9122 } 9123 9124 if (LiteralKind == Sema::LK_String) 9125 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 9126 << Literal->getSourceRange(); 9127 else 9128 S.Diag(Loc, diag::warn_objc_literal_comparison) 9129 << LiteralKind << Literal->getSourceRange(); 9130 9131 if (BinaryOperator::isEqualityOp(Opc) && 9132 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 9133 SourceLocation Start = LHS.get()->getLocStart(); 9134 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd()); 9135 CharSourceRange OpRange = 9136 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 9137 9138 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 9139 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 9140 << FixItHint::CreateReplacement(OpRange, " isEqual:") 9141 << FixItHint::CreateInsertion(End, "]"); 9142 } 9143 } 9144 9145 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 9146 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 9147 ExprResult &RHS, SourceLocation Loc, 9148 BinaryOperatorKind Opc) { 9149 // Check that left hand side is !something. 9150 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 9151 if (!UO || UO->getOpcode() != UO_LNot) return; 9152 9153 // Only check if the right hand side is non-bool arithmetic type. 9154 if (RHS.get()->isKnownToHaveBooleanValue()) return; 9155 9156 // Make sure that the something in !something is not bool. 9157 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 9158 if (SubExpr->isKnownToHaveBooleanValue()) return; 9159 9160 // Emit warning. 9161 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 9162 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 9163 << Loc << IsBitwiseOp; 9164 9165 // First note suggest !(x < y) 9166 SourceLocation FirstOpen = SubExpr->getLocStart(); 9167 SourceLocation FirstClose = RHS.get()->getLocEnd(); 9168 FirstClose = S.getLocForEndOfToken(FirstClose); 9169 if (FirstClose.isInvalid()) 9170 FirstOpen = SourceLocation(); 9171 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 9172 << IsBitwiseOp 9173 << FixItHint::CreateInsertion(FirstOpen, "(") 9174 << FixItHint::CreateInsertion(FirstClose, ")"); 9175 9176 // Second note suggests (!x) < y 9177 SourceLocation SecondOpen = LHS.get()->getLocStart(); 9178 SourceLocation SecondClose = LHS.get()->getLocEnd(); 9179 SecondClose = S.getLocForEndOfToken(SecondClose); 9180 if (SecondClose.isInvalid()) 9181 SecondOpen = SourceLocation(); 9182 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 9183 << FixItHint::CreateInsertion(SecondOpen, "(") 9184 << FixItHint::CreateInsertion(SecondClose, ")"); 9185 } 9186 9187 // Get the decl for a simple expression: a reference to a variable, 9188 // an implicit C++ field reference, or an implicit ObjC ivar reference. 9189 static ValueDecl *getCompareDecl(Expr *E) { 9190 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E)) 9191 return DR->getDecl(); 9192 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 9193 if (Ivar->isFreeIvar()) 9194 return Ivar->getDecl(); 9195 } 9196 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) { 9197 if (Mem->isImplicitAccess()) 9198 return Mem->getMemberDecl(); 9199 } 9200 return nullptr; 9201 } 9202 9203 // C99 6.5.8, C++ [expr.rel] 9204 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 9205 SourceLocation Loc, BinaryOperatorKind Opc, 9206 bool IsRelational) { 9207 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 9208 9209 // Handle vector comparisons separately. 9210 if (LHS.get()->getType()->isVectorType() || 9211 RHS.get()->getType()->isVectorType()) 9212 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 9213 9214 QualType LHSType = LHS.get()->getType(); 9215 QualType RHSType = RHS.get()->getType(); 9216 9217 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 9218 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 9219 9220 checkEnumComparison(*this, Loc, LHS.get(), RHS.get()); 9221 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 9222 9223 if (!LHSType->hasFloatingRepresentation() && 9224 !(LHSType->isBlockPointerType() && IsRelational) && 9225 !LHS.get()->getLocStart().isMacroID() && 9226 !RHS.get()->getLocStart().isMacroID() && 9227 ActiveTemplateInstantiations.empty()) { 9228 // For non-floating point types, check for self-comparisons of the form 9229 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9230 // often indicate logic errors in the program. 9231 // 9232 // NOTE: Don't warn about comparison expressions resulting from macro 9233 // expansion. Also don't warn about comparisons which are only self 9234 // comparisons within a template specialization. The warnings should catch 9235 // obvious cases in the definition of the template anyways. The idea is to 9236 // warn when the typed comparison operator will always evaluate to the same 9237 // result. 9238 ValueDecl *DL = getCompareDecl(LHSStripped); 9239 ValueDecl *DR = getCompareDecl(RHSStripped); 9240 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) { 9241 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 9242 << 0 // self- 9243 << (Opc == BO_EQ 9244 || Opc == BO_LE 9245 || Opc == BO_GE)); 9246 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() && 9247 !DL->getType()->isReferenceType() && 9248 !DR->getType()->isReferenceType()) { 9249 // what is it always going to eval to? 9250 char always_evals_to; 9251 switch(Opc) { 9252 case BO_EQ: // e.g. array1 == array2 9253 always_evals_to = 0; // false 9254 break; 9255 case BO_NE: // e.g. array1 != array2 9256 always_evals_to = 1; // true 9257 break; 9258 default: 9259 // best we can say is 'a constant' 9260 always_evals_to = 2; // e.g. array1 <= array2 9261 break; 9262 } 9263 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 9264 << 1 // array 9265 << always_evals_to); 9266 } 9267 9268 if (isa<CastExpr>(LHSStripped)) 9269 LHSStripped = LHSStripped->IgnoreParenCasts(); 9270 if (isa<CastExpr>(RHSStripped)) 9271 RHSStripped = RHSStripped->IgnoreParenCasts(); 9272 9273 // Warn about comparisons against a string constant (unless the other 9274 // operand is null), the user probably wants strcmp. 9275 Expr *literalString = nullptr; 9276 Expr *literalStringStripped = nullptr; 9277 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 9278 !RHSStripped->isNullPointerConstant(Context, 9279 Expr::NPC_ValueDependentIsNull)) { 9280 literalString = LHS.get(); 9281 literalStringStripped = LHSStripped; 9282 } else if ((isa<StringLiteral>(RHSStripped) || 9283 isa<ObjCEncodeExpr>(RHSStripped)) && 9284 !LHSStripped->isNullPointerConstant(Context, 9285 Expr::NPC_ValueDependentIsNull)) { 9286 literalString = RHS.get(); 9287 literalStringStripped = RHSStripped; 9288 } 9289 9290 if (literalString) { 9291 DiagRuntimeBehavior(Loc, nullptr, 9292 PDiag(diag::warn_stringcompare) 9293 << isa<ObjCEncodeExpr>(literalStringStripped) 9294 << literalString->getSourceRange()); 9295 } 9296 } 9297 9298 // C99 6.5.8p3 / C99 6.5.9p4 9299 UsualArithmeticConversions(LHS, RHS); 9300 if (LHS.isInvalid() || RHS.isInvalid()) 9301 return QualType(); 9302 9303 LHSType = LHS.get()->getType(); 9304 RHSType = RHS.get()->getType(); 9305 9306 // The result of comparisons is 'bool' in C++, 'int' in C. 9307 QualType ResultTy = Context.getLogicalOperationType(); 9308 9309 if (IsRelational) { 9310 if (LHSType->isRealType() && RHSType->isRealType()) 9311 return ResultTy; 9312 } else { 9313 // Check for comparisons of floating point operands using != and ==. 9314 if (LHSType->hasFloatingRepresentation()) 9315 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9316 9317 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 9318 return ResultTy; 9319 } 9320 9321 const Expr::NullPointerConstantKind LHSNullKind = 9322 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9323 const Expr::NullPointerConstantKind RHSNullKind = 9324 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9325 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 9326 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 9327 9328 if (!IsRelational && LHSIsNull != RHSIsNull) { 9329 bool IsEquality = Opc == BO_EQ; 9330 if (RHSIsNull) 9331 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 9332 RHS.get()->getSourceRange()); 9333 else 9334 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 9335 LHS.get()->getSourceRange()); 9336 } 9337 9338 if ((LHSType->isIntegerType() && !LHSIsNull) || 9339 (RHSType->isIntegerType() && !RHSIsNull)) { 9340 // Skip normal pointer conversion checks in this case; we have better 9341 // diagnostics for this below. 9342 } else if (getLangOpts().CPlusPlus) { 9343 // Equality comparison of a function pointer to a void pointer is invalid, 9344 // but we allow it as an extension. 9345 // FIXME: If we really want to allow this, should it be part of composite 9346 // pointer type computation so it works in conditionals too? 9347 if (!IsRelational && 9348 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 9349 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 9350 // This is a gcc extension compatibility comparison. 9351 // In a SFINAE context, we treat this as a hard error to maintain 9352 // conformance with the C++ standard. 9353 diagnoseFunctionPointerToVoidComparison( 9354 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 9355 9356 if (isSFINAEContext()) 9357 return QualType(); 9358 9359 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9360 return ResultTy; 9361 } 9362 9363 // C++ [expr.eq]p2: 9364 // If at least one operand is a pointer [...] bring them to their 9365 // composite pointer type. 9366 // C++ [expr.rel]p2: 9367 // If both operands are pointers, [...] bring them to their composite 9368 // pointer type. 9369 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 9370 (IsRelational ? 2 : 1)) { 9371 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9372 return QualType(); 9373 else 9374 return ResultTy; 9375 } 9376 } else if (LHSType->isPointerType() && 9377 RHSType->isPointerType()) { // C99 6.5.8p2 9378 // All of the following pointer-related warnings are GCC extensions, except 9379 // when handling null pointer constants. 9380 QualType LCanPointeeTy = 9381 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9382 QualType RCanPointeeTy = 9383 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9384 9385 // C99 6.5.9p2 and C99 6.5.8p2 9386 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 9387 RCanPointeeTy.getUnqualifiedType())) { 9388 // Valid unless a relational comparison of function pointers 9389 if (IsRelational && LCanPointeeTy->isFunctionType()) { 9390 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 9391 << LHSType << RHSType << LHS.get()->getSourceRange() 9392 << RHS.get()->getSourceRange(); 9393 } 9394 } else if (!IsRelational && 9395 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 9396 // Valid unless comparison between non-null pointer and function pointer 9397 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 9398 && !LHSIsNull && !RHSIsNull) 9399 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 9400 /*isError*/false); 9401 } else { 9402 // Invalid 9403 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 9404 } 9405 if (LCanPointeeTy != RCanPointeeTy) { 9406 // Treat NULL constant as a special case in OpenCL. 9407 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 9408 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 9409 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 9410 Diag(Loc, 9411 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 9412 << LHSType << RHSType << 0 /* comparison */ 9413 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9414 } 9415 } 9416 unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace(); 9417 unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace(); 9418 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 9419 : CK_BitCast; 9420 if (LHSIsNull && !RHSIsNull) 9421 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 9422 else 9423 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 9424 } 9425 return ResultTy; 9426 } 9427 9428 if (getLangOpts().CPlusPlus) { 9429 // C++ [expr.eq]p4: 9430 // Two operands of type std::nullptr_t or one operand of type 9431 // std::nullptr_t and the other a null pointer constant compare equal. 9432 if (!IsRelational && LHSIsNull && RHSIsNull) { 9433 if (LHSType->isNullPtrType()) { 9434 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9435 return ResultTy; 9436 } 9437 if (RHSType->isNullPtrType()) { 9438 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9439 return ResultTy; 9440 } 9441 } 9442 9443 // Comparison of Objective-C pointers and block pointers against nullptr_t. 9444 // These aren't covered by the composite pointer type rules. 9445 if (!IsRelational && RHSType->isNullPtrType() && 9446 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 9447 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9448 return ResultTy; 9449 } 9450 if (!IsRelational && LHSType->isNullPtrType() && 9451 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 9452 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9453 return ResultTy; 9454 } 9455 9456 if (IsRelational && 9457 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 9458 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 9459 // HACK: Relational comparison of nullptr_t against a pointer type is 9460 // invalid per DR583, but we allow it within std::less<> and friends, 9461 // since otherwise common uses of it break. 9462 // FIXME: Consider removing this hack once LWG fixes std::less<> and 9463 // friends to have std::nullptr_t overload candidates. 9464 DeclContext *DC = CurContext; 9465 if (isa<FunctionDecl>(DC)) 9466 DC = DC->getParent(); 9467 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 9468 if (CTSD->isInStdNamespace() && 9469 llvm::StringSwitch<bool>(CTSD->getName()) 9470 .Cases("less", "less_equal", "greater", "greater_equal", true) 9471 .Default(false)) { 9472 if (RHSType->isNullPtrType()) 9473 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9474 else 9475 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9476 return ResultTy; 9477 } 9478 } 9479 } 9480 9481 // C++ [expr.eq]p2: 9482 // If at least one operand is a pointer to member, [...] bring them to 9483 // their composite pointer type. 9484 if (!IsRelational && 9485 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 9486 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9487 return QualType(); 9488 else 9489 return ResultTy; 9490 } 9491 9492 // Handle scoped enumeration types specifically, since they don't promote 9493 // to integers. 9494 if (LHS.get()->getType()->isEnumeralType() && 9495 Context.hasSameUnqualifiedType(LHS.get()->getType(), 9496 RHS.get()->getType())) 9497 return ResultTy; 9498 } 9499 9500 // Handle block pointer types. 9501 if (!IsRelational && LHSType->isBlockPointerType() && 9502 RHSType->isBlockPointerType()) { 9503 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 9504 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 9505 9506 if (!LHSIsNull && !RHSIsNull && 9507 !Context.typesAreCompatible(lpointee, rpointee)) { 9508 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9509 << LHSType << RHSType << LHS.get()->getSourceRange() 9510 << RHS.get()->getSourceRange(); 9511 } 9512 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9513 return ResultTy; 9514 } 9515 9516 // Allow block pointers to be compared with null pointer constants. 9517 if (!IsRelational 9518 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 9519 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 9520 if (!LHSIsNull && !RHSIsNull) { 9521 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 9522 ->getPointeeType()->isVoidType()) 9523 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 9524 ->getPointeeType()->isVoidType()))) 9525 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9526 << LHSType << RHSType << LHS.get()->getSourceRange() 9527 << RHS.get()->getSourceRange(); 9528 } 9529 if (LHSIsNull && !RHSIsNull) 9530 LHS = ImpCastExprToType(LHS.get(), RHSType, 9531 RHSType->isPointerType() ? CK_BitCast 9532 : CK_AnyPointerToBlockPointerCast); 9533 else 9534 RHS = ImpCastExprToType(RHS.get(), LHSType, 9535 LHSType->isPointerType() ? CK_BitCast 9536 : CK_AnyPointerToBlockPointerCast); 9537 return ResultTy; 9538 } 9539 9540 if (LHSType->isObjCObjectPointerType() || 9541 RHSType->isObjCObjectPointerType()) { 9542 const PointerType *LPT = LHSType->getAs<PointerType>(); 9543 const PointerType *RPT = RHSType->getAs<PointerType>(); 9544 if (LPT || RPT) { 9545 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 9546 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 9547 9548 if (!LPtrToVoid && !RPtrToVoid && 9549 !Context.typesAreCompatible(LHSType, RHSType)) { 9550 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9551 /*isError*/false); 9552 } 9553 if (LHSIsNull && !RHSIsNull) { 9554 Expr *E = LHS.get(); 9555 if (getLangOpts().ObjCAutoRefCount) 9556 CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion); 9557 LHS = ImpCastExprToType(E, RHSType, 9558 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9559 } 9560 else { 9561 Expr *E = RHS.get(); 9562 if (getLangOpts().ObjCAutoRefCount) 9563 CheckObjCARCConversion(SourceRange(), LHSType, E, 9564 CCK_ImplicitConversion, /*Diagnose=*/true, 9565 /*DiagnoseCFAudited=*/false, Opc); 9566 RHS = ImpCastExprToType(E, LHSType, 9567 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9568 } 9569 return ResultTy; 9570 } 9571 if (LHSType->isObjCObjectPointerType() && 9572 RHSType->isObjCObjectPointerType()) { 9573 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 9574 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9575 /*isError*/false); 9576 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 9577 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 9578 9579 if (LHSIsNull && !RHSIsNull) 9580 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9581 else 9582 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9583 return ResultTy; 9584 } 9585 } 9586 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 9587 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 9588 unsigned DiagID = 0; 9589 bool isError = false; 9590 if (LangOpts.DebuggerSupport) { 9591 // Under a debugger, allow the comparison of pointers to integers, 9592 // since users tend to want to compare addresses. 9593 } else if ((LHSIsNull && LHSType->isIntegerType()) || 9594 (RHSIsNull && RHSType->isIntegerType())) { 9595 if (IsRelational) { 9596 isError = getLangOpts().CPlusPlus; 9597 DiagID = 9598 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 9599 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 9600 } 9601 } else if (getLangOpts().CPlusPlus) { 9602 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 9603 isError = true; 9604 } else if (IsRelational) 9605 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 9606 else 9607 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 9608 9609 if (DiagID) { 9610 Diag(Loc, DiagID) 9611 << LHSType << RHSType << LHS.get()->getSourceRange() 9612 << RHS.get()->getSourceRange(); 9613 if (isError) 9614 return QualType(); 9615 } 9616 9617 if (LHSType->isIntegerType()) 9618 LHS = ImpCastExprToType(LHS.get(), RHSType, 9619 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 9620 else 9621 RHS = ImpCastExprToType(RHS.get(), LHSType, 9622 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 9623 return ResultTy; 9624 } 9625 9626 // Handle block pointers. 9627 if (!IsRelational && RHSIsNull 9628 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 9629 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9630 return ResultTy; 9631 } 9632 if (!IsRelational && LHSIsNull 9633 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 9634 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9635 return ResultTy; 9636 } 9637 9638 return InvalidOperands(Loc, LHS, RHS); 9639 } 9640 9641 9642 // Return a signed type that is of identical size and number of elements. 9643 // For floating point vectors, return an integer type of identical size 9644 // and number of elements. 9645 QualType Sema::GetSignedVectorType(QualType V) { 9646 const VectorType *VTy = V->getAs<VectorType>(); 9647 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 9648 if (TypeSize == Context.getTypeSize(Context.CharTy)) 9649 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 9650 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 9651 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 9652 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 9653 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 9654 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 9655 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 9656 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 9657 "Unhandled vector element size in vector compare"); 9658 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 9659 } 9660 9661 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 9662 /// operates on extended vector types. Instead of producing an IntTy result, 9663 /// like a scalar comparison, a vector comparison produces a vector of integer 9664 /// types. 9665 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 9666 SourceLocation Loc, 9667 bool IsRelational) { 9668 // Check to make sure we're operating on vectors of the same type and width, 9669 // Allowing one side to be a scalar of element type. 9670 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 9671 /*AllowBothBool*/true, 9672 /*AllowBoolConversions*/getLangOpts().ZVector); 9673 if (vType.isNull()) 9674 return vType; 9675 9676 QualType LHSType = LHS.get()->getType(); 9677 9678 // If AltiVec, the comparison results in a numeric type, i.e. 9679 // bool for C++, int for C 9680 if (getLangOpts().AltiVec && 9681 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 9682 return Context.getLogicalOperationType(); 9683 9684 // For non-floating point types, check for self-comparisons of the form 9685 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9686 // often indicate logic errors in the program. 9687 if (!LHSType->hasFloatingRepresentation() && 9688 ActiveTemplateInstantiations.empty()) { 9689 if (DeclRefExpr* DRL 9690 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 9691 if (DeclRefExpr* DRR 9692 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 9693 if (DRL->getDecl() == DRR->getDecl()) 9694 DiagRuntimeBehavior(Loc, nullptr, 9695 PDiag(diag::warn_comparison_always) 9696 << 0 // self- 9697 << 2 // "a constant" 9698 ); 9699 } 9700 9701 // Check for comparisons of floating point operands using != and ==. 9702 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 9703 assert (RHS.get()->getType()->hasFloatingRepresentation()); 9704 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9705 } 9706 9707 // Return a signed type for the vector. 9708 return GetSignedVectorType(vType); 9709 } 9710 9711 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 9712 SourceLocation Loc) { 9713 // Ensure that either both operands are of the same vector type, or 9714 // one operand is of a vector type and the other is of its element type. 9715 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 9716 /*AllowBothBool*/true, 9717 /*AllowBoolConversions*/false); 9718 if (vType.isNull()) 9719 return InvalidOperands(Loc, LHS, RHS); 9720 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 9721 vType->hasFloatingRepresentation()) 9722 return InvalidOperands(Loc, LHS, RHS); 9723 9724 return GetSignedVectorType(LHS.get()->getType()); 9725 } 9726 9727 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 9728 SourceLocation Loc, 9729 BinaryOperatorKind Opc) { 9730 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9731 9732 bool IsCompAssign = 9733 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 9734 9735 if (LHS.get()->getType()->isVectorType() || 9736 RHS.get()->getType()->isVectorType()) { 9737 if (LHS.get()->getType()->hasIntegerRepresentation() && 9738 RHS.get()->getType()->hasIntegerRepresentation()) 9739 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9740 /*AllowBothBool*/true, 9741 /*AllowBoolConversions*/getLangOpts().ZVector); 9742 return InvalidOperands(Loc, LHS, RHS); 9743 } 9744 9745 if (Opc == BO_And) 9746 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 9747 9748 ExprResult LHSResult = LHS, RHSResult = RHS; 9749 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 9750 IsCompAssign); 9751 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 9752 return QualType(); 9753 LHS = LHSResult.get(); 9754 RHS = RHSResult.get(); 9755 9756 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 9757 return compType; 9758 return InvalidOperands(Loc, LHS, RHS); 9759 } 9760 9761 // C99 6.5.[13,14] 9762 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 9763 SourceLocation Loc, 9764 BinaryOperatorKind Opc) { 9765 // Check vector operands differently. 9766 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 9767 return CheckVectorLogicalOperands(LHS, RHS, Loc); 9768 9769 // Diagnose cases where the user write a logical and/or but probably meant a 9770 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 9771 // is a constant. 9772 if (LHS.get()->getType()->isIntegerType() && 9773 !LHS.get()->getType()->isBooleanType() && 9774 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 9775 // Don't warn in macros or template instantiations. 9776 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) { 9777 // If the RHS can be constant folded, and if it constant folds to something 9778 // that isn't 0 or 1 (which indicate a potential logical operation that 9779 // happened to fold to true/false) then warn. 9780 // Parens on the RHS are ignored. 9781 llvm::APSInt Result; 9782 if (RHS.get()->EvaluateAsInt(Result, Context)) 9783 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 9784 !RHS.get()->getExprLoc().isMacroID()) || 9785 (Result != 0 && Result != 1)) { 9786 Diag(Loc, diag::warn_logical_instead_of_bitwise) 9787 << RHS.get()->getSourceRange() 9788 << (Opc == BO_LAnd ? "&&" : "||"); 9789 // Suggest replacing the logical operator with the bitwise version 9790 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 9791 << (Opc == BO_LAnd ? "&" : "|") 9792 << FixItHint::CreateReplacement(SourceRange( 9793 Loc, getLocForEndOfToken(Loc)), 9794 Opc == BO_LAnd ? "&" : "|"); 9795 if (Opc == BO_LAnd) 9796 // Suggest replacing "Foo() && kNonZero" with "Foo()" 9797 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 9798 << FixItHint::CreateRemoval( 9799 SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()), 9800 RHS.get()->getLocEnd())); 9801 } 9802 } 9803 9804 if (!Context.getLangOpts().CPlusPlus) { 9805 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 9806 // not operate on the built-in scalar and vector float types. 9807 if (Context.getLangOpts().OpenCL && 9808 Context.getLangOpts().OpenCLVersion < 120) { 9809 if (LHS.get()->getType()->isFloatingType() || 9810 RHS.get()->getType()->isFloatingType()) 9811 return InvalidOperands(Loc, LHS, RHS); 9812 } 9813 9814 LHS = UsualUnaryConversions(LHS.get()); 9815 if (LHS.isInvalid()) 9816 return QualType(); 9817 9818 RHS = UsualUnaryConversions(RHS.get()); 9819 if (RHS.isInvalid()) 9820 return QualType(); 9821 9822 if (!LHS.get()->getType()->isScalarType() || 9823 !RHS.get()->getType()->isScalarType()) 9824 return InvalidOperands(Loc, LHS, RHS); 9825 9826 return Context.IntTy; 9827 } 9828 9829 // The following is safe because we only use this method for 9830 // non-overloadable operands. 9831 9832 // C++ [expr.log.and]p1 9833 // C++ [expr.log.or]p1 9834 // The operands are both contextually converted to type bool. 9835 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 9836 if (LHSRes.isInvalid()) 9837 return InvalidOperands(Loc, LHS, RHS); 9838 LHS = LHSRes; 9839 9840 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 9841 if (RHSRes.isInvalid()) 9842 return InvalidOperands(Loc, LHS, RHS); 9843 RHS = RHSRes; 9844 9845 // C++ [expr.log.and]p2 9846 // C++ [expr.log.or]p2 9847 // The result is a bool. 9848 return Context.BoolTy; 9849 } 9850 9851 static bool IsReadonlyMessage(Expr *E, Sema &S) { 9852 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 9853 if (!ME) return false; 9854 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 9855 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 9856 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 9857 if (!Base) return false; 9858 return Base->getMethodDecl() != nullptr; 9859 } 9860 9861 /// Is the given expression (which must be 'const') a reference to a 9862 /// variable which was originally non-const, but which has become 9863 /// 'const' due to being captured within a block? 9864 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 9865 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 9866 assert(E->isLValue() && E->getType().isConstQualified()); 9867 E = E->IgnoreParens(); 9868 9869 // Must be a reference to a declaration from an enclosing scope. 9870 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 9871 if (!DRE) return NCCK_None; 9872 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 9873 9874 // The declaration must be a variable which is not declared 'const'. 9875 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 9876 if (!var) return NCCK_None; 9877 if (var->getType().isConstQualified()) return NCCK_None; 9878 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 9879 9880 // Decide whether the first capture was for a block or a lambda. 9881 DeclContext *DC = S.CurContext, *Prev = nullptr; 9882 // Decide whether the first capture was for a block or a lambda. 9883 while (DC) { 9884 // For init-capture, it is possible that the variable belongs to the 9885 // template pattern of the current context. 9886 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 9887 if (var->isInitCapture() && 9888 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 9889 break; 9890 if (DC == var->getDeclContext()) 9891 break; 9892 Prev = DC; 9893 DC = DC->getParent(); 9894 } 9895 // Unless we have an init-capture, we've gone one step too far. 9896 if (!var->isInitCapture()) 9897 DC = Prev; 9898 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 9899 } 9900 9901 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 9902 Ty = Ty.getNonReferenceType(); 9903 if (IsDereference && Ty->isPointerType()) 9904 Ty = Ty->getPointeeType(); 9905 return !Ty.isConstQualified(); 9906 } 9907 9908 /// Emit the "read-only variable not assignable" error and print notes to give 9909 /// more information about why the variable is not assignable, such as pointing 9910 /// to the declaration of a const variable, showing that a method is const, or 9911 /// that the function is returning a const reference. 9912 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 9913 SourceLocation Loc) { 9914 // Update err_typecheck_assign_const and note_typecheck_assign_const 9915 // when this enum is changed. 9916 enum { 9917 ConstFunction, 9918 ConstVariable, 9919 ConstMember, 9920 ConstMethod, 9921 ConstUnknown, // Keep as last element 9922 }; 9923 9924 SourceRange ExprRange = E->getSourceRange(); 9925 9926 // Only emit one error on the first const found. All other consts will emit 9927 // a note to the error. 9928 bool DiagnosticEmitted = false; 9929 9930 // Track if the current expression is the result of a dereference, and if the 9931 // next checked expression is the result of a dereference. 9932 bool IsDereference = false; 9933 bool NextIsDereference = false; 9934 9935 // Loop to process MemberExpr chains. 9936 while (true) { 9937 IsDereference = NextIsDereference; 9938 9939 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 9940 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 9941 NextIsDereference = ME->isArrow(); 9942 const ValueDecl *VD = ME->getMemberDecl(); 9943 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 9944 // Mutable fields can be modified even if the class is const. 9945 if (Field->isMutable()) { 9946 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 9947 break; 9948 } 9949 9950 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 9951 if (!DiagnosticEmitted) { 9952 S.Diag(Loc, diag::err_typecheck_assign_const) 9953 << ExprRange << ConstMember << false /*static*/ << Field 9954 << Field->getType(); 9955 DiagnosticEmitted = true; 9956 } 9957 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9958 << ConstMember << false /*static*/ << Field << Field->getType() 9959 << Field->getSourceRange(); 9960 } 9961 E = ME->getBase(); 9962 continue; 9963 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 9964 if (VDecl->getType().isConstQualified()) { 9965 if (!DiagnosticEmitted) { 9966 S.Diag(Loc, diag::err_typecheck_assign_const) 9967 << ExprRange << ConstMember << true /*static*/ << VDecl 9968 << VDecl->getType(); 9969 DiagnosticEmitted = true; 9970 } 9971 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9972 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 9973 << VDecl->getSourceRange(); 9974 } 9975 // Static fields do not inherit constness from parents. 9976 break; 9977 } 9978 break; 9979 } // End MemberExpr 9980 break; 9981 } 9982 9983 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9984 // Function calls 9985 const FunctionDecl *FD = CE->getDirectCallee(); 9986 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 9987 if (!DiagnosticEmitted) { 9988 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 9989 << ConstFunction << FD; 9990 DiagnosticEmitted = true; 9991 } 9992 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 9993 diag::note_typecheck_assign_const) 9994 << ConstFunction << FD << FD->getReturnType() 9995 << FD->getReturnTypeSourceRange(); 9996 } 9997 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9998 // Point to variable declaration. 9999 if (const ValueDecl *VD = DRE->getDecl()) { 10000 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 10001 if (!DiagnosticEmitted) { 10002 S.Diag(Loc, diag::err_typecheck_assign_const) 10003 << ExprRange << ConstVariable << VD << VD->getType(); 10004 DiagnosticEmitted = true; 10005 } 10006 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10007 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 10008 } 10009 } 10010 } else if (isa<CXXThisExpr>(E)) { 10011 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 10012 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 10013 if (MD->isConst()) { 10014 if (!DiagnosticEmitted) { 10015 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 10016 << ConstMethod << MD; 10017 DiagnosticEmitted = true; 10018 } 10019 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 10020 << ConstMethod << MD << MD->getSourceRange(); 10021 } 10022 } 10023 } 10024 } 10025 10026 if (DiagnosticEmitted) 10027 return; 10028 10029 // Can't determine a more specific message, so display the generic error. 10030 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 10031 } 10032 10033 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 10034 /// emit an error and return true. If so, return false. 10035 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 10036 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 10037 10038 S.CheckShadowingDeclModification(E, Loc); 10039 10040 SourceLocation OrigLoc = Loc; 10041 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 10042 &Loc); 10043 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 10044 IsLV = Expr::MLV_InvalidMessageExpression; 10045 if (IsLV == Expr::MLV_Valid) 10046 return false; 10047 10048 unsigned DiagID = 0; 10049 bool NeedType = false; 10050 switch (IsLV) { // C99 6.5.16p2 10051 case Expr::MLV_ConstQualified: 10052 // Use a specialized diagnostic when we're assigning to an object 10053 // from an enclosing function or block. 10054 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 10055 if (NCCK == NCCK_Block) 10056 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 10057 else 10058 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 10059 break; 10060 } 10061 10062 // In ARC, use some specialized diagnostics for occasions where we 10063 // infer 'const'. These are always pseudo-strong variables. 10064 if (S.getLangOpts().ObjCAutoRefCount) { 10065 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 10066 if (declRef && isa<VarDecl>(declRef->getDecl())) { 10067 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 10068 10069 // Use the normal diagnostic if it's pseudo-__strong but the 10070 // user actually wrote 'const'. 10071 if (var->isARCPseudoStrong() && 10072 (!var->getTypeSourceInfo() || 10073 !var->getTypeSourceInfo()->getType().isConstQualified())) { 10074 // There are two pseudo-strong cases: 10075 // - self 10076 ObjCMethodDecl *method = S.getCurMethodDecl(); 10077 if (method && var == method->getSelfDecl()) 10078 DiagID = method->isClassMethod() 10079 ? diag::err_typecheck_arc_assign_self_class_method 10080 : diag::err_typecheck_arc_assign_self; 10081 10082 // - fast enumeration variables 10083 else 10084 DiagID = diag::err_typecheck_arr_assign_enumeration; 10085 10086 SourceRange Assign; 10087 if (Loc != OrigLoc) 10088 Assign = SourceRange(OrigLoc, OrigLoc); 10089 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10090 // We need to preserve the AST regardless, so migration tool 10091 // can do its job. 10092 return false; 10093 } 10094 } 10095 } 10096 10097 // If none of the special cases above are triggered, then this is a 10098 // simple const assignment. 10099 if (DiagID == 0) { 10100 DiagnoseConstAssignment(S, E, Loc); 10101 return true; 10102 } 10103 10104 break; 10105 case Expr::MLV_ConstAddrSpace: 10106 DiagnoseConstAssignment(S, E, Loc); 10107 return true; 10108 case Expr::MLV_ArrayType: 10109 case Expr::MLV_ArrayTemporary: 10110 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 10111 NeedType = true; 10112 break; 10113 case Expr::MLV_NotObjectType: 10114 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 10115 NeedType = true; 10116 break; 10117 case Expr::MLV_LValueCast: 10118 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 10119 break; 10120 case Expr::MLV_Valid: 10121 llvm_unreachable("did not take early return for MLV_Valid"); 10122 case Expr::MLV_InvalidExpression: 10123 case Expr::MLV_MemberFunction: 10124 case Expr::MLV_ClassTemporary: 10125 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 10126 break; 10127 case Expr::MLV_IncompleteType: 10128 case Expr::MLV_IncompleteVoidType: 10129 return S.RequireCompleteType(Loc, E->getType(), 10130 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 10131 case Expr::MLV_DuplicateVectorComponents: 10132 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 10133 break; 10134 case Expr::MLV_NoSetterProperty: 10135 llvm_unreachable("readonly properties should be processed differently"); 10136 case Expr::MLV_InvalidMessageExpression: 10137 DiagID = diag::err_readonly_message_assignment; 10138 break; 10139 case Expr::MLV_SubObjCPropertySetting: 10140 DiagID = diag::err_no_subobject_property_setting; 10141 break; 10142 } 10143 10144 SourceRange Assign; 10145 if (Loc != OrigLoc) 10146 Assign = SourceRange(OrigLoc, OrigLoc); 10147 if (NeedType) 10148 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 10149 else 10150 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10151 return true; 10152 } 10153 10154 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 10155 SourceLocation Loc, 10156 Sema &Sema) { 10157 // C / C++ fields 10158 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 10159 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 10160 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 10161 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 10162 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 10163 } 10164 10165 // Objective-C instance variables 10166 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 10167 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 10168 if (OL && OR && OL->getDecl() == OR->getDecl()) { 10169 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 10170 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 10171 if (RL && RR && RL->getDecl() == RR->getDecl()) 10172 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 10173 } 10174 } 10175 10176 // C99 6.5.16.1 10177 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 10178 SourceLocation Loc, 10179 QualType CompoundType) { 10180 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 10181 10182 // Verify that LHS is a modifiable lvalue, and emit error if not. 10183 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 10184 return QualType(); 10185 10186 QualType LHSType = LHSExpr->getType(); 10187 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 10188 CompoundType; 10189 // OpenCL v1.2 s6.1.1.1 p2: 10190 // The half data type can only be used to declare a pointer to a buffer that 10191 // contains half values 10192 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 10193 LHSType->isHalfType()) { 10194 Diag(Loc, diag::err_opencl_half_load_store) << 1 10195 << LHSType.getUnqualifiedType(); 10196 return QualType(); 10197 } 10198 10199 AssignConvertType ConvTy; 10200 if (CompoundType.isNull()) { 10201 Expr *RHSCheck = RHS.get(); 10202 10203 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 10204 10205 QualType LHSTy(LHSType); 10206 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 10207 if (RHS.isInvalid()) 10208 return QualType(); 10209 // Special case of NSObject attributes on c-style pointer types. 10210 if (ConvTy == IncompatiblePointer && 10211 ((Context.isObjCNSObjectType(LHSType) && 10212 RHSType->isObjCObjectPointerType()) || 10213 (Context.isObjCNSObjectType(RHSType) && 10214 LHSType->isObjCObjectPointerType()))) 10215 ConvTy = Compatible; 10216 10217 if (ConvTy == Compatible && 10218 LHSType->isObjCObjectType()) 10219 Diag(Loc, diag::err_objc_object_assignment) 10220 << LHSType; 10221 10222 // If the RHS is a unary plus or minus, check to see if they = and + are 10223 // right next to each other. If so, the user may have typo'd "x =+ 4" 10224 // instead of "x += 4". 10225 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 10226 RHSCheck = ICE->getSubExpr(); 10227 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 10228 if ((UO->getOpcode() == UO_Plus || 10229 UO->getOpcode() == UO_Minus) && 10230 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 10231 // Only if the two operators are exactly adjacent. 10232 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 10233 // And there is a space or other character before the subexpr of the 10234 // unary +/-. We don't want to warn on "x=-1". 10235 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 10236 UO->getSubExpr()->getLocStart().isFileID()) { 10237 Diag(Loc, diag::warn_not_compound_assign) 10238 << (UO->getOpcode() == UO_Plus ? "+" : "-") 10239 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 10240 } 10241 } 10242 10243 if (ConvTy == Compatible) { 10244 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 10245 // Warn about retain cycles where a block captures the LHS, but 10246 // not if the LHS is a simple variable into which the block is 10247 // being stored...unless that variable can be captured by reference! 10248 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 10249 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 10250 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 10251 checkRetainCycles(LHSExpr, RHS.get()); 10252 10253 // It is safe to assign a weak reference into a strong variable. 10254 // Although this code can still have problems: 10255 // id x = self.weakProp; 10256 // id y = self.weakProp; 10257 // we do not warn to warn spuriously when 'x' and 'y' are on separate 10258 // paths through the function. This should be revisited if 10259 // -Wrepeated-use-of-weak is made flow-sensitive. 10260 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 10261 RHS.get()->getLocStart())) 10262 getCurFunction()->markSafeWeakUse(RHS.get()); 10263 10264 } else if (getLangOpts().ObjCAutoRefCount) { 10265 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 10266 } 10267 } 10268 } else { 10269 // Compound assignment "x += y" 10270 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 10271 } 10272 10273 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 10274 RHS.get(), AA_Assigning)) 10275 return QualType(); 10276 10277 CheckForNullPointerDereference(*this, LHSExpr); 10278 10279 // C99 6.5.16p3: The type of an assignment expression is the type of the 10280 // left operand unless the left operand has qualified type, in which case 10281 // it is the unqualified version of the type of the left operand. 10282 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 10283 // is converted to the type of the assignment expression (above). 10284 // C++ 5.17p1: the type of the assignment expression is that of its left 10285 // operand. 10286 return (getLangOpts().CPlusPlus 10287 ? LHSType : LHSType.getUnqualifiedType()); 10288 } 10289 10290 // Only ignore explicit casts to void. 10291 static bool IgnoreCommaOperand(const Expr *E) { 10292 E = E->IgnoreParens(); 10293 10294 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 10295 if (CE->getCastKind() == CK_ToVoid) { 10296 return true; 10297 } 10298 } 10299 10300 return false; 10301 } 10302 10303 // Look for instances where it is likely the comma operator is confused with 10304 // another operator. There is a whitelist of acceptable expressions for the 10305 // left hand side of the comma operator, otherwise emit a warning. 10306 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 10307 // No warnings in macros 10308 if (Loc.isMacroID()) 10309 return; 10310 10311 // Don't warn in template instantiations. 10312 if (!ActiveTemplateInstantiations.empty()) 10313 return; 10314 10315 // Scope isn't fine-grained enough to whitelist the specific cases, so 10316 // instead, skip more than needed, then call back into here with the 10317 // CommaVisitor in SemaStmt.cpp. 10318 // The whitelisted locations are the initialization and increment portions 10319 // of a for loop. The additional checks are on the condition of 10320 // if statements, do/while loops, and for loops. 10321 const unsigned ForIncrementFlags = 10322 Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope; 10323 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 10324 const unsigned ScopeFlags = getCurScope()->getFlags(); 10325 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 10326 (ScopeFlags & ForInitFlags) == ForInitFlags) 10327 return; 10328 10329 // If there are multiple comma operators used together, get the RHS of the 10330 // of the comma operator as the LHS. 10331 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 10332 if (BO->getOpcode() != BO_Comma) 10333 break; 10334 LHS = BO->getRHS(); 10335 } 10336 10337 // Only allow some expressions on LHS to not warn. 10338 if (IgnoreCommaOperand(LHS)) 10339 return; 10340 10341 Diag(Loc, diag::warn_comma_operator); 10342 Diag(LHS->getLocStart(), diag::note_cast_to_void) 10343 << LHS->getSourceRange() 10344 << FixItHint::CreateInsertion(LHS->getLocStart(), 10345 LangOpts.CPlusPlus ? "static_cast<void>(" 10346 : "(void)(") 10347 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()), 10348 ")"); 10349 } 10350 10351 // C99 6.5.17 10352 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 10353 SourceLocation Loc) { 10354 LHS = S.CheckPlaceholderExpr(LHS.get()); 10355 RHS = S.CheckPlaceholderExpr(RHS.get()); 10356 if (LHS.isInvalid() || RHS.isInvalid()) 10357 return QualType(); 10358 10359 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 10360 // operands, but not unary promotions. 10361 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 10362 10363 // So we treat the LHS as a ignored value, and in C++ we allow the 10364 // containing site to determine what should be done with the RHS. 10365 LHS = S.IgnoredValueConversions(LHS.get()); 10366 if (LHS.isInvalid()) 10367 return QualType(); 10368 10369 S.DiagnoseUnusedExprResult(LHS.get()); 10370 10371 if (!S.getLangOpts().CPlusPlus) { 10372 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 10373 if (RHS.isInvalid()) 10374 return QualType(); 10375 if (!RHS.get()->getType()->isVoidType()) 10376 S.RequireCompleteType(Loc, RHS.get()->getType(), 10377 diag::err_incomplete_type); 10378 } 10379 10380 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 10381 S.DiagnoseCommaOperator(LHS.get(), Loc); 10382 10383 return RHS.get()->getType(); 10384 } 10385 10386 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 10387 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 10388 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 10389 ExprValueKind &VK, 10390 ExprObjectKind &OK, 10391 SourceLocation OpLoc, 10392 bool IsInc, bool IsPrefix) { 10393 if (Op->isTypeDependent()) 10394 return S.Context.DependentTy; 10395 10396 QualType ResType = Op->getType(); 10397 // Atomic types can be used for increment / decrement where the non-atomic 10398 // versions can, so ignore the _Atomic() specifier for the purpose of 10399 // checking. 10400 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10401 ResType = ResAtomicType->getValueType(); 10402 10403 assert(!ResType.isNull() && "no type for increment/decrement expression"); 10404 10405 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 10406 // Decrement of bool is not allowed. 10407 if (!IsInc) { 10408 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 10409 return QualType(); 10410 } 10411 // Increment of bool sets it to true, but is deprecated. 10412 S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool 10413 : diag::warn_increment_bool) 10414 << Op->getSourceRange(); 10415 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 10416 // Error on enum increments and decrements in C++ mode 10417 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 10418 return QualType(); 10419 } else if (ResType->isRealType()) { 10420 // OK! 10421 } else if (ResType->isPointerType()) { 10422 // C99 6.5.2.4p2, 6.5.6p2 10423 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 10424 return QualType(); 10425 } else if (ResType->isObjCObjectPointerType()) { 10426 // On modern runtimes, ObjC pointer arithmetic is forbidden. 10427 // Otherwise, we just need a complete type. 10428 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 10429 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 10430 return QualType(); 10431 } else if (ResType->isAnyComplexType()) { 10432 // C99 does not support ++/-- on complex types, we allow as an extension. 10433 S.Diag(OpLoc, diag::ext_integer_increment_complex) 10434 << ResType << Op->getSourceRange(); 10435 } else if (ResType->isPlaceholderType()) { 10436 ExprResult PR = S.CheckPlaceholderExpr(Op); 10437 if (PR.isInvalid()) return QualType(); 10438 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 10439 IsInc, IsPrefix); 10440 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 10441 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 10442 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 10443 (ResType->getAs<VectorType>()->getVectorKind() != 10444 VectorType::AltiVecBool)) { 10445 // The z vector extensions allow ++ and -- for non-bool vectors. 10446 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 10447 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 10448 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 10449 } else { 10450 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 10451 << ResType << int(IsInc) << Op->getSourceRange(); 10452 return QualType(); 10453 } 10454 // At this point, we know we have a real, complex or pointer type. 10455 // Now make sure the operand is a modifiable lvalue. 10456 if (CheckForModifiableLvalue(Op, OpLoc, S)) 10457 return QualType(); 10458 // In C++, a prefix increment is the same type as the operand. Otherwise 10459 // (in C or with postfix), the increment is the unqualified type of the 10460 // operand. 10461 if (IsPrefix && S.getLangOpts().CPlusPlus) { 10462 VK = VK_LValue; 10463 OK = Op->getObjectKind(); 10464 return ResType; 10465 } else { 10466 VK = VK_RValue; 10467 return ResType.getUnqualifiedType(); 10468 } 10469 } 10470 10471 10472 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 10473 /// This routine allows us to typecheck complex/recursive expressions 10474 /// where the declaration is needed for type checking. We only need to 10475 /// handle cases when the expression references a function designator 10476 /// or is an lvalue. Here are some examples: 10477 /// - &(x) => x 10478 /// - &*****f => f for f a function designator. 10479 /// - &s.xx => s 10480 /// - &s.zz[1].yy -> s, if zz is an array 10481 /// - *(x + 1) -> x, if x is an array 10482 /// - &"123"[2] -> 0 10483 /// - & __real__ x -> x 10484 static ValueDecl *getPrimaryDecl(Expr *E) { 10485 switch (E->getStmtClass()) { 10486 case Stmt::DeclRefExprClass: 10487 return cast<DeclRefExpr>(E)->getDecl(); 10488 case Stmt::MemberExprClass: 10489 // If this is an arrow operator, the address is an offset from 10490 // the base's value, so the object the base refers to is 10491 // irrelevant. 10492 if (cast<MemberExpr>(E)->isArrow()) 10493 return nullptr; 10494 // Otherwise, the expression refers to a part of the base 10495 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 10496 case Stmt::ArraySubscriptExprClass: { 10497 // FIXME: This code shouldn't be necessary! We should catch the implicit 10498 // promotion of register arrays earlier. 10499 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 10500 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 10501 if (ICE->getSubExpr()->getType()->isArrayType()) 10502 return getPrimaryDecl(ICE->getSubExpr()); 10503 } 10504 return nullptr; 10505 } 10506 case Stmt::UnaryOperatorClass: { 10507 UnaryOperator *UO = cast<UnaryOperator>(E); 10508 10509 switch(UO->getOpcode()) { 10510 case UO_Real: 10511 case UO_Imag: 10512 case UO_Extension: 10513 return getPrimaryDecl(UO->getSubExpr()); 10514 default: 10515 return nullptr; 10516 } 10517 } 10518 case Stmt::ParenExprClass: 10519 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 10520 case Stmt::ImplicitCastExprClass: 10521 // If the result of an implicit cast is an l-value, we care about 10522 // the sub-expression; otherwise, the result here doesn't matter. 10523 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 10524 default: 10525 return nullptr; 10526 } 10527 } 10528 10529 namespace { 10530 enum { 10531 AO_Bit_Field = 0, 10532 AO_Vector_Element = 1, 10533 AO_Property_Expansion = 2, 10534 AO_Register_Variable = 3, 10535 AO_No_Error = 4 10536 }; 10537 } 10538 /// \brief Diagnose invalid operand for address of operations. 10539 /// 10540 /// \param Type The type of operand which cannot have its address taken. 10541 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 10542 Expr *E, unsigned Type) { 10543 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 10544 } 10545 10546 /// CheckAddressOfOperand - The operand of & must be either a function 10547 /// designator or an lvalue designating an object. If it is an lvalue, the 10548 /// object cannot be declared with storage class register or be a bit field. 10549 /// Note: The usual conversions are *not* applied to the operand of the & 10550 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 10551 /// In C++, the operand might be an overloaded function name, in which case 10552 /// we allow the '&' but retain the overloaded-function type. 10553 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 10554 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 10555 if (PTy->getKind() == BuiltinType::Overload) { 10556 Expr *E = OrigOp.get()->IgnoreParens(); 10557 if (!isa<OverloadExpr>(E)) { 10558 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 10559 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 10560 << OrigOp.get()->getSourceRange(); 10561 return QualType(); 10562 } 10563 10564 OverloadExpr *Ovl = cast<OverloadExpr>(E); 10565 if (isa<UnresolvedMemberExpr>(Ovl)) 10566 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 10567 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10568 << OrigOp.get()->getSourceRange(); 10569 return QualType(); 10570 } 10571 10572 return Context.OverloadTy; 10573 } 10574 10575 if (PTy->getKind() == BuiltinType::UnknownAny) 10576 return Context.UnknownAnyTy; 10577 10578 if (PTy->getKind() == BuiltinType::BoundMember) { 10579 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10580 << OrigOp.get()->getSourceRange(); 10581 return QualType(); 10582 } 10583 10584 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 10585 if (OrigOp.isInvalid()) return QualType(); 10586 } 10587 10588 if (OrigOp.get()->isTypeDependent()) 10589 return Context.DependentTy; 10590 10591 assert(!OrigOp.get()->getType()->isPlaceholderType()); 10592 10593 // Make sure to ignore parentheses in subsequent checks 10594 Expr *op = OrigOp.get()->IgnoreParens(); 10595 10596 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 10597 if (LangOpts.OpenCL && op->getType()->isFunctionType()) { 10598 Diag(op->getExprLoc(), diag::err_opencl_taking_function_address); 10599 return QualType(); 10600 } 10601 10602 if (getLangOpts().C99) { 10603 // Implement C99-only parts of addressof rules. 10604 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 10605 if (uOp->getOpcode() == UO_Deref) 10606 // Per C99 6.5.3.2, the address of a deref always returns a valid result 10607 // (assuming the deref expression is valid). 10608 return uOp->getSubExpr()->getType(); 10609 } 10610 // Technically, there should be a check for array subscript 10611 // expressions here, but the result of one is always an lvalue anyway. 10612 } 10613 ValueDecl *dcl = getPrimaryDecl(op); 10614 10615 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 10616 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 10617 op->getLocStart())) 10618 return QualType(); 10619 10620 Expr::LValueClassification lval = op->ClassifyLValue(Context); 10621 unsigned AddressOfError = AO_No_Error; 10622 10623 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 10624 bool sfinae = (bool)isSFINAEContext(); 10625 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 10626 : diag::ext_typecheck_addrof_temporary) 10627 << op->getType() << op->getSourceRange(); 10628 if (sfinae) 10629 return QualType(); 10630 // Materialize the temporary as an lvalue so that we can take its address. 10631 OrigOp = op = 10632 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 10633 } else if (isa<ObjCSelectorExpr>(op)) { 10634 return Context.getPointerType(op->getType()); 10635 } else if (lval == Expr::LV_MemberFunction) { 10636 // If it's an instance method, make a member pointer. 10637 // The expression must have exactly the form &A::foo. 10638 10639 // If the underlying expression isn't a decl ref, give up. 10640 if (!isa<DeclRefExpr>(op)) { 10641 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10642 << OrigOp.get()->getSourceRange(); 10643 return QualType(); 10644 } 10645 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 10646 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 10647 10648 // The id-expression was parenthesized. 10649 if (OrigOp.get() != DRE) { 10650 Diag(OpLoc, diag::err_parens_pointer_member_function) 10651 << OrigOp.get()->getSourceRange(); 10652 10653 // The method was named without a qualifier. 10654 } else if (!DRE->getQualifier()) { 10655 if (MD->getParent()->getName().empty()) 10656 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 10657 << op->getSourceRange(); 10658 else { 10659 SmallString<32> Str; 10660 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 10661 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 10662 << op->getSourceRange() 10663 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 10664 } 10665 } 10666 10667 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 10668 if (isa<CXXDestructorDecl>(MD)) 10669 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 10670 10671 QualType MPTy = Context.getMemberPointerType( 10672 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 10673 // Under the MS ABI, lock down the inheritance model now. 10674 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 10675 (void)isCompleteType(OpLoc, MPTy); 10676 return MPTy; 10677 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 10678 // C99 6.5.3.2p1 10679 // The operand must be either an l-value or a function designator 10680 if (!op->getType()->isFunctionType()) { 10681 // Use a special diagnostic for loads from property references. 10682 if (isa<PseudoObjectExpr>(op)) { 10683 AddressOfError = AO_Property_Expansion; 10684 } else { 10685 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 10686 << op->getType() << op->getSourceRange(); 10687 return QualType(); 10688 } 10689 } 10690 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 10691 // The operand cannot be a bit-field 10692 AddressOfError = AO_Bit_Field; 10693 } else if (op->getObjectKind() == OK_VectorComponent) { 10694 // The operand cannot be an element of a vector 10695 AddressOfError = AO_Vector_Element; 10696 } else if (dcl) { // C99 6.5.3.2p1 10697 // We have an lvalue with a decl. Make sure the decl is not declared 10698 // with the register storage-class specifier. 10699 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 10700 // in C++ it is not error to take address of a register 10701 // variable (c++03 7.1.1P3) 10702 if (vd->getStorageClass() == SC_Register && 10703 !getLangOpts().CPlusPlus) { 10704 AddressOfError = AO_Register_Variable; 10705 } 10706 } else if (isa<MSPropertyDecl>(dcl)) { 10707 AddressOfError = AO_Property_Expansion; 10708 } else if (isa<FunctionTemplateDecl>(dcl)) { 10709 return Context.OverloadTy; 10710 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 10711 // Okay: we can take the address of a field. 10712 // Could be a pointer to member, though, if there is an explicit 10713 // scope qualifier for the class. 10714 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 10715 DeclContext *Ctx = dcl->getDeclContext(); 10716 if (Ctx && Ctx->isRecord()) { 10717 if (dcl->getType()->isReferenceType()) { 10718 Diag(OpLoc, 10719 diag::err_cannot_form_pointer_to_member_of_reference_type) 10720 << dcl->getDeclName() << dcl->getType(); 10721 return QualType(); 10722 } 10723 10724 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 10725 Ctx = Ctx->getParent(); 10726 10727 QualType MPTy = Context.getMemberPointerType( 10728 op->getType(), 10729 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 10730 // Under the MS ABI, lock down the inheritance model now. 10731 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 10732 (void)isCompleteType(OpLoc, MPTy); 10733 return MPTy; 10734 } 10735 } 10736 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 10737 !isa<BindingDecl>(dcl)) 10738 llvm_unreachable("Unknown/unexpected decl type"); 10739 } 10740 10741 if (AddressOfError != AO_No_Error) { 10742 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 10743 return QualType(); 10744 } 10745 10746 if (lval == Expr::LV_IncompleteVoidType) { 10747 // Taking the address of a void variable is technically illegal, but we 10748 // allow it in cases which are otherwise valid. 10749 // Example: "extern void x; void* y = &x;". 10750 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 10751 } 10752 10753 // If the operand has type "type", the result has type "pointer to type". 10754 if (op->getType()->isObjCObjectType()) 10755 return Context.getObjCObjectPointerType(op->getType()); 10756 10757 CheckAddressOfPackedMember(op); 10758 10759 return Context.getPointerType(op->getType()); 10760 } 10761 10762 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 10763 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 10764 if (!DRE) 10765 return; 10766 const Decl *D = DRE->getDecl(); 10767 if (!D) 10768 return; 10769 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 10770 if (!Param) 10771 return; 10772 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 10773 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 10774 return; 10775 if (FunctionScopeInfo *FD = S.getCurFunction()) 10776 if (!FD->ModifiedNonNullParams.count(Param)) 10777 FD->ModifiedNonNullParams.insert(Param); 10778 } 10779 10780 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 10781 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 10782 SourceLocation OpLoc) { 10783 if (Op->isTypeDependent()) 10784 return S.Context.DependentTy; 10785 10786 ExprResult ConvResult = S.UsualUnaryConversions(Op); 10787 if (ConvResult.isInvalid()) 10788 return QualType(); 10789 Op = ConvResult.get(); 10790 QualType OpTy = Op->getType(); 10791 QualType Result; 10792 10793 if (isa<CXXReinterpretCastExpr>(Op)) { 10794 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 10795 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 10796 Op->getSourceRange()); 10797 } 10798 10799 if (const PointerType *PT = OpTy->getAs<PointerType>()) 10800 { 10801 Result = PT->getPointeeType(); 10802 } 10803 else if (const ObjCObjectPointerType *OPT = 10804 OpTy->getAs<ObjCObjectPointerType>()) 10805 Result = OPT->getPointeeType(); 10806 else { 10807 ExprResult PR = S.CheckPlaceholderExpr(Op); 10808 if (PR.isInvalid()) return QualType(); 10809 if (PR.get() != Op) 10810 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 10811 } 10812 10813 if (Result.isNull()) { 10814 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 10815 << OpTy << Op->getSourceRange(); 10816 return QualType(); 10817 } 10818 10819 // Note that per both C89 and C99, indirection is always legal, even if Result 10820 // is an incomplete type or void. It would be possible to warn about 10821 // dereferencing a void pointer, but it's completely well-defined, and such a 10822 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 10823 // for pointers to 'void' but is fine for any other pointer type: 10824 // 10825 // C++ [expr.unary.op]p1: 10826 // [...] the expression to which [the unary * operator] is applied shall 10827 // be a pointer to an object type, or a pointer to a function type 10828 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 10829 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 10830 << OpTy << Op->getSourceRange(); 10831 10832 // Dereferences are usually l-values... 10833 VK = VK_LValue; 10834 10835 // ...except that certain expressions are never l-values in C. 10836 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 10837 VK = VK_RValue; 10838 10839 return Result; 10840 } 10841 10842 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 10843 BinaryOperatorKind Opc; 10844 switch (Kind) { 10845 default: llvm_unreachable("Unknown binop!"); 10846 case tok::periodstar: Opc = BO_PtrMemD; break; 10847 case tok::arrowstar: Opc = BO_PtrMemI; break; 10848 case tok::star: Opc = BO_Mul; break; 10849 case tok::slash: Opc = BO_Div; break; 10850 case tok::percent: Opc = BO_Rem; break; 10851 case tok::plus: Opc = BO_Add; break; 10852 case tok::minus: Opc = BO_Sub; break; 10853 case tok::lessless: Opc = BO_Shl; break; 10854 case tok::greatergreater: Opc = BO_Shr; break; 10855 case tok::lessequal: Opc = BO_LE; break; 10856 case tok::less: Opc = BO_LT; break; 10857 case tok::greaterequal: Opc = BO_GE; break; 10858 case tok::greater: Opc = BO_GT; break; 10859 case tok::exclaimequal: Opc = BO_NE; break; 10860 case tok::equalequal: Opc = BO_EQ; break; 10861 case tok::amp: Opc = BO_And; break; 10862 case tok::caret: Opc = BO_Xor; break; 10863 case tok::pipe: Opc = BO_Or; break; 10864 case tok::ampamp: Opc = BO_LAnd; break; 10865 case tok::pipepipe: Opc = BO_LOr; break; 10866 case tok::equal: Opc = BO_Assign; break; 10867 case tok::starequal: Opc = BO_MulAssign; break; 10868 case tok::slashequal: Opc = BO_DivAssign; break; 10869 case tok::percentequal: Opc = BO_RemAssign; break; 10870 case tok::plusequal: Opc = BO_AddAssign; break; 10871 case tok::minusequal: Opc = BO_SubAssign; break; 10872 case tok::lesslessequal: Opc = BO_ShlAssign; break; 10873 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 10874 case tok::ampequal: Opc = BO_AndAssign; break; 10875 case tok::caretequal: Opc = BO_XorAssign; break; 10876 case tok::pipeequal: Opc = BO_OrAssign; break; 10877 case tok::comma: Opc = BO_Comma; break; 10878 } 10879 return Opc; 10880 } 10881 10882 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 10883 tok::TokenKind Kind) { 10884 UnaryOperatorKind Opc; 10885 switch (Kind) { 10886 default: llvm_unreachable("Unknown unary op!"); 10887 case tok::plusplus: Opc = UO_PreInc; break; 10888 case tok::minusminus: Opc = UO_PreDec; break; 10889 case tok::amp: Opc = UO_AddrOf; break; 10890 case tok::star: Opc = UO_Deref; break; 10891 case tok::plus: Opc = UO_Plus; break; 10892 case tok::minus: Opc = UO_Minus; break; 10893 case tok::tilde: Opc = UO_Not; break; 10894 case tok::exclaim: Opc = UO_LNot; break; 10895 case tok::kw___real: Opc = UO_Real; break; 10896 case tok::kw___imag: Opc = UO_Imag; break; 10897 case tok::kw___extension__: Opc = UO_Extension; break; 10898 } 10899 return Opc; 10900 } 10901 10902 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 10903 /// This warning is only emitted for builtin assignment operations. It is also 10904 /// suppressed in the event of macro expansions. 10905 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 10906 SourceLocation OpLoc) { 10907 if (!S.ActiveTemplateInstantiations.empty()) 10908 return; 10909 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 10910 return; 10911 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 10912 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 10913 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 10914 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 10915 if (!LHSDeclRef || !RHSDeclRef || 10916 LHSDeclRef->getLocation().isMacroID() || 10917 RHSDeclRef->getLocation().isMacroID()) 10918 return; 10919 const ValueDecl *LHSDecl = 10920 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 10921 const ValueDecl *RHSDecl = 10922 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 10923 if (LHSDecl != RHSDecl) 10924 return; 10925 if (LHSDecl->getType().isVolatileQualified()) 10926 return; 10927 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 10928 if (RefTy->getPointeeType().isVolatileQualified()) 10929 return; 10930 10931 S.Diag(OpLoc, diag::warn_self_assignment) 10932 << LHSDeclRef->getType() 10933 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10934 } 10935 10936 /// Check if a bitwise-& is performed on an Objective-C pointer. This 10937 /// is usually indicative of introspection within the Objective-C pointer. 10938 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 10939 SourceLocation OpLoc) { 10940 if (!S.getLangOpts().ObjC1) 10941 return; 10942 10943 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 10944 const Expr *LHS = L.get(); 10945 const Expr *RHS = R.get(); 10946 10947 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 10948 ObjCPointerExpr = LHS; 10949 OtherExpr = RHS; 10950 } 10951 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 10952 ObjCPointerExpr = RHS; 10953 OtherExpr = LHS; 10954 } 10955 10956 // This warning is deliberately made very specific to reduce false 10957 // positives with logic that uses '&' for hashing. This logic mainly 10958 // looks for code trying to introspect into tagged pointers, which 10959 // code should generally never do. 10960 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 10961 unsigned Diag = diag::warn_objc_pointer_masking; 10962 // Determine if we are introspecting the result of performSelectorXXX. 10963 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 10964 // Special case messages to -performSelector and friends, which 10965 // can return non-pointer values boxed in a pointer value. 10966 // Some clients may wish to silence warnings in this subcase. 10967 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 10968 Selector S = ME->getSelector(); 10969 StringRef SelArg0 = S.getNameForSlot(0); 10970 if (SelArg0.startswith("performSelector")) 10971 Diag = diag::warn_objc_pointer_masking_performSelector; 10972 } 10973 10974 S.Diag(OpLoc, Diag) 10975 << ObjCPointerExpr->getSourceRange(); 10976 } 10977 } 10978 10979 static NamedDecl *getDeclFromExpr(Expr *E) { 10980 if (!E) 10981 return nullptr; 10982 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 10983 return DRE->getDecl(); 10984 if (auto *ME = dyn_cast<MemberExpr>(E)) 10985 return ME->getMemberDecl(); 10986 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 10987 return IRE->getDecl(); 10988 return nullptr; 10989 } 10990 10991 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 10992 /// operator @p Opc at location @c TokLoc. This routine only supports 10993 /// built-in operations; ActOnBinOp handles overloaded operators. 10994 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 10995 BinaryOperatorKind Opc, 10996 Expr *LHSExpr, Expr *RHSExpr) { 10997 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 10998 // The syntax only allows initializer lists on the RHS of assignment, 10999 // so we don't need to worry about accepting invalid code for 11000 // non-assignment operators. 11001 // C++11 5.17p9: 11002 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 11003 // of x = {} is x = T(). 11004 InitializationKind Kind = 11005 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 11006 InitializedEntity Entity = 11007 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 11008 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 11009 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 11010 if (Init.isInvalid()) 11011 return Init; 11012 RHSExpr = Init.get(); 11013 } 11014 11015 ExprResult LHS = LHSExpr, RHS = RHSExpr; 11016 QualType ResultTy; // Result type of the binary operator. 11017 // The following two variables are used for compound assignment operators 11018 QualType CompLHSTy; // Type of LHS after promotions for computation 11019 QualType CompResultTy; // Type of computation result 11020 ExprValueKind VK = VK_RValue; 11021 ExprObjectKind OK = OK_Ordinary; 11022 11023 if (!getLangOpts().CPlusPlus) { 11024 // C cannot handle TypoExpr nodes on either side of a binop because it 11025 // doesn't handle dependent types properly, so make sure any TypoExprs have 11026 // been dealt with before checking the operands. 11027 LHS = CorrectDelayedTyposInExpr(LHSExpr); 11028 RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) { 11029 if (Opc != BO_Assign) 11030 return ExprResult(E); 11031 // Avoid correcting the RHS to the same Expr as the LHS. 11032 Decl *D = getDeclFromExpr(E); 11033 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 11034 }); 11035 if (!LHS.isUsable() || !RHS.isUsable()) 11036 return ExprError(); 11037 } 11038 11039 if (getLangOpts().OpenCL) { 11040 QualType LHSTy = LHSExpr->getType(); 11041 QualType RHSTy = RHSExpr->getType(); 11042 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 11043 // the ATOMIC_VAR_INIT macro. 11044 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 11045 SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 11046 if (BO_Assign == Opc) 11047 Diag(OpLoc, diag::err_atomic_init_constant) << SR; 11048 else 11049 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 11050 return ExprError(); 11051 } 11052 11053 // OpenCL special types - image, sampler, pipe, and blocks are to be used 11054 // only with a builtin functions and therefore should be disallowed here. 11055 if (LHSTy->isImageType() || RHSTy->isImageType() || 11056 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 11057 LHSTy->isPipeType() || RHSTy->isPipeType() || 11058 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 11059 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 11060 return ExprError(); 11061 } 11062 } 11063 11064 switch (Opc) { 11065 case BO_Assign: 11066 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 11067 if (getLangOpts().CPlusPlus && 11068 LHS.get()->getObjectKind() != OK_ObjCProperty) { 11069 VK = LHS.get()->getValueKind(); 11070 OK = LHS.get()->getObjectKind(); 11071 } 11072 if (!ResultTy.isNull()) { 11073 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 11074 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 11075 } 11076 RecordModifiableNonNullParam(*this, LHS.get()); 11077 break; 11078 case BO_PtrMemD: 11079 case BO_PtrMemI: 11080 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 11081 Opc == BO_PtrMemI); 11082 break; 11083 case BO_Mul: 11084 case BO_Div: 11085 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 11086 Opc == BO_Div); 11087 break; 11088 case BO_Rem: 11089 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 11090 break; 11091 case BO_Add: 11092 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 11093 break; 11094 case BO_Sub: 11095 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 11096 break; 11097 case BO_Shl: 11098 case BO_Shr: 11099 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 11100 break; 11101 case BO_LE: 11102 case BO_LT: 11103 case BO_GE: 11104 case BO_GT: 11105 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 11106 break; 11107 case BO_EQ: 11108 case BO_NE: 11109 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 11110 break; 11111 case BO_And: 11112 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 11113 case BO_Xor: 11114 case BO_Or: 11115 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 11116 break; 11117 case BO_LAnd: 11118 case BO_LOr: 11119 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 11120 break; 11121 case BO_MulAssign: 11122 case BO_DivAssign: 11123 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 11124 Opc == BO_DivAssign); 11125 CompLHSTy = CompResultTy; 11126 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11127 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11128 break; 11129 case BO_RemAssign: 11130 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 11131 CompLHSTy = CompResultTy; 11132 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11133 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11134 break; 11135 case BO_AddAssign: 11136 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 11137 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11138 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11139 break; 11140 case BO_SubAssign: 11141 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 11142 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11143 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11144 break; 11145 case BO_ShlAssign: 11146 case BO_ShrAssign: 11147 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 11148 CompLHSTy = CompResultTy; 11149 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11150 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11151 break; 11152 case BO_AndAssign: 11153 case BO_OrAssign: // fallthrough 11154 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 11155 case BO_XorAssign: 11156 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 11157 CompLHSTy = CompResultTy; 11158 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11159 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11160 break; 11161 case BO_Comma: 11162 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 11163 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 11164 VK = RHS.get()->getValueKind(); 11165 OK = RHS.get()->getObjectKind(); 11166 } 11167 break; 11168 } 11169 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 11170 return ExprError(); 11171 11172 // Check for array bounds violations for both sides of the BinaryOperator 11173 CheckArrayAccess(LHS.get()); 11174 CheckArrayAccess(RHS.get()); 11175 11176 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 11177 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 11178 &Context.Idents.get("object_setClass"), 11179 SourceLocation(), LookupOrdinaryName); 11180 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 11181 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd()); 11182 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 11183 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 11184 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 11185 FixItHint::CreateInsertion(RHSLocEnd, ")"); 11186 } 11187 else 11188 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 11189 } 11190 else if (const ObjCIvarRefExpr *OIRE = 11191 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 11192 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 11193 11194 if (CompResultTy.isNull()) 11195 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 11196 OK, OpLoc, FPFeatures.fp_contract); 11197 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 11198 OK_ObjCProperty) { 11199 VK = VK_LValue; 11200 OK = LHS.get()->getObjectKind(); 11201 } 11202 return new (Context) CompoundAssignOperator( 11203 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 11204 OpLoc, FPFeatures.fp_contract); 11205 } 11206 11207 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 11208 /// operators are mixed in a way that suggests that the programmer forgot that 11209 /// comparison operators have higher precedence. The most typical example of 11210 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 11211 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 11212 SourceLocation OpLoc, Expr *LHSExpr, 11213 Expr *RHSExpr) { 11214 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 11215 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 11216 11217 // Check that one of the sides is a comparison operator and the other isn't. 11218 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 11219 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 11220 if (isLeftComp == isRightComp) 11221 return; 11222 11223 // Bitwise operations are sometimes used as eager logical ops. 11224 // Don't diagnose this. 11225 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 11226 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 11227 if (isLeftBitwise || isRightBitwise) 11228 return; 11229 11230 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 11231 OpLoc) 11232 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 11233 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 11234 SourceRange ParensRange = isLeftComp ? 11235 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 11236 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd()); 11237 11238 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 11239 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 11240 SuggestParentheses(Self, OpLoc, 11241 Self.PDiag(diag::note_precedence_silence) << OpStr, 11242 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 11243 SuggestParentheses(Self, OpLoc, 11244 Self.PDiag(diag::note_precedence_bitwise_first) 11245 << BinaryOperator::getOpcodeStr(Opc), 11246 ParensRange); 11247 } 11248 11249 /// \brief It accepts a '&&' expr that is inside a '||' one. 11250 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 11251 /// in parentheses. 11252 static void 11253 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 11254 BinaryOperator *Bop) { 11255 assert(Bop->getOpcode() == BO_LAnd); 11256 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 11257 << Bop->getSourceRange() << OpLoc; 11258 SuggestParentheses(Self, Bop->getOperatorLoc(), 11259 Self.PDiag(diag::note_precedence_silence) 11260 << Bop->getOpcodeStr(), 11261 Bop->getSourceRange()); 11262 } 11263 11264 /// \brief Returns true if the given expression can be evaluated as a constant 11265 /// 'true'. 11266 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 11267 bool Res; 11268 return !E->isValueDependent() && 11269 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 11270 } 11271 11272 /// \brief Returns true if the given expression can be evaluated as a constant 11273 /// 'false'. 11274 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 11275 bool Res; 11276 return !E->isValueDependent() && 11277 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 11278 } 11279 11280 /// \brief Look for '&&' in the left hand of a '||' expr. 11281 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 11282 Expr *LHSExpr, Expr *RHSExpr) { 11283 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 11284 if (Bop->getOpcode() == BO_LAnd) { 11285 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 11286 if (EvaluatesAsFalse(S, RHSExpr)) 11287 return; 11288 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 11289 if (!EvaluatesAsTrue(S, Bop->getLHS())) 11290 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11291 } else if (Bop->getOpcode() == BO_LOr) { 11292 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 11293 // If it's "a || b && 1 || c" we didn't warn earlier for 11294 // "a || b && 1", but warn now. 11295 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 11296 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 11297 } 11298 } 11299 } 11300 } 11301 11302 /// \brief Look for '&&' in the right hand of a '||' expr. 11303 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 11304 Expr *LHSExpr, Expr *RHSExpr) { 11305 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 11306 if (Bop->getOpcode() == BO_LAnd) { 11307 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 11308 if (EvaluatesAsFalse(S, LHSExpr)) 11309 return; 11310 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 11311 if (!EvaluatesAsTrue(S, Bop->getRHS())) 11312 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11313 } 11314 } 11315 } 11316 11317 /// \brief Look for bitwise op in the left or right hand of a bitwise op with 11318 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 11319 /// the '&' expression in parentheses. 11320 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 11321 SourceLocation OpLoc, Expr *SubExpr) { 11322 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11323 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 11324 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 11325 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 11326 << Bop->getSourceRange() << OpLoc; 11327 SuggestParentheses(S, Bop->getOperatorLoc(), 11328 S.PDiag(diag::note_precedence_silence) 11329 << Bop->getOpcodeStr(), 11330 Bop->getSourceRange()); 11331 } 11332 } 11333 } 11334 11335 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 11336 Expr *SubExpr, StringRef Shift) { 11337 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11338 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 11339 StringRef Op = Bop->getOpcodeStr(); 11340 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 11341 << Bop->getSourceRange() << OpLoc << Shift << Op; 11342 SuggestParentheses(S, Bop->getOperatorLoc(), 11343 S.PDiag(diag::note_precedence_silence) << Op, 11344 Bop->getSourceRange()); 11345 } 11346 } 11347 } 11348 11349 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 11350 Expr *LHSExpr, Expr *RHSExpr) { 11351 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 11352 if (!OCE) 11353 return; 11354 11355 FunctionDecl *FD = OCE->getDirectCallee(); 11356 if (!FD || !FD->isOverloadedOperator()) 11357 return; 11358 11359 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 11360 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 11361 return; 11362 11363 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 11364 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 11365 << (Kind == OO_LessLess); 11366 SuggestParentheses(S, OCE->getOperatorLoc(), 11367 S.PDiag(diag::note_precedence_silence) 11368 << (Kind == OO_LessLess ? "<<" : ">>"), 11369 OCE->getSourceRange()); 11370 SuggestParentheses(S, OpLoc, 11371 S.PDiag(diag::note_evaluate_comparison_first), 11372 SourceRange(OCE->getArg(1)->getLocStart(), 11373 RHSExpr->getLocEnd())); 11374 } 11375 11376 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 11377 /// precedence. 11378 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 11379 SourceLocation OpLoc, Expr *LHSExpr, 11380 Expr *RHSExpr){ 11381 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 11382 if (BinaryOperator::isBitwiseOp(Opc)) 11383 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 11384 11385 // Diagnose "arg1 & arg2 | arg3" 11386 if ((Opc == BO_Or || Opc == BO_Xor) && 11387 !OpLoc.isMacroID()/* Don't warn in macros. */) { 11388 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 11389 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 11390 } 11391 11392 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 11393 // We don't warn for 'assert(a || b && "bad")' since this is safe. 11394 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 11395 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 11396 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 11397 } 11398 11399 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 11400 || Opc == BO_Shr) { 11401 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 11402 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 11403 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 11404 } 11405 11406 // Warn on overloaded shift operators and comparisons, such as: 11407 // cout << 5 == 4; 11408 if (BinaryOperator::isComparisonOp(Opc)) 11409 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 11410 } 11411 11412 // Binary Operators. 'Tok' is the token for the operator. 11413 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 11414 tok::TokenKind Kind, 11415 Expr *LHSExpr, Expr *RHSExpr) { 11416 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 11417 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 11418 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 11419 11420 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 11421 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 11422 11423 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 11424 } 11425 11426 /// Build an overloaded binary operator expression in the given scope. 11427 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 11428 BinaryOperatorKind Opc, 11429 Expr *LHS, Expr *RHS) { 11430 // Find all of the overloaded operators visible from this 11431 // point. We perform both an operator-name lookup from the local 11432 // scope and an argument-dependent lookup based on the types of 11433 // the arguments. 11434 UnresolvedSet<16> Functions; 11435 OverloadedOperatorKind OverOp 11436 = BinaryOperator::getOverloadedOperator(Opc); 11437 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 11438 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 11439 RHS->getType(), Functions); 11440 11441 // Build the (potentially-overloaded, potentially-dependent) 11442 // binary operation. 11443 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 11444 } 11445 11446 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 11447 BinaryOperatorKind Opc, 11448 Expr *LHSExpr, Expr *RHSExpr) { 11449 // We want to end up calling one of checkPseudoObjectAssignment 11450 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 11451 // both expressions are overloadable or either is type-dependent), 11452 // or CreateBuiltinBinOp (in any other case). We also want to get 11453 // any placeholder types out of the way. 11454 11455 // Handle pseudo-objects in the LHS. 11456 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 11457 // Assignments with a pseudo-object l-value need special analysis. 11458 if (pty->getKind() == BuiltinType::PseudoObject && 11459 BinaryOperator::isAssignmentOp(Opc)) 11460 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 11461 11462 // Don't resolve overloads if the other type is overloadable. 11463 if (pty->getKind() == BuiltinType::Overload) { 11464 // We can't actually test that if we still have a placeholder, 11465 // though. Fortunately, none of the exceptions we see in that 11466 // code below are valid when the LHS is an overload set. Note 11467 // that an overload set can be dependently-typed, but it never 11468 // instantiates to having an overloadable type. 11469 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 11470 if (resolvedRHS.isInvalid()) return ExprError(); 11471 RHSExpr = resolvedRHS.get(); 11472 11473 if (RHSExpr->isTypeDependent() || 11474 RHSExpr->getType()->isOverloadableType()) 11475 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11476 } 11477 11478 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 11479 if (LHS.isInvalid()) return ExprError(); 11480 LHSExpr = LHS.get(); 11481 } 11482 11483 // Handle pseudo-objects in the RHS. 11484 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 11485 // An overload in the RHS can potentially be resolved by the type 11486 // being assigned to. 11487 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 11488 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 11489 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11490 11491 if (LHSExpr->getType()->isOverloadableType()) 11492 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11493 11494 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 11495 } 11496 11497 // Don't resolve overloads if the other type is overloadable. 11498 if (pty->getKind() == BuiltinType::Overload && 11499 LHSExpr->getType()->isOverloadableType()) 11500 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11501 11502 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 11503 if (!resolvedRHS.isUsable()) return ExprError(); 11504 RHSExpr = resolvedRHS.get(); 11505 } 11506 11507 if (getLangOpts().CPlusPlus) { 11508 // If either expression is type-dependent, always build an 11509 // overloaded op. 11510 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 11511 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11512 11513 // Otherwise, build an overloaded op if either expression has an 11514 // overloadable type. 11515 if (LHSExpr->getType()->isOverloadableType() || 11516 RHSExpr->getType()->isOverloadableType()) 11517 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11518 } 11519 11520 // Build a built-in binary operation. 11521 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 11522 } 11523 11524 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 11525 UnaryOperatorKind Opc, 11526 Expr *InputExpr) { 11527 ExprResult Input = InputExpr; 11528 ExprValueKind VK = VK_RValue; 11529 ExprObjectKind OK = OK_Ordinary; 11530 QualType resultType; 11531 if (getLangOpts().OpenCL) { 11532 QualType Ty = InputExpr->getType(); 11533 // The only legal unary operation for atomics is '&'. 11534 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 11535 // OpenCL special types - image, sampler, pipe, and blocks are to be used 11536 // only with a builtin functions and therefore should be disallowed here. 11537 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 11538 || Ty->isBlockPointerType())) { 11539 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11540 << InputExpr->getType() 11541 << Input.get()->getSourceRange()); 11542 } 11543 } 11544 switch (Opc) { 11545 case UO_PreInc: 11546 case UO_PreDec: 11547 case UO_PostInc: 11548 case UO_PostDec: 11549 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 11550 OpLoc, 11551 Opc == UO_PreInc || 11552 Opc == UO_PostInc, 11553 Opc == UO_PreInc || 11554 Opc == UO_PreDec); 11555 break; 11556 case UO_AddrOf: 11557 resultType = CheckAddressOfOperand(Input, OpLoc); 11558 RecordModifiableNonNullParam(*this, InputExpr); 11559 break; 11560 case UO_Deref: { 11561 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 11562 if (Input.isInvalid()) return ExprError(); 11563 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 11564 break; 11565 } 11566 case UO_Plus: 11567 case UO_Minus: 11568 Input = UsualUnaryConversions(Input.get()); 11569 if (Input.isInvalid()) return ExprError(); 11570 resultType = Input.get()->getType(); 11571 if (resultType->isDependentType()) 11572 break; 11573 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 11574 break; 11575 else if (resultType->isVectorType() && 11576 // The z vector extensions don't allow + or - with bool vectors. 11577 (!Context.getLangOpts().ZVector || 11578 resultType->getAs<VectorType>()->getVectorKind() != 11579 VectorType::AltiVecBool)) 11580 break; 11581 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 11582 Opc == UO_Plus && 11583 resultType->isPointerType()) 11584 break; 11585 11586 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11587 << resultType << Input.get()->getSourceRange()); 11588 11589 case UO_Not: // bitwise complement 11590 Input = UsualUnaryConversions(Input.get()); 11591 if (Input.isInvalid()) 11592 return ExprError(); 11593 resultType = Input.get()->getType(); 11594 if (resultType->isDependentType()) 11595 break; 11596 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 11597 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 11598 // C99 does not support '~' for complex conjugation. 11599 Diag(OpLoc, diag::ext_integer_complement_complex) 11600 << resultType << Input.get()->getSourceRange(); 11601 else if (resultType->hasIntegerRepresentation()) 11602 break; 11603 else if (resultType->isExtVectorType()) { 11604 if (Context.getLangOpts().OpenCL) { 11605 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 11606 // on vector float types. 11607 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 11608 if (!T->isIntegerType()) 11609 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11610 << resultType << Input.get()->getSourceRange()); 11611 } 11612 break; 11613 } else { 11614 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11615 << resultType << Input.get()->getSourceRange()); 11616 } 11617 break; 11618 11619 case UO_LNot: // logical negation 11620 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 11621 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 11622 if (Input.isInvalid()) return ExprError(); 11623 resultType = Input.get()->getType(); 11624 11625 // Though we still have to promote half FP to float... 11626 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 11627 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 11628 resultType = Context.FloatTy; 11629 } 11630 11631 if (resultType->isDependentType()) 11632 break; 11633 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 11634 // C99 6.5.3.3p1: ok, fallthrough; 11635 if (Context.getLangOpts().CPlusPlus) { 11636 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 11637 // operand contextually converted to bool. 11638 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 11639 ScalarTypeToBooleanCastKind(resultType)); 11640 } else if (Context.getLangOpts().OpenCL && 11641 Context.getLangOpts().OpenCLVersion < 120) { 11642 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 11643 // operate on scalar float types. 11644 if (!resultType->isIntegerType()) 11645 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11646 << resultType << Input.get()->getSourceRange()); 11647 } 11648 } else if (resultType->isExtVectorType()) { 11649 if (Context.getLangOpts().OpenCL && 11650 Context.getLangOpts().OpenCLVersion < 120) { 11651 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 11652 // operate on vector float types. 11653 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 11654 if (!T->isIntegerType()) 11655 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11656 << resultType << Input.get()->getSourceRange()); 11657 } 11658 // Vector logical not returns the signed variant of the operand type. 11659 resultType = GetSignedVectorType(resultType); 11660 break; 11661 } else { 11662 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11663 << resultType << Input.get()->getSourceRange()); 11664 } 11665 11666 // LNot always has type int. C99 6.5.3.3p5. 11667 // In C++, it's bool. C++ 5.3.1p8 11668 resultType = Context.getLogicalOperationType(); 11669 break; 11670 case UO_Real: 11671 case UO_Imag: 11672 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 11673 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 11674 // complex l-values to ordinary l-values and all other values to r-values. 11675 if (Input.isInvalid()) return ExprError(); 11676 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 11677 if (Input.get()->getValueKind() != VK_RValue && 11678 Input.get()->getObjectKind() == OK_Ordinary) 11679 VK = Input.get()->getValueKind(); 11680 } else if (!getLangOpts().CPlusPlus) { 11681 // In C, a volatile scalar is read by __imag. In C++, it is not. 11682 Input = DefaultLvalueConversion(Input.get()); 11683 } 11684 break; 11685 case UO_Extension: 11686 case UO_Coawait: 11687 resultType = Input.get()->getType(); 11688 VK = Input.get()->getValueKind(); 11689 OK = Input.get()->getObjectKind(); 11690 break; 11691 } 11692 if (resultType.isNull() || Input.isInvalid()) 11693 return ExprError(); 11694 11695 // Check for array bounds violations in the operand of the UnaryOperator, 11696 // except for the '*' and '&' operators that have to be handled specially 11697 // by CheckArrayAccess (as there are special cases like &array[arraysize] 11698 // that are explicitly defined as valid by the standard). 11699 if (Opc != UO_AddrOf && Opc != UO_Deref) 11700 CheckArrayAccess(Input.get()); 11701 11702 return new (Context) 11703 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc); 11704 } 11705 11706 /// \brief Determine whether the given expression is a qualified member 11707 /// access expression, of a form that could be turned into a pointer to member 11708 /// with the address-of operator. 11709 static bool isQualifiedMemberAccess(Expr *E) { 11710 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11711 if (!DRE->getQualifier()) 11712 return false; 11713 11714 ValueDecl *VD = DRE->getDecl(); 11715 if (!VD->isCXXClassMember()) 11716 return false; 11717 11718 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 11719 return true; 11720 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 11721 return Method->isInstance(); 11722 11723 return false; 11724 } 11725 11726 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 11727 if (!ULE->getQualifier()) 11728 return false; 11729 11730 for (NamedDecl *D : ULE->decls()) { 11731 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 11732 if (Method->isInstance()) 11733 return true; 11734 } else { 11735 // Overload set does not contain methods. 11736 break; 11737 } 11738 } 11739 11740 return false; 11741 } 11742 11743 return false; 11744 } 11745 11746 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 11747 UnaryOperatorKind Opc, Expr *Input) { 11748 // First things first: handle placeholders so that the 11749 // overloaded-operator check considers the right type. 11750 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 11751 // Increment and decrement of pseudo-object references. 11752 if (pty->getKind() == BuiltinType::PseudoObject && 11753 UnaryOperator::isIncrementDecrementOp(Opc)) 11754 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 11755 11756 // extension is always a builtin operator. 11757 if (Opc == UO_Extension) 11758 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11759 11760 // & gets special logic for several kinds of placeholder. 11761 // The builtin code knows what to do. 11762 if (Opc == UO_AddrOf && 11763 (pty->getKind() == BuiltinType::Overload || 11764 pty->getKind() == BuiltinType::UnknownAny || 11765 pty->getKind() == BuiltinType::BoundMember)) 11766 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11767 11768 // Anything else needs to be handled now. 11769 ExprResult Result = CheckPlaceholderExpr(Input); 11770 if (Result.isInvalid()) return ExprError(); 11771 Input = Result.get(); 11772 } 11773 11774 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 11775 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 11776 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 11777 // Find all of the overloaded operators visible from this 11778 // point. We perform both an operator-name lookup from the local 11779 // scope and an argument-dependent lookup based on the types of 11780 // the arguments. 11781 UnresolvedSet<16> Functions; 11782 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 11783 if (S && OverOp != OO_None) 11784 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 11785 Functions); 11786 11787 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 11788 } 11789 11790 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11791 } 11792 11793 // Unary Operators. 'Tok' is the token for the operator. 11794 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 11795 tok::TokenKind Op, Expr *Input) { 11796 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 11797 } 11798 11799 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 11800 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 11801 LabelDecl *TheDecl) { 11802 TheDecl->markUsed(Context); 11803 // Create the AST node. The address of a label always has type 'void*'. 11804 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 11805 Context.getPointerType(Context.VoidTy)); 11806 } 11807 11808 /// Given the last statement in a statement-expression, check whether 11809 /// the result is a producing expression (like a call to an 11810 /// ns_returns_retained function) and, if so, rebuild it to hoist the 11811 /// release out of the full-expression. Otherwise, return null. 11812 /// Cannot fail. 11813 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 11814 // Should always be wrapped with one of these. 11815 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 11816 if (!cleanups) return nullptr; 11817 11818 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 11819 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 11820 return nullptr; 11821 11822 // Splice out the cast. This shouldn't modify any interesting 11823 // features of the statement. 11824 Expr *producer = cast->getSubExpr(); 11825 assert(producer->getType() == cast->getType()); 11826 assert(producer->getValueKind() == cast->getValueKind()); 11827 cleanups->setSubExpr(producer); 11828 return cleanups; 11829 } 11830 11831 void Sema::ActOnStartStmtExpr() { 11832 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 11833 } 11834 11835 void Sema::ActOnStmtExprError() { 11836 // Note that function is also called by TreeTransform when leaving a 11837 // StmtExpr scope without rebuilding anything. 11838 11839 DiscardCleanupsInEvaluationContext(); 11840 PopExpressionEvaluationContext(); 11841 } 11842 11843 ExprResult 11844 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 11845 SourceLocation RPLoc) { // "({..})" 11846 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 11847 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 11848 11849 if (hasAnyUnrecoverableErrorsInThisFunction()) 11850 DiscardCleanupsInEvaluationContext(); 11851 assert(!Cleanup.exprNeedsCleanups() && 11852 "cleanups within StmtExpr not correctly bound!"); 11853 PopExpressionEvaluationContext(); 11854 11855 // FIXME: there are a variety of strange constraints to enforce here, for 11856 // example, it is not possible to goto into a stmt expression apparently. 11857 // More semantic analysis is needed. 11858 11859 // If there are sub-stmts in the compound stmt, take the type of the last one 11860 // as the type of the stmtexpr. 11861 QualType Ty = Context.VoidTy; 11862 bool StmtExprMayBindToTemp = false; 11863 if (!Compound->body_empty()) { 11864 Stmt *LastStmt = Compound->body_back(); 11865 LabelStmt *LastLabelStmt = nullptr; 11866 // If LastStmt is a label, skip down through into the body. 11867 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 11868 LastLabelStmt = Label; 11869 LastStmt = Label->getSubStmt(); 11870 } 11871 11872 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 11873 // Do function/array conversion on the last expression, but not 11874 // lvalue-to-rvalue. However, initialize an unqualified type. 11875 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 11876 if (LastExpr.isInvalid()) 11877 return ExprError(); 11878 Ty = LastExpr.get()->getType().getUnqualifiedType(); 11879 11880 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 11881 // In ARC, if the final expression ends in a consume, splice 11882 // the consume out and bind it later. In the alternate case 11883 // (when dealing with a retainable type), the result 11884 // initialization will create a produce. In both cases the 11885 // result will be +1, and we'll need to balance that out with 11886 // a bind. 11887 if (Expr *rebuiltLastStmt 11888 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 11889 LastExpr = rebuiltLastStmt; 11890 } else { 11891 LastExpr = PerformCopyInitialization( 11892 InitializedEntity::InitializeResult(LPLoc, 11893 Ty, 11894 false), 11895 SourceLocation(), 11896 LastExpr); 11897 } 11898 11899 if (LastExpr.isInvalid()) 11900 return ExprError(); 11901 if (LastExpr.get() != nullptr) { 11902 if (!LastLabelStmt) 11903 Compound->setLastStmt(LastExpr.get()); 11904 else 11905 LastLabelStmt->setSubStmt(LastExpr.get()); 11906 StmtExprMayBindToTemp = true; 11907 } 11908 } 11909 } 11910 } 11911 11912 // FIXME: Check that expression type is complete/non-abstract; statement 11913 // expressions are not lvalues. 11914 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 11915 if (StmtExprMayBindToTemp) 11916 return MaybeBindToTemporary(ResStmtExpr); 11917 return ResStmtExpr; 11918 } 11919 11920 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 11921 TypeSourceInfo *TInfo, 11922 ArrayRef<OffsetOfComponent> Components, 11923 SourceLocation RParenLoc) { 11924 QualType ArgTy = TInfo->getType(); 11925 bool Dependent = ArgTy->isDependentType(); 11926 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 11927 11928 // We must have at least one component that refers to the type, and the first 11929 // one is known to be a field designator. Verify that the ArgTy represents 11930 // a struct/union/class. 11931 if (!Dependent && !ArgTy->isRecordType()) 11932 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 11933 << ArgTy << TypeRange); 11934 11935 // Type must be complete per C99 7.17p3 because a declaring a variable 11936 // with an incomplete type would be ill-formed. 11937 if (!Dependent 11938 && RequireCompleteType(BuiltinLoc, ArgTy, 11939 diag::err_offsetof_incomplete_type, TypeRange)) 11940 return ExprError(); 11941 11942 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 11943 // GCC extension, diagnose them. 11944 // FIXME: This diagnostic isn't actually visible because the location is in 11945 // a system header! 11946 if (Components.size() != 1) 11947 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 11948 << SourceRange(Components[1].LocStart, Components.back().LocEnd); 11949 11950 bool DidWarnAboutNonPOD = false; 11951 QualType CurrentType = ArgTy; 11952 SmallVector<OffsetOfNode, 4> Comps; 11953 SmallVector<Expr*, 4> Exprs; 11954 for (const OffsetOfComponent &OC : Components) { 11955 if (OC.isBrackets) { 11956 // Offset of an array sub-field. TODO: Should we allow vector elements? 11957 if (!CurrentType->isDependentType()) { 11958 const ArrayType *AT = Context.getAsArrayType(CurrentType); 11959 if(!AT) 11960 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 11961 << CurrentType); 11962 CurrentType = AT->getElementType(); 11963 } else 11964 CurrentType = Context.DependentTy; 11965 11966 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 11967 if (IdxRval.isInvalid()) 11968 return ExprError(); 11969 Expr *Idx = IdxRval.get(); 11970 11971 // The expression must be an integral expression. 11972 // FIXME: An integral constant expression? 11973 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 11974 !Idx->getType()->isIntegerType()) 11975 return ExprError(Diag(Idx->getLocStart(), 11976 diag::err_typecheck_subscript_not_integer) 11977 << Idx->getSourceRange()); 11978 11979 // Record this array index. 11980 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 11981 Exprs.push_back(Idx); 11982 continue; 11983 } 11984 11985 // Offset of a field. 11986 if (CurrentType->isDependentType()) { 11987 // We have the offset of a field, but we can't look into the dependent 11988 // type. Just record the identifier of the field. 11989 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 11990 CurrentType = Context.DependentTy; 11991 continue; 11992 } 11993 11994 // We need to have a complete type to look into. 11995 if (RequireCompleteType(OC.LocStart, CurrentType, 11996 diag::err_offsetof_incomplete_type)) 11997 return ExprError(); 11998 11999 // Look for the designated field. 12000 const RecordType *RC = CurrentType->getAs<RecordType>(); 12001 if (!RC) 12002 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 12003 << CurrentType); 12004 RecordDecl *RD = RC->getDecl(); 12005 12006 // C++ [lib.support.types]p5: 12007 // The macro offsetof accepts a restricted set of type arguments in this 12008 // International Standard. type shall be a POD structure or a POD union 12009 // (clause 9). 12010 // C++11 [support.types]p4: 12011 // If type is not a standard-layout class (Clause 9), the results are 12012 // undefined. 12013 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 12014 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 12015 unsigned DiagID = 12016 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 12017 : diag::ext_offsetof_non_pod_type; 12018 12019 if (!IsSafe && !DidWarnAboutNonPOD && 12020 DiagRuntimeBehavior(BuiltinLoc, nullptr, 12021 PDiag(DiagID) 12022 << SourceRange(Components[0].LocStart, OC.LocEnd) 12023 << CurrentType)) 12024 DidWarnAboutNonPOD = true; 12025 } 12026 12027 // Look for the field. 12028 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 12029 LookupQualifiedName(R, RD); 12030 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 12031 IndirectFieldDecl *IndirectMemberDecl = nullptr; 12032 if (!MemberDecl) { 12033 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 12034 MemberDecl = IndirectMemberDecl->getAnonField(); 12035 } 12036 12037 if (!MemberDecl) 12038 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 12039 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 12040 OC.LocEnd)); 12041 12042 // C99 7.17p3: 12043 // (If the specified member is a bit-field, the behavior is undefined.) 12044 // 12045 // We diagnose this as an error. 12046 if (MemberDecl->isBitField()) { 12047 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 12048 << MemberDecl->getDeclName() 12049 << SourceRange(BuiltinLoc, RParenLoc); 12050 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 12051 return ExprError(); 12052 } 12053 12054 RecordDecl *Parent = MemberDecl->getParent(); 12055 if (IndirectMemberDecl) 12056 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 12057 12058 // If the member was found in a base class, introduce OffsetOfNodes for 12059 // the base class indirections. 12060 CXXBasePaths Paths; 12061 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 12062 Paths)) { 12063 if (Paths.getDetectedVirtual()) { 12064 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 12065 << MemberDecl->getDeclName() 12066 << SourceRange(BuiltinLoc, RParenLoc); 12067 return ExprError(); 12068 } 12069 12070 CXXBasePath &Path = Paths.front(); 12071 for (const CXXBasePathElement &B : Path) 12072 Comps.push_back(OffsetOfNode(B.Base)); 12073 } 12074 12075 if (IndirectMemberDecl) { 12076 for (auto *FI : IndirectMemberDecl->chain()) { 12077 assert(isa<FieldDecl>(FI)); 12078 Comps.push_back(OffsetOfNode(OC.LocStart, 12079 cast<FieldDecl>(FI), OC.LocEnd)); 12080 } 12081 } else 12082 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 12083 12084 CurrentType = MemberDecl->getType().getNonReferenceType(); 12085 } 12086 12087 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 12088 Comps, Exprs, RParenLoc); 12089 } 12090 12091 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 12092 SourceLocation BuiltinLoc, 12093 SourceLocation TypeLoc, 12094 ParsedType ParsedArgTy, 12095 ArrayRef<OffsetOfComponent> Components, 12096 SourceLocation RParenLoc) { 12097 12098 TypeSourceInfo *ArgTInfo; 12099 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 12100 if (ArgTy.isNull()) 12101 return ExprError(); 12102 12103 if (!ArgTInfo) 12104 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 12105 12106 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 12107 } 12108 12109 12110 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 12111 Expr *CondExpr, 12112 Expr *LHSExpr, Expr *RHSExpr, 12113 SourceLocation RPLoc) { 12114 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 12115 12116 ExprValueKind VK = VK_RValue; 12117 ExprObjectKind OK = OK_Ordinary; 12118 QualType resType; 12119 bool ValueDependent = false; 12120 bool CondIsTrue = false; 12121 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 12122 resType = Context.DependentTy; 12123 ValueDependent = true; 12124 } else { 12125 // The conditional expression is required to be a constant expression. 12126 llvm::APSInt condEval(32); 12127 ExprResult CondICE 12128 = VerifyIntegerConstantExpression(CondExpr, &condEval, 12129 diag::err_typecheck_choose_expr_requires_constant, false); 12130 if (CondICE.isInvalid()) 12131 return ExprError(); 12132 CondExpr = CondICE.get(); 12133 CondIsTrue = condEval.getZExtValue(); 12134 12135 // If the condition is > zero, then the AST type is the same as the LSHExpr. 12136 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 12137 12138 resType = ActiveExpr->getType(); 12139 ValueDependent = ActiveExpr->isValueDependent(); 12140 VK = ActiveExpr->getValueKind(); 12141 OK = ActiveExpr->getObjectKind(); 12142 } 12143 12144 return new (Context) 12145 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 12146 CondIsTrue, resType->isDependentType(), ValueDependent); 12147 } 12148 12149 //===----------------------------------------------------------------------===// 12150 // Clang Extensions. 12151 //===----------------------------------------------------------------------===// 12152 12153 /// ActOnBlockStart - This callback is invoked when a block literal is started. 12154 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 12155 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 12156 12157 if (LangOpts.CPlusPlus) { 12158 Decl *ManglingContextDecl; 12159 if (MangleNumberingContext *MCtx = 12160 getCurrentMangleNumberContext(Block->getDeclContext(), 12161 ManglingContextDecl)) { 12162 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 12163 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 12164 } 12165 } 12166 12167 PushBlockScope(CurScope, Block); 12168 CurContext->addDecl(Block); 12169 if (CurScope) 12170 PushDeclContext(CurScope, Block); 12171 else 12172 CurContext = Block; 12173 12174 getCurBlock()->HasImplicitReturnType = true; 12175 12176 // Enter a new evaluation context to insulate the block from any 12177 // cleanups from the enclosing full-expression. 12178 PushExpressionEvaluationContext(PotentiallyEvaluated); 12179 } 12180 12181 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 12182 Scope *CurScope) { 12183 assert(ParamInfo.getIdentifier() == nullptr && 12184 "block-id should have no identifier!"); 12185 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 12186 BlockScopeInfo *CurBlock = getCurBlock(); 12187 12188 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 12189 QualType T = Sig->getType(); 12190 12191 // FIXME: We should allow unexpanded parameter packs here, but that would, 12192 // in turn, make the block expression contain unexpanded parameter packs. 12193 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 12194 // Drop the parameters. 12195 FunctionProtoType::ExtProtoInfo EPI; 12196 EPI.HasTrailingReturn = false; 12197 EPI.TypeQuals |= DeclSpec::TQ_const; 12198 T = Context.getFunctionType(Context.DependentTy, None, EPI); 12199 Sig = Context.getTrivialTypeSourceInfo(T); 12200 } 12201 12202 // GetTypeForDeclarator always produces a function type for a block 12203 // literal signature. Furthermore, it is always a FunctionProtoType 12204 // unless the function was written with a typedef. 12205 assert(T->isFunctionType() && 12206 "GetTypeForDeclarator made a non-function block signature"); 12207 12208 // Look for an explicit signature in that function type. 12209 FunctionProtoTypeLoc ExplicitSignature; 12210 12211 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 12212 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) { 12213 12214 // Check whether that explicit signature was synthesized by 12215 // GetTypeForDeclarator. If so, don't save that as part of the 12216 // written signature. 12217 if (ExplicitSignature.getLocalRangeBegin() == 12218 ExplicitSignature.getLocalRangeEnd()) { 12219 // This would be much cheaper if we stored TypeLocs instead of 12220 // TypeSourceInfos. 12221 TypeLoc Result = ExplicitSignature.getReturnLoc(); 12222 unsigned Size = Result.getFullDataSize(); 12223 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 12224 Sig->getTypeLoc().initializeFullCopy(Result, Size); 12225 12226 ExplicitSignature = FunctionProtoTypeLoc(); 12227 } 12228 } 12229 12230 CurBlock->TheDecl->setSignatureAsWritten(Sig); 12231 CurBlock->FunctionType = T; 12232 12233 const FunctionType *Fn = T->getAs<FunctionType>(); 12234 QualType RetTy = Fn->getReturnType(); 12235 bool isVariadic = 12236 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 12237 12238 CurBlock->TheDecl->setIsVariadic(isVariadic); 12239 12240 // Context.DependentTy is used as a placeholder for a missing block 12241 // return type. TODO: what should we do with declarators like: 12242 // ^ * { ... } 12243 // If the answer is "apply template argument deduction".... 12244 if (RetTy != Context.DependentTy) { 12245 CurBlock->ReturnType = RetTy; 12246 CurBlock->TheDecl->setBlockMissingReturnType(false); 12247 CurBlock->HasImplicitReturnType = false; 12248 } 12249 12250 // Push block parameters from the declarator if we had them. 12251 SmallVector<ParmVarDecl*, 8> Params; 12252 if (ExplicitSignature) { 12253 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 12254 ParmVarDecl *Param = ExplicitSignature.getParam(I); 12255 if (Param->getIdentifier() == nullptr && 12256 !Param->isImplicit() && 12257 !Param->isInvalidDecl() && 12258 !getLangOpts().CPlusPlus) 12259 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 12260 Params.push_back(Param); 12261 } 12262 12263 // Fake up parameter variables if we have a typedef, like 12264 // ^ fntype { ... } 12265 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 12266 for (const auto &I : Fn->param_types()) { 12267 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 12268 CurBlock->TheDecl, ParamInfo.getLocStart(), I); 12269 Params.push_back(Param); 12270 } 12271 } 12272 12273 // Set the parameters on the block decl. 12274 if (!Params.empty()) { 12275 CurBlock->TheDecl->setParams(Params); 12276 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 12277 /*CheckParameterNames=*/false); 12278 } 12279 12280 // Finally we can process decl attributes. 12281 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 12282 12283 // Put the parameter variables in scope. 12284 for (auto AI : CurBlock->TheDecl->parameters()) { 12285 AI->setOwningFunction(CurBlock->TheDecl); 12286 12287 // If this has an identifier, add it to the scope stack. 12288 if (AI->getIdentifier()) { 12289 CheckShadow(CurBlock->TheScope, AI); 12290 12291 PushOnScopeChains(AI, CurBlock->TheScope); 12292 } 12293 } 12294 } 12295 12296 /// ActOnBlockError - If there is an error parsing a block, this callback 12297 /// is invoked to pop the information about the block from the action impl. 12298 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 12299 // Leave the expression-evaluation context. 12300 DiscardCleanupsInEvaluationContext(); 12301 PopExpressionEvaluationContext(); 12302 12303 // Pop off CurBlock, handle nested blocks. 12304 PopDeclContext(); 12305 PopFunctionScopeInfo(); 12306 } 12307 12308 /// ActOnBlockStmtExpr - This is called when the body of a block statement 12309 /// literal was successfully completed. ^(int x){...} 12310 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 12311 Stmt *Body, Scope *CurScope) { 12312 // If blocks are disabled, emit an error. 12313 if (!LangOpts.Blocks) 12314 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 12315 12316 // Leave the expression-evaluation context. 12317 if (hasAnyUnrecoverableErrorsInThisFunction()) 12318 DiscardCleanupsInEvaluationContext(); 12319 assert(!Cleanup.exprNeedsCleanups() && 12320 "cleanups within block not correctly bound!"); 12321 PopExpressionEvaluationContext(); 12322 12323 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 12324 12325 if (BSI->HasImplicitReturnType) 12326 deduceClosureReturnType(*BSI); 12327 12328 PopDeclContext(); 12329 12330 QualType RetTy = Context.VoidTy; 12331 if (!BSI->ReturnType.isNull()) 12332 RetTy = BSI->ReturnType; 12333 12334 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 12335 QualType BlockTy; 12336 12337 // Set the captured variables on the block. 12338 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 12339 SmallVector<BlockDecl::Capture, 4> Captures; 12340 for (CapturingScopeInfo::Capture &Cap : BSI->Captures) { 12341 if (Cap.isThisCapture()) 12342 continue; 12343 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 12344 Cap.isNested(), Cap.getInitExpr()); 12345 Captures.push_back(NewCap); 12346 } 12347 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 12348 12349 // If the user wrote a function type in some form, try to use that. 12350 if (!BSI->FunctionType.isNull()) { 12351 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 12352 12353 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 12354 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 12355 12356 // Turn protoless block types into nullary block types. 12357 if (isa<FunctionNoProtoType>(FTy)) { 12358 FunctionProtoType::ExtProtoInfo EPI; 12359 EPI.ExtInfo = Ext; 12360 BlockTy = Context.getFunctionType(RetTy, None, EPI); 12361 12362 // Otherwise, if we don't need to change anything about the function type, 12363 // preserve its sugar structure. 12364 } else if (FTy->getReturnType() == RetTy && 12365 (!NoReturn || FTy->getNoReturnAttr())) { 12366 BlockTy = BSI->FunctionType; 12367 12368 // Otherwise, make the minimal modifications to the function type. 12369 } else { 12370 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 12371 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 12372 EPI.TypeQuals = 0; // FIXME: silently? 12373 EPI.ExtInfo = Ext; 12374 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 12375 } 12376 12377 // If we don't have a function type, just build one from nothing. 12378 } else { 12379 FunctionProtoType::ExtProtoInfo EPI; 12380 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 12381 BlockTy = Context.getFunctionType(RetTy, None, EPI); 12382 } 12383 12384 DiagnoseUnusedParameters(BSI->TheDecl->parameters()); 12385 BlockTy = Context.getBlockPointerType(BlockTy); 12386 12387 // If needed, diagnose invalid gotos and switches in the block. 12388 if (getCurFunction()->NeedsScopeChecking() && 12389 !PP.isCodeCompletionEnabled()) 12390 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 12391 12392 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 12393 12394 // Try to apply the named return value optimization. We have to check again 12395 // if we can do this, though, because blocks keep return statements around 12396 // to deduce an implicit return type. 12397 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 12398 !BSI->TheDecl->isDependentContext()) 12399 computeNRVO(Body, BSI); 12400 12401 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 12402 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 12403 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 12404 12405 // If the block isn't obviously global, i.e. it captures anything at 12406 // all, then we need to do a few things in the surrounding context: 12407 if (Result->getBlockDecl()->hasCaptures()) { 12408 // First, this expression has a new cleanup object. 12409 ExprCleanupObjects.push_back(Result->getBlockDecl()); 12410 Cleanup.setExprNeedsCleanups(true); 12411 12412 // It also gets a branch-protected scope if any of the captured 12413 // variables needs destruction. 12414 for (const auto &CI : Result->getBlockDecl()->captures()) { 12415 const VarDecl *var = CI.getVariable(); 12416 if (var->getType().isDestructedType() != QualType::DK_none) { 12417 getCurFunction()->setHasBranchProtectedScope(); 12418 break; 12419 } 12420 } 12421 } 12422 12423 return Result; 12424 } 12425 12426 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 12427 SourceLocation RPLoc) { 12428 TypeSourceInfo *TInfo; 12429 GetTypeFromParser(Ty, &TInfo); 12430 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 12431 } 12432 12433 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 12434 Expr *E, TypeSourceInfo *TInfo, 12435 SourceLocation RPLoc) { 12436 Expr *OrigExpr = E; 12437 bool IsMS = false; 12438 12439 // CUDA device code does not support varargs. 12440 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 12441 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 12442 CUDAFunctionTarget T = IdentifyCUDATarget(F); 12443 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 12444 return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device)); 12445 } 12446 } 12447 12448 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 12449 // as Microsoft ABI on an actual Microsoft platform, where 12450 // __builtin_ms_va_list and __builtin_va_list are the same.) 12451 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 12452 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 12453 QualType MSVaListType = Context.getBuiltinMSVaListType(); 12454 if (Context.hasSameType(MSVaListType, E->getType())) { 12455 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 12456 return ExprError(); 12457 IsMS = true; 12458 } 12459 } 12460 12461 // Get the va_list type 12462 QualType VaListType = Context.getBuiltinVaListType(); 12463 if (!IsMS) { 12464 if (VaListType->isArrayType()) { 12465 // Deal with implicit array decay; for example, on x86-64, 12466 // va_list is an array, but it's supposed to decay to 12467 // a pointer for va_arg. 12468 VaListType = Context.getArrayDecayedType(VaListType); 12469 // Make sure the input expression also decays appropriately. 12470 ExprResult Result = UsualUnaryConversions(E); 12471 if (Result.isInvalid()) 12472 return ExprError(); 12473 E = Result.get(); 12474 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 12475 // If va_list is a record type and we are compiling in C++ mode, 12476 // check the argument using reference binding. 12477 InitializedEntity Entity = InitializedEntity::InitializeParameter( 12478 Context, Context.getLValueReferenceType(VaListType), false); 12479 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 12480 if (Init.isInvalid()) 12481 return ExprError(); 12482 E = Init.getAs<Expr>(); 12483 } else { 12484 // Otherwise, the va_list argument must be an l-value because 12485 // it is modified by va_arg. 12486 if (!E->isTypeDependent() && 12487 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 12488 return ExprError(); 12489 } 12490 } 12491 12492 if (!IsMS && !E->isTypeDependent() && 12493 !Context.hasSameType(VaListType, E->getType())) 12494 return ExprError(Diag(E->getLocStart(), 12495 diag::err_first_argument_to_va_arg_not_of_type_va_list) 12496 << OrigExpr->getType() << E->getSourceRange()); 12497 12498 if (!TInfo->getType()->isDependentType()) { 12499 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 12500 diag::err_second_parameter_to_va_arg_incomplete, 12501 TInfo->getTypeLoc())) 12502 return ExprError(); 12503 12504 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 12505 TInfo->getType(), 12506 diag::err_second_parameter_to_va_arg_abstract, 12507 TInfo->getTypeLoc())) 12508 return ExprError(); 12509 12510 if (!TInfo->getType().isPODType(Context)) { 12511 Diag(TInfo->getTypeLoc().getBeginLoc(), 12512 TInfo->getType()->isObjCLifetimeType() 12513 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 12514 : diag::warn_second_parameter_to_va_arg_not_pod) 12515 << TInfo->getType() 12516 << TInfo->getTypeLoc().getSourceRange(); 12517 } 12518 12519 // Check for va_arg where arguments of the given type will be promoted 12520 // (i.e. this va_arg is guaranteed to have undefined behavior). 12521 QualType PromoteType; 12522 if (TInfo->getType()->isPromotableIntegerType()) { 12523 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 12524 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 12525 PromoteType = QualType(); 12526 } 12527 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 12528 PromoteType = Context.DoubleTy; 12529 if (!PromoteType.isNull()) 12530 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 12531 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 12532 << TInfo->getType() 12533 << PromoteType 12534 << TInfo->getTypeLoc().getSourceRange()); 12535 } 12536 12537 QualType T = TInfo->getType().getNonLValueExprType(Context); 12538 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 12539 } 12540 12541 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 12542 // The type of __null will be int or long, depending on the size of 12543 // pointers on the target. 12544 QualType Ty; 12545 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 12546 if (pw == Context.getTargetInfo().getIntWidth()) 12547 Ty = Context.IntTy; 12548 else if (pw == Context.getTargetInfo().getLongWidth()) 12549 Ty = Context.LongTy; 12550 else if (pw == Context.getTargetInfo().getLongLongWidth()) 12551 Ty = Context.LongLongTy; 12552 else { 12553 llvm_unreachable("I don't know size of pointer!"); 12554 } 12555 12556 return new (Context) GNUNullExpr(Ty, TokenLoc); 12557 } 12558 12559 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 12560 bool Diagnose) { 12561 if (!getLangOpts().ObjC1) 12562 return false; 12563 12564 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 12565 if (!PT) 12566 return false; 12567 12568 if (!PT->isObjCIdType()) { 12569 // Check if the destination is the 'NSString' interface. 12570 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 12571 if (!ID || !ID->getIdentifier()->isStr("NSString")) 12572 return false; 12573 } 12574 12575 // Ignore any parens, implicit casts (should only be 12576 // array-to-pointer decays), and not-so-opaque values. The last is 12577 // important for making this trigger for property assignments. 12578 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 12579 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 12580 if (OV->getSourceExpr()) 12581 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 12582 12583 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 12584 if (!SL || !SL->isAscii()) 12585 return false; 12586 if (Diagnose) { 12587 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix) 12588 << FixItHint::CreateInsertion(SL->getLocStart(), "@"); 12589 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get(); 12590 } 12591 return true; 12592 } 12593 12594 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 12595 const Expr *SrcExpr) { 12596 if (!DstType->isFunctionPointerType() || 12597 !SrcExpr->getType()->isFunctionType()) 12598 return false; 12599 12600 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 12601 if (!DRE) 12602 return false; 12603 12604 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 12605 if (!FD) 12606 return false; 12607 12608 return !S.checkAddressOfFunctionIsAvailable(FD, 12609 /*Complain=*/true, 12610 SrcExpr->getLocStart()); 12611 } 12612 12613 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 12614 SourceLocation Loc, 12615 QualType DstType, QualType SrcType, 12616 Expr *SrcExpr, AssignmentAction Action, 12617 bool *Complained) { 12618 if (Complained) 12619 *Complained = false; 12620 12621 // Decode the result (notice that AST's are still created for extensions). 12622 bool CheckInferredResultType = false; 12623 bool isInvalid = false; 12624 unsigned DiagKind = 0; 12625 FixItHint Hint; 12626 ConversionFixItGenerator ConvHints; 12627 bool MayHaveConvFixit = false; 12628 bool MayHaveFunctionDiff = false; 12629 const ObjCInterfaceDecl *IFace = nullptr; 12630 const ObjCProtocolDecl *PDecl = nullptr; 12631 12632 switch (ConvTy) { 12633 case Compatible: 12634 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 12635 return false; 12636 12637 case PointerToInt: 12638 DiagKind = diag::ext_typecheck_convert_pointer_int; 12639 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12640 MayHaveConvFixit = true; 12641 break; 12642 case IntToPointer: 12643 DiagKind = diag::ext_typecheck_convert_int_pointer; 12644 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12645 MayHaveConvFixit = true; 12646 break; 12647 case IncompatiblePointer: 12648 if (Action == AA_Passing_CFAudited) 12649 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 12650 else if (SrcType->isFunctionPointerType() && 12651 DstType->isFunctionPointerType()) 12652 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 12653 else 12654 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 12655 12656 CheckInferredResultType = DstType->isObjCObjectPointerType() && 12657 SrcType->isObjCObjectPointerType(); 12658 if (Hint.isNull() && !CheckInferredResultType) { 12659 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12660 } 12661 else if (CheckInferredResultType) { 12662 SrcType = SrcType.getUnqualifiedType(); 12663 DstType = DstType.getUnqualifiedType(); 12664 } 12665 MayHaveConvFixit = true; 12666 break; 12667 case IncompatiblePointerSign: 12668 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 12669 break; 12670 case FunctionVoidPointer: 12671 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 12672 break; 12673 case IncompatiblePointerDiscardsQualifiers: { 12674 // Perform array-to-pointer decay if necessary. 12675 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 12676 12677 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 12678 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 12679 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 12680 DiagKind = diag::err_typecheck_incompatible_address_space; 12681 break; 12682 12683 12684 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 12685 DiagKind = diag::err_typecheck_incompatible_ownership; 12686 break; 12687 } 12688 12689 llvm_unreachable("unknown error case for discarding qualifiers!"); 12690 // fallthrough 12691 } 12692 case CompatiblePointerDiscardsQualifiers: 12693 // If the qualifiers lost were because we were applying the 12694 // (deprecated) C++ conversion from a string literal to a char* 12695 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 12696 // Ideally, this check would be performed in 12697 // checkPointerTypesForAssignment. However, that would require a 12698 // bit of refactoring (so that the second argument is an 12699 // expression, rather than a type), which should be done as part 12700 // of a larger effort to fix checkPointerTypesForAssignment for 12701 // C++ semantics. 12702 if (getLangOpts().CPlusPlus && 12703 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 12704 return false; 12705 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 12706 break; 12707 case IncompatibleNestedPointerQualifiers: 12708 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 12709 break; 12710 case IntToBlockPointer: 12711 DiagKind = diag::err_int_to_block_pointer; 12712 break; 12713 case IncompatibleBlockPointer: 12714 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 12715 break; 12716 case IncompatibleObjCQualifiedId: { 12717 if (SrcType->isObjCQualifiedIdType()) { 12718 const ObjCObjectPointerType *srcOPT = 12719 SrcType->getAs<ObjCObjectPointerType>(); 12720 for (auto *srcProto : srcOPT->quals()) { 12721 PDecl = srcProto; 12722 break; 12723 } 12724 if (const ObjCInterfaceType *IFaceT = 12725 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 12726 IFace = IFaceT->getDecl(); 12727 } 12728 else if (DstType->isObjCQualifiedIdType()) { 12729 const ObjCObjectPointerType *dstOPT = 12730 DstType->getAs<ObjCObjectPointerType>(); 12731 for (auto *dstProto : dstOPT->quals()) { 12732 PDecl = dstProto; 12733 break; 12734 } 12735 if (const ObjCInterfaceType *IFaceT = 12736 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 12737 IFace = IFaceT->getDecl(); 12738 } 12739 DiagKind = diag::warn_incompatible_qualified_id; 12740 break; 12741 } 12742 case IncompatibleVectors: 12743 DiagKind = diag::warn_incompatible_vectors; 12744 break; 12745 case IncompatibleObjCWeakRef: 12746 DiagKind = diag::err_arc_weak_unavailable_assign; 12747 break; 12748 case Incompatible: 12749 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 12750 if (Complained) 12751 *Complained = true; 12752 return true; 12753 } 12754 12755 DiagKind = diag::err_typecheck_convert_incompatible; 12756 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12757 MayHaveConvFixit = true; 12758 isInvalid = true; 12759 MayHaveFunctionDiff = true; 12760 break; 12761 } 12762 12763 QualType FirstType, SecondType; 12764 switch (Action) { 12765 case AA_Assigning: 12766 case AA_Initializing: 12767 // The destination type comes first. 12768 FirstType = DstType; 12769 SecondType = SrcType; 12770 break; 12771 12772 case AA_Returning: 12773 case AA_Passing: 12774 case AA_Passing_CFAudited: 12775 case AA_Converting: 12776 case AA_Sending: 12777 case AA_Casting: 12778 // The source type comes first. 12779 FirstType = SrcType; 12780 SecondType = DstType; 12781 break; 12782 } 12783 12784 PartialDiagnostic FDiag = PDiag(DiagKind); 12785 if (Action == AA_Passing_CFAudited) 12786 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 12787 else 12788 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 12789 12790 // If we can fix the conversion, suggest the FixIts. 12791 assert(ConvHints.isNull() || Hint.isNull()); 12792 if (!ConvHints.isNull()) { 12793 for (FixItHint &H : ConvHints.Hints) 12794 FDiag << H; 12795 } else { 12796 FDiag << Hint; 12797 } 12798 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 12799 12800 if (MayHaveFunctionDiff) 12801 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 12802 12803 Diag(Loc, FDiag); 12804 if (DiagKind == diag::warn_incompatible_qualified_id && 12805 PDecl && IFace && !IFace->hasDefinition()) 12806 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 12807 << IFace->getName() << PDecl->getName(); 12808 12809 if (SecondType == Context.OverloadTy) 12810 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 12811 FirstType, /*TakingAddress=*/true); 12812 12813 if (CheckInferredResultType) 12814 EmitRelatedResultTypeNote(SrcExpr); 12815 12816 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 12817 EmitRelatedResultTypeNoteForReturn(DstType); 12818 12819 if (Complained) 12820 *Complained = true; 12821 return isInvalid; 12822 } 12823 12824 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12825 llvm::APSInt *Result) { 12826 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 12827 public: 12828 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12829 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 12830 } 12831 } Diagnoser; 12832 12833 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 12834 } 12835 12836 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12837 llvm::APSInt *Result, 12838 unsigned DiagID, 12839 bool AllowFold) { 12840 class IDDiagnoser : public VerifyICEDiagnoser { 12841 unsigned DiagID; 12842 12843 public: 12844 IDDiagnoser(unsigned DiagID) 12845 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 12846 12847 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12848 S.Diag(Loc, DiagID) << SR; 12849 } 12850 } Diagnoser(DiagID); 12851 12852 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 12853 } 12854 12855 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 12856 SourceRange SR) { 12857 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 12858 } 12859 12860 ExprResult 12861 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 12862 VerifyICEDiagnoser &Diagnoser, 12863 bool AllowFold) { 12864 SourceLocation DiagLoc = E->getLocStart(); 12865 12866 if (getLangOpts().CPlusPlus11) { 12867 // C++11 [expr.const]p5: 12868 // If an expression of literal class type is used in a context where an 12869 // integral constant expression is required, then that class type shall 12870 // have a single non-explicit conversion function to an integral or 12871 // unscoped enumeration type 12872 ExprResult Converted; 12873 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 12874 public: 12875 CXX11ConvertDiagnoser(bool Silent) 12876 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 12877 Silent, true) {} 12878 12879 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 12880 QualType T) override { 12881 return S.Diag(Loc, diag::err_ice_not_integral) << T; 12882 } 12883 12884 SemaDiagnosticBuilder diagnoseIncomplete( 12885 Sema &S, SourceLocation Loc, QualType T) override { 12886 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 12887 } 12888 12889 SemaDiagnosticBuilder diagnoseExplicitConv( 12890 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12891 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 12892 } 12893 12894 SemaDiagnosticBuilder noteExplicitConv( 12895 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12896 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12897 << ConvTy->isEnumeralType() << ConvTy; 12898 } 12899 12900 SemaDiagnosticBuilder diagnoseAmbiguous( 12901 Sema &S, SourceLocation Loc, QualType T) override { 12902 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 12903 } 12904 12905 SemaDiagnosticBuilder noteAmbiguous( 12906 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12907 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12908 << ConvTy->isEnumeralType() << ConvTy; 12909 } 12910 12911 SemaDiagnosticBuilder diagnoseConversion( 12912 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12913 llvm_unreachable("conversion functions are permitted"); 12914 } 12915 } ConvertDiagnoser(Diagnoser.Suppress); 12916 12917 Converted = PerformContextualImplicitConversion(DiagLoc, E, 12918 ConvertDiagnoser); 12919 if (Converted.isInvalid()) 12920 return Converted; 12921 E = Converted.get(); 12922 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 12923 return ExprError(); 12924 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 12925 // An ICE must be of integral or unscoped enumeration type. 12926 if (!Diagnoser.Suppress) 12927 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 12928 return ExprError(); 12929 } 12930 12931 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 12932 // in the non-ICE case. 12933 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 12934 if (Result) 12935 *Result = E->EvaluateKnownConstInt(Context); 12936 return E; 12937 } 12938 12939 Expr::EvalResult EvalResult; 12940 SmallVector<PartialDiagnosticAt, 8> Notes; 12941 EvalResult.Diag = &Notes; 12942 12943 // Try to evaluate the expression, and produce diagnostics explaining why it's 12944 // not a constant expression as a side-effect. 12945 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 12946 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 12947 12948 // In C++11, we can rely on diagnostics being produced for any expression 12949 // which is not a constant expression. If no diagnostics were produced, then 12950 // this is a constant expression. 12951 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 12952 if (Result) 12953 *Result = EvalResult.Val.getInt(); 12954 return E; 12955 } 12956 12957 // If our only note is the usual "invalid subexpression" note, just point 12958 // the caret at its location rather than producing an essentially 12959 // redundant note. 12960 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 12961 diag::note_invalid_subexpr_in_const_expr) { 12962 DiagLoc = Notes[0].first; 12963 Notes.clear(); 12964 } 12965 12966 if (!Folded || !AllowFold) { 12967 if (!Diagnoser.Suppress) { 12968 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 12969 for (const PartialDiagnosticAt &Note : Notes) 12970 Diag(Note.first, Note.second); 12971 } 12972 12973 return ExprError(); 12974 } 12975 12976 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 12977 for (const PartialDiagnosticAt &Note : Notes) 12978 Diag(Note.first, Note.second); 12979 12980 if (Result) 12981 *Result = EvalResult.Val.getInt(); 12982 return E; 12983 } 12984 12985 namespace { 12986 // Handle the case where we conclude a expression which we speculatively 12987 // considered to be unevaluated is actually evaluated. 12988 class TransformToPE : public TreeTransform<TransformToPE> { 12989 typedef TreeTransform<TransformToPE> BaseTransform; 12990 12991 public: 12992 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 12993 12994 // Make sure we redo semantic analysis 12995 bool AlwaysRebuild() { return true; } 12996 12997 // Make sure we handle LabelStmts correctly. 12998 // FIXME: This does the right thing, but maybe we need a more general 12999 // fix to TreeTransform? 13000 StmtResult TransformLabelStmt(LabelStmt *S) { 13001 S->getDecl()->setStmt(nullptr); 13002 return BaseTransform::TransformLabelStmt(S); 13003 } 13004 13005 // We need to special-case DeclRefExprs referring to FieldDecls which 13006 // are not part of a member pointer formation; normal TreeTransforming 13007 // doesn't catch this case because of the way we represent them in the AST. 13008 // FIXME: This is a bit ugly; is it really the best way to handle this 13009 // case? 13010 // 13011 // Error on DeclRefExprs referring to FieldDecls. 13012 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 13013 if (isa<FieldDecl>(E->getDecl()) && 13014 !SemaRef.isUnevaluatedContext()) 13015 return SemaRef.Diag(E->getLocation(), 13016 diag::err_invalid_non_static_member_use) 13017 << E->getDecl() << E->getSourceRange(); 13018 13019 return BaseTransform::TransformDeclRefExpr(E); 13020 } 13021 13022 // Exception: filter out member pointer formation 13023 ExprResult TransformUnaryOperator(UnaryOperator *E) { 13024 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 13025 return E; 13026 13027 return BaseTransform::TransformUnaryOperator(E); 13028 } 13029 13030 ExprResult TransformLambdaExpr(LambdaExpr *E) { 13031 // Lambdas never need to be transformed. 13032 return E; 13033 } 13034 }; 13035 } 13036 13037 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 13038 assert(isUnevaluatedContext() && 13039 "Should only transform unevaluated expressions"); 13040 ExprEvalContexts.back().Context = 13041 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 13042 if (isUnevaluatedContext()) 13043 return E; 13044 return TransformToPE(*this).TransformExpr(E); 13045 } 13046 13047 void 13048 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 13049 Decl *LambdaContextDecl, 13050 bool IsDecltype) { 13051 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 13052 LambdaContextDecl, IsDecltype); 13053 Cleanup.reset(); 13054 if (!MaybeODRUseExprs.empty()) 13055 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 13056 } 13057 13058 void 13059 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 13060 ReuseLambdaContextDecl_t, 13061 bool IsDecltype) { 13062 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 13063 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 13064 } 13065 13066 void Sema::PopExpressionEvaluationContext() { 13067 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 13068 unsigned NumTypos = Rec.NumTypos; 13069 13070 if (!Rec.Lambdas.empty()) { 13071 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 13072 unsigned D; 13073 if (Rec.isUnevaluated()) { 13074 // C++11 [expr.prim.lambda]p2: 13075 // A lambda-expression shall not appear in an unevaluated operand 13076 // (Clause 5). 13077 D = diag::err_lambda_unevaluated_operand; 13078 } else { 13079 // C++1y [expr.const]p2: 13080 // A conditional-expression e is a core constant expression unless the 13081 // evaluation of e, following the rules of the abstract machine, would 13082 // evaluate [...] a lambda-expression. 13083 D = diag::err_lambda_in_constant_expression; 13084 } 13085 for (const auto *L : Rec.Lambdas) 13086 Diag(L->getLocStart(), D); 13087 } else { 13088 // Mark the capture expressions odr-used. This was deferred 13089 // during lambda expression creation. 13090 for (auto *Lambda : Rec.Lambdas) { 13091 for (auto *C : Lambda->capture_inits()) 13092 MarkDeclarationsReferencedInExpr(C); 13093 } 13094 } 13095 } 13096 13097 // When are coming out of an unevaluated context, clear out any 13098 // temporaries that we may have created as part of the evaluation of 13099 // the expression in that context: they aren't relevant because they 13100 // will never be constructed. 13101 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 13102 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 13103 ExprCleanupObjects.end()); 13104 Cleanup = Rec.ParentCleanup; 13105 CleanupVarDeclMarking(); 13106 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 13107 // Otherwise, merge the contexts together. 13108 } else { 13109 Cleanup.mergeFrom(Rec.ParentCleanup); 13110 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 13111 Rec.SavedMaybeODRUseExprs.end()); 13112 } 13113 13114 // Pop the current expression evaluation context off the stack. 13115 ExprEvalContexts.pop_back(); 13116 13117 if (!ExprEvalContexts.empty()) 13118 ExprEvalContexts.back().NumTypos += NumTypos; 13119 else 13120 assert(NumTypos == 0 && "There are outstanding typos after popping the " 13121 "last ExpressionEvaluationContextRecord"); 13122 } 13123 13124 void Sema::DiscardCleanupsInEvaluationContext() { 13125 ExprCleanupObjects.erase( 13126 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 13127 ExprCleanupObjects.end()); 13128 Cleanup.reset(); 13129 MaybeODRUseExprs.clear(); 13130 } 13131 13132 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 13133 if (!E->getType()->isVariablyModifiedType()) 13134 return E; 13135 return TransformToPotentiallyEvaluated(E); 13136 } 13137 13138 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) { 13139 // Do not mark anything as "used" within a dependent context; wait for 13140 // an instantiation. 13141 if (SemaRef.CurContext->isDependentContext()) 13142 return false; 13143 13144 switch (SemaRef.ExprEvalContexts.back().Context) { 13145 case Sema::Unevaluated: 13146 case Sema::UnevaluatedAbstract: 13147 // We are in an expression that is not potentially evaluated; do nothing. 13148 // (Depending on how you read the standard, we actually do need to do 13149 // something here for null pointer constants, but the standard's 13150 // definition of a null pointer constant is completely crazy.) 13151 return false; 13152 13153 case Sema::DiscardedStatement: 13154 // These are technically a potentially evaluated but they have the effect 13155 // of suppressing use marking. 13156 return false; 13157 13158 case Sema::ConstantEvaluated: 13159 case Sema::PotentiallyEvaluated: 13160 // We are in a potentially evaluated expression (or a constant-expression 13161 // in C++03); we need to do implicit template instantiation, implicitly 13162 // define class members, and mark most declarations as used. 13163 return true; 13164 13165 case Sema::PotentiallyEvaluatedIfUsed: 13166 // Referenced declarations will only be used if the construct in the 13167 // containing expression is used. 13168 return false; 13169 } 13170 llvm_unreachable("Invalid context"); 13171 } 13172 13173 /// \brief Mark a function referenced, and check whether it is odr-used 13174 /// (C++ [basic.def.odr]p2, C99 6.9p3) 13175 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 13176 bool MightBeOdrUse) { 13177 assert(Func && "No function?"); 13178 13179 Func->setReferenced(); 13180 13181 // C++11 [basic.def.odr]p3: 13182 // A function whose name appears as a potentially-evaluated expression is 13183 // odr-used if it is the unique lookup result or the selected member of a 13184 // set of overloaded functions [...]. 13185 // 13186 // We (incorrectly) mark overload resolution as an unevaluated context, so we 13187 // can just check that here. 13188 bool OdrUse = MightBeOdrUse && IsPotentiallyEvaluatedContext(*this); 13189 13190 // Determine whether we require a function definition to exist, per 13191 // C++11 [temp.inst]p3: 13192 // Unless a function template specialization has been explicitly 13193 // instantiated or explicitly specialized, the function template 13194 // specialization is implicitly instantiated when the specialization is 13195 // referenced in a context that requires a function definition to exist. 13196 // 13197 // We consider constexpr function templates to be referenced in a context 13198 // that requires a definition to exist whenever they are referenced. 13199 // 13200 // FIXME: This instantiates constexpr functions too frequently. If this is 13201 // really an unevaluated context (and we're not just in the definition of a 13202 // function template or overload resolution or other cases which we 13203 // incorrectly consider to be unevaluated contexts), and we're not in a 13204 // subexpression which we actually need to evaluate (for instance, a 13205 // template argument, array bound or an expression in a braced-init-list), 13206 // we are not permitted to instantiate this constexpr function definition. 13207 // 13208 // FIXME: This also implicitly defines special members too frequently. They 13209 // are only supposed to be implicitly defined if they are odr-used, but they 13210 // are not odr-used from constant expressions in unevaluated contexts. 13211 // However, they cannot be referenced if they are deleted, and they are 13212 // deleted whenever the implicit definition of the special member would 13213 // fail (with very few exceptions). 13214 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 13215 bool NeedDefinition = 13216 OdrUse || (Func->isConstexpr() && (Func->isImplicitlyInstantiable() || 13217 (MD && !MD->isUserProvided()))); 13218 13219 // C++14 [temp.expl.spec]p6: 13220 // If a template [...] is explicitly specialized then that specialization 13221 // shall be declared before the first use of that specialization that would 13222 // cause an implicit instantiation to take place, in every translation unit 13223 // in which such a use occurs 13224 if (NeedDefinition && 13225 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 13226 Func->getMemberSpecializationInfo())) 13227 checkSpecializationVisibility(Loc, Func); 13228 13229 // C++14 [except.spec]p17: 13230 // An exception-specification is considered to be needed when: 13231 // - the function is odr-used or, if it appears in an unevaluated operand, 13232 // would be odr-used if the expression were potentially-evaluated; 13233 // 13234 // Note, we do this even if MightBeOdrUse is false. That indicates that the 13235 // function is a pure virtual function we're calling, and in that case the 13236 // function was selected by overload resolution and we need to resolve its 13237 // exception specification for a different reason. 13238 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 13239 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 13240 ResolveExceptionSpec(Loc, FPT); 13241 13242 // If we don't need to mark the function as used, and we don't need to 13243 // try to provide a definition, there's nothing more to do. 13244 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) && 13245 (!NeedDefinition || Func->getBody())) 13246 return; 13247 13248 // Note that this declaration has been used. 13249 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 13250 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 13251 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 13252 if (Constructor->isDefaultConstructor()) { 13253 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 13254 return; 13255 DefineImplicitDefaultConstructor(Loc, Constructor); 13256 } else if (Constructor->isCopyConstructor()) { 13257 DefineImplicitCopyConstructor(Loc, Constructor); 13258 } else if (Constructor->isMoveConstructor()) { 13259 DefineImplicitMoveConstructor(Loc, Constructor); 13260 } 13261 } else if (Constructor->getInheritedConstructor()) { 13262 DefineInheritingConstructor(Loc, Constructor); 13263 } 13264 } else if (CXXDestructorDecl *Destructor = 13265 dyn_cast<CXXDestructorDecl>(Func)) { 13266 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 13267 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 13268 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 13269 return; 13270 DefineImplicitDestructor(Loc, Destructor); 13271 } 13272 if (Destructor->isVirtual() && getLangOpts().AppleKext) 13273 MarkVTableUsed(Loc, Destructor->getParent()); 13274 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 13275 if (MethodDecl->isOverloadedOperator() && 13276 MethodDecl->getOverloadedOperator() == OO_Equal) { 13277 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 13278 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 13279 if (MethodDecl->isCopyAssignmentOperator()) 13280 DefineImplicitCopyAssignment(Loc, MethodDecl); 13281 else if (MethodDecl->isMoveAssignmentOperator()) 13282 DefineImplicitMoveAssignment(Loc, MethodDecl); 13283 } 13284 } else if (isa<CXXConversionDecl>(MethodDecl) && 13285 MethodDecl->getParent()->isLambda()) { 13286 CXXConversionDecl *Conversion = 13287 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 13288 if (Conversion->isLambdaToBlockPointerConversion()) 13289 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 13290 else 13291 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 13292 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 13293 MarkVTableUsed(Loc, MethodDecl->getParent()); 13294 } 13295 13296 // Recursive functions should be marked when used from another function. 13297 // FIXME: Is this really right? 13298 if (CurContext == Func) return; 13299 13300 // Implicit instantiation of function templates and member functions of 13301 // class templates. 13302 if (Func->isImplicitlyInstantiable()) { 13303 bool AlreadyInstantiated = false; 13304 SourceLocation PointOfInstantiation = Loc; 13305 if (FunctionTemplateSpecializationInfo *SpecInfo 13306 = Func->getTemplateSpecializationInfo()) { 13307 if (SpecInfo->getPointOfInstantiation().isInvalid()) 13308 SpecInfo->setPointOfInstantiation(Loc); 13309 else if (SpecInfo->getTemplateSpecializationKind() 13310 == TSK_ImplicitInstantiation) { 13311 AlreadyInstantiated = true; 13312 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 13313 } 13314 } else if (MemberSpecializationInfo *MSInfo 13315 = Func->getMemberSpecializationInfo()) { 13316 if (MSInfo->getPointOfInstantiation().isInvalid()) 13317 MSInfo->setPointOfInstantiation(Loc); 13318 else if (MSInfo->getTemplateSpecializationKind() 13319 == TSK_ImplicitInstantiation) { 13320 AlreadyInstantiated = true; 13321 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 13322 } 13323 } 13324 13325 if (!AlreadyInstantiated || Func->isConstexpr()) { 13326 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 13327 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 13328 ActiveTemplateInstantiations.size()) 13329 PendingLocalImplicitInstantiations.push_back( 13330 std::make_pair(Func, PointOfInstantiation)); 13331 else if (Func->isConstexpr()) 13332 // Do not defer instantiations of constexpr functions, to avoid the 13333 // expression evaluator needing to call back into Sema if it sees a 13334 // call to such a function. 13335 InstantiateFunctionDefinition(PointOfInstantiation, Func); 13336 else { 13337 PendingInstantiations.push_back(std::make_pair(Func, 13338 PointOfInstantiation)); 13339 // Notify the consumer that a function was implicitly instantiated. 13340 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 13341 } 13342 } 13343 } else { 13344 // Walk redefinitions, as some of them may be instantiable. 13345 for (auto i : Func->redecls()) { 13346 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 13347 MarkFunctionReferenced(Loc, i, OdrUse); 13348 } 13349 } 13350 13351 if (!OdrUse) return; 13352 13353 // Keep track of used but undefined functions. 13354 if (!Func->isDefined()) { 13355 if (mightHaveNonExternalLinkage(Func)) 13356 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 13357 else if (Func->getMostRecentDecl()->isInlined() && 13358 !LangOpts.GNUInline && 13359 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 13360 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 13361 } 13362 13363 Func->markUsed(Context); 13364 } 13365 13366 static void 13367 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 13368 ValueDecl *var, DeclContext *DC) { 13369 DeclContext *VarDC = var->getDeclContext(); 13370 13371 // If the parameter still belongs to the translation unit, then 13372 // we're actually just using one parameter in the declaration of 13373 // the next. 13374 if (isa<ParmVarDecl>(var) && 13375 isa<TranslationUnitDecl>(VarDC)) 13376 return; 13377 13378 // For C code, don't diagnose about capture if we're not actually in code 13379 // right now; it's impossible to write a non-constant expression outside of 13380 // function context, so we'll get other (more useful) diagnostics later. 13381 // 13382 // For C++, things get a bit more nasty... it would be nice to suppress this 13383 // diagnostic for certain cases like using a local variable in an array bound 13384 // for a member of a local class, but the correct predicate is not obvious. 13385 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 13386 return; 13387 13388 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 13389 unsigned ContextKind = 3; // unknown 13390 if (isa<CXXMethodDecl>(VarDC) && 13391 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 13392 ContextKind = 2; 13393 } else if (isa<FunctionDecl>(VarDC)) { 13394 ContextKind = 0; 13395 } else if (isa<BlockDecl>(VarDC)) { 13396 ContextKind = 1; 13397 } 13398 13399 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 13400 << var << ValueKind << ContextKind << VarDC; 13401 S.Diag(var->getLocation(), diag::note_entity_declared_at) 13402 << var; 13403 13404 // FIXME: Add additional diagnostic info about class etc. which prevents 13405 // capture. 13406 } 13407 13408 13409 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 13410 bool &SubCapturesAreNested, 13411 QualType &CaptureType, 13412 QualType &DeclRefType) { 13413 // Check whether we've already captured it. 13414 if (CSI->CaptureMap.count(Var)) { 13415 // If we found a capture, any subcaptures are nested. 13416 SubCapturesAreNested = true; 13417 13418 // Retrieve the capture type for this variable. 13419 CaptureType = CSI->getCapture(Var).getCaptureType(); 13420 13421 // Compute the type of an expression that refers to this variable. 13422 DeclRefType = CaptureType.getNonReferenceType(); 13423 13424 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 13425 // are mutable in the sense that user can change their value - they are 13426 // private instances of the captured declarations. 13427 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 13428 if (Cap.isCopyCapture() && 13429 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 13430 !(isa<CapturedRegionScopeInfo>(CSI) && 13431 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 13432 DeclRefType.addConst(); 13433 return true; 13434 } 13435 return false; 13436 } 13437 13438 // Only block literals, captured statements, and lambda expressions can 13439 // capture; other scopes don't work. 13440 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 13441 SourceLocation Loc, 13442 const bool Diagnose, Sema &S) { 13443 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 13444 return getLambdaAwareParentOfDeclContext(DC); 13445 else if (Var->hasLocalStorage()) { 13446 if (Diagnose) 13447 diagnoseUncapturableValueReference(S, Loc, Var, DC); 13448 } 13449 return nullptr; 13450 } 13451 13452 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 13453 // certain types of variables (unnamed, variably modified types etc.) 13454 // so check for eligibility. 13455 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 13456 SourceLocation Loc, 13457 const bool Diagnose, Sema &S) { 13458 13459 bool IsBlock = isa<BlockScopeInfo>(CSI); 13460 bool IsLambda = isa<LambdaScopeInfo>(CSI); 13461 13462 // Lambdas are not allowed to capture unnamed variables 13463 // (e.g. anonymous unions). 13464 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 13465 // assuming that's the intent. 13466 if (IsLambda && !Var->getDeclName()) { 13467 if (Diagnose) { 13468 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 13469 S.Diag(Var->getLocation(), diag::note_declared_at); 13470 } 13471 return false; 13472 } 13473 13474 // Prohibit variably-modified types in blocks; they're difficult to deal with. 13475 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 13476 if (Diagnose) { 13477 S.Diag(Loc, diag::err_ref_vm_type); 13478 S.Diag(Var->getLocation(), diag::note_previous_decl) 13479 << Var->getDeclName(); 13480 } 13481 return false; 13482 } 13483 // Prohibit structs with flexible array members too. 13484 // We cannot capture what is in the tail end of the struct. 13485 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 13486 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 13487 if (Diagnose) { 13488 if (IsBlock) 13489 S.Diag(Loc, diag::err_ref_flexarray_type); 13490 else 13491 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 13492 << Var->getDeclName(); 13493 S.Diag(Var->getLocation(), diag::note_previous_decl) 13494 << Var->getDeclName(); 13495 } 13496 return false; 13497 } 13498 } 13499 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 13500 // Lambdas and captured statements are not allowed to capture __block 13501 // variables; they don't support the expected semantics. 13502 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 13503 if (Diagnose) { 13504 S.Diag(Loc, diag::err_capture_block_variable) 13505 << Var->getDeclName() << !IsLambda; 13506 S.Diag(Var->getLocation(), diag::note_previous_decl) 13507 << Var->getDeclName(); 13508 } 13509 return false; 13510 } 13511 13512 return true; 13513 } 13514 13515 // Returns true if the capture by block was successful. 13516 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 13517 SourceLocation Loc, 13518 const bool BuildAndDiagnose, 13519 QualType &CaptureType, 13520 QualType &DeclRefType, 13521 const bool Nested, 13522 Sema &S) { 13523 Expr *CopyExpr = nullptr; 13524 bool ByRef = false; 13525 13526 // Blocks are not allowed to capture arrays. 13527 if (CaptureType->isArrayType()) { 13528 if (BuildAndDiagnose) { 13529 S.Diag(Loc, diag::err_ref_array_type); 13530 S.Diag(Var->getLocation(), diag::note_previous_decl) 13531 << Var->getDeclName(); 13532 } 13533 return false; 13534 } 13535 13536 // Forbid the block-capture of autoreleasing variables. 13537 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 13538 if (BuildAndDiagnose) { 13539 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 13540 << /*block*/ 0; 13541 S.Diag(Var->getLocation(), diag::note_previous_decl) 13542 << Var->getDeclName(); 13543 } 13544 return false; 13545 } 13546 13547 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 13548 if (auto *PT = dyn_cast<PointerType>(CaptureType)) { 13549 QualType PointeeTy = PT->getPointeeType(); 13550 if (isa<ObjCObjectPointerType>(PointeeTy.getCanonicalType()) && 13551 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 13552 !isa<AttributedType>(PointeeTy)) { 13553 if (BuildAndDiagnose) { 13554 SourceLocation VarLoc = Var->getLocation(); 13555 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 13556 S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing) << 13557 FixItHint::CreateInsertion(VarLoc, "__autoreleasing"); 13558 S.Diag(VarLoc, diag::note_declare_parameter_strong); 13559 } 13560 } 13561 } 13562 13563 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 13564 if (HasBlocksAttr || CaptureType->isReferenceType() || 13565 (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) { 13566 // Block capture by reference does not change the capture or 13567 // declaration reference types. 13568 ByRef = true; 13569 } else { 13570 // Block capture by copy introduces 'const'. 13571 CaptureType = CaptureType.getNonReferenceType().withConst(); 13572 DeclRefType = CaptureType; 13573 13574 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 13575 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 13576 // The capture logic needs the destructor, so make sure we mark it. 13577 // Usually this is unnecessary because most local variables have 13578 // their destructors marked at declaration time, but parameters are 13579 // an exception because it's technically only the call site that 13580 // actually requires the destructor. 13581 if (isa<ParmVarDecl>(Var)) 13582 S.FinalizeVarWithDestructor(Var, Record); 13583 13584 // Enter a new evaluation context to insulate the copy 13585 // full-expression. 13586 EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated); 13587 13588 // According to the blocks spec, the capture of a variable from 13589 // the stack requires a const copy constructor. This is not true 13590 // of the copy/move done to move a __block variable to the heap. 13591 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 13592 DeclRefType.withConst(), 13593 VK_LValue, Loc); 13594 13595 ExprResult Result 13596 = S.PerformCopyInitialization( 13597 InitializedEntity::InitializeBlock(Var->getLocation(), 13598 CaptureType, false), 13599 Loc, DeclRef); 13600 13601 // Build a full-expression copy expression if initialization 13602 // succeeded and used a non-trivial constructor. Recover from 13603 // errors by pretending that the copy isn't necessary. 13604 if (!Result.isInvalid() && 13605 !cast<CXXConstructExpr>(Result.get())->getConstructor() 13606 ->isTrivial()) { 13607 Result = S.MaybeCreateExprWithCleanups(Result); 13608 CopyExpr = Result.get(); 13609 } 13610 } 13611 } 13612 } 13613 13614 // Actually capture the variable. 13615 if (BuildAndDiagnose) 13616 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 13617 SourceLocation(), CaptureType, CopyExpr); 13618 13619 return true; 13620 13621 } 13622 13623 13624 /// \brief Capture the given variable in the captured region. 13625 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 13626 VarDecl *Var, 13627 SourceLocation Loc, 13628 const bool BuildAndDiagnose, 13629 QualType &CaptureType, 13630 QualType &DeclRefType, 13631 const bool RefersToCapturedVariable, 13632 Sema &S) { 13633 // By default, capture variables by reference. 13634 bool ByRef = true; 13635 // Using an LValue reference type is consistent with Lambdas (see below). 13636 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 13637 if (S.IsOpenMPCapturedDecl(Var)) 13638 DeclRefType = DeclRefType.getUnqualifiedType(); 13639 ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel); 13640 } 13641 13642 if (ByRef) 13643 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 13644 else 13645 CaptureType = DeclRefType; 13646 13647 Expr *CopyExpr = nullptr; 13648 if (BuildAndDiagnose) { 13649 // The current implementation assumes that all variables are captured 13650 // by references. Since there is no capture by copy, no expression 13651 // evaluation will be needed. 13652 RecordDecl *RD = RSI->TheRecordDecl; 13653 13654 FieldDecl *Field 13655 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 13656 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 13657 nullptr, false, ICIS_NoInit); 13658 Field->setImplicit(true); 13659 Field->setAccess(AS_private); 13660 RD->addDecl(Field); 13661 13662 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, 13663 DeclRefType, VK_LValue, Loc); 13664 Var->setReferenced(true); 13665 Var->markUsed(S.Context); 13666 } 13667 13668 // Actually capture the variable. 13669 if (BuildAndDiagnose) 13670 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 13671 SourceLocation(), CaptureType, CopyExpr); 13672 13673 13674 return true; 13675 } 13676 13677 /// \brief Create a field within the lambda class for the variable 13678 /// being captured. 13679 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, 13680 QualType FieldType, QualType DeclRefType, 13681 SourceLocation Loc, 13682 bool RefersToCapturedVariable) { 13683 CXXRecordDecl *Lambda = LSI->Lambda; 13684 13685 // Build the non-static data member. 13686 FieldDecl *Field 13687 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 13688 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 13689 nullptr, false, ICIS_NoInit); 13690 Field->setImplicit(true); 13691 Field->setAccess(AS_private); 13692 Lambda->addDecl(Field); 13693 } 13694 13695 /// \brief Capture the given variable in the lambda. 13696 static bool captureInLambda(LambdaScopeInfo *LSI, 13697 VarDecl *Var, 13698 SourceLocation Loc, 13699 const bool BuildAndDiagnose, 13700 QualType &CaptureType, 13701 QualType &DeclRefType, 13702 const bool RefersToCapturedVariable, 13703 const Sema::TryCaptureKind Kind, 13704 SourceLocation EllipsisLoc, 13705 const bool IsTopScope, 13706 Sema &S) { 13707 13708 // Determine whether we are capturing by reference or by value. 13709 bool ByRef = false; 13710 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 13711 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 13712 } else { 13713 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 13714 } 13715 13716 // Compute the type of the field that will capture this variable. 13717 if (ByRef) { 13718 // C++11 [expr.prim.lambda]p15: 13719 // An entity is captured by reference if it is implicitly or 13720 // explicitly captured but not captured by copy. It is 13721 // unspecified whether additional unnamed non-static data 13722 // members are declared in the closure type for entities 13723 // captured by reference. 13724 // 13725 // FIXME: It is not clear whether we want to build an lvalue reference 13726 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 13727 // to do the former, while EDG does the latter. Core issue 1249 will 13728 // clarify, but for now we follow GCC because it's a more permissive and 13729 // easily defensible position. 13730 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 13731 } else { 13732 // C++11 [expr.prim.lambda]p14: 13733 // For each entity captured by copy, an unnamed non-static 13734 // data member is declared in the closure type. The 13735 // declaration order of these members is unspecified. The type 13736 // of such a data member is the type of the corresponding 13737 // captured entity if the entity is not a reference to an 13738 // object, or the referenced type otherwise. [Note: If the 13739 // captured entity is a reference to a function, the 13740 // corresponding data member is also a reference to a 13741 // function. - end note ] 13742 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 13743 if (!RefType->getPointeeType()->isFunctionType()) 13744 CaptureType = RefType->getPointeeType(); 13745 } 13746 13747 // Forbid the lambda copy-capture of autoreleasing variables. 13748 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 13749 if (BuildAndDiagnose) { 13750 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 13751 S.Diag(Var->getLocation(), diag::note_previous_decl) 13752 << Var->getDeclName(); 13753 } 13754 return false; 13755 } 13756 13757 // Make sure that by-copy captures are of a complete and non-abstract type. 13758 if (BuildAndDiagnose) { 13759 if (!CaptureType->isDependentType() && 13760 S.RequireCompleteType(Loc, CaptureType, 13761 diag::err_capture_of_incomplete_type, 13762 Var->getDeclName())) 13763 return false; 13764 13765 if (S.RequireNonAbstractType(Loc, CaptureType, 13766 diag::err_capture_of_abstract_type)) 13767 return false; 13768 } 13769 } 13770 13771 // Capture this variable in the lambda. 13772 if (BuildAndDiagnose) 13773 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc, 13774 RefersToCapturedVariable); 13775 13776 // Compute the type of a reference to this captured variable. 13777 if (ByRef) 13778 DeclRefType = CaptureType.getNonReferenceType(); 13779 else { 13780 // C++ [expr.prim.lambda]p5: 13781 // The closure type for a lambda-expression has a public inline 13782 // function call operator [...]. This function call operator is 13783 // declared const (9.3.1) if and only if the lambda-expression's 13784 // parameter-declaration-clause is not followed by mutable. 13785 DeclRefType = CaptureType.getNonReferenceType(); 13786 if (!LSI->Mutable && !CaptureType->isReferenceType()) 13787 DeclRefType.addConst(); 13788 } 13789 13790 // Add the capture. 13791 if (BuildAndDiagnose) 13792 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 13793 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 13794 13795 return true; 13796 } 13797 13798 bool Sema::tryCaptureVariable( 13799 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 13800 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 13801 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 13802 // An init-capture is notionally from the context surrounding its 13803 // declaration, but its parent DC is the lambda class. 13804 DeclContext *VarDC = Var->getDeclContext(); 13805 if (Var->isInitCapture()) 13806 VarDC = VarDC->getParent(); 13807 13808 DeclContext *DC = CurContext; 13809 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 13810 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 13811 // We need to sync up the Declaration Context with the 13812 // FunctionScopeIndexToStopAt 13813 if (FunctionScopeIndexToStopAt) { 13814 unsigned FSIndex = FunctionScopes.size() - 1; 13815 while (FSIndex != MaxFunctionScopesIndex) { 13816 DC = getLambdaAwareParentOfDeclContext(DC); 13817 --FSIndex; 13818 } 13819 } 13820 13821 13822 // If the variable is declared in the current context, there is no need to 13823 // capture it. 13824 if (VarDC == DC) return true; 13825 13826 // Capture global variables if it is required to use private copy of this 13827 // variable. 13828 bool IsGlobal = !Var->hasLocalStorage(); 13829 if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var))) 13830 return true; 13831 13832 // Walk up the stack to determine whether we can capture the variable, 13833 // performing the "simple" checks that don't depend on type. We stop when 13834 // we've either hit the declared scope of the variable or find an existing 13835 // capture of that variable. We start from the innermost capturing-entity 13836 // (the DC) and ensure that all intervening capturing-entities 13837 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 13838 // declcontext can either capture the variable or have already captured 13839 // the variable. 13840 CaptureType = Var->getType(); 13841 DeclRefType = CaptureType.getNonReferenceType(); 13842 bool Nested = false; 13843 bool Explicit = (Kind != TryCapture_Implicit); 13844 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 13845 do { 13846 // Only block literals, captured statements, and lambda expressions can 13847 // capture; other scopes don't work. 13848 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 13849 ExprLoc, 13850 BuildAndDiagnose, 13851 *this); 13852 // We need to check for the parent *first* because, if we *have* 13853 // private-captured a global variable, we need to recursively capture it in 13854 // intermediate blocks, lambdas, etc. 13855 if (!ParentDC) { 13856 if (IsGlobal) { 13857 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 13858 break; 13859 } 13860 return true; 13861 } 13862 13863 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 13864 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 13865 13866 13867 // Check whether we've already captured it. 13868 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 13869 DeclRefType)) 13870 break; 13871 // If we are instantiating a generic lambda call operator body, 13872 // we do not want to capture new variables. What was captured 13873 // during either a lambdas transformation or initial parsing 13874 // should be used. 13875 if (isGenericLambdaCallOperatorSpecialization(DC)) { 13876 if (BuildAndDiagnose) { 13877 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 13878 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 13879 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 13880 Diag(Var->getLocation(), diag::note_previous_decl) 13881 << Var->getDeclName(); 13882 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); 13883 } else 13884 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 13885 } 13886 return true; 13887 } 13888 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 13889 // certain types of variables (unnamed, variably modified types etc.) 13890 // so check for eligibility. 13891 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 13892 return true; 13893 13894 // Try to capture variable-length arrays types. 13895 if (Var->getType()->isVariablyModifiedType()) { 13896 // We're going to walk down into the type and look for VLA 13897 // expressions. 13898 QualType QTy = Var->getType(); 13899 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 13900 QTy = PVD->getOriginalType(); 13901 captureVariablyModifiedType(Context, QTy, CSI); 13902 } 13903 13904 if (getLangOpts().OpenMP) { 13905 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13906 // OpenMP private variables should not be captured in outer scope, so 13907 // just break here. Similarly, global variables that are captured in a 13908 // target region should not be captured outside the scope of the region. 13909 if (RSI->CapRegionKind == CR_OpenMP) { 13910 auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 13911 // When we detect target captures we are looking from inside the 13912 // target region, therefore we need to propagate the capture from the 13913 // enclosing region. Therefore, the capture is not initially nested. 13914 if (IsTargetCap) 13915 FunctionScopesIndex--; 13916 13917 if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) { 13918 Nested = !IsTargetCap; 13919 DeclRefType = DeclRefType.getUnqualifiedType(); 13920 CaptureType = Context.getLValueReferenceType(DeclRefType); 13921 break; 13922 } 13923 } 13924 } 13925 } 13926 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 13927 // No capture-default, and this is not an explicit capture 13928 // so cannot capture this variable. 13929 if (BuildAndDiagnose) { 13930 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 13931 Diag(Var->getLocation(), diag::note_previous_decl) 13932 << Var->getDeclName(); 13933 if (cast<LambdaScopeInfo>(CSI)->Lambda) 13934 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 13935 diag::note_lambda_decl); 13936 // FIXME: If we error out because an outer lambda can not implicitly 13937 // capture a variable that an inner lambda explicitly captures, we 13938 // should have the inner lambda do the explicit capture - because 13939 // it makes for cleaner diagnostics later. This would purely be done 13940 // so that the diagnostic does not misleadingly claim that a variable 13941 // can not be captured by a lambda implicitly even though it is captured 13942 // explicitly. Suggestion: 13943 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 13944 // at the function head 13945 // - cache the StartingDeclContext - this must be a lambda 13946 // - captureInLambda in the innermost lambda the variable. 13947 } 13948 return true; 13949 } 13950 13951 FunctionScopesIndex--; 13952 DC = ParentDC; 13953 Explicit = false; 13954 } while (!VarDC->Equals(DC)); 13955 13956 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 13957 // computing the type of the capture at each step, checking type-specific 13958 // requirements, and adding captures if requested. 13959 // If the variable had already been captured previously, we start capturing 13960 // at the lambda nested within that one. 13961 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 13962 ++I) { 13963 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 13964 13965 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 13966 if (!captureInBlock(BSI, Var, ExprLoc, 13967 BuildAndDiagnose, CaptureType, 13968 DeclRefType, Nested, *this)) 13969 return true; 13970 Nested = true; 13971 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13972 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 13973 BuildAndDiagnose, CaptureType, 13974 DeclRefType, Nested, *this)) 13975 return true; 13976 Nested = true; 13977 } else { 13978 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 13979 if (!captureInLambda(LSI, Var, ExprLoc, 13980 BuildAndDiagnose, CaptureType, 13981 DeclRefType, Nested, Kind, EllipsisLoc, 13982 /*IsTopScope*/I == N - 1, *this)) 13983 return true; 13984 Nested = true; 13985 } 13986 } 13987 return false; 13988 } 13989 13990 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 13991 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 13992 QualType CaptureType; 13993 QualType DeclRefType; 13994 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 13995 /*BuildAndDiagnose=*/true, CaptureType, 13996 DeclRefType, nullptr); 13997 } 13998 13999 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 14000 QualType CaptureType; 14001 QualType DeclRefType; 14002 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 14003 /*BuildAndDiagnose=*/false, CaptureType, 14004 DeclRefType, nullptr); 14005 } 14006 14007 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 14008 QualType CaptureType; 14009 QualType DeclRefType; 14010 14011 // Determine whether we can capture this variable. 14012 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 14013 /*BuildAndDiagnose=*/false, CaptureType, 14014 DeclRefType, nullptr)) 14015 return QualType(); 14016 14017 return DeclRefType; 14018 } 14019 14020 14021 14022 // If either the type of the variable or the initializer is dependent, 14023 // return false. Otherwise, determine whether the variable is a constant 14024 // expression. Use this if you need to know if a variable that might or 14025 // might not be dependent is truly a constant expression. 14026 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 14027 ASTContext &Context) { 14028 14029 if (Var->getType()->isDependentType()) 14030 return false; 14031 const VarDecl *DefVD = nullptr; 14032 Var->getAnyInitializer(DefVD); 14033 if (!DefVD) 14034 return false; 14035 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 14036 Expr *Init = cast<Expr>(Eval->Value); 14037 if (Init->isValueDependent()) 14038 return false; 14039 return IsVariableAConstantExpression(Var, Context); 14040 } 14041 14042 14043 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 14044 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 14045 // an object that satisfies the requirements for appearing in a 14046 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 14047 // is immediately applied." This function handles the lvalue-to-rvalue 14048 // conversion part. 14049 MaybeODRUseExprs.erase(E->IgnoreParens()); 14050 14051 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 14052 // to a variable that is a constant expression, and if so, identify it as 14053 // a reference to a variable that does not involve an odr-use of that 14054 // variable. 14055 if (LambdaScopeInfo *LSI = getCurLambda()) { 14056 Expr *SansParensExpr = E->IgnoreParens(); 14057 VarDecl *Var = nullptr; 14058 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 14059 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 14060 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 14061 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 14062 14063 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 14064 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 14065 } 14066 } 14067 14068 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 14069 Res = CorrectDelayedTyposInExpr(Res); 14070 14071 if (!Res.isUsable()) 14072 return Res; 14073 14074 // If a constant-expression is a reference to a variable where we delay 14075 // deciding whether it is an odr-use, just assume we will apply the 14076 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 14077 // (a non-type template argument), we have special handling anyway. 14078 UpdateMarkingForLValueToRValue(Res.get()); 14079 return Res; 14080 } 14081 14082 void Sema::CleanupVarDeclMarking() { 14083 for (Expr *E : MaybeODRUseExprs) { 14084 VarDecl *Var; 14085 SourceLocation Loc; 14086 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 14087 Var = cast<VarDecl>(DRE->getDecl()); 14088 Loc = DRE->getLocation(); 14089 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 14090 Var = cast<VarDecl>(ME->getMemberDecl()); 14091 Loc = ME->getMemberLoc(); 14092 } else { 14093 llvm_unreachable("Unexpected expression"); 14094 } 14095 14096 MarkVarDeclODRUsed(Var, Loc, *this, 14097 /*MaxFunctionScopeIndex Pointer*/ nullptr); 14098 } 14099 14100 MaybeODRUseExprs.clear(); 14101 } 14102 14103 14104 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 14105 VarDecl *Var, Expr *E) { 14106 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 14107 "Invalid Expr argument to DoMarkVarDeclReferenced"); 14108 Var->setReferenced(); 14109 14110 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 14111 bool MarkODRUsed = true; 14112 14113 // If the context is not potentially evaluated, this is not an odr-use and 14114 // does not trigger instantiation. 14115 if (!IsPotentiallyEvaluatedContext(SemaRef)) { 14116 if (SemaRef.isUnevaluatedContext()) 14117 return; 14118 14119 // If we don't yet know whether this context is going to end up being an 14120 // evaluated context, and we're referencing a variable from an enclosing 14121 // scope, add a potential capture. 14122 // 14123 // FIXME: Is this necessary? These contexts are only used for default 14124 // arguments, where local variables can't be used. 14125 const bool RefersToEnclosingScope = 14126 (SemaRef.CurContext != Var->getDeclContext() && 14127 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 14128 if (RefersToEnclosingScope) { 14129 if (LambdaScopeInfo *const LSI = 14130 SemaRef.getCurLambda(/*IgnoreCapturedRegions=*/true)) { 14131 // If a variable could potentially be odr-used, defer marking it so 14132 // until we finish analyzing the full expression for any 14133 // lvalue-to-rvalue 14134 // or discarded value conversions that would obviate odr-use. 14135 // Add it to the list of potential captures that will be analyzed 14136 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 14137 // unless the variable is a reference that was initialized by a constant 14138 // expression (this will never need to be captured or odr-used). 14139 assert(E && "Capture variable should be used in an expression."); 14140 if (!Var->getType()->isReferenceType() || 14141 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 14142 LSI->addPotentialCapture(E->IgnoreParens()); 14143 } 14144 } 14145 14146 if (!isTemplateInstantiation(TSK)) 14147 return; 14148 14149 // Instantiate, but do not mark as odr-used, variable templates. 14150 MarkODRUsed = false; 14151 } 14152 14153 VarTemplateSpecializationDecl *VarSpec = 14154 dyn_cast<VarTemplateSpecializationDecl>(Var); 14155 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 14156 "Can't instantiate a partial template specialization."); 14157 14158 // If this might be a member specialization of a static data member, check 14159 // the specialization is visible. We already did the checks for variable 14160 // template specializations when we created them. 14161 if (TSK != TSK_Undeclared && !isa<VarTemplateSpecializationDecl>(Var)) 14162 SemaRef.checkSpecializationVisibility(Loc, Var); 14163 14164 // Perform implicit instantiation of static data members, static data member 14165 // templates of class templates, and variable template specializations. Delay 14166 // instantiations of variable templates, except for those that could be used 14167 // in a constant expression. 14168 if (isTemplateInstantiation(TSK)) { 14169 bool TryInstantiating = TSK == TSK_ImplicitInstantiation; 14170 14171 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) { 14172 if (Var->getPointOfInstantiation().isInvalid()) { 14173 // This is a modification of an existing AST node. Notify listeners. 14174 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 14175 L->StaticDataMemberInstantiated(Var); 14176 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context)) 14177 // Don't bother trying to instantiate it again, unless we might need 14178 // its initializer before we get to the end of the TU. 14179 TryInstantiating = false; 14180 } 14181 14182 if (Var->getPointOfInstantiation().isInvalid()) 14183 Var->setTemplateSpecializationKind(TSK, Loc); 14184 14185 if (TryInstantiating) { 14186 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 14187 bool InstantiationDependent = false; 14188 bool IsNonDependent = 14189 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 14190 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 14191 : true; 14192 14193 // Do not instantiate specializations that are still type-dependent. 14194 if (IsNonDependent) { 14195 if (Var->isUsableInConstantExpressions(SemaRef.Context)) { 14196 // Do not defer instantiations of variables which could be used in a 14197 // constant expression. 14198 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 14199 } else { 14200 SemaRef.PendingInstantiations 14201 .push_back(std::make_pair(Var, PointOfInstantiation)); 14202 } 14203 } 14204 } 14205 } 14206 14207 if (!MarkODRUsed) 14208 return; 14209 14210 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 14211 // the requirements for appearing in a constant expression (5.19) and, if 14212 // it is an object, the lvalue-to-rvalue conversion (4.1) 14213 // is immediately applied." We check the first part here, and 14214 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 14215 // Note that we use the C++11 definition everywhere because nothing in 14216 // C++03 depends on whether we get the C++03 version correct. The second 14217 // part does not apply to references, since they are not objects. 14218 if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) { 14219 // A reference initialized by a constant expression can never be 14220 // odr-used, so simply ignore it. 14221 if (!Var->getType()->isReferenceType()) 14222 SemaRef.MaybeODRUseExprs.insert(E); 14223 } else 14224 MarkVarDeclODRUsed(Var, Loc, SemaRef, 14225 /*MaxFunctionScopeIndex ptr*/ nullptr); 14226 } 14227 14228 /// \brief Mark a variable referenced, and check whether it is odr-used 14229 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 14230 /// used directly for normal expressions referring to VarDecl. 14231 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 14232 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 14233 } 14234 14235 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 14236 Decl *D, Expr *E, bool MightBeOdrUse) { 14237 if (SemaRef.isInOpenMPDeclareTargetContext()) 14238 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 14239 14240 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 14241 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 14242 return; 14243 } 14244 14245 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 14246 14247 // If this is a call to a method via a cast, also mark the method in the 14248 // derived class used in case codegen can devirtualize the call. 14249 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 14250 if (!ME) 14251 return; 14252 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 14253 if (!MD) 14254 return; 14255 // Only attempt to devirtualize if this is truly a virtual call. 14256 bool IsVirtualCall = MD->isVirtual() && 14257 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 14258 if (!IsVirtualCall) 14259 return; 14260 const Expr *Base = ME->getBase(); 14261 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType(); 14262 if (!MostDerivedClassDecl) 14263 return; 14264 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl); 14265 if (!DM || DM->isPure()) 14266 return; 14267 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 14268 } 14269 14270 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 14271 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) { 14272 // TODO: update this with DR# once a defect report is filed. 14273 // C++11 defect. The address of a pure member should not be an ODR use, even 14274 // if it's a qualified reference. 14275 bool OdrUse = true; 14276 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 14277 if (Method->isVirtual()) 14278 OdrUse = false; 14279 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 14280 } 14281 14282 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 14283 void Sema::MarkMemberReferenced(MemberExpr *E) { 14284 // C++11 [basic.def.odr]p2: 14285 // A non-overloaded function whose name appears as a potentially-evaluated 14286 // expression or a member of a set of candidate functions, if selected by 14287 // overload resolution when referred to from a potentially-evaluated 14288 // expression, is odr-used, unless it is a pure virtual function and its 14289 // name is not explicitly qualified. 14290 bool MightBeOdrUse = true; 14291 if (E->performsVirtualDispatch(getLangOpts())) { 14292 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 14293 if (Method->isPure()) 14294 MightBeOdrUse = false; 14295 } 14296 SourceLocation Loc = E->getMemberLoc().isValid() ? 14297 E->getMemberLoc() : E->getLocStart(); 14298 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 14299 } 14300 14301 /// \brief Perform marking for a reference to an arbitrary declaration. It 14302 /// marks the declaration referenced, and performs odr-use checking for 14303 /// functions and variables. This method should not be used when building a 14304 /// normal expression which refers to a variable. 14305 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 14306 bool MightBeOdrUse) { 14307 if (MightBeOdrUse) { 14308 if (auto *VD = dyn_cast<VarDecl>(D)) { 14309 MarkVariableReferenced(Loc, VD); 14310 return; 14311 } 14312 } 14313 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 14314 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 14315 return; 14316 } 14317 D->setReferenced(); 14318 } 14319 14320 namespace { 14321 // Mark all of the declarations referenced 14322 // FIXME: Not fully implemented yet! We need to have a better understanding 14323 // of when we're entering 14324 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 14325 Sema &S; 14326 SourceLocation Loc; 14327 14328 public: 14329 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 14330 14331 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 14332 14333 bool TraverseTemplateArgument(const TemplateArgument &Arg); 14334 bool TraverseRecordType(RecordType *T); 14335 }; 14336 } 14337 14338 bool MarkReferencedDecls::TraverseTemplateArgument( 14339 const TemplateArgument &Arg) { 14340 if (Arg.getKind() == TemplateArgument::Declaration) { 14341 if (Decl *D = Arg.getAsDecl()) 14342 S.MarkAnyDeclReferenced(Loc, D, true); 14343 } 14344 14345 return Inherited::TraverseTemplateArgument(Arg); 14346 } 14347 14348 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) { 14349 if (ClassTemplateSpecializationDecl *Spec 14350 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) { 14351 const TemplateArgumentList &Args = Spec->getTemplateArgs(); 14352 return TraverseTemplateArguments(Args.data(), Args.size()); 14353 } 14354 14355 return true; 14356 } 14357 14358 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 14359 MarkReferencedDecls Marker(*this, Loc); 14360 Marker.TraverseType(Context.getCanonicalType(T)); 14361 } 14362 14363 namespace { 14364 /// \brief Helper class that marks all of the declarations referenced by 14365 /// potentially-evaluated subexpressions as "referenced". 14366 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 14367 Sema &S; 14368 bool SkipLocalVariables; 14369 14370 public: 14371 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 14372 14373 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 14374 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 14375 14376 void VisitDeclRefExpr(DeclRefExpr *E) { 14377 // If we were asked not to visit local variables, don't. 14378 if (SkipLocalVariables) { 14379 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 14380 if (VD->hasLocalStorage()) 14381 return; 14382 } 14383 14384 S.MarkDeclRefReferenced(E); 14385 } 14386 14387 void VisitMemberExpr(MemberExpr *E) { 14388 S.MarkMemberReferenced(E); 14389 Inherited::VisitMemberExpr(E); 14390 } 14391 14392 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 14393 S.MarkFunctionReferenced(E->getLocStart(), 14394 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 14395 Visit(E->getSubExpr()); 14396 } 14397 14398 void VisitCXXNewExpr(CXXNewExpr *E) { 14399 if (E->getOperatorNew()) 14400 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 14401 if (E->getOperatorDelete()) 14402 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 14403 Inherited::VisitCXXNewExpr(E); 14404 } 14405 14406 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 14407 if (E->getOperatorDelete()) 14408 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 14409 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 14410 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 14411 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 14412 S.MarkFunctionReferenced(E->getLocStart(), 14413 S.LookupDestructor(Record)); 14414 } 14415 14416 Inherited::VisitCXXDeleteExpr(E); 14417 } 14418 14419 void VisitCXXConstructExpr(CXXConstructExpr *E) { 14420 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 14421 Inherited::VisitCXXConstructExpr(E); 14422 } 14423 14424 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 14425 Visit(E->getExpr()); 14426 } 14427 14428 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 14429 Inherited::VisitImplicitCastExpr(E); 14430 14431 if (E->getCastKind() == CK_LValueToRValue) 14432 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 14433 } 14434 }; 14435 } 14436 14437 /// \brief Mark any declarations that appear within this expression or any 14438 /// potentially-evaluated subexpressions as "referenced". 14439 /// 14440 /// \param SkipLocalVariables If true, don't mark local variables as 14441 /// 'referenced'. 14442 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 14443 bool SkipLocalVariables) { 14444 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 14445 } 14446 14447 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 14448 /// of the program being compiled. 14449 /// 14450 /// This routine emits the given diagnostic when the code currently being 14451 /// type-checked is "potentially evaluated", meaning that there is a 14452 /// possibility that the code will actually be executable. Code in sizeof() 14453 /// expressions, code used only during overload resolution, etc., are not 14454 /// potentially evaluated. This routine will suppress such diagnostics or, 14455 /// in the absolutely nutty case of potentially potentially evaluated 14456 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 14457 /// later. 14458 /// 14459 /// This routine should be used for all diagnostics that describe the run-time 14460 /// behavior of a program, such as passing a non-POD value through an ellipsis. 14461 /// Failure to do so will likely result in spurious diagnostics or failures 14462 /// during overload resolution or within sizeof/alignof/typeof/typeid. 14463 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 14464 const PartialDiagnostic &PD) { 14465 switch (ExprEvalContexts.back().Context) { 14466 case Unevaluated: 14467 case UnevaluatedAbstract: 14468 case DiscardedStatement: 14469 // The argument will never be evaluated, so don't complain. 14470 break; 14471 14472 case ConstantEvaluated: 14473 // Relevant diagnostics should be produced by constant evaluation. 14474 break; 14475 14476 case PotentiallyEvaluated: 14477 case PotentiallyEvaluatedIfUsed: 14478 if (Statement && getCurFunctionOrMethodDecl()) { 14479 FunctionScopes.back()->PossiblyUnreachableDiags. 14480 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 14481 } 14482 else 14483 Diag(Loc, PD); 14484 14485 return true; 14486 } 14487 14488 return false; 14489 } 14490 14491 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 14492 CallExpr *CE, FunctionDecl *FD) { 14493 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 14494 return false; 14495 14496 // If we're inside a decltype's expression, don't check for a valid return 14497 // type or construct temporaries until we know whether this is the last call. 14498 if (ExprEvalContexts.back().IsDecltype) { 14499 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 14500 return false; 14501 } 14502 14503 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 14504 FunctionDecl *FD; 14505 CallExpr *CE; 14506 14507 public: 14508 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 14509 : FD(FD), CE(CE) { } 14510 14511 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 14512 if (!FD) { 14513 S.Diag(Loc, diag::err_call_incomplete_return) 14514 << T << CE->getSourceRange(); 14515 return; 14516 } 14517 14518 S.Diag(Loc, diag::err_call_function_incomplete_return) 14519 << CE->getSourceRange() << FD->getDeclName() << T; 14520 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 14521 << FD->getDeclName(); 14522 } 14523 } Diagnoser(FD, CE); 14524 14525 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 14526 return true; 14527 14528 return false; 14529 } 14530 14531 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 14532 // will prevent this condition from triggering, which is what we want. 14533 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 14534 SourceLocation Loc; 14535 14536 unsigned diagnostic = diag::warn_condition_is_assignment; 14537 bool IsOrAssign = false; 14538 14539 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 14540 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 14541 return; 14542 14543 IsOrAssign = Op->getOpcode() == BO_OrAssign; 14544 14545 // Greylist some idioms by putting them into a warning subcategory. 14546 if (ObjCMessageExpr *ME 14547 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 14548 Selector Sel = ME->getSelector(); 14549 14550 // self = [<foo> init...] 14551 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 14552 diagnostic = diag::warn_condition_is_idiomatic_assignment; 14553 14554 // <foo> = [<bar> nextObject] 14555 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 14556 diagnostic = diag::warn_condition_is_idiomatic_assignment; 14557 } 14558 14559 Loc = Op->getOperatorLoc(); 14560 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 14561 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 14562 return; 14563 14564 IsOrAssign = Op->getOperator() == OO_PipeEqual; 14565 Loc = Op->getOperatorLoc(); 14566 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 14567 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 14568 else { 14569 // Not an assignment. 14570 return; 14571 } 14572 14573 Diag(Loc, diagnostic) << E->getSourceRange(); 14574 14575 SourceLocation Open = E->getLocStart(); 14576 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 14577 Diag(Loc, diag::note_condition_assign_silence) 14578 << FixItHint::CreateInsertion(Open, "(") 14579 << FixItHint::CreateInsertion(Close, ")"); 14580 14581 if (IsOrAssign) 14582 Diag(Loc, diag::note_condition_or_assign_to_comparison) 14583 << FixItHint::CreateReplacement(Loc, "!="); 14584 else 14585 Diag(Loc, diag::note_condition_assign_to_comparison) 14586 << FixItHint::CreateReplacement(Loc, "=="); 14587 } 14588 14589 /// \brief Redundant parentheses over an equality comparison can indicate 14590 /// that the user intended an assignment used as condition. 14591 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 14592 // Don't warn if the parens came from a macro. 14593 SourceLocation parenLoc = ParenE->getLocStart(); 14594 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 14595 return; 14596 // Don't warn for dependent expressions. 14597 if (ParenE->isTypeDependent()) 14598 return; 14599 14600 Expr *E = ParenE->IgnoreParens(); 14601 14602 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 14603 if (opE->getOpcode() == BO_EQ && 14604 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 14605 == Expr::MLV_Valid) { 14606 SourceLocation Loc = opE->getOperatorLoc(); 14607 14608 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 14609 SourceRange ParenERange = ParenE->getSourceRange(); 14610 Diag(Loc, diag::note_equality_comparison_silence) 14611 << FixItHint::CreateRemoval(ParenERange.getBegin()) 14612 << FixItHint::CreateRemoval(ParenERange.getEnd()); 14613 Diag(Loc, diag::note_equality_comparison_to_assign) 14614 << FixItHint::CreateReplacement(Loc, "="); 14615 } 14616 } 14617 14618 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 14619 bool IsConstexpr) { 14620 DiagnoseAssignmentAsCondition(E); 14621 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 14622 DiagnoseEqualityWithExtraParens(parenE); 14623 14624 ExprResult result = CheckPlaceholderExpr(E); 14625 if (result.isInvalid()) return ExprError(); 14626 E = result.get(); 14627 14628 if (!E->isTypeDependent()) { 14629 if (getLangOpts().CPlusPlus) 14630 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 14631 14632 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 14633 if (ERes.isInvalid()) 14634 return ExprError(); 14635 E = ERes.get(); 14636 14637 QualType T = E->getType(); 14638 if (!T->isScalarType()) { // C99 6.8.4.1p1 14639 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 14640 << T << E->getSourceRange(); 14641 return ExprError(); 14642 } 14643 CheckBoolLikeConversion(E, Loc); 14644 } 14645 14646 return E; 14647 } 14648 14649 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 14650 Expr *SubExpr, ConditionKind CK) { 14651 // Empty conditions are valid in for-statements. 14652 if (!SubExpr) 14653 return ConditionResult(); 14654 14655 ExprResult Cond; 14656 switch (CK) { 14657 case ConditionKind::Boolean: 14658 Cond = CheckBooleanCondition(Loc, SubExpr); 14659 break; 14660 14661 case ConditionKind::ConstexprIf: 14662 Cond = CheckBooleanCondition(Loc, SubExpr, true); 14663 break; 14664 14665 case ConditionKind::Switch: 14666 Cond = CheckSwitchCondition(Loc, SubExpr); 14667 break; 14668 } 14669 if (Cond.isInvalid()) 14670 return ConditionError(); 14671 14672 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 14673 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 14674 if (!FullExpr.get()) 14675 return ConditionError(); 14676 14677 return ConditionResult(*this, nullptr, FullExpr, 14678 CK == ConditionKind::ConstexprIf); 14679 } 14680 14681 namespace { 14682 /// A visitor for rebuilding a call to an __unknown_any expression 14683 /// to have an appropriate type. 14684 struct RebuildUnknownAnyFunction 14685 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 14686 14687 Sema &S; 14688 14689 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 14690 14691 ExprResult VisitStmt(Stmt *S) { 14692 llvm_unreachable("unexpected statement!"); 14693 } 14694 14695 ExprResult VisitExpr(Expr *E) { 14696 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 14697 << E->getSourceRange(); 14698 return ExprError(); 14699 } 14700 14701 /// Rebuild an expression which simply semantically wraps another 14702 /// expression which it shares the type and value kind of. 14703 template <class T> ExprResult rebuildSugarExpr(T *E) { 14704 ExprResult SubResult = Visit(E->getSubExpr()); 14705 if (SubResult.isInvalid()) return ExprError(); 14706 14707 Expr *SubExpr = SubResult.get(); 14708 E->setSubExpr(SubExpr); 14709 E->setType(SubExpr->getType()); 14710 E->setValueKind(SubExpr->getValueKind()); 14711 assert(E->getObjectKind() == OK_Ordinary); 14712 return E; 14713 } 14714 14715 ExprResult VisitParenExpr(ParenExpr *E) { 14716 return rebuildSugarExpr(E); 14717 } 14718 14719 ExprResult VisitUnaryExtension(UnaryOperator *E) { 14720 return rebuildSugarExpr(E); 14721 } 14722 14723 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 14724 ExprResult SubResult = Visit(E->getSubExpr()); 14725 if (SubResult.isInvalid()) return ExprError(); 14726 14727 Expr *SubExpr = SubResult.get(); 14728 E->setSubExpr(SubExpr); 14729 E->setType(S.Context.getPointerType(SubExpr->getType())); 14730 assert(E->getValueKind() == VK_RValue); 14731 assert(E->getObjectKind() == OK_Ordinary); 14732 return E; 14733 } 14734 14735 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 14736 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 14737 14738 E->setType(VD->getType()); 14739 14740 assert(E->getValueKind() == VK_RValue); 14741 if (S.getLangOpts().CPlusPlus && 14742 !(isa<CXXMethodDecl>(VD) && 14743 cast<CXXMethodDecl>(VD)->isInstance())) 14744 E->setValueKind(VK_LValue); 14745 14746 return E; 14747 } 14748 14749 ExprResult VisitMemberExpr(MemberExpr *E) { 14750 return resolveDecl(E, E->getMemberDecl()); 14751 } 14752 14753 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 14754 return resolveDecl(E, E->getDecl()); 14755 } 14756 }; 14757 } 14758 14759 /// Given a function expression of unknown-any type, try to rebuild it 14760 /// to have a function type. 14761 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 14762 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 14763 if (Result.isInvalid()) return ExprError(); 14764 return S.DefaultFunctionArrayConversion(Result.get()); 14765 } 14766 14767 namespace { 14768 /// A visitor for rebuilding an expression of type __unknown_anytype 14769 /// into one which resolves the type directly on the referring 14770 /// expression. Strict preservation of the original source 14771 /// structure is not a goal. 14772 struct RebuildUnknownAnyExpr 14773 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 14774 14775 Sema &S; 14776 14777 /// The current destination type. 14778 QualType DestType; 14779 14780 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 14781 : S(S), DestType(CastType) {} 14782 14783 ExprResult VisitStmt(Stmt *S) { 14784 llvm_unreachable("unexpected statement!"); 14785 } 14786 14787 ExprResult VisitExpr(Expr *E) { 14788 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 14789 << E->getSourceRange(); 14790 return ExprError(); 14791 } 14792 14793 ExprResult VisitCallExpr(CallExpr *E); 14794 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 14795 14796 /// Rebuild an expression which simply semantically wraps another 14797 /// expression which it shares the type and value kind of. 14798 template <class T> ExprResult rebuildSugarExpr(T *E) { 14799 ExprResult SubResult = Visit(E->getSubExpr()); 14800 if (SubResult.isInvalid()) return ExprError(); 14801 Expr *SubExpr = SubResult.get(); 14802 E->setSubExpr(SubExpr); 14803 E->setType(SubExpr->getType()); 14804 E->setValueKind(SubExpr->getValueKind()); 14805 assert(E->getObjectKind() == OK_Ordinary); 14806 return E; 14807 } 14808 14809 ExprResult VisitParenExpr(ParenExpr *E) { 14810 return rebuildSugarExpr(E); 14811 } 14812 14813 ExprResult VisitUnaryExtension(UnaryOperator *E) { 14814 return rebuildSugarExpr(E); 14815 } 14816 14817 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 14818 const PointerType *Ptr = DestType->getAs<PointerType>(); 14819 if (!Ptr) { 14820 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 14821 << E->getSourceRange(); 14822 return ExprError(); 14823 } 14824 14825 if (isa<CallExpr>(E->getSubExpr())) { 14826 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 14827 << E->getSourceRange(); 14828 return ExprError(); 14829 } 14830 14831 assert(E->getValueKind() == VK_RValue); 14832 assert(E->getObjectKind() == OK_Ordinary); 14833 E->setType(DestType); 14834 14835 // Build the sub-expression as if it were an object of the pointee type. 14836 DestType = Ptr->getPointeeType(); 14837 ExprResult SubResult = Visit(E->getSubExpr()); 14838 if (SubResult.isInvalid()) return ExprError(); 14839 E->setSubExpr(SubResult.get()); 14840 return E; 14841 } 14842 14843 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 14844 14845 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 14846 14847 ExprResult VisitMemberExpr(MemberExpr *E) { 14848 return resolveDecl(E, E->getMemberDecl()); 14849 } 14850 14851 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 14852 return resolveDecl(E, E->getDecl()); 14853 } 14854 }; 14855 } 14856 14857 /// Rebuilds a call expression which yielded __unknown_anytype. 14858 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 14859 Expr *CalleeExpr = E->getCallee(); 14860 14861 enum FnKind { 14862 FK_MemberFunction, 14863 FK_FunctionPointer, 14864 FK_BlockPointer 14865 }; 14866 14867 FnKind Kind; 14868 QualType CalleeType = CalleeExpr->getType(); 14869 if (CalleeType == S.Context.BoundMemberTy) { 14870 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 14871 Kind = FK_MemberFunction; 14872 CalleeType = Expr::findBoundMemberType(CalleeExpr); 14873 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 14874 CalleeType = Ptr->getPointeeType(); 14875 Kind = FK_FunctionPointer; 14876 } else { 14877 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 14878 Kind = FK_BlockPointer; 14879 } 14880 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 14881 14882 // Verify that this is a legal result type of a function. 14883 if (DestType->isArrayType() || DestType->isFunctionType()) { 14884 unsigned diagID = diag::err_func_returning_array_function; 14885 if (Kind == FK_BlockPointer) 14886 diagID = diag::err_block_returning_array_function; 14887 14888 S.Diag(E->getExprLoc(), diagID) 14889 << DestType->isFunctionType() << DestType; 14890 return ExprError(); 14891 } 14892 14893 // Otherwise, go ahead and set DestType as the call's result. 14894 E->setType(DestType.getNonLValueExprType(S.Context)); 14895 E->setValueKind(Expr::getValueKindForType(DestType)); 14896 assert(E->getObjectKind() == OK_Ordinary); 14897 14898 // Rebuild the function type, replacing the result type with DestType. 14899 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 14900 if (Proto) { 14901 // __unknown_anytype(...) is a special case used by the debugger when 14902 // it has no idea what a function's signature is. 14903 // 14904 // We want to build this call essentially under the K&R 14905 // unprototyped rules, but making a FunctionNoProtoType in C++ 14906 // would foul up all sorts of assumptions. However, we cannot 14907 // simply pass all arguments as variadic arguments, nor can we 14908 // portably just call the function under a non-variadic type; see 14909 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 14910 // However, it turns out that in practice it is generally safe to 14911 // call a function declared as "A foo(B,C,D);" under the prototype 14912 // "A foo(B,C,D,...);". The only known exception is with the 14913 // Windows ABI, where any variadic function is implicitly cdecl 14914 // regardless of its normal CC. Therefore we change the parameter 14915 // types to match the types of the arguments. 14916 // 14917 // This is a hack, but it is far superior to moving the 14918 // corresponding target-specific code from IR-gen to Sema/AST. 14919 14920 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 14921 SmallVector<QualType, 8> ArgTypes; 14922 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 14923 ArgTypes.reserve(E->getNumArgs()); 14924 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 14925 Expr *Arg = E->getArg(i); 14926 QualType ArgType = Arg->getType(); 14927 if (E->isLValue()) { 14928 ArgType = S.Context.getLValueReferenceType(ArgType); 14929 } else if (E->isXValue()) { 14930 ArgType = S.Context.getRValueReferenceType(ArgType); 14931 } 14932 ArgTypes.push_back(ArgType); 14933 } 14934 ParamTypes = ArgTypes; 14935 } 14936 DestType = S.Context.getFunctionType(DestType, ParamTypes, 14937 Proto->getExtProtoInfo()); 14938 } else { 14939 DestType = S.Context.getFunctionNoProtoType(DestType, 14940 FnType->getExtInfo()); 14941 } 14942 14943 // Rebuild the appropriate pointer-to-function type. 14944 switch (Kind) { 14945 case FK_MemberFunction: 14946 // Nothing to do. 14947 break; 14948 14949 case FK_FunctionPointer: 14950 DestType = S.Context.getPointerType(DestType); 14951 break; 14952 14953 case FK_BlockPointer: 14954 DestType = S.Context.getBlockPointerType(DestType); 14955 break; 14956 } 14957 14958 // Finally, we can recurse. 14959 ExprResult CalleeResult = Visit(CalleeExpr); 14960 if (!CalleeResult.isUsable()) return ExprError(); 14961 E->setCallee(CalleeResult.get()); 14962 14963 // Bind a temporary if necessary. 14964 return S.MaybeBindToTemporary(E); 14965 } 14966 14967 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 14968 // Verify that this is a legal result type of a call. 14969 if (DestType->isArrayType() || DestType->isFunctionType()) { 14970 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 14971 << DestType->isFunctionType() << DestType; 14972 return ExprError(); 14973 } 14974 14975 // Rewrite the method result type if available. 14976 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 14977 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 14978 Method->setReturnType(DestType); 14979 } 14980 14981 // Change the type of the message. 14982 E->setType(DestType.getNonReferenceType()); 14983 E->setValueKind(Expr::getValueKindForType(DestType)); 14984 14985 return S.MaybeBindToTemporary(E); 14986 } 14987 14988 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 14989 // The only case we should ever see here is a function-to-pointer decay. 14990 if (E->getCastKind() == CK_FunctionToPointerDecay) { 14991 assert(E->getValueKind() == VK_RValue); 14992 assert(E->getObjectKind() == OK_Ordinary); 14993 14994 E->setType(DestType); 14995 14996 // Rebuild the sub-expression as the pointee (function) type. 14997 DestType = DestType->castAs<PointerType>()->getPointeeType(); 14998 14999 ExprResult Result = Visit(E->getSubExpr()); 15000 if (!Result.isUsable()) return ExprError(); 15001 15002 E->setSubExpr(Result.get()); 15003 return E; 15004 } else if (E->getCastKind() == CK_LValueToRValue) { 15005 assert(E->getValueKind() == VK_RValue); 15006 assert(E->getObjectKind() == OK_Ordinary); 15007 15008 assert(isa<BlockPointerType>(E->getType())); 15009 15010 E->setType(DestType); 15011 15012 // The sub-expression has to be a lvalue reference, so rebuild it as such. 15013 DestType = S.Context.getLValueReferenceType(DestType); 15014 15015 ExprResult Result = Visit(E->getSubExpr()); 15016 if (!Result.isUsable()) return ExprError(); 15017 15018 E->setSubExpr(Result.get()); 15019 return E; 15020 } else { 15021 llvm_unreachable("Unhandled cast type!"); 15022 } 15023 } 15024 15025 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 15026 ExprValueKind ValueKind = VK_LValue; 15027 QualType Type = DestType; 15028 15029 // We know how to make this work for certain kinds of decls: 15030 15031 // - functions 15032 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 15033 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 15034 DestType = Ptr->getPointeeType(); 15035 ExprResult Result = resolveDecl(E, VD); 15036 if (Result.isInvalid()) return ExprError(); 15037 return S.ImpCastExprToType(Result.get(), Type, 15038 CK_FunctionToPointerDecay, VK_RValue); 15039 } 15040 15041 if (!Type->isFunctionType()) { 15042 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 15043 << VD << E->getSourceRange(); 15044 return ExprError(); 15045 } 15046 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 15047 // We must match the FunctionDecl's type to the hack introduced in 15048 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 15049 // type. See the lengthy commentary in that routine. 15050 QualType FDT = FD->getType(); 15051 const FunctionType *FnType = FDT->castAs<FunctionType>(); 15052 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 15053 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 15054 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 15055 SourceLocation Loc = FD->getLocation(); 15056 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(), 15057 FD->getDeclContext(), 15058 Loc, Loc, FD->getNameInfo().getName(), 15059 DestType, FD->getTypeSourceInfo(), 15060 SC_None, false/*isInlineSpecified*/, 15061 FD->hasPrototype(), 15062 false/*isConstexprSpecified*/); 15063 15064 if (FD->getQualifier()) 15065 NewFD->setQualifierInfo(FD->getQualifierLoc()); 15066 15067 SmallVector<ParmVarDecl*, 16> Params; 15068 for (const auto &AI : FT->param_types()) { 15069 ParmVarDecl *Param = 15070 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 15071 Param->setScopeInfo(0, Params.size()); 15072 Params.push_back(Param); 15073 } 15074 NewFD->setParams(Params); 15075 DRE->setDecl(NewFD); 15076 VD = DRE->getDecl(); 15077 } 15078 } 15079 15080 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 15081 if (MD->isInstance()) { 15082 ValueKind = VK_RValue; 15083 Type = S.Context.BoundMemberTy; 15084 } 15085 15086 // Function references aren't l-values in C. 15087 if (!S.getLangOpts().CPlusPlus) 15088 ValueKind = VK_RValue; 15089 15090 // - variables 15091 } else if (isa<VarDecl>(VD)) { 15092 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 15093 Type = RefTy->getPointeeType(); 15094 } else if (Type->isFunctionType()) { 15095 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 15096 << VD << E->getSourceRange(); 15097 return ExprError(); 15098 } 15099 15100 // - nothing else 15101 } else { 15102 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 15103 << VD << E->getSourceRange(); 15104 return ExprError(); 15105 } 15106 15107 // Modifying the declaration like this is friendly to IR-gen but 15108 // also really dangerous. 15109 VD->setType(DestType); 15110 E->setType(Type); 15111 E->setValueKind(ValueKind); 15112 return E; 15113 } 15114 15115 /// Check a cast of an unknown-any type. We intentionally only 15116 /// trigger this for C-style casts. 15117 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 15118 Expr *CastExpr, CastKind &CastKind, 15119 ExprValueKind &VK, CXXCastPath &Path) { 15120 // The type we're casting to must be either void or complete. 15121 if (!CastType->isVoidType() && 15122 RequireCompleteType(TypeRange.getBegin(), CastType, 15123 diag::err_typecheck_cast_to_incomplete)) 15124 return ExprError(); 15125 15126 // Rewrite the casted expression from scratch. 15127 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 15128 if (!result.isUsable()) return ExprError(); 15129 15130 CastExpr = result.get(); 15131 VK = CastExpr->getValueKind(); 15132 CastKind = CK_NoOp; 15133 15134 return CastExpr; 15135 } 15136 15137 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 15138 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 15139 } 15140 15141 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 15142 Expr *arg, QualType ¶mType) { 15143 // If the syntactic form of the argument is not an explicit cast of 15144 // any sort, just do default argument promotion. 15145 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 15146 if (!castArg) { 15147 ExprResult result = DefaultArgumentPromotion(arg); 15148 if (result.isInvalid()) return ExprError(); 15149 paramType = result.get()->getType(); 15150 return result; 15151 } 15152 15153 // Otherwise, use the type that was written in the explicit cast. 15154 assert(!arg->hasPlaceholderType()); 15155 paramType = castArg->getTypeAsWritten(); 15156 15157 // Copy-initialize a parameter of that type. 15158 InitializedEntity entity = 15159 InitializedEntity::InitializeParameter(Context, paramType, 15160 /*consumed*/ false); 15161 return PerformCopyInitialization(entity, callLoc, arg); 15162 } 15163 15164 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 15165 Expr *orig = E; 15166 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 15167 while (true) { 15168 E = E->IgnoreParenImpCasts(); 15169 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 15170 E = call->getCallee(); 15171 diagID = diag::err_uncasted_call_of_unknown_any; 15172 } else { 15173 break; 15174 } 15175 } 15176 15177 SourceLocation loc; 15178 NamedDecl *d; 15179 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 15180 loc = ref->getLocation(); 15181 d = ref->getDecl(); 15182 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 15183 loc = mem->getMemberLoc(); 15184 d = mem->getMemberDecl(); 15185 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 15186 diagID = diag::err_uncasted_call_of_unknown_any; 15187 loc = msg->getSelectorStartLoc(); 15188 d = msg->getMethodDecl(); 15189 if (!d) { 15190 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 15191 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 15192 << orig->getSourceRange(); 15193 return ExprError(); 15194 } 15195 } else { 15196 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 15197 << E->getSourceRange(); 15198 return ExprError(); 15199 } 15200 15201 S.Diag(loc, diagID) << d << orig->getSourceRange(); 15202 15203 // Never recoverable. 15204 return ExprError(); 15205 } 15206 15207 /// Check for operands with placeholder types and complain if found. 15208 /// Returns true if there was an error and no recovery was possible. 15209 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 15210 if (!getLangOpts().CPlusPlus) { 15211 // C cannot handle TypoExpr nodes on either side of a binop because it 15212 // doesn't handle dependent types properly, so make sure any TypoExprs have 15213 // been dealt with before checking the operands. 15214 ExprResult Result = CorrectDelayedTyposInExpr(E); 15215 if (!Result.isUsable()) return ExprError(); 15216 E = Result.get(); 15217 } 15218 15219 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 15220 if (!placeholderType) return E; 15221 15222 switch (placeholderType->getKind()) { 15223 15224 // Overloaded expressions. 15225 case BuiltinType::Overload: { 15226 // Try to resolve a single function template specialization. 15227 // This is obligatory. 15228 ExprResult Result = E; 15229 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 15230 return Result; 15231 15232 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 15233 // leaves Result unchanged on failure. 15234 Result = E; 15235 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) 15236 return Result; 15237 15238 // If that failed, try to recover with a call. 15239 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 15240 /*complain*/ true); 15241 return Result; 15242 } 15243 15244 // Bound member functions. 15245 case BuiltinType::BoundMember: { 15246 ExprResult result = E; 15247 const Expr *BME = E->IgnoreParens(); 15248 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 15249 // Try to give a nicer diagnostic if it is a bound member that we recognize. 15250 if (isa<CXXPseudoDestructorExpr>(BME)) { 15251 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 15252 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 15253 if (ME->getMemberNameInfo().getName().getNameKind() == 15254 DeclarationName::CXXDestructorName) 15255 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 15256 } 15257 tryToRecoverWithCall(result, PD, 15258 /*complain*/ true); 15259 return result; 15260 } 15261 15262 // ARC unbridged casts. 15263 case BuiltinType::ARCUnbridgedCast: { 15264 Expr *realCast = stripARCUnbridgedCast(E); 15265 diagnoseARCUnbridgedCast(realCast); 15266 return realCast; 15267 } 15268 15269 // Expressions of unknown type. 15270 case BuiltinType::UnknownAny: 15271 return diagnoseUnknownAnyExpr(*this, E); 15272 15273 // Pseudo-objects. 15274 case BuiltinType::PseudoObject: 15275 return checkPseudoObjectRValue(E); 15276 15277 case BuiltinType::BuiltinFn: { 15278 // Accept __noop without parens by implicitly converting it to a call expr. 15279 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 15280 if (DRE) { 15281 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 15282 if (FD->getBuiltinID() == Builtin::BI__noop) { 15283 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 15284 CK_BuiltinFnToFnPtr).get(); 15285 return new (Context) CallExpr(Context, E, None, Context.IntTy, 15286 VK_RValue, SourceLocation()); 15287 } 15288 } 15289 15290 Diag(E->getLocStart(), diag::err_builtin_fn_use); 15291 return ExprError(); 15292 } 15293 15294 // Expressions of unknown type. 15295 case BuiltinType::OMPArraySection: 15296 Diag(E->getLocStart(), diag::err_omp_array_section_use); 15297 return ExprError(); 15298 15299 // Everything else should be impossible. 15300 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 15301 case BuiltinType::Id: 15302 #include "clang/Basic/OpenCLImageTypes.def" 15303 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 15304 #define PLACEHOLDER_TYPE(Id, SingletonId) 15305 #include "clang/AST/BuiltinTypes.def" 15306 break; 15307 } 15308 15309 llvm_unreachable("invalid placeholder type!"); 15310 } 15311 15312 bool Sema::CheckCaseExpression(Expr *E) { 15313 if (E->isTypeDependent()) 15314 return true; 15315 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 15316 return E->getType()->isIntegralOrEnumerationType(); 15317 return false; 15318 } 15319 15320 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 15321 ExprResult 15322 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 15323 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 15324 "Unknown Objective-C Boolean value!"); 15325 QualType BoolT = Context.ObjCBuiltinBoolTy; 15326 if (!Context.getBOOLDecl()) { 15327 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 15328 Sema::LookupOrdinaryName); 15329 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 15330 NamedDecl *ND = Result.getFoundDecl(); 15331 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 15332 Context.setBOOLDecl(TD); 15333 } 15334 } 15335 if (Context.getBOOLDecl()) 15336 BoolT = Context.getBOOLType(); 15337 return new (Context) 15338 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 15339 } 15340 15341 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 15342 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 15343 SourceLocation RParen) { 15344 15345 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 15346 15347 auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(), 15348 [&](const AvailabilitySpec &Spec) { 15349 return Spec.getPlatform() == Platform; 15350 }); 15351 15352 VersionTuple Version; 15353 if (Spec != AvailSpecs.end()) 15354 Version = Spec->getVersion(); 15355 15356 return new (Context) 15357 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 15358 } 15359