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 Sema::ShouldDiagnoseAvailabilityOfDecl( 107 NamedDecl *&D, VersionTuple ContextVersion, std::string *Message) { 108 AvailabilityResult Result = D->getAvailability(Message, ContextVersion); 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, ContextVersion); 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, ContextVersion); 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, ContextVersion); 136 } 137 138 switch (Result) { 139 case AR_Available: 140 return Result; 141 142 case AR_Unavailable: 143 case AR_Deprecated: 144 return getCurContextAvailability() != Result ? Result : AR_Available; 145 146 case AR_NotYetIntroduced: { 147 // Don't do this for enums, they can't be redeclared. 148 if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D)) 149 return AR_Available; 150 151 bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited(); 152 // Objective-C method declarations in categories are not modelled as 153 // redeclarations, so manually look for a redeclaration in a category 154 // if necessary. 155 if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D)) 156 Warn = false; 157 // In general, D will point to the most recent redeclaration. However, 158 // for `@class A;` decls, this isn't true -- manually go through the 159 // redecl chain in that case. 160 if (Warn && isa<ObjCInterfaceDecl>(D)) 161 for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn; 162 Redecl = Redecl->getPreviousDecl()) 163 if (!Redecl->hasAttr<AvailabilityAttr>() || 164 Redecl->getAttr<AvailabilityAttr>()->isInherited()) 165 Warn = false; 166 167 return Warn ? AR_NotYetIntroduced : AR_Available; 168 } 169 } 170 llvm_unreachable("Unknown availability result!"); 171 } 172 173 static void 174 DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc, 175 const ObjCInterfaceDecl *UnknownObjCClass, 176 bool ObjCPropertyAccess) { 177 VersionTuple ContextVersion; 178 if (const DeclContext *DC = S.getCurObjCLexicalContext()) 179 ContextVersion = S.getVersionForDecl(cast<Decl>(DC)); 180 181 std::string Message; 182 // See if this declaration is unavailable, deprecated, or partial in the 183 // current context. 184 if (AvailabilityResult Result = 185 S.ShouldDiagnoseAvailabilityOfDecl(D, ContextVersion, &Message)) { 186 187 if (Result == AR_NotYetIntroduced && S.getCurFunctionOrMethodDecl()) { 188 S.getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 189 return; 190 } 191 192 const ObjCPropertyDecl *ObjCPDecl = nullptr; 193 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 194 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) { 195 AvailabilityResult PDeclResult = 196 PD->getAvailability(nullptr, ContextVersion); 197 if (PDeclResult == Result) 198 ObjCPDecl = PD; 199 } 200 } 201 202 S.EmitAvailabilityWarning(Result, D, Message, Loc, UnknownObjCClass, 203 ObjCPDecl, ObjCPropertyAccess); 204 } 205 } 206 207 /// \brief Emit a note explaining that this function is deleted. 208 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 209 assert(Decl->isDeleted()); 210 211 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 212 213 if (Method && Method->isDeleted() && Method->isDefaulted()) { 214 // If the method was explicitly defaulted, point at that declaration. 215 if (!Method->isImplicit()) 216 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 217 218 // Try to diagnose why this special member function was implicitly 219 // deleted. This might fail, if that reason no longer applies. 220 CXXSpecialMember CSM = getSpecialMember(Method); 221 if (CSM != CXXInvalid) 222 ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true); 223 224 return; 225 } 226 227 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 228 if (Ctor && Ctor->isInheritingConstructor()) 229 return NoteDeletedInheritingConstructor(Ctor); 230 231 Diag(Decl->getLocation(), diag::note_availability_specified_here) 232 << Decl << true; 233 } 234 235 /// \brief Determine whether a FunctionDecl was ever declared with an 236 /// explicit storage class. 237 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 238 for (auto I : D->redecls()) { 239 if (I->getStorageClass() != SC_None) 240 return true; 241 } 242 return false; 243 } 244 245 /// \brief Check whether we're in an extern inline function and referring to a 246 /// variable or function with internal linkage (C11 6.7.4p3). 247 /// 248 /// This is only a warning because we used to silently accept this code, but 249 /// in many cases it will not behave correctly. This is not enabled in C++ mode 250 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 251 /// and so while there may still be user mistakes, most of the time we can't 252 /// prove that there are errors. 253 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 254 const NamedDecl *D, 255 SourceLocation Loc) { 256 // This is disabled under C++; there are too many ways for this to fire in 257 // contexts where the warning is a false positive, or where it is technically 258 // correct but benign. 259 if (S.getLangOpts().CPlusPlus) 260 return; 261 262 // Check if this is an inlined function or method. 263 FunctionDecl *Current = S.getCurFunctionDecl(); 264 if (!Current) 265 return; 266 if (!Current->isInlined()) 267 return; 268 if (!Current->isExternallyVisible()) 269 return; 270 271 // Check if the decl has internal linkage. 272 if (D->getFormalLinkage() != InternalLinkage) 273 return; 274 275 // Downgrade from ExtWarn to Extension if 276 // (1) the supposedly external inline function is in the main file, 277 // and probably won't be included anywhere else. 278 // (2) the thing we're referencing is a pure function. 279 // (3) the thing we're referencing is another inline function. 280 // This last can give us false negatives, but it's better than warning on 281 // wrappers for simple C library functions. 282 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 283 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 284 if (!DowngradeWarning && UsedFn) 285 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 286 287 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 288 : diag::ext_internal_in_extern_inline) 289 << /*IsVar=*/!UsedFn << D; 290 291 S.MaybeSuggestAddingStaticToDecl(Current); 292 293 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 294 << D; 295 } 296 297 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 298 const FunctionDecl *First = Cur->getFirstDecl(); 299 300 // Suggest "static" on the function, if possible. 301 if (!hasAnyExplicitStorageClass(First)) { 302 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 303 Diag(DeclBegin, diag::note_convert_inline_to_static) 304 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 305 } 306 } 307 308 /// \brief Determine whether the use of this declaration is valid, and 309 /// emit any corresponding diagnostics. 310 /// 311 /// This routine diagnoses various problems with referencing 312 /// declarations that can occur when using a declaration. For example, 313 /// it might warn if a deprecated or unavailable declaration is being 314 /// used, or produce an error (and return true) if a C++0x deleted 315 /// function is being used. 316 /// 317 /// \returns true if there was an error (this declaration cannot be 318 /// referenced), false otherwise. 319 /// 320 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 321 const ObjCInterfaceDecl *UnknownObjCClass, 322 bool ObjCPropertyAccess) { 323 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 324 // If there were any diagnostics suppressed by template argument deduction, 325 // emit them now. 326 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 327 if (Pos != SuppressedDiagnostics.end()) { 328 for (const PartialDiagnosticAt &Suppressed : Pos->second) 329 Diag(Suppressed.first, Suppressed.second); 330 331 // Clear out the list of suppressed diagnostics, so that we don't emit 332 // them again for this specialization. However, we don't obsolete this 333 // entry from the table, because we want to avoid ever emitting these 334 // diagnostics again. 335 Pos->second.clear(); 336 } 337 338 // C++ [basic.start.main]p3: 339 // The function 'main' shall not be used within a program. 340 if (cast<FunctionDecl>(D)->isMain()) 341 Diag(Loc, diag::ext_main_used); 342 } 343 344 // See if this is an auto-typed variable whose initializer we are parsing. 345 if (ParsingInitForAutoVars.count(D)) { 346 if (isa<BindingDecl>(D)) { 347 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 348 << D->getDeclName(); 349 } else { 350 const AutoType *AT = cast<VarDecl>(D)->getType()->getContainedAutoType(); 351 352 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 353 << D->getDeclName() << (unsigned)AT->getKeyword(); 354 } 355 return true; 356 } 357 358 // See if this is a deleted function. 359 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 360 if (FD->isDeleted()) { 361 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 362 if (Ctor && Ctor->isInheritingConstructor()) 363 Diag(Loc, diag::err_deleted_inherited_ctor_use) 364 << Ctor->getParent() 365 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 366 else 367 Diag(Loc, diag::err_deleted_function_use); 368 NoteDeletedFunction(FD); 369 return true; 370 } 371 372 // If the function has a deduced return type, and we can't deduce it, 373 // then we can't use it either. 374 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 375 DeduceReturnType(FD, Loc)) 376 return true; 377 378 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 379 return true; 380 } 381 382 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 383 // Only the variables omp_in and omp_out are allowed in the combiner. 384 // Only the variables omp_priv and omp_orig are allowed in the 385 // initializer-clause. 386 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 387 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 388 isa<VarDecl>(D)) { 389 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 390 << getCurFunction()->HasOMPDeclareReductionCombiner; 391 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 392 return true; 393 } 394 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass, 395 ObjCPropertyAccess); 396 397 DiagnoseUnusedOfDecl(*this, D, Loc); 398 399 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 400 401 return false; 402 } 403 404 /// \brief Retrieve the message suffix that should be added to a 405 /// diagnostic complaining about the given function being deleted or 406 /// unavailable. 407 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 408 std::string Message; 409 if (FD->getAvailability(&Message)) 410 return ": " + Message; 411 412 return std::string(); 413 } 414 415 /// DiagnoseSentinelCalls - This routine checks whether a call or 416 /// message-send is to a declaration with the sentinel attribute, and 417 /// if so, it checks that the requirements of the sentinel are 418 /// satisfied. 419 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 420 ArrayRef<Expr *> Args) { 421 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 422 if (!attr) 423 return; 424 425 // The number of formal parameters of the declaration. 426 unsigned numFormalParams; 427 428 // The kind of declaration. This is also an index into a %select in 429 // the diagnostic. 430 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 431 432 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 433 numFormalParams = MD->param_size(); 434 calleeType = CT_Method; 435 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 436 numFormalParams = FD->param_size(); 437 calleeType = CT_Function; 438 } else if (isa<VarDecl>(D)) { 439 QualType type = cast<ValueDecl>(D)->getType(); 440 const FunctionType *fn = nullptr; 441 if (const PointerType *ptr = type->getAs<PointerType>()) { 442 fn = ptr->getPointeeType()->getAs<FunctionType>(); 443 if (!fn) return; 444 calleeType = CT_Function; 445 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 446 fn = ptr->getPointeeType()->castAs<FunctionType>(); 447 calleeType = CT_Block; 448 } else { 449 return; 450 } 451 452 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 453 numFormalParams = proto->getNumParams(); 454 } else { 455 numFormalParams = 0; 456 } 457 } else { 458 return; 459 } 460 461 // "nullPos" is the number of formal parameters at the end which 462 // effectively count as part of the variadic arguments. This is 463 // useful if you would prefer to not have *any* formal parameters, 464 // but the language forces you to have at least one. 465 unsigned nullPos = attr->getNullPos(); 466 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 467 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 468 469 // The number of arguments which should follow the sentinel. 470 unsigned numArgsAfterSentinel = attr->getSentinel(); 471 472 // If there aren't enough arguments for all the formal parameters, 473 // the sentinel, and the args after the sentinel, complain. 474 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 475 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 476 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 477 return; 478 } 479 480 // Otherwise, find the sentinel expression. 481 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 482 if (!sentinelExpr) return; 483 if (sentinelExpr->isValueDependent()) return; 484 if (Context.isSentinelNullExpr(sentinelExpr)) return; 485 486 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 487 // or 'NULL' if those are actually defined in the context. Only use 488 // 'nil' for ObjC methods, where it's much more likely that the 489 // variadic arguments form a list of object pointers. 490 SourceLocation MissingNilLoc 491 = getLocForEndOfToken(sentinelExpr->getLocEnd()); 492 std::string NullValue; 493 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 494 NullValue = "nil"; 495 else if (getLangOpts().CPlusPlus11) 496 NullValue = "nullptr"; 497 else if (PP.isMacroDefined("NULL")) 498 NullValue = "NULL"; 499 else 500 NullValue = "(void*) 0"; 501 502 if (MissingNilLoc.isInvalid()) 503 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 504 else 505 Diag(MissingNilLoc, diag::warn_missing_sentinel) 506 << int(calleeType) 507 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 508 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 509 } 510 511 SourceRange Sema::getExprRange(Expr *E) const { 512 return E ? E->getSourceRange() : SourceRange(); 513 } 514 515 //===----------------------------------------------------------------------===// 516 // Standard Promotions and Conversions 517 //===----------------------------------------------------------------------===// 518 519 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 520 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 521 // Handle any placeholder expressions which made it here. 522 if (E->getType()->isPlaceholderType()) { 523 ExprResult result = CheckPlaceholderExpr(E); 524 if (result.isInvalid()) return ExprError(); 525 E = result.get(); 526 } 527 528 QualType Ty = E->getType(); 529 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 530 531 if (Ty->isFunctionType()) { 532 // If we are here, we are not calling a function but taking 533 // its address (which is not allowed in OpenCL v1.0 s6.8.a.3). 534 if (getLangOpts().OpenCL) { 535 if (Diagnose) 536 Diag(E->getExprLoc(), diag::err_opencl_taking_function_address); 537 return ExprError(); 538 } 539 540 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 541 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 542 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 543 return ExprError(); 544 545 E = ImpCastExprToType(E, Context.getPointerType(Ty), 546 CK_FunctionToPointerDecay).get(); 547 } else if (Ty->isArrayType()) { 548 // In C90 mode, arrays only promote to pointers if the array expression is 549 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 550 // type 'array of type' is converted to an expression that has type 'pointer 551 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 552 // that has type 'array of type' ...". The relevant change is "an lvalue" 553 // (C90) to "an expression" (C99). 554 // 555 // C++ 4.2p1: 556 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 557 // T" can be converted to an rvalue of type "pointer to T". 558 // 559 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 560 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 561 CK_ArrayToPointerDecay).get(); 562 } 563 return E; 564 } 565 566 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 567 // Check to see if we are dereferencing a null pointer. If so, 568 // and if not volatile-qualified, this is undefined behavior that the 569 // optimizer will delete, so warn about it. People sometimes try to use this 570 // to get a deterministic trap and are surprised by clang's behavior. This 571 // only handles the pattern "*null", which is a very syntactic check. 572 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 573 if (UO->getOpcode() == UO_Deref && 574 UO->getSubExpr()->IgnoreParenCasts()-> 575 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 576 !UO->getType().isVolatileQualified()) { 577 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 578 S.PDiag(diag::warn_indirection_through_null) 579 << UO->getSubExpr()->getSourceRange()); 580 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 581 S.PDiag(diag::note_indirection_through_null)); 582 } 583 } 584 585 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 586 SourceLocation AssignLoc, 587 const Expr* RHS) { 588 const ObjCIvarDecl *IV = OIRE->getDecl(); 589 if (!IV) 590 return; 591 592 DeclarationName MemberName = IV->getDeclName(); 593 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 594 if (!Member || !Member->isStr("isa")) 595 return; 596 597 const Expr *Base = OIRE->getBase(); 598 QualType BaseType = Base->getType(); 599 if (OIRE->isArrow()) 600 BaseType = BaseType->getPointeeType(); 601 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 602 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 603 ObjCInterfaceDecl *ClassDeclared = nullptr; 604 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 605 if (!ClassDeclared->getSuperClass() 606 && (*ClassDeclared->ivar_begin()) == IV) { 607 if (RHS) { 608 NamedDecl *ObjectSetClass = 609 S.LookupSingleName(S.TUScope, 610 &S.Context.Idents.get("object_setClass"), 611 SourceLocation(), S.LookupOrdinaryName); 612 if (ObjectSetClass) { 613 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd()); 614 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 615 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 616 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 617 AssignLoc), ",") << 618 FixItHint::CreateInsertion(RHSLocEnd, ")"); 619 } 620 else 621 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 622 } else { 623 NamedDecl *ObjectGetClass = 624 S.LookupSingleName(S.TUScope, 625 &S.Context.Idents.get("object_getClass"), 626 SourceLocation(), S.LookupOrdinaryName); 627 if (ObjectGetClass) 628 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 629 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 630 FixItHint::CreateReplacement( 631 SourceRange(OIRE->getOpLoc(), 632 OIRE->getLocEnd()), ")"); 633 else 634 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 635 } 636 S.Diag(IV->getLocation(), diag::note_ivar_decl); 637 } 638 } 639 } 640 641 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 642 // Handle any placeholder expressions which made it here. 643 if (E->getType()->isPlaceholderType()) { 644 ExprResult result = CheckPlaceholderExpr(E); 645 if (result.isInvalid()) return ExprError(); 646 E = result.get(); 647 } 648 649 // C++ [conv.lval]p1: 650 // A glvalue of a non-function, non-array type T can be 651 // converted to a prvalue. 652 if (!E->isGLValue()) return E; 653 654 QualType T = E->getType(); 655 assert(!T.isNull() && "r-value conversion on typeless expression?"); 656 657 // We don't want to throw lvalue-to-rvalue casts on top of 658 // expressions of certain types in C++. 659 if (getLangOpts().CPlusPlus && 660 (E->getType() == Context.OverloadTy || 661 T->isDependentType() || 662 T->isRecordType())) 663 return E; 664 665 // The C standard is actually really unclear on this point, and 666 // DR106 tells us what the result should be but not why. It's 667 // generally best to say that void types just doesn't undergo 668 // lvalue-to-rvalue at all. Note that expressions of unqualified 669 // 'void' type are never l-values, but qualified void can be. 670 if (T->isVoidType()) 671 return E; 672 673 // OpenCL usually rejects direct accesses to values of 'half' type. 674 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 && 675 T->isHalfType()) { 676 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 677 << 0 << T; 678 return ExprError(); 679 } 680 681 CheckForNullPointerDereference(*this, E); 682 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 683 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 684 &Context.Idents.get("object_getClass"), 685 SourceLocation(), LookupOrdinaryName); 686 if (ObjectGetClass) 687 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 688 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 689 FixItHint::CreateReplacement( 690 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 691 else 692 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 693 } 694 else if (const ObjCIvarRefExpr *OIRE = 695 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 696 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 697 698 // C++ [conv.lval]p1: 699 // [...] If T is a non-class type, the type of the prvalue is the 700 // cv-unqualified version of T. Otherwise, the type of the 701 // rvalue is T. 702 // 703 // C99 6.3.2.1p2: 704 // If the lvalue has qualified type, the value has the unqualified 705 // version of the type of the lvalue; otherwise, the value has the 706 // type of the lvalue. 707 if (T.hasQualifiers()) 708 T = T.getUnqualifiedType(); 709 710 // Under the MS ABI, lock down the inheritance model now. 711 if (T->isMemberPointerType() && 712 Context.getTargetInfo().getCXXABI().isMicrosoft()) 713 (void)isCompleteType(E->getExprLoc(), T); 714 715 UpdateMarkingForLValueToRValue(E); 716 717 // Loading a __weak object implicitly retains the value, so we need a cleanup to 718 // balance that. 719 if (getLangOpts().ObjCAutoRefCount && 720 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 721 Cleanup.setExprNeedsCleanups(true); 722 723 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 724 nullptr, VK_RValue); 725 726 // C11 6.3.2.1p2: 727 // ... if the lvalue has atomic type, the value has the non-atomic version 728 // of the type of the lvalue ... 729 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 730 T = Atomic->getValueType().getUnqualifiedType(); 731 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 732 nullptr, VK_RValue); 733 } 734 735 return Res; 736 } 737 738 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 739 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 740 if (Res.isInvalid()) 741 return ExprError(); 742 Res = DefaultLvalueConversion(Res.get()); 743 if (Res.isInvalid()) 744 return ExprError(); 745 return Res; 746 } 747 748 /// CallExprUnaryConversions - a special case of an unary conversion 749 /// performed on a function designator of a call expression. 750 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 751 QualType Ty = E->getType(); 752 ExprResult Res = E; 753 // Only do implicit cast for a function type, but not for a pointer 754 // to function type. 755 if (Ty->isFunctionType()) { 756 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 757 CK_FunctionToPointerDecay).get(); 758 if (Res.isInvalid()) 759 return ExprError(); 760 } 761 Res = DefaultLvalueConversion(Res.get()); 762 if (Res.isInvalid()) 763 return ExprError(); 764 return Res.get(); 765 } 766 767 /// UsualUnaryConversions - Performs various conversions that are common to most 768 /// operators (C99 6.3). The conversions of array and function types are 769 /// sometimes suppressed. For example, the array->pointer conversion doesn't 770 /// apply if the array is an argument to the sizeof or address (&) operators. 771 /// In these instances, this routine should *not* be called. 772 ExprResult Sema::UsualUnaryConversions(Expr *E) { 773 // First, convert to an r-value. 774 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 775 if (Res.isInvalid()) 776 return ExprError(); 777 E = Res.get(); 778 779 QualType Ty = E->getType(); 780 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 781 782 // Half FP have to be promoted to float unless it is natively supported 783 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 784 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 785 786 // Try to perform integral promotions if the object has a theoretically 787 // promotable type. 788 if (Ty->isIntegralOrUnscopedEnumerationType()) { 789 // C99 6.3.1.1p2: 790 // 791 // The following may be used in an expression wherever an int or 792 // unsigned int may be used: 793 // - an object or expression with an integer type whose integer 794 // conversion rank is less than or equal to the rank of int 795 // and unsigned int. 796 // - A bit-field of type _Bool, int, signed int, or unsigned int. 797 // 798 // If an int can represent all values of the original type, the 799 // value is converted to an int; otherwise, it is converted to an 800 // unsigned int. These are called the integer promotions. All 801 // other types are unchanged by the integer promotions. 802 803 QualType PTy = Context.isPromotableBitField(E); 804 if (!PTy.isNull()) { 805 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 806 return E; 807 } 808 if (Ty->isPromotableIntegerType()) { 809 QualType PT = Context.getPromotedIntegerType(Ty); 810 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 811 return E; 812 } 813 } 814 return E; 815 } 816 817 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 818 /// do not have a prototype. Arguments that have type float or __fp16 819 /// are promoted to double. All other argument types are converted by 820 /// UsualUnaryConversions(). 821 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 822 QualType Ty = E->getType(); 823 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 824 825 ExprResult Res = UsualUnaryConversions(E); 826 if (Res.isInvalid()) 827 return ExprError(); 828 E = Res.get(); 829 830 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to 831 // double. 832 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 833 if (BTy && (BTy->getKind() == BuiltinType::Half || 834 BTy->getKind() == BuiltinType::Float)) 835 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 836 837 // C++ performs lvalue-to-rvalue conversion as a default argument 838 // promotion, even on class types, but note: 839 // C++11 [conv.lval]p2: 840 // When an lvalue-to-rvalue conversion occurs in an unevaluated 841 // operand or a subexpression thereof the value contained in the 842 // referenced object is not accessed. Otherwise, if the glvalue 843 // has a class type, the conversion copy-initializes a temporary 844 // of type T from the glvalue and the result of the conversion 845 // is a prvalue for the temporary. 846 // FIXME: add some way to gate this entire thing for correctness in 847 // potentially potentially evaluated contexts. 848 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 849 ExprResult Temp = PerformCopyInitialization( 850 InitializedEntity::InitializeTemporary(E->getType()), 851 E->getExprLoc(), E); 852 if (Temp.isInvalid()) 853 return ExprError(); 854 E = Temp.get(); 855 } 856 857 return E; 858 } 859 860 /// Determine the degree of POD-ness for an expression. 861 /// Incomplete types are considered POD, since this check can be performed 862 /// when we're in an unevaluated context. 863 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 864 if (Ty->isIncompleteType()) { 865 // C++11 [expr.call]p7: 866 // After these conversions, if the argument does not have arithmetic, 867 // enumeration, pointer, pointer to member, or class type, the program 868 // is ill-formed. 869 // 870 // Since we've already performed array-to-pointer and function-to-pointer 871 // decay, the only such type in C++ is cv void. This also handles 872 // initializer lists as variadic arguments. 873 if (Ty->isVoidType()) 874 return VAK_Invalid; 875 876 if (Ty->isObjCObjectType()) 877 return VAK_Invalid; 878 return VAK_Valid; 879 } 880 881 if (Ty.isCXX98PODType(Context)) 882 return VAK_Valid; 883 884 // C++11 [expr.call]p7: 885 // Passing a potentially-evaluated argument of class type (Clause 9) 886 // having a non-trivial copy constructor, a non-trivial move constructor, 887 // or a non-trivial destructor, with no corresponding parameter, 888 // is conditionally-supported with implementation-defined semantics. 889 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 890 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 891 if (!Record->hasNonTrivialCopyConstructor() && 892 !Record->hasNonTrivialMoveConstructor() && 893 !Record->hasNonTrivialDestructor()) 894 return VAK_ValidInCXX11; 895 896 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 897 return VAK_Valid; 898 899 if (Ty->isObjCObjectType()) 900 return VAK_Invalid; 901 902 if (getLangOpts().MSVCCompat) 903 return VAK_MSVCUndefined; 904 905 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 906 // permitted to reject them. We should consider doing so. 907 return VAK_Undefined; 908 } 909 910 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 911 // Don't allow one to pass an Objective-C interface to a vararg. 912 const QualType &Ty = E->getType(); 913 VarArgKind VAK = isValidVarArgType(Ty); 914 915 // Complain about passing non-POD types through varargs. 916 switch (VAK) { 917 case VAK_ValidInCXX11: 918 DiagRuntimeBehavior( 919 E->getLocStart(), nullptr, 920 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 921 << Ty << CT); 922 // Fall through. 923 case VAK_Valid: 924 if (Ty->isRecordType()) { 925 // This is unlikely to be what the user intended. If the class has a 926 // 'c_str' member function, the user probably meant to call that. 927 DiagRuntimeBehavior(E->getLocStart(), nullptr, 928 PDiag(diag::warn_pass_class_arg_to_vararg) 929 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 930 } 931 break; 932 933 case VAK_Undefined: 934 case VAK_MSVCUndefined: 935 DiagRuntimeBehavior( 936 E->getLocStart(), nullptr, 937 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 938 << getLangOpts().CPlusPlus11 << Ty << CT); 939 break; 940 941 case VAK_Invalid: 942 if (Ty->isObjCObjectType()) 943 DiagRuntimeBehavior( 944 E->getLocStart(), nullptr, 945 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 946 << Ty << CT); 947 else 948 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg) 949 << isa<InitListExpr>(E) << Ty << CT; 950 break; 951 } 952 } 953 954 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 955 /// will create a trap if the resulting type is not a POD type. 956 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 957 FunctionDecl *FDecl) { 958 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 959 // Strip the unbridged-cast placeholder expression off, if applicable. 960 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 961 (CT == VariadicMethod || 962 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 963 E = stripARCUnbridgedCast(E); 964 965 // Otherwise, do normal placeholder checking. 966 } else { 967 ExprResult ExprRes = CheckPlaceholderExpr(E); 968 if (ExprRes.isInvalid()) 969 return ExprError(); 970 E = ExprRes.get(); 971 } 972 } 973 974 ExprResult ExprRes = DefaultArgumentPromotion(E); 975 if (ExprRes.isInvalid()) 976 return ExprError(); 977 E = ExprRes.get(); 978 979 // Diagnostics regarding non-POD argument types are 980 // emitted along with format string checking in Sema::CheckFunctionCall(). 981 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 982 // Turn this into a trap. 983 CXXScopeSpec SS; 984 SourceLocation TemplateKWLoc; 985 UnqualifiedId Name; 986 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 987 E->getLocStart()); 988 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 989 Name, true, false); 990 if (TrapFn.isInvalid()) 991 return ExprError(); 992 993 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 994 E->getLocStart(), None, 995 E->getLocEnd()); 996 if (Call.isInvalid()) 997 return ExprError(); 998 999 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 1000 Call.get(), E); 1001 if (Comma.isInvalid()) 1002 return ExprError(); 1003 return Comma.get(); 1004 } 1005 1006 if (!getLangOpts().CPlusPlus && 1007 RequireCompleteType(E->getExprLoc(), E->getType(), 1008 diag::err_call_incomplete_argument)) 1009 return ExprError(); 1010 1011 return E; 1012 } 1013 1014 /// \brief Converts an integer to complex float type. Helper function of 1015 /// UsualArithmeticConversions() 1016 /// 1017 /// \return false if the integer expression is an integer type and is 1018 /// successfully converted to the complex type. 1019 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1020 ExprResult &ComplexExpr, 1021 QualType IntTy, 1022 QualType ComplexTy, 1023 bool SkipCast) { 1024 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1025 if (SkipCast) return false; 1026 if (IntTy->isIntegerType()) { 1027 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1028 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1029 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1030 CK_FloatingRealToComplex); 1031 } else { 1032 assert(IntTy->isComplexIntegerType()); 1033 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1034 CK_IntegralComplexToFloatingComplex); 1035 } 1036 return false; 1037 } 1038 1039 /// \brief Handle arithmetic conversion with complex types. Helper function of 1040 /// UsualArithmeticConversions() 1041 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1042 ExprResult &RHS, QualType LHSType, 1043 QualType RHSType, 1044 bool IsCompAssign) { 1045 // if we have an integer operand, the result is the complex type. 1046 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1047 /*skipCast*/false)) 1048 return LHSType; 1049 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1050 /*skipCast*/IsCompAssign)) 1051 return RHSType; 1052 1053 // This handles complex/complex, complex/float, or float/complex. 1054 // When both operands are complex, the shorter operand is converted to the 1055 // type of the longer, and that is the type of the result. This corresponds 1056 // to what is done when combining two real floating-point operands. 1057 // The fun begins when size promotion occur across type domains. 1058 // From H&S 6.3.4: When one operand is complex and the other is a real 1059 // floating-point type, the less precise type is converted, within it's 1060 // real or complex domain, to the precision of the other type. For example, 1061 // when combining a "long double" with a "double _Complex", the 1062 // "double _Complex" is promoted to "long double _Complex". 1063 1064 // Compute the rank of the two types, regardless of whether they are complex. 1065 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1066 1067 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1068 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1069 QualType LHSElementType = 1070 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1071 QualType RHSElementType = 1072 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1073 1074 QualType ResultType = S.Context.getComplexType(LHSElementType); 1075 if (Order < 0) { 1076 // Promote the precision of the LHS if not an assignment. 1077 ResultType = S.Context.getComplexType(RHSElementType); 1078 if (!IsCompAssign) { 1079 if (LHSComplexType) 1080 LHS = 1081 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1082 else 1083 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1084 } 1085 } else if (Order > 0) { 1086 // Promote the precision of the RHS. 1087 if (RHSComplexType) 1088 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1089 else 1090 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1091 } 1092 return ResultType; 1093 } 1094 1095 /// \brief Hande arithmetic conversion from integer to float. Helper function 1096 /// of UsualArithmeticConversions() 1097 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1098 ExprResult &IntExpr, 1099 QualType FloatTy, QualType IntTy, 1100 bool ConvertFloat, bool ConvertInt) { 1101 if (IntTy->isIntegerType()) { 1102 if (ConvertInt) 1103 // Convert intExpr to the lhs floating point type. 1104 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1105 CK_IntegralToFloating); 1106 return FloatTy; 1107 } 1108 1109 // Convert both sides to the appropriate complex float. 1110 assert(IntTy->isComplexIntegerType()); 1111 QualType result = S.Context.getComplexType(FloatTy); 1112 1113 // _Complex int -> _Complex float 1114 if (ConvertInt) 1115 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1116 CK_IntegralComplexToFloatingComplex); 1117 1118 // float -> _Complex float 1119 if (ConvertFloat) 1120 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1121 CK_FloatingRealToComplex); 1122 1123 return result; 1124 } 1125 1126 /// \brief Handle arithmethic conversion with floating point types. Helper 1127 /// function of UsualArithmeticConversions() 1128 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1129 ExprResult &RHS, QualType LHSType, 1130 QualType RHSType, bool IsCompAssign) { 1131 bool LHSFloat = LHSType->isRealFloatingType(); 1132 bool RHSFloat = RHSType->isRealFloatingType(); 1133 1134 // If we have two real floating types, convert the smaller operand 1135 // to the bigger result. 1136 if (LHSFloat && RHSFloat) { 1137 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1138 if (order > 0) { 1139 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1140 return LHSType; 1141 } 1142 1143 assert(order < 0 && "illegal float comparison"); 1144 if (!IsCompAssign) 1145 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1146 return RHSType; 1147 } 1148 1149 if (LHSFloat) { 1150 // Half FP has to be promoted to float unless it is natively supported 1151 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1152 LHSType = S.Context.FloatTy; 1153 1154 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1155 /*convertFloat=*/!IsCompAssign, 1156 /*convertInt=*/ true); 1157 } 1158 assert(RHSFloat); 1159 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1160 /*convertInt=*/ true, 1161 /*convertFloat=*/!IsCompAssign); 1162 } 1163 1164 /// \brief Diagnose attempts to convert between __float128 and long double if 1165 /// there is no support for such conversion. Helper function of 1166 /// UsualArithmeticConversions(). 1167 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1168 QualType RHSType) { 1169 /* No issue converting if at least one of the types is not a floating point 1170 type or the two types have the same rank. 1171 */ 1172 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1173 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1174 return false; 1175 1176 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1177 "The remaining types must be floating point types."); 1178 1179 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1180 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1181 1182 QualType LHSElemType = LHSComplex ? 1183 LHSComplex->getElementType() : LHSType; 1184 QualType RHSElemType = RHSComplex ? 1185 RHSComplex->getElementType() : RHSType; 1186 1187 // No issue if the two types have the same representation 1188 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1189 &S.Context.getFloatTypeSemantics(RHSElemType)) 1190 return false; 1191 1192 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1193 RHSElemType == S.Context.LongDoubleTy); 1194 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1195 RHSElemType == S.Context.Float128Ty); 1196 1197 /* We've handled the situation where __float128 and long double have the same 1198 representation. The only other allowable conversion is if long double is 1199 really just double. 1200 */ 1201 return Float128AndLongDouble && 1202 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) != 1203 &llvm::APFloat::IEEEdouble); 1204 } 1205 1206 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1207 1208 namespace { 1209 /// These helper callbacks are placed in an anonymous namespace to 1210 /// permit their use as function template parameters. 1211 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1212 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1213 } 1214 1215 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1216 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1217 CK_IntegralComplexCast); 1218 } 1219 } 1220 1221 /// \brief Handle integer arithmetic conversions. Helper function of 1222 /// UsualArithmeticConversions() 1223 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1224 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1225 ExprResult &RHS, QualType LHSType, 1226 QualType RHSType, bool IsCompAssign) { 1227 // The rules for this case are in C99 6.3.1.8 1228 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1229 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1230 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1231 if (LHSSigned == RHSSigned) { 1232 // Same signedness; use the higher-ranked type 1233 if (order >= 0) { 1234 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1235 return LHSType; 1236 } else if (!IsCompAssign) 1237 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1238 return RHSType; 1239 } else if (order != (LHSSigned ? 1 : -1)) { 1240 // The unsigned type has greater than or equal rank to the 1241 // signed type, so use the unsigned type 1242 if (RHSSigned) { 1243 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1244 return LHSType; 1245 } else if (!IsCompAssign) 1246 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1247 return RHSType; 1248 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1249 // The two types are different widths; if we are here, that 1250 // means the signed type is larger than the unsigned type, so 1251 // use the signed type. 1252 if (LHSSigned) { 1253 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1254 return LHSType; 1255 } else if (!IsCompAssign) 1256 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1257 return RHSType; 1258 } else { 1259 // The signed type is higher-ranked than the unsigned type, 1260 // but isn't actually any bigger (like unsigned int and long 1261 // on most 32-bit systems). Use the unsigned type corresponding 1262 // to the signed type. 1263 QualType result = 1264 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1265 RHS = (*doRHSCast)(S, RHS.get(), result); 1266 if (!IsCompAssign) 1267 LHS = (*doLHSCast)(S, LHS.get(), result); 1268 return result; 1269 } 1270 } 1271 1272 /// \brief Handle conversions with GCC complex int extension. Helper function 1273 /// of UsualArithmeticConversions() 1274 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1275 ExprResult &RHS, QualType LHSType, 1276 QualType RHSType, 1277 bool IsCompAssign) { 1278 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1279 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1280 1281 if (LHSComplexInt && RHSComplexInt) { 1282 QualType LHSEltType = LHSComplexInt->getElementType(); 1283 QualType RHSEltType = RHSComplexInt->getElementType(); 1284 QualType ScalarType = 1285 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1286 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1287 1288 return S.Context.getComplexType(ScalarType); 1289 } 1290 1291 if (LHSComplexInt) { 1292 QualType LHSEltType = LHSComplexInt->getElementType(); 1293 QualType ScalarType = 1294 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1295 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1296 QualType ComplexType = S.Context.getComplexType(ScalarType); 1297 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1298 CK_IntegralRealToComplex); 1299 1300 return ComplexType; 1301 } 1302 1303 assert(RHSComplexInt); 1304 1305 QualType RHSEltType = RHSComplexInt->getElementType(); 1306 QualType ScalarType = 1307 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1308 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1309 QualType ComplexType = S.Context.getComplexType(ScalarType); 1310 1311 if (!IsCompAssign) 1312 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1313 CK_IntegralRealToComplex); 1314 return ComplexType; 1315 } 1316 1317 /// UsualArithmeticConversions - Performs various conversions that are common to 1318 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1319 /// routine returns the first non-arithmetic type found. The client is 1320 /// responsible for emitting appropriate error diagnostics. 1321 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1322 bool IsCompAssign) { 1323 if (!IsCompAssign) { 1324 LHS = UsualUnaryConversions(LHS.get()); 1325 if (LHS.isInvalid()) 1326 return QualType(); 1327 } 1328 1329 RHS = UsualUnaryConversions(RHS.get()); 1330 if (RHS.isInvalid()) 1331 return QualType(); 1332 1333 // For conversion purposes, we ignore any qualifiers. 1334 // For example, "const float" and "float" are equivalent. 1335 QualType LHSType = 1336 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1337 QualType RHSType = 1338 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1339 1340 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1341 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1342 LHSType = AtomicLHS->getValueType(); 1343 1344 // If both types are identical, no conversion is needed. 1345 if (LHSType == RHSType) 1346 return LHSType; 1347 1348 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1349 // The caller can deal with this (e.g. pointer + int). 1350 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1351 return QualType(); 1352 1353 // Apply unary and bitfield promotions to the LHS's type. 1354 QualType LHSUnpromotedType = LHSType; 1355 if (LHSType->isPromotableIntegerType()) 1356 LHSType = Context.getPromotedIntegerType(LHSType); 1357 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1358 if (!LHSBitfieldPromoteTy.isNull()) 1359 LHSType = LHSBitfieldPromoteTy; 1360 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1361 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1362 1363 // If both types are identical, no conversion is needed. 1364 if (LHSType == RHSType) 1365 return LHSType; 1366 1367 // At this point, we have two different arithmetic types. 1368 1369 // Diagnose attempts to convert between __float128 and long double where 1370 // such conversions currently can't be handled. 1371 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1372 return QualType(); 1373 1374 // Handle complex types first (C99 6.3.1.8p1). 1375 if (LHSType->isComplexType() || RHSType->isComplexType()) 1376 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1377 IsCompAssign); 1378 1379 // Now handle "real" floating types (i.e. float, double, long double). 1380 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1381 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1382 IsCompAssign); 1383 1384 // Handle GCC complex int extension. 1385 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1386 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1387 IsCompAssign); 1388 1389 // Finally, we have two differing integer types. 1390 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1391 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1392 } 1393 1394 1395 //===----------------------------------------------------------------------===// 1396 // Semantic Analysis for various Expression Types 1397 //===----------------------------------------------------------------------===// 1398 1399 1400 ExprResult 1401 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1402 SourceLocation DefaultLoc, 1403 SourceLocation RParenLoc, 1404 Expr *ControllingExpr, 1405 ArrayRef<ParsedType> ArgTypes, 1406 ArrayRef<Expr *> ArgExprs) { 1407 unsigned NumAssocs = ArgTypes.size(); 1408 assert(NumAssocs == ArgExprs.size()); 1409 1410 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1411 for (unsigned i = 0; i < NumAssocs; ++i) { 1412 if (ArgTypes[i]) 1413 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1414 else 1415 Types[i] = nullptr; 1416 } 1417 1418 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1419 ControllingExpr, 1420 llvm::makeArrayRef(Types, NumAssocs), 1421 ArgExprs); 1422 delete [] Types; 1423 return ER; 1424 } 1425 1426 ExprResult 1427 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1428 SourceLocation DefaultLoc, 1429 SourceLocation RParenLoc, 1430 Expr *ControllingExpr, 1431 ArrayRef<TypeSourceInfo *> Types, 1432 ArrayRef<Expr *> Exprs) { 1433 unsigned NumAssocs = Types.size(); 1434 assert(NumAssocs == Exprs.size()); 1435 1436 // Decay and strip qualifiers for the controlling expression type, and handle 1437 // placeholder type replacement. See committee discussion from WG14 DR423. 1438 { 1439 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 1440 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1441 if (R.isInvalid()) 1442 return ExprError(); 1443 ControllingExpr = R.get(); 1444 } 1445 1446 // The controlling expression is an unevaluated operand, so side effects are 1447 // likely unintended. 1448 if (ActiveTemplateInstantiations.empty() && 1449 ControllingExpr->HasSideEffects(Context, false)) 1450 Diag(ControllingExpr->getExprLoc(), 1451 diag::warn_side_effects_unevaluated_context); 1452 1453 bool TypeErrorFound = false, 1454 IsResultDependent = ControllingExpr->isTypeDependent(), 1455 ContainsUnexpandedParameterPack 1456 = ControllingExpr->containsUnexpandedParameterPack(); 1457 1458 for (unsigned i = 0; i < NumAssocs; ++i) { 1459 if (Exprs[i]->containsUnexpandedParameterPack()) 1460 ContainsUnexpandedParameterPack = true; 1461 1462 if (Types[i]) { 1463 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1464 ContainsUnexpandedParameterPack = true; 1465 1466 if (Types[i]->getType()->isDependentType()) { 1467 IsResultDependent = true; 1468 } else { 1469 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1470 // complete object type other than a variably modified type." 1471 unsigned D = 0; 1472 if (Types[i]->getType()->isIncompleteType()) 1473 D = diag::err_assoc_type_incomplete; 1474 else if (!Types[i]->getType()->isObjectType()) 1475 D = diag::err_assoc_type_nonobject; 1476 else if (Types[i]->getType()->isVariablyModifiedType()) 1477 D = diag::err_assoc_type_variably_modified; 1478 1479 if (D != 0) { 1480 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1481 << Types[i]->getTypeLoc().getSourceRange() 1482 << Types[i]->getType(); 1483 TypeErrorFound = true; 1484 } 1485 1486 // C11 6.5.1.1p2 "No two generic associations in the same generic 1487 // selection shall specify compatible types." 1488 for (unsigned j = i+1; j < NumAssocs; ++j) 1489 if (Types[j] && !Types[j]->getType()->isDependentType() && 1490 Context.typesAreCompatible(Types[i]->getType(), 1491 Types[j]->getType())) { 1492 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1493 diag::err_assoc_compatible_types) 1494 << Types[j]->getTypeLoc().getSourceRange() 1495 << Types[j]->getType() 1496 << Types[i]->getType(); 1497 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1498 diag::note_compat_assoc) 1499 << Types[i]->getTypeLoc().getSourceRange() 1500 << Types[i]->getType(); 1501 TypeErrorFound = true; 1502 } 1503 } 1504 } 1505 } 1506 if (TypeErrorFound) 1507 return ExprError(); 1508 1509 // If we determined that the generic selection is result-dependent, don't 1510 // try to compute the result expression. 1511 if (IsResultDependent) 1512 return new (Context) GenericSelectionExpr( 1513 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1514 ContainsUnexpandedParameterPack); 1515 1516 SmallVector<unsigned, 1> CompatIndices; 1517 unsigned DefaultIndex = -1U; 1518 for (unsigned i = 0; i < NumAssocs; ++i) { 1519 if (!Types[i]) 1520 DefaultIndex = i; 1521 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1522 Types[i]->getType())) 1523 CompatIndices.push_back(i); 1524 } 1525 1526 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1527 // type compatible with at most one of the types named in its generic 1528 // association list." 1529 if (CompatIndices.size() > 1) { 1530 // We strip parens here because the controlling expression is typically 1531 // parenthesized in macro definitions. 1532 ControllingExpr = ControllingExpr->IgnoreParens(); 1533 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1534 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1535 << (unsigned) CompatIndices.size(); 1536 for (unsigned I : CompatIndices) { 1537 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1538 diag::note_compat_assoc) 1539 << Types[I]->getTypeLoc().getSourceRange() 1540 << Types[I]->getType(); 1541 } 1542 return ExprError(); 1543 } 1544 1545 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1546 // its controlling expression shall have type compatible with exactly one of 1547 // the types named in its generic association list." 1548 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1549 // We strip parens here because the controlling expression is typically 1550 // parenthesized in macro definitions. 1551 ControllingExpr = ControllingExpr->IgnoreParens(); 1552 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1553 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1554 return ExprError(); 1555 } 1556 1557 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1558 // type name that is compatible with the type of the controlling expression, 1559 // then the result expression of the generic selection is the expression 1560 // in that generic association. Otherwise, the result expression of the 1561 // generic selection is the expression in the default generic association." 1562 unsigned ResultIndex = 1563 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1564 1565 return new (Context) GenericSelectionExpr( 1566 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1567 ContainsUnexpandedParameterPack, ResultIndex); 1568 } 1569 1570 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1571 /// location of the token and the offset of the ud-suffix within it. 1572 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1573 unsigned Offset) { 1574 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1575 S.getLangOpts()); 1576 } 1577 1578 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1579 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1580 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1581 IdentifierInfo *UDSuffix, 1582 SourceLocation UDSuffixLoc, 1583 ArrayRef<Expr*> Args, 1584 SourceLocation LitEndLoc) { 1585 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1586 1587 QualType ArgTy[2]; 1588 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1589 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1590 if (ArgTy[ArgIdx]->isArrayType()) 1591 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1592 } 1593 1594 DeclarationName OpName = 1595 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1596 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1597 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1598 1599 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1600 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1601 /*AllowRaw*/false, /*AllowTemplate*/false, 1602 /*AllowStringTemplate*/false) == Sema::LOLR_Error) 1603 return ExprError(); 1604 1605 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1606 } 1607 1608 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1609 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1610 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1611 /// multiple tokens. However, the common case is that StringToks points to one 1612 /// string. 1613 /// 1614 ExprResult 1615 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1616 assert(!StringToks.empty() && "Must have at least one string!"); 1617 1618 StringLiteralParser Literal(StringToks, PP); 1619 if (Literal.hadError) 1620 return ExprError(); 1621 1622 SmallVector<SourceLocation, 4> StringTokLocs; 1623 for (const Token &Tok : StringToks) 1624 StringTokLocs.push_back(Tok.getLocation()); 1625 1626 QualType CharTy = Context.CharTy; 1627 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1628 if (Literal.isWide()) { 1629 CharTy = Context.getWideCharType(); 1630 Kind = StringLiteral::Wide; 1631 } else if (Literal.isUTF8()) { 1632 Kind = StringLiteral::UTF8; 1633 } else if (Literal.isUTF16()) { 1634 CharTy = Context.Char16Ty; 1635 Kind = StringLiteral::UTF16; 1636 } else if (Literal.isUTF32()) { 1637 CharTy = Context.Char32Ty; 1638 Kind = StringLiteral::UTF32; 1639 } else if (Literal.isPascal()) { 1640 CharTy = Context.UnsignedCharTy; 1641 } 1642 1643 QualType CharTyConst = CharTy; 1644 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1645 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1646 CharTyConst.addConst(); 1647 1648 // Get an array type for the string, according to C99 6.4.5. This includes 1649 // the nul terminator character as well as the string length for pascal 1650 // strings. 1651 QualType StrTy = Context.getConstantArrayType(CharTyConst, 1652 llvm::APInt(32, Literal.GetNumStringChars()+1), 1653 ArrayType::Normal, 0); 1654 1655 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 1656 if (getLangOpts().OpenCL) { 1657 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant); 1658 } 1659 1660 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1661 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1662 Kind, Literal.Pascal, StrTy, 1663 &StringTokLocs[0], 1664 StringTokLocs.size()); 1665 if (Literal.getUDSuffix().empty()) 1666 return Lit; 1667 1668 // We're building a user-defined literal. 1669 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1670 SourceLocation UDSuffixLoc = 1671 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1672 Literal.getUDSuffixOffset()); 1673 1674 // Make sure we're allowed user-defined literals here. 1675 if (!UDLScope) 1676 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1677 1678 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1679 // operator "" X (str, len) 1680 QualType SizeType = Context.getSizeType(); 1681 1682 DeclarationName OpName = 1683 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1684 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1685 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1686 1687 QualType ArgTy[] = { 1688 Context.getArrayDecayedType(StrTy), SizeType 1689 }; 1690 1691 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1692 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1693 /*AllowRaw*/false, /*AllowTemplate*/false, 1694 /*AllowStringTemplate*/true)) { 1695 1696 case LOLR_Cooked: { 1697 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1698 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1699 StringTokLocs[0]); 1700 Expr *Args[] = { Lit, LenArg }; 1701 1702 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1703 } 1704 1705 case LOLR_StringTemplate: { 1706 TemplateArgumentListInfo ExplicitArgs; 1707 1708 unsigned CharBits = Context.getIntWidth(CharTy); 1709 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1710 llvm::APSInt Value(CharBits, CharIsUnsigned); 1711 1712 TemplateArgument TypeArg(CharTy); 1713 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1714 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1715 1716 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1717 Value = Lit->getCodeUnit(I); 1718 TemplateArgument Arg(Context, Value, CharTy); 1719 TemplateArgumentLocInfo ArgInfo; 1720 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1721 } 1722 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1723 &ExplicitArgs); 1724 } 1725 case LOLR_Raw: 1726 case LOLR_Template: 1727 llvm_unreachable("unexpected literal operator lookup result"); 1728 case LOLR_Error: 1729 return ExprError(); 1730 } 1731 llvm_unreachable("unexpected literal operator lookup result"); 1732 } 1733 1734 ExprResult 1735 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1736 SourceLocation Loc, 1737 const CXXScopeSpec *SS) { 1738 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1739 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1740 } 1741 1742 /// BuildDeclRefExpr - Build an expression that references a 1743 /// declaration that does not require a closure capture. 1744 ExprResult 1745 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1746 const DeclarationNameInfo &NameInfo, 1747 const CXXScopeSpec *SS, NamedDecl *FoundD, 1748 const TemplateArgumentListInfo *TemplateArgs) { 1749 bool RefersToCapturedVariable = 1750 isa<VarDecl>(D) && 1751 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1752 1753 DeclRefExpr *E; 1754 if (isa<VarTemplateSpecializationDecl>(D)) { 1755 VarTemplateSpecializationDecl *VarSpec = 1756 cast<VarTemplateSpecializationDecl>(D); 1757 1758 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1759 : NestedNameSpecifierLoc(), 1760 VarSpec->getTemplateKeywordLoc(), D, 1761 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK, 1762 FoundD, TemplateArgs); 1763 } else { 1764 assert(!TemplateArgs && "No template arguments for non-variable" 1765 " template specialization references"); 1766 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1767 : NestedNameSpecifierLoc(), 1768 SourceLocation(), D, RefersToCapturedVariable, 1769 NameInfo, Ty, VK, FoundD); 1770 } 1771 1772 MarkDeclRefReferenced(E); 1773 1774 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1775 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && 1776 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart())) 1777 recordUseOfEvaluatedWeak(E); 1778 1779 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 1780 UnusedPrivateFields.remove(FD); 1781 // Just in case we're building an illegal pointer-to-member. 1782 if (FD->isBitField()) 1783 E->setObjectKind(OK_BitField); 1784 } 1785 1786 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1787 // designates a bit-field. 1788 if (auto *BD = dyn_cast<BindingDecl>(D)) 1789 if (auto *BE = BD->getBinding()) 1790 E->setObjectKind(BE->getObjectKind()); 1791 1792 return E; 1793 } 1794 1795 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1796 /// possibly a list of template arguments. 1797 /// 1798 /// If this produces template arguments, it is permitted to call 1799 /// DecomposeTemplateName. 1800 /// 1801 /// This actually loses a lot of source location information for 1802 /// non-standard name kinds; we should consider preserving that in 1803 /// some way. 1804 void 1805 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1806 TemplateArgumentListInfo &Buffer, 1807 DeclarationNameInfo &NameInfo, 1808 const TemplateArgumentListInfo *&TemplateArgs) { 1809 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1810 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1811 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1812 1813 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1814 Id.TemplateId->NumArgs); 1815 translateTemplateArguments(TemplateArgsPtr, Buffer); 1816 1817 TemplateName TName = Id.TemplateId->Template.get(); 1818 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1819 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1820 TemplateArgs = &Buffer; 1821 } else { 1822 NameInfo = GetNameFromUnqualifiedId(Id); 1823 TemplateArgs = nullptr; 1824 } 1825 } 1826 1827 static void emitEmptyLookupTypoDiagnostic( 1828 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1829 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1830 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1831 DeclContext *Ctx = 1832 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1833 if (!TC) { 1834 // Emit a special diagnostic for failed member lookups. 1835 // FIXME: computing the declaration context might fail here (?) 1836 if (Ctx) 1837 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1838 << SS.getRange(); 1839 else 1840 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1841 return; 1842 } 1843 1844 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1845 bool DroppedSpecifier = 1846 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1847 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1848 ? diag::note_implicit_param_decl 1849 : diag::note_previous_decl; 1850 if (!Ctx) 1851 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1852 SemaRef.PDiag(NoteID)); 1853 else 1854 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1855 << Typo << Ctx << DroppedSpecifier 1856 << SS.getRange(), 1857 SemaRef.PDiag(NoteID)); 1858 } 1859 1860 /// Diagnose an empty lookup. 1861 /// 1862 /// \return false if new lookup candidates were found 1863 bool 1864 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1865 std::unique_ptr<CorrectionCandidateCallback> CCC, 1866 TemplateArgumentListInfo *ExplicitTemplateArgs, 1867 ArrayRef<Expr *> Args, TypoExpr **Out) { 1868 DeclarationName Name = R.getLookupName(); 1869 1870 unsigned diagnostic = diag::err_undeclared_var_use; 1871 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1872 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1873 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1874 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1875 diagnostic = diag::err_undeclared_use; 1876 diagnostic_suggest = diag::err_undeclared_use_suggest; 1877 } 1878 1879 // If the original lookup was an unqualified lookup, fake an 1880 // unqualified lookup. This is useful when (for example) the 1881 // original lookup would not have found something because it was a 1882 // dependent name. 1883 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1884 while (DC) { 1885 if (isa<CXXRecordDecl>(DC)) { 1886 LookupQualifiedName(R, DC); 1887 1888 if (!R.empty()) { 1889 // Don't give errors about ambiguities in this lookup. 1890 R.suppressDiagnostics(); 1891 1892 // During a default argument instantiation the CurContext points 1893 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1894 // function parameter list, hence add an explicit check. 1895 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() && 1896 ActiveTemplateInstantiations.back().Kind == 1897 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation; 1898 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1899 bool isInstance = CurMethod && 1900 CurMethod->isInstance() && 1901 DC == CurMethod->getParent() && !isDefaultArgument; 1902 1903 // Give a code modification hint to insert 'this->'. 1904 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1905 // Actually quite difficult! 1906 if (getLangOpts().MSVCCompat) 1907 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1908 if (isInstance) { 1909 Diag(R.getNameLoc(), diagnostic) << Name 1910 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1911 CheckCXXThisCapture(R.getNameLoc()); 1912 } else { 1913 Diag(R.getNameLoc(), diagnostic) << Name; 1914 } 1915 1916 // Do we really want to note all of these? 1917 for (NamedDecl *D : R) 1918 Diag(D->getLocation(), diag::note_dependent_var_use); 1919 1920 // Return true if we are inside a default argument instantiation 1921 // and the found name refers to an instance member function, otherwise 1922 // the function calling DiagnoseEmptyLookup will try to create an 1923 // implicit member call and this is wrong for default argument. 1924 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1925 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1926 return true; 1927 } 1928 1929 // Tell the callee to try to recover. 1930 return false; 1931 } 1932 1933 R.clear(); 1934 } 1935 1936 // In Microsoft mode, if we are performing lookup from within a friend 1937 // function definition declared at class scope then we must set 1938 // DC to the lexical parent to be able to search into the parent 1939 // class. 1940 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1941 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1942 DC->getLexicalParent()->isRecord()) 1943 DC = DC->getLexicalParent(); 1944 else 1945 DC = DC->getParent(); 1946 } 1947 1948 // We didn't find anything, so try to correct for a typo. 1949 TypoCorrection Corrected; 1950 if (S && Out) { 1951 SourceLocation TypoLoc = R.getNameLoc(); 1952 assert(!ExplicitTemplateArgs && 1953 "Diagnosing an empty lookup with explicit template args!"); 1954 *Out = CorrectTypoDelayed( 1955 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC), 1956 [=](const TypoCorrection &TC) { 1957 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 1958 diagnostic, diagnostic_suggest); 1959 }, 1960 nullptr, CTK_ErrorRecovery); 1961 if (*Out) 1962 return true; 1963 } else if (S && (Corrected = 1964 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, 1965 &SS, std::move(CCC), CTK_ErrorRecovery))) { 1966 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1967 bool DroppedSpecifier = 1968 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1969 R.setLookupName(Corrected.getCorrection()); 1970 1971 bool AcceptableWithRecovery = false; 1972 bool AcceptableWithoutRecovery = false; 1973 NamedDecl *ND = Corrected.getFoundDecl(); 1974 if (ND) { 1975 if (Corrected.isOverloaded()) { 1976 OverloadCandidateSet OCS(R.getNameLoc(), 1977 OverloadCandidateSet::CSK_Normal); 1978 OverloadCandidateSet::iterator Best; 1979 for (NamedDecl *CD : Corrected) { 1980 if (FunctionTemplateDecl *FTD = 1981 dyn_cast<FunctionTemplateDecl>(CD)) 1982 AddTemplateOverloadCandidate( 1983 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1984 Args, OCS); 1985 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 1986 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1987 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1988 Args, OCS); 1989 } 1990 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1991 case OR_Success: 1992 ND = Best->FoundDecl; 1993 Corrected.setCorrectionDecl(ND); 1994 break; 1995 default: 1996 // FIXME: Arbitrarily pick the first declaration for the note. 1997 Corrected.setCorrectionDecl(ND); 1998 break; 1999 } 2000 } 2001 R.addDecl(ND); 2002 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2003 CXXRecordDecl *Record = nullptr; 2004 if (Corrected.getCorrectionSpecifier()) { 2005 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2006 Record = Ty->getAsCXXRecordDecl(); 2007 } 2008 if (!Record) 2009 Record = cast<CXXRecordDecl>( 2010 ND->getDeclContext()->getRedeclContext()); 2011 R.setNamingClass(Record); 2012 } 2013 2014 auto *UnderlyingND = ND->getUnderlyingDecl(); 2015 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2016 isa<FunctionTemplateDecl>(UnderlyingND); 2017 // FIXME: If we ended up with a typo for a type name or 2018 // Objective-C class name, we're in trouble because the parser 2019 // is in the wrong place to recover. Suggest the typo 2020 // correction, but don't make it a fix-it since we're not going 2021 // to recover well anyway. 2022 AcceptableWithoutRecovery = 2023 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND); 2024 } else { 2025 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2026 // because we aren't able to recover. 2027 AcceptableWithoutRecovery = true; 2028 } 2029 2030 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2031 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2032 ? diag::note_implicit_param_decl 2033 : diag::note_previous_decl; 2034 if (SS.isEmpty()) 2035 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2036 PDiag(NoteID), AcceptableWithRecovery); 2037 else 2038 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2039 << Name << computeDeclContext(SS, false) 2040 << DroppedSpecifier << SS.getRange(), 2041 PDiag(NoteID), AcceptableWithRecovery); 2042 2043 // Tell the callee whether to try to recover. 2044 return !AcceptableWithRecovery; 2045 } 2046 } 2047 R.clear(); 2048 2049 // Emit a special diagnostic for failed member lookups. 2050 // FIXME: computing the declaration context might fail here (?) 2051 if (!SS.isEmpty()) { 2052 Diag(R.getNameLoc(), diag::err_no_member) 2053 << Name << computeDeclContext(SS, false) 2054 << SS.getRange(); 2055 return true; 2056 } 2057 2058 // Give up, we can't recover. 2059 Diag(R.getNameLoc(), diagnostic) << Name; 2060 return true; 2061 } 2062 2063 /// In Microsoft mode, if we are inside a template class whose parent class has 2064 /// dependent base classes, and we can't resolve an unqualified identifier, then 2065 /// assume the identifier is a member of a dependent base class. We can only 2066 /// recover successfully in static methods, instance methods, and other contexts 2067 /// where 'this' is available. This doesn't precisely match MSVC's 2068 /// instantiation model, but it's close enough. 2069 static Expr * 2070 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2071 DeclarationNameInfo &NameInfo, 2072 SourceLocation TemplateKWLoc, 2073 const TemplateArgumentListInfo *TemplateArgs) { 2074 // Only try to recover from lookup into dependent bases in static methods or 2075 // contexts where 'this' is available. 2076 QualType ThisType = S.getCurrentThisType(); 2077 const CXXRecordDecl *RD = nullptr; 2078 if (!ThisType.isNull()) 2079 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2080 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2081 RD = MD->getParent(); 2082 if (!RD || !RD->hasAnyDependentBases()) 2083 return nullptr; 2084 2085 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2086 // is available, suggest inserting 'this->' as a fixit. 2087 SourceLocation Loc = NameInfo.getLoc(); 2088 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2089 DB << NameInfo.getName() << RD; 2090 2091 if (!ThisType.isNull()) { 2092 DB << FixItHint::CreateInsertion(Loc, "this->"); 2093 return CXXDependentScopeMemberExpr::Create( 2094 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2095 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2096 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 2097 } 2098 2099 // Synthesize a fake NNS that points to the derived class. This will 2100 // perform name lookup during template instantiation. 2101 CXXScopeSpec SS; 2102 auto *NNS = 2103 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2104 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2105 return DependentScopeDeclRefExpr::Create( 2106 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2107 TemplateArgs); 2108 } 2109 2110 ExprResult 2111 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2112 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2113 bool HasTrailingLParen, bool IsAddressOfOperand, 2114 std::unique_ptr<CorrectionCandidateCallback> CCC, 2115 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2116 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2117 "cannot be direct & operand and have a trailing lparen"); 2118 if (SS.isInvalid()) 2119 return ExprError(); 2120 2121 TemplateArgumentListInfo TemplateArgsBuffer; 2122 2123 // Decompose the UnqualifiedId into the following data. 2124 DeclarationNameInfo NameInfo; 2125 const TemplateArgumentListInfo *TemplateArgs; 2126 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2127 2128 DeclarationName Name = NameInfo.getName(); 2129 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2130 SourceLocation NameLoc = NameInfo.getLoc(); 2131 2132 // C++ [temp.dep.expr]p3: 2133 // An id-expression is type-dependent if it contains: 2134 // -- an identifier that was declared with a dependent type, 2135 // (note: handled after lookup) 2136 // -- a template-id that is dependent, 2137 // (note: handled in BuildTemplateIdExpr) 2138 // -- a conversion-function-id that specifies a dependent type, 2139 // -- a nested-name-specifier that contains a class-name that 2140 // names a dependent type. 2141 // Determine whether this is a member of an unknown specialization; 2142 // we need to handle these differently. 2143 bool DependentID = false; 2144 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2145 Name.getCXXNameType()->isDependentType()) { 2146 DependentID = true; 2147 } else if (SS.isSet()) { 2148 if (DeclContext *DC = computeDeclContext(SS, false)) { 2149 if (RequireCompleteDeclContext(SS, DC)) 2150 return ExprError(); 2151 } else { 2152 DependentID = true; 2153 } 2154 } 2155 2156 if (DependentID) 2157 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2158 IsAddressOfOperand, TemplateArgs); 2159 2160 // Perform the required lookup. 2161 LookupResult R(*this, NameInfo, 2162 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 2163 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 2164 if (TemplateArgs) { 2165 // Lookup the template name again to correctly establish the context in 2166 // which it was found. This is really unfortunate as we already did the 2167 // lookup to determine that it was a template name in the first place. If 2168 // this becomes a performance hit, we can work harder to preserve those 2169 // results until we get here but it's likely not worth it. 2170 bool MemberOfUnknownSpecialization; 2171 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2172 MemberOfUnknownSpecialization); 2173 2174 if (MemberOfUnknownSpecialization || 2175 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2176 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2177 IsAddressOfOperand, TemplateArgs); 2178 } else { 2179 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2180 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2181 2182 // If the result might be in a dependent base class, this is a dependent 2183 // id-expression. 2184 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2185 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2186 IsAddressOfOperand, TemplateArgs); 2187 2188 // If this reference is in an Objective-C method, then we need to do 2189 // some special Objective-C lookup, too. 2190 if (IvarLookupFollowUp) { 2191 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2192 if (E.isInvalid()) 2193 return ExprError(); 2194 2195 if (Expr *Ex = E.getAs<Expr>()) 2196 return Ex; 2197 } 2198 } 2199 2200 if (R.isAmbiguous()) 2201 return ExprError(); 2202 2203 // This could be an implicitly declared function reference (legal in C90, 2204 // extension in C99, forbidden in C++). 2205 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2206 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2207 if (D) R.addDecl(D); 2208 } 2209 2210 // Determine whether this name might be a candidate for 2211 // argument-dependent lookup. 2212 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2213 2214 if (R.empty() && !ADL) { 2215 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2216 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2217 TemplateKWLoc, TemplateArgs)) 2218 return E; 2219 } 2220 2221 // Don't diagnose an empty lookup for inline assembly. 2222 if (IsInlineAsmIdentifier) 2223 return ExprError(); 2224 2225 // If this name wasn't predeclared and if this is not a function 2226 // call, diagnose the problem. 2227 TypoExpr *TE = nullptr; 2228 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2229 II, SS.isValid() ? SS.getScopeRep() : nullptr); 2230 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; 2231 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2232 "Typo correction callback misconfigured"); 2233 if (CCC) { 2234 // Make sure the callback knows what the typo being diagnosed is. 2235 CCC->setTypoName(II); 2236 if (SS.isValid()) 2237 CCC->setTypoNNS(SS.getScopeRep()); 2238 } 2239 if (DiagnoseEmptyLookup(S, SS, R, 2240 CCC ? std::move(CCC) : std::move(DefaultValidator), 2241 nullptr, None, &TE)) { 2242 if (TE && KeywordReplacement) { 2243 auto &State = getTypoExprState(TE); 2244 auto BestTC = State.Consumer->getNextCorrection(); 2245 if (BestTC.isKeyword()) { 2246 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2247 if (State.DiagHandler) 2248 State.DiagHandler(BestTC); 2249 KeywordReplacement->startToken(); 2250 KeywordReplacement->setKind(II->getTokenID()); 2251 KeywordReplacement->setIdentifierInfo(II); 2252 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2253 // Clean up the state associated with the TypoExpr, since it has 2254 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2255 clearDelayedTypo(TE); 2256 // Signal that a correction to a keyword was performed by returning a 2257 // valid-but-null ExprResult. 2258 return (Expr*)nullptr; 2259 } 2260 State.Consumer->resetCorrectionStream(); 2261 } 2262 return TE ? TE : ExprError(); 2263 } 2264 2265 assert(!R.empty() && 2266 "DiagnoseEmptyLookup returned false but added no results"); 2267 2268 // If we found an Objective-C instance variable, let 2269 // LookupInObjCMethod build the appropriate expression to 2270 // reference the ivar. 2271 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2272 R.clear(); 2273 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2274 // In a hopelessly buggy code, Objective-C instance variable 2275 // lookup fails and no expression will be built to reference it. 2276 if (!E.isInvalid() && !E.get()) 2277 return ExprError(); 2278 return E; 2279 } 2280 } 2281 2282 // This is guaranteed from this point on. 2283 assert(!R.empty() || ADL); 2284 2285 // Check whether this might be a C++ implicit instance member access. 2286 // C++ [class.mfct.non-static]p3: 2287 // When an id-expression that is not part of a class member access 2288 // syntax and not used to form a pointer to member is used in the 2289 // body of a non-static member function of class X, if name lookup 2290 // resolves the name in the id-expression to a non-static non-type 2291 // member of some class C, the id-expression is transformed into a 2292 // class member access expression using (*this) as the 2293 // postfix-expression to the left of the . operator. 2294 // 2295 // But we don't actually need to do this for '&' operands if R 2296 // resolved to a function or overloaded function set, because the 2297 // expression is ill-formed if it actually works out to be a 2298 // non-static member function: 2299 // 2300 // C++ [expr.ref]p4: 2301 // Otherwise, if E1.E2 refers to a non-static member function. . . 2302 // [t]he expression can be used only as the left-hand operand of a 2303 // member function call. 2304 // 2305 // There are other safeguards against such uses, but it's important 2306 // to get this right here so that we don't end up making a 2307 // spuriously dependent expression if we're inside a dependent 2308 // instance method. 2309 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2310 bool MightBeImplicitMember; 2311 if (!IsAddressOfOperand) 2312 MightBeImplicitMember = true; 2313 else if (!SS.isEmpty()) 2314 MightBeImplicitMember = false; 2315 else if (R.isOverloadedResult()) 2316 MightBeImplicitMember = false; 2317 else if (R.isUnresolvableResult()) 2318 MightBeImplicitMember = true; 2319 else 2320 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2321 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2322 isa<MSPropertyDecl>(R.getFoundDecl()); 2323 2324 if (MightBeImplicitMember) 2325 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2326 R, TemplateArgs, S); 2327 } 2328 2329 if (TemplateArgs || TemplateKWLoc.isValid()) { 2330 2331 // In C++1y, if this is a variable template id, then check it 2332 // in BuildTemplateIdExpr(). 2333 // The single lookup result must be a variable template declaration. 2334 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId && 2335 Id.TemplateId->Kind == TNK_Var_template) { 2336 assert(R.getAsSingle<VarTemplateDecl>() && 2337 "There should only be one declaration found."); 2338 } 2339 2340 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2341 } 2342 2343 return BuildDeclarationNameExpr(SS, R, ADL); 2344 } 2345 2346 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2347 /// declaration name, generally during template instantiation. 2348 /// There's a large number of things which don't need to be done along 2349 /// this path. 2350 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2351 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2352 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2353 DeclContext *DC = computeDeclContext(SS, false); 2354 if (!DC) 2355 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2356 NameInfo, /*TemplateArgs=*/nullptr); 2357 2358 if (RequireCompleteDeclContext(SS, DC)) 2359 return ExprError(); 2360 2361 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2362 LookupQualifiedName(R, DC); 2363 2364 if (R.isAmbiguous()) 2365 return ExprError(); 2366 2367 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2368 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2369 NameInfo, /*TemplateArgs=*/nullptr); 2370 2371 if (R.empty()) { 2372 Diag(NameInfo.getLoc(), diag::err_no_member) 2373 << NameInfo.getName() << DC << SS.getRange(); 2374 return ExprError(); 2375 } 2376 2377 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2378 // Diagnose a missing typename if this resolved unambiguously to a type in 2379 // a dependent context. If we can recover with a type, downgrade this to 2380 // a warning in Microsoft compatibility mode. 2381 unsigned DiagID = diag::err_typename_missing; 2382 if (RecoveryTSI && getLangOpts().MSVCCompat) 2383 DiagID = diag::ext_typename_missing; 2384 SourceLocation Loc = SS.getBeginLoc(); 2385 auto D = Diag(Loc, DiagID); 2386 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2387 << SourceRange(Loc, NameInfo.getEndLoc()); 2388 2389 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2390 // context. 2391 if (!RecoveryTSI) 2392 return ExprError(); 2393 2394 // Only issue the fixit if we're prepared to recover. 2395 D << FixItHint::CreateInsertion(Loc, "typename "); 2396 2397 // Recover by pretending this was an elaborated type. 2398 QualType Ty = Context.getTypeDeclType(TD); 2399 TypeLocBuilder TLB; 2400 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2401 2402 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2403 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2404 QTL.setElaboratedKeywordLoc(SourceLocation()); 2405 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2406 2407 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2408 2409 return ExprEmpty(); 2410 } 2411 2412 // Defend against this resolving to an implicit member access. We usually 2413 // won't get here if this might be a legitimate a class member (we end up in 2414 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2415 // a pointer-to-member or in an unevaluated context in C++11. 2416 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2417 return BuildPossibleImplicitMemberExpr(SS, 2418 /*TemplateKWLoc=*/SourceLocation(), 2419 R, /*TemplateArgs=*/nullptr, S); 2420 2421 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2422 } 2423 2424 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2425 /// detected that we're currently inside an ObjC method. Perform some 2426 /// additional lookup. 2427 /// 2428 /// Ideally, most of this would be done by lookup, but there's 2429 /// actually quite a lot of extra work involved. 2430 /// 2431 /// Returns a null sentinel to indicate trivial success. 2432 ExprResult 2433 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2434 IdentifierInfo *II, bool AllowBuiltinCreation) { 2435 SourceLocation Loc = Lookup.getNameLoc(); 2436 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2437 2438 // Check for error condition which is already reported. 2439 if (!CurMethod) 2440 return ExprError(); 2441 2442 // There are two cases to handle here. 1) scoped lookup could have failed, 2443 // in which case we should look for an ivar. 2) scoped lookup could have 2444 // found a decl, but that decl is outside the current instance method (i.e. 2445 // a global variable). In these two cases, we do a lookup for an ivar with 2446 // this name, if the lookup sucedes, we replace it our current decl. 2447 2448 // If we're in a class method, we don't normally want to look for 2449 // ivars. But if we don't find anything else, and there's an 2450 // ivar, that's an error. 2451 bool IsClassMethod = CurMethod->isClassMethod(); 2452 2453 bool LookForIvars; 2454 if (Lookup.empty()) 2455 LookForIvars = true; 2456 else if (IsClassMethod) 2457 LookForIvars = false; 2458 else 2459 LookForIvars = (Lookup.isSingleResult() && 2460 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2461 ObjCInterfaceDecl *IFace = nullptr; 2462 if (LookForIvars) { 2463 IFace = CurMethod->getClassInterface(); 2464 ObjCInterfaceDecl *ClassDeclared; 2465 ObjCIvarDecl *IV = nullptr; 2466 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2467 // Diagnose using an ivar in a class method. 2468 if (IsClassMethod) 2469 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2470 << IV->getDeclName()); 2471 2472 // If we're referencing an invalid decl, just return this as a silent 2473 // error node. The error diagnostic was already emitted on the decl. 2474 if (IV->isInvalidDecl()) 2475 return ExprError(); 2476 2477 // Check if referencing a field with __attribute__((deprecated)). 2478 if (DiagnoseUseOfDecl(IV, Loc)) 2479 return ExprError(); 2480 2481 // Diagnose the use of an ivar outside of the declaring class. 2482 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2483 !declaresSameEntity(ClassDeclared, IFace) && 2484 !getLangOpts().DebuggerSupport) 2485 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 2486 2487 // FIXME: This should use a new expr for a direct reference, don't 2488 // turn this into Self->ivar, just return a BareIVarExpr or something. 2489 IdentifierInfo &II = Context.Idents.get("self"); 2490 UnqualifiedId SelfName; 2491 SelfName.setIdentifier(&II, SourceLocation()); 2492 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2493 CXXScopeSpec SelfScopeSpec; 2494 SourceLocation TemplateKWLoc; 2495 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2496 SelfName, false, false); 2497 if (SelfExpr.isInvalid()) 2498 return ExprError(); 2499 2500 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2501 if (SelfExpr.isInvalid()) 2502 return ExprError(); 2503 2504 MarkAnyDeclReferenced(Loc, IV, true); 2505 2506 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2507 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2508 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2509 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2510 2511 ObjCIvarRefExpr *Result = new (Context) 2512 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2513 IV->getLocation(), SelfExpr.get(), true, true); 2514 2515 if (getLangOpts().ObjCAutoRefCount) { 2516 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2517 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2518 recordUseOfEvaluatedWeak(Result); 2519 } 2520 if (CurContext->isClosure()) 2521 Diag(Loc, diag::warn_implicitly_retains_self) 2522 << FixItHint::CreateInsertion(Loc, "self->"); 2523 } 2524 2525 return Result; 2526 } 2527 } else if (CurMethod->isInstanceMethod()) { 2528 // We should warn if a local variable hides an ivar. 2529 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2530 ObjCInterfaceDecl *ClassDeclared; 2531 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2532 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2533 declaresSameEntity(IFace, ClassDeclared)) 2534 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2535 } 2536 } 2537 } else if (Lookup.isSingleResult() && 2538 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2539 // If accessing a stand-alone ivar in a class method, this is an error. 2540 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2541 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2542 << IV->getDeclName()); 2543 } 2544 2545 if (Lookup.empty() && II && AllowBuiltinCreation) { 2546 // FIXME. Consolidate this with similar code in LookupName. 2547 if (unsigned BuiltinID = II->getBuiltinID()) { 2548 if (!(getLangOpts().CPlusPlus && 2549 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2550 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2551 S, Lookup.isForRedeclaration(), 2552 Lookup.getNameLoc()); 2553 if (D) Lookup.addDecl(D); 2554 } 2555 } 2556 } 2557 // Sentinel value saying that we didn't do anything special. 2558 return ExprResult((Expr *)nullptr); 2559 } 2560 2561 /// \brief Cast a base object to a member's actual type. 2562 /// 2563 /// Logically this happens in three phases: 2564 /// 2565 /// * First we cast from the base type to the naming class. 2566 /// The naming class is the class into which we were looking 2567 /// when we found the member; it's the qualifier type if a 2568 /// qualifier was provided, and otherwise it's the base type. 2569 /// 2570 /// * Next we cast from the naming class to the declaring class. 2571 /// If the member we found was brought into a class's scope by 2572 /// a using declaration, this is that class; otherwise it's 2573 /// the class declaring the member. 2574 /// 2575 /// * Finally we cast from the declaring class to the "true" 2576 /// declaring class of the member. This conversion does not 2577 /// obey access control. 2578 ExprResult 2579 Sema::PerformObjectMemberConversion(Expr *From, 2580 NestedNameSpecifier *Qualifier, 2581 NamedDecl *FoundDecl, 2582 NamedDecl *Member) { 2583 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2584 if (!RD) 2585 return From; 2586 2587 QualType DestRecordType; 2588 QualType DestType; 2589 QualType FromRecordType; 2590 QualType FromType = From->getType(); 2591 bool PointerConversions = false; 2592 if (isa<FieldDecl>(Member)) { 2593 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2594 2595 if (FromType->getAs<PointerType>()) { 2596 DestType = Context.getPointerType(DestRecordType); 2597 FromRecordType = FromType->getPointeeType(); 2598 PointerConversions = true; 2599 } else { 2600 DestType = DestRecordType; 2601 FromRecordType = FromType; 2602 } 2603 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2604 if (Method->isStatic()) 2605 return From; 2606 2607 DestType = Method->getThisType(Context); 2608 DestRecordType = DestType->getPointeeType(); 2609 2610 if (FromType->getAs<PointerType>()) { 2611 FromRecordType = FromType->getPointeeType(); 2612 PointerConversions = true; 2613 } else { 2614 FromRecordType = FromType; 2615 DestType = DestRecordType; 2616 } 2617 } else { 2618 // No conversion necessary. 2619 return From; 2620 } 2621 2622 if (DestType->isDependentType() || FromType->isDependentType()) 2623 return From; 2624 2625 // If the unqualified types are the same, no conversion is necessary. 2626 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2627 return From; 2628 2629 SourceRange FromRange = From->getSourceRange(); 2630 SourceLocation FromLoc = FromRange.getBegin(); 2631 2632 ExprValueKind VK = From->getValueKind(); 2633 2634 // C++ [class.member.lookup]p8: 2635 // [...] Ambiguities can often be resolved by qualifying a name with its 2636 // class name. 2637 // 2638 // If the member was a qualified name and the qualified referred to a 2639 // specific base subobject type, we'll cast to that intermediate type 2640 // first and then to the object in which the member is declared. That allows 2641 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2642 // 2643 // class Base { public: int x; }; 2644 // class Derived1 : public Base { }; 2645 // class Derived2 : public Base { }; 2646 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2647 // 2648 // void VeryDerived::f() { 2649 // x = 17; // error: ambiguous base subobjects 2650 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2651 // } 2652 if (Qualifier && Qualifier->getAsType()) { 2653 QualType QType = QualType(Qualifier->getAsType(), 0); 2654 assert(QType->isRecordType() && "lookup done with non-record type"); 2655 2656 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2657 2658 // In C++98, the qualifier type doesn't actually have to be a base 2659 // type of the object type, in which case we just ignore it. 2660 // Otherwise build the appropriate casts. 2661 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2662 CXXCastPath BasePath; 2663 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2664 FromLoc, FromRange, &BasePath)) 2665 return ExprError(); 2666 2667 if (PointerConversions) 2668 QType = Context.getPointerType(QType); 2669 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2670 VK, &BasePath).get(); 2671 2672 FromType = QType; 2673 FromRecordType = QRecordType; 2674 2675 // If the qualifier type was the same as the destination type, 2676 // we're done. 2677 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2678 return From; 2679 } 2680 } 2681 2682 bool IgnoreAccess = false; 2683 2684 // If we actually found the member through a using declaration, cast 2685 // down to the using declaration's type. 2686 // 2687 // Pointer equality is fine here because only one declaration of a 2688 // class ever has member declarations. 2689 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2690 assert(isa<UsingShadowDecl>(FoundDecl)); 2691 QualType URecordType = Context.getTypeDeclType( 2692 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2693 2694 // We only need to do this if the naming-class to declaring-class 2695 // conversion is non-trivial. 2696 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2697 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2698 CXXCastPath BasePath; 2699 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2700 FromLoc, FromRange, &BasePath)) 2701 return ExprError(); 2702 2703 QualType UType = URecordType; 2704 if (PointerConversions) 2705 UType = Context.getPointerType(UType); 2706 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2707 VK, &BasePath).get(); 2708 FromType = UType; 2709 FromRecordType = URecordType; 2710 } 2711 2712 // We don't do access control for the conversion from the 2713 // declaring class to the true declaring class. 2714 IgnoreAccess = true; 2715 } 2716 2717 CXXCastPath BasePath; 2718 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2719 FromLoc, FromRange, &BasePath, 2720 IgnoreAccess)) 2721 return ExprError(); 2722 2723 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2724 VK, &BasePath); 2725 } 2726 2727 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2728 const LookupResult &R, 2729 bool HasTrailingLParen) { 2730 // Only when used directly as the postfix-expression of a call. 2731 if (!HasTrailingLParen) 2732 return false; 2733 2734 // Never if a scope specifier was provided. 2735 if (SS.isSet()) 2736 return false; 2737 2738 // Only in C++ or ObjC++. 2739 if (!getLangOpts().CPlusPlus) 2740 return false; 2741 2742 // Turn off ADL when we find certain kinds of declarations during 2743 // normal lookup: 2744 for (NamedDecl *D : R) { 2745 // C++0x [basic.lookup.argdep]p3: 2746 // -- a declaration of a class member 2747 // Since using decls preserve this property, we check this on the 2748 // original decl. 2749 if (D->isCXXClassMember()) 2750 return false; 2751 2752 // C++0x [basic.lookup.argdep]p3: 2753 // -- a block-scope function declaration that is not a 2754 // using-declaration 2755 // NOTE: we also trigger this for function templates (in fact, we 2756 // don't check the decl type at all, since all other decl types 2757 // turn off ADL anyway). 2758 if (isa<UsingShadowDecl>(D)) 2759 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2760 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2761 return false; 2762 2763 // C++0x [basic.lookup.argdep]p3: 2764 // -- a declaration that is neither a function or a function 2765 // template 2766 // And also for builtin functions. 2767 if (isa<FunctionDecl>(D)) { 2768 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2769 2770 // But also builtin functions. 2771 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2772 return false; 2773 } else if (!isa<FunctionTemplateDecl>(D)) 2774 return false; 2775 } 2776 2777 return true; 2778 } 2779 2780 2781 /// Diagnoses obvious problems with the use of the given declaration 2782 /// as an expression. This is only actually called for lookups that 2783 /// were not overloaded, and it doesn't promise that the declaration 2784 /// will in fact be used. 2785 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2786 if (isa<TypedefNameDecl>(D)) { 2787 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2788 return true; 2789 } 2790 2791 if (isa<ObjCInterfaceDecl>(D)) { 2792 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2793 return true; 2794 } 2795 2796 if (isa<NamespaceDecl>(D)) { 2797 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2798 return true; 2799 } 2800 2801 return false; 2802 } 2803 2804 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2805 LookupResult &R, bool NeedsADL, 2806 bool AcceptInvalidDecl) { 2807 // If this is a single, fully-resolved result and we don't need ADL, 2808 // just build an ordinary singleton decl ref. 2809 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2810 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2811 R.getRepresentativeDecl(), nullptr, 2812 AcceptInvalidDecl); 2813 2814 // We only need to check the declaration if there's exactly one 2815 // result, because in the overloaded case the results can only be 2816 // functions and function templates. 2817 if (R.isSingleResult() && 2818 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2819 return ExprError(); 2820 2821 // Otherwise, just build an unresolved lookup expression. Suppress 2822 // any lookup-related diagnostics; we'll hash these out later, when 2823 // we've picked a target. 2824 R.suppressDiagnostics(); 2825 2826 UnresolvedLookupExpr *ULE 2827 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2828 SS.getWithLocInContext(Context), 2829 R.getLookupNameInfo(), 2830 NeedsADL, R.isOverloadedResult(), 2831 R.begin(), R.end()); 2832 2833 return ULE; 2834 } 2835 2836 static void 2837 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 2838 ValueDecl *var, DeclContext *DC); 2839 2840 /// \brief Complete semantic analysis for a reference to the given declaration. 2841 ExprResult Sema::BuildDeclarationNameExpr( 2842 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2843 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2844 bool AcceptInvalidDecl) { 2845 assert(D && "Cannot refer to a NULL declaration"); 2846 assert(!isa<FunctionTemplateDecl>(D) && 2847 "Cannot refer unambiguously to a function template"); 2848 2849 SourceLocation Loc = NameInfo.getLoc(); 2850 if (CheckDeclInExpr(*this, Loc, D)) 2851 return ExprError(); 2852 2853 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2854 // Specifically diagnose references to class templates that are missing 2855 // a template argument list. 2856 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2857 << Template << SS.getRange(); 2858 Diag(Template->getLocation(), diag::note_template_decl_here); 2859 return ExprError(); 2860 } 2861 2862 // Make sure that we're referring to a value. 2863 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2864 if (!VD) { 2865 Diag(Loc, diag::err_ref_non_value) 2866 << D << SS.getRange(); 2867 Diag(D->getLocation(), diag::note_declared_at); 2868 return ExprError(); 2869 } 2870 2871 // Check whether this declaration can be used. Note that we suppress 2872 // this check when we're going to perform argument-dependent lookup 2873 // on this function name, because this might not be the function 2874 // that overload resolution actually selects. 2875 if (DiagnoseUseOfDecl(VD, Loc)) 2876 return ExprError(); 2877 2878 // Only create DeclRefExpr's for valid Decl's. 2879 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2880 return ExprError(); 2881 2882 // Handle members of anonymous structs and unions. If we got here, 2883 // and the reference is to a class member indirect field, then this 2884 // must be the subject of a pointer-to-member expression. 2885 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2886 if (!indirectField->isCXXClassMember()) 2887 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2888 indirectField); 2889 2890 { 2891 QualType type = VD->getType(); 2892 if (auto *FPT = type->getAs<FunctionProtoType>()) { 2893 // C++ [except.spec]p17: 2894 // An exception-specification is considered to be needed when: 2895 // - in an expression, the function is the unique lookup result or 2896 // the selected member of a set of overloaded functions. 2897 ResolveExceptionSpec(Loc, FPT); 2898 type = VD->getType(); 2899 } 2900 ExprValueKind valueKind = VK_RValue; 2901 2902 switch (D->getKind()) { 2903 // Ignore all the non-ValueDecl kinds. 2904 #define ABSTRACT_DECL(kind) 2905 #define VALUE(type, base) 2906 #define DECL(type, base) \ 2907 case Decl::type: 2908 #include "clang/AST/DeclNodes.inc" 2909 llvm_unreachable("invalid value decl kind"); 2910 2911 // These shouldn't make it here. 2912 case Decl::ObjCAtDefsField: 2913 case Decl::ObjCIvar: 2914 llvm_unreachable("forming non-member reference to ivar?"); 2915 2916 // Enum constants are always r-values and never references. 2917 // Unresolved using declarations are dependent. 2918 case Decl::EnumConstant: 2919 case Decl::UnresolvedUsingValue: 2920 case Decl::OMPDeclareReduction: 2921 valueKind = VK_RValue; 2922 break; 2923 2924 // Fields and indirect fields that got here must be for 2925 // pointer-to-member expressions; we just call them l-values for 2926 // internal consistency, because this subexpression doesn't really 2927 // exist in the high-level semantics. 2928 case Decl::Field: 2929 case Decl::IndirectField: 2930 assert(getLangOpts().CPlusPlus && 2931 "building reference to field in C?"); 2932 2933 // These can't have reference type in well-formed programs, but 2934 // for internal consistency we do this anyway. 2935 type = type.getNonReferenceType(); 2936 valueKind = VK_LValue; 2937 break; 2938 2939 // Non-type template parameters are either l-values or r-values 2940 // depending on the type. 2941 case Decl::NonTypeTemplateParm: { 2942 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2943 type = reftype->getPointeeType(); 2944 valueKind = VK_LValue; // even if the parameter is an r-value reference 2945 break; 2946 } 2947 2948 // For non-references, we need to strip qualifiers just in case 2949 // the template parameter was declared as 'const int' or whatever. 2950 valueKind = VK_RValue; 2951 type = type.getUnqualifiedType(); 2952 break; 2953 } 2954 2955 case Decl::Var: 2956 case Decl::VarTemplateSpecialization: 2957 case Decl::VarTemplatePartialSpecialization: 2958 case Decl::Decomposition: 2959 case Decl::OMPCapturedExpr: 2960 // In C, "extern void blah;" is valid and is an r-value. 2961 if (!getLangOpts().CPlusPlus && 2962 !type.hasQualifiers() && 2963 type->isVoidType()) { 2964 valueKind = VK_RValue; 2965 break; 2966 } 2967 // fallthrough 2968 2969 case Decl::ImplicitParam: 2970 case Decl::ParmVar: { 2971 // These are always l-values. 2972 valueKind = VK_LValue; 2973 type = type.getNonReferenceType(); 2974 2975 // FIXME: Does the addition of const really only apply in 2976 // potentially-evaluated contexts? Since the variable isn't actually 2977 // captured in an unevaluated context, it seems that the answer is no. 2978 if (!isUnevaluatedContext()) { 2979 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2980 if (!CapturedType.isNull()) 2981 type = CapturedType; 2982 } 2983 2984 break; 2985 } 2986 2987 case Decl::Binding: { 2988 // These are always lvalues. 2989 valueKind = VK_LValue; 2990 type = type.getNonReferenceType(); 2991 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 2992 // decides how that's supposed to work. 2993 auto *BD = cast<BindingDecl>(VD); 2994 if (BD->getDeclContext()->isFunctionOrMethod() && 2995 BD->getDeclContext() != CurContext) 2996 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 2997 break; 2998 } 2999 3000 case Decl::Function: { 3001 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3002 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3003 type = Context.BuiltinFnTy; 3004 valueKind = VK_RValue; 3005 break; 3006 } 3007 } 3008 3009 const FunctionType *fty = type->castAs<FunctionType>(); 3010 3011 // If we're referring to a function with an __unknown_anytype 3012 // result type, make the entire expression __unknown_anytype. 3013 if (fty->getReturnType() == Context.UnknownAnyTy) { 3014 type = Context.UnknownAnyTy; 3015 valueKind = VK_RValue; 3016 break; 3017 } 3018 3019 // Functions are l-values in C++. 3020 if (getLangOpts().CPlusPlus) { 3021 valueKind = VK_LValue; 3022 break; 3023 } 3024 3025 // C99 DR 316 says that, if a function type comes from a 3026 // function definition (without a prototype), that type is only 3027 // used for checking compatibility. Therefore, when referencing 3028 // the function, we pretend that we don't have the full function 3029 // type. 3030 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3031 isa<FunctionProtoType>(fty)) 3032 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3033 fty->getExtInfo()); 3034 3035 // Functions are r-values in C. 3036 valueKind = VK_RValue; 3037 break; 3038 } 3039 3040 case Decl::MSProperty: 3041 valueKind = VK_LValue; 3042 break; 3043 3044 case Decl::CXXMethod: 3045 // If we're referring to a method with an __unknown_anytype 3046 // result type, make the entire expression __unknown_anytype. 3047 // This should only be possible with a type written directly. 3048 if (const FunctionProtoType *proto 3049 = dyn_cast<FunctionProtoType>(VD->getType())) 3050 if (proto->getReturnType() == Context.UnknownAnyTy) { 3051 type = Context.UnknownAnyTy; 3052 valueKind = VK_RValue; 3053 break; 3054 } 3055 3056 // C++ methods are l-values if static, r-values if non-static. 3057 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3058 valueKind = VK_LValue; 3059 break; 3060 } 3061 // fallthrough 3062 3063 case Decl::CXXConversion: 3064 case Decl::CXXDestructor: 3065 case Decl::CXXConstructor: 3066 valueKind = VK_RValue; 3067 break; 3068 } 3069 3070 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3071 TemplateArgs); 3072 } 3073 } 3074 3075 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3076 SmallString<32> &Target) { 3077 Target.resize(CharByteWidth * (Source.size() + 1)); 3078 char *ResultPtr = &Target[0]; 3079 const llvm::UTF8 *ErrorPtr; 3080 bool success = 3081 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3082 (void)success; 3083 assert(success); 3084 Target.resize(ResultPtr - &Target[0]); 3085 } 3086 3087 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3088 PredefinedExpr::IdentType IT) { 3089 // Pick the current block, lambda, captured statement or function. 3090 Decl *currentDecl = nullptr; 3091 if (const BlockScopeInfo *BSI = getCurBlock()) 3092 currentDecl = BSI->TheDecl; 3093 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3094 currentDecl = LSI->CallOperator; 3095 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3096 currentDecl = CSI->TheCapturedDecl; 3097 else 3098 currentDecl = getCurFunctionOrMethodDecl(); 3099 3100 if (!currentDecl) { 3101 Diag(Loc, diag::ext_predef_outside_function); 3102 currentDecl = Context.getTranslationUnitDecl(); 3103 } 3104 3105 QualType ResTy; 3106 StringLiteral *SL = nullptr; 3107 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3108 ResTy = Context.DependentTy; 3109 else { 3110 // Pre-defined identifiers are of type char[x], where x is the length of 3111 // the string. 3112 auto Str = PredefinedExpr::ComputeName(IT, currentDecl); 3113 unsigned Length = Str.length(); 3114 3115 llvm::APInt LengthI(32, Length + 1); 3116 if (IT == PredefinedExpr::LFunction) { 3117 ResTy = Context.WideCharTy.withConst(); 3118 SmallString<32> RawChars; 3119 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3120 Str, RawChars); 3121 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3122 /*IndexTypeQuals*/ 0); 3123 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3124 /*Pascal*/ false, ResTy, Loc); 3125 } else { 3126 ResTy = Context.CharTy.withConst(); 3127 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3128 /*IndexTypeQuals*/ 0); 3129 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3130 /*Pascal*/ false, ResTy, Loc); 3131 } 3132 } 3133 3134 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL); 3135 } 3136 3137 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3138 PredefinedExpr::IdentType IT; 3139 3140 switch (Kind) { 3141 default: llvm_unreachable("Unknown simple primary expr!"); 3142 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3143 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 3144 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 3145 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS] 3146 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 3147 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 3148 } 3149 3150 return BuildPredefinedExpr(Loc, IT); 3151 } 3152 3153 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3154 SmallString<16> CharBuffer; 3155 bool Invalid = false; 3156 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3157 if (Invalid) 3158 return ExprError(); 3159 3160 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3161 PP, Tok.getKind()); 3162 if (Literal.hadError()) 3163 return ExprError(); 3164 3165 QualType Ty; 3166 if (Literal.isWide()) 3167 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3168 else if (Literal.isUTF16()) 3169 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3170 else if (Literal.isUTF32()) 3171 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3172 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3173 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3174 else 3175 Ty = Context.CharTy; // 'x' -> char in C++ 3176 3177 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3178 if (Literal.isWide()) 3179 Kind = CharacterLiteral::Wide; 3180 else if (Literal.isUTF16()) 3181 Kind = CharacterLiteral::UTF16; 3182 else if (Literal.isUTF32()) 3183 Kind = CharacterLiteral::UTF32; 3184 else if (Literal.isUTF8()) 3185 Kind = CharacterLiteral::UTF8; 3186 3187 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3188 Tok.getLocation()); 3189 3190 if (Literal.getUDSuffix().empty()) 3191 return Lit; 3192 3193 // We're building a user-defined literal. 3194 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3195 SourceLocation UDSuffixLoc = 3196 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3197 3198 // Make sure we're allowed user-defined literals here. 3199 if (!UDLScope) 3200 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3201 3202 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3203 // operator "" X (ch) 3204 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3205 Lit, Tok.getLocation()); 3206 } 3207 3208 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3209 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3210 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3211 Context.IntTy, Loc); 3212 } 3213 3214 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3215 QualType Ty, SourceLocation Loc) { 3216 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3217 3218 using llvm::APFloat; 3219 APFloat Val(Format); 3220 3221 APFloat::opStatus result = Literal.GetFloatValue(Val); 3222 3223 // Overflow is always an error, but underflow is only an error if 3224 // we underflowed to zero (APFloat reports denormals as underflow). 3225 if ((result & APFloat::opOverflow) || 3226 ((result & APFloat::opUnderflow) && Val.isZero())) { 3227 unsigned diagnostic; 3228 SmallString<20> buffer; 3229 if (result & APFloat::opOverflow) { 3230 diagnostic = diag::warn_float_overflow; 3231 APFloat::getLargest(Format).toString(buffer); 3232 } else { 3233 diagnostic = diag::warn_float_underflow; 3234 APFloat::getSmallest(Format).toString(buffer); 3235 } 3236 3237 S.Diag(Loc, diagnostic) 3238 << Ty 3239 << StringRef(buffer.data(), buffer.size()); 3240 } 3241 3242 bool isExact = (result == APFloat::opOK); 3243 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3244 } 3245 3246 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3247 assert(E && "Invalid expression"); 3248 3249 if (E->isValueDependent()) 3250 return false; 3251 3252 QualType QT = E->getType(); 3253 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3254 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3255 return true; 3256 } 3257 3258 llvm::APSInt ValueAPS; 3259 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3260 3261 if (R.isInvalid()) 3262 return true; 3263 3264 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3265 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3266 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3267 << ValueAPS.toString(10) << ValueIsPositive; 3268 return true; 3269 } 3270 3271 return false; 3272 } 3273 3274 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3275 // Fast path for a single digit (which is quite common). A single digit 3276 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3277 if (Tok.getLength() == 1) { 3278 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3279 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3280 } 3281 3282 SmallString<128> SpellingBuffer; 3283 // NumericLiteralParser wants to overread by one character. Add padding to 3284 // the buffer in case the token is copied to the buffer. If getSpelling() 3285 // returns a StringRef to the memory buffer, it should have a null char at 3286 // the EOF, so it is also safe. 3287 SpellingBuffer.resize(Tok.getLength() + 1); 3288 3289 // Get the spelling of the token, which eliminates trigraphs, etc. 3290 bool Invalid = false; 3291 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3292 if (Invalid) 3293 return ExprError(); 3294 3295 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3296 if (Literal.hadError) 3297 return ExprError(); 3298 3299 if (Literal.hasUDSuffix()) { 3300 // We're building a user-defined literal. 3301 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3302 SourceLocation UDSuffixLoc = 3303 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3304 3305 // Make sure we're allowed user-defined literals here. 3306 if (!UDLScope) 3307 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3308 3309 QualType CookedTy; 3310 if (Literal.isFloatingLiteral()) { 3311 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3312 // long double, the literal is treated as a call of the form 3313 // operator "" X (f L) 3314 CookedTy = Context.LongDoubleTy; 3315 } else { 3316 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3317 // unsigned long long, the literal is treated as a call of the form 3318 // operator "" X (n ULL) 3319 CookedTy = Context.UnsignedLongLongTy; 3320 } 3321 3322 DeclarationName OpName = 3323 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3324 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3325 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3326 3327 SourceLocation TokLoc = Tok.getLocation(); 3328 3329 // Perform literal operator lookup to determine if we're building a raw 3330 // literal or a cooked one. 3331 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3332 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3333 /*AllowRaw*/true, /*AllowTemplate*/true, 3334 /*AllowStringTemplate*/false)) { 3335 case LOLR_Error: 3336 return ExprError(); 3337 3338 case LOLR_Cooked: { 3339 Expr *Lit; 3340 if (Literal.isFloatingLiteral()) { 3341 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3342 } else { 3343 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3344 if (Literal.GetIntegerValue(ResultVal)) 3345 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3346 << /* Unsigned */ 1; 3347 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3348 Tok.getLocation()); 3349 } 3350 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3351 } 3352 3353 case LOLR_Raw: { 3354 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3355 // literal is treated as a call of the form 3356 // operator "" X ("n") 3357 unsigned Length = Literal.getUDSuffixOffset(); 3358 QualType StrTy = Context.getConstantArrayType( 3359 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 3360 ArrayType::Normal, 0); 3361 Expr *Lit = StringLiteral::Create( 3362 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3363 /*Pascal*/false, StrTy, &TokLoc, 1); 3364 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3365 } 3366 3367 case LOLR_Template: { 3368 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3369 // template), L is treated as a call fo the form 3370 // operator "" X <'c1', 'c2', ... 'ck'>() 3371 // where n is the source character sequence c1 c2 ... ck. 3372 TemplateArgumentListInfo ExplicitArgs; 3373 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3374 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3375 llvm::APSInt Value(CharBits, CharIsUnsigned); 3376 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3377 Value = TokSpelling[I]; 3378 TemplateArgument Arg(Context, Value, Context.CharTy); 3379 TemplateArgumentLocInfo ArgInfo; 3380 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3381 } 3382 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3383 &ExplicitArgs); 3384 } 3385 case LOLR_StringTemplate: 3386 llvm_unreachable("unexpected literal operator lookup result"); 3387 } 3388 } 3389 3390 Expr *Res; 3391 3392 if (Literal.isFloatingLiteral()) { 3393 QualType Ty; 3394 if (Literal.isHalf){ 3395 if (getOpenCLOptions().cl_khr_fp16) 3396 Ty = Context.HalfTy; 3397 else { 3398 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3399 return ExprError(); 3400 } 3401 } else if (Literal.isFloat) 3402 Ty = Context.FloatTy; 3403 else if (Literal.isLong) 3404 Ty = Context.LongDoubleTy; 3405 else if (Literal.isFloat128) 3406 Ty = Context.Float128Ty; 3407 else 3408 Ty = Context.DoubleTy; 3409 3410 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3411 3412 if (Ty == Context.DoubleTy) { 3413 if (getLangOpts().SinglePrecisionConstants) { 3414 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3415 } else if (getLangOpts().OpenCL && 3416 !((getLangOpts().OpenCLVersion >= 120) || 3417 getOpenCLOptions().cl_khr_fp64)) { 3418 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3419 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3420 } 3421 } 3422 } else if (!Literal.isIntegerLiteral()) { 3423 return ExprError(); 3424 } else { 3425 QualType Ty; 3426 3427 // 'long long' is a C99 or C++11 feature. 3428 if (!getLangOpts().C99 && Literal.isLongLong) { 3429 if (getLangOpts().CPlusPlus) 3430 Diag(Tok.getLocation(), 3431 getLangOpts().CPlusPlus11 ? 3432 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3433 else 3434 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3435 } 3436 3437 // Get the value in the widest-possible width. 3438 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3439 llvm::APInt ResultVal(MaxWidth, 0); 3440 3441 if (Literal.GetIntegerValue(ResultVal)) { 3442 // If this value didn't fit into uintmax_t, error and force to ull. 3443 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3444 << /* Unsigned */ 1; 3445 Ty = Context.UnsignedLongLongTy; 3446 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3447 "long long is not intmax_t?"); 3448 } else { 3449 // If this value fits into a ULL, try to figure out what else it fits into 3450 // according to the rules of C99 6.4.4.1p5. 3451 3452 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3453 // be an unsigned int. 3454 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3455 3456 // Check from smallest to largest, picking the smallest type we can. 3457 unsigned Width = 0; 3458 3459 // Microsoft specific integer suffixes are explicitly sized. 3460 if (Literal.MicrosoftInteger) { 3461 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3462 Width = 8; 3463 Ty = Context.CharTy; 3464 } else { 3465 Width = Literal.MicrosoftInteger; 3466 Ty = Context.getIntTypeForBitwidth(Width, 3467 /*Signed=*/!Literal.isUnsigned); 3468 } 3469 } 3470 3471 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3472 // Are int/unsigned possibilities? 3473 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3474 3475 // Does it fit in a unsigned int? 3476 if (ResultVal.isIntN(IntSize)) { 3477 // Does it fit in a signed int? 3478 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3479 Ty = Context.IntTy; 3480 else if (AllowUnsigned) 3481 Ty = Context.UnsignedIntTy; 3482 Width = IntSize; 3483 } 3484 } 3485 3486 // Are long/unsigned long possibilities? 3487 if (Ty.isNull() && !Literal.isLongLong) { 3488 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3489 3490 // Does it fit in a unsigned long? 3491 if (ResultVal.isIntN(LongSize)) { 3492 // Does it fit in a signed long? 3493 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3494 Ty = Context.LongTy; 3495 else if (AllowUnsigned) 3496 Ty = Context.UnsignedLongTy; 3497 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3498 // is compatible. 3499 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3500 const unsigned LongLongSize = 3501 Context.getTargetInfo().getLongLongWidth(); 3502 Diag(Tok.getLocation(), 3503 getLangOpts().CPlusPlus 3504 ? Literal.isLong 3505 ? diag::warn_old_implicitly_unsigned_long_cxx 3506 : /*C++98 UB*/ diag:: 3507 ext_old_implicitly_unsigned_long_cxx 3508 : diag::warn_old_implicitly_unsigned_long) 3509 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3510 : /*will be ill-formed*/ 1); 3511 Ty = Context.UnsignedLongTy; 3512 } 3513 Width = LongSize; 3514 } 3515 } 3516 3517 // Check long long if needed. 3518 if (Ty.isNull()) { 3519 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3520 3521 // Does it fit in a unsigned long long? 3522 if (ResultVal.isIntN(LongLongSize)) { 3523 // Does it fit in a signed long long? 3524 // To be compatible with MSVC, hex integer literals ending with the 3525 // LL or i64 suffix are always signed in Microsoft mode. 3526 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3527 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3528 Ty = Context.LongLongTy; 3529 else if (AllowUnsigned) 3530 Ty = Context.UnsignedLongLongTy; 3531 Width = LongLongSize; 3532 } 3533 } 3534 3535 // If we still couldn't decide a type, we probably have something that 3536 // does not fit in a signed long long, but has no U suffix. 3537 if (Ty.isNull()) { 3538 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3539 Ty = Context.UnsignedLongLongTy; 3540 Width = Context.getTargetInfo().getLongLongWidth(); 3541 } 3542 3543 if (ResultVal.getBitWidth() != Width) 3544 ResultVal = ResultVal.trunc(Width); 3545 } 3546 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3547 } 3548 3549 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3550 if (Literal.isImaginary) 3551 Res = new (Context) ImaginaryLiteral(Res, 3552 Context.getComplexType(Res->getType())); 3553 3554 return Res; 3555 } 3556 3557 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3558 assert(E && "ActOnParenExpr() missing expr"); 3559 return new (Context) ParenExpr(L, R, E); 3560 } 3561 3562 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3563 SourceLocation Loc, 3564 SourceRange ArgRange) { 3565 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3566 // scalar or vector data type argument..." 3567 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3568 // type (C99 6.2.5p18) or void. 3569 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3570 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3571 << T << ArgRange; 3572 return true; 3573 } 3574 3575 assert((T->isVoidType() || !T->isIncompleteType()) && 3576 "Scalar types should always be complete"); 3577 return false; 3578 } 3579 3580 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3581 SourceLocation Loc, 3582 SourceRange ArgRange, 3583 UnaryExprOrTypeTrait TraitKind) { 3584 // Invalid types must be hard errors for SFINAE in C++. 3585 if (S.LangOpts.CPlusPlus) 3586 return true; 3587 3588 // C99 6.5.3.4p1: 3589 if (T->isFunctionType() && 3590 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3591 // sizeof(function)/alignof(function) is allowed as an extension. 3592 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3593 << TraitKind << ArgRange; 3594 return false; 3595 } 3596 3597 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3598 // this is an error (OpenCL v1.1 s6.3.k) 3599 if (T->isVoidType()) { 3600 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3601 : diag::ext_sizeof_alignof_void_type; 3602 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3603 return false; 3604 } 3605 3606 return true; 3607 } 3608 3609 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3610 SourceLocation Loc, 3611 SourceRange ArgRange, 3612 UnaryExprOrTypeTrait TraitKind) { 3613 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3614 // runtime doesn't allow it. 3615 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3616 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3617 << T << (TraitKind == UETT_SizeOf) 3618 << ArgRange; 3619 return true; 3620 } 3621 3622 return false; 3623 } 3624 3625 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3626 /// pointer type is equal to T) and emit a warning if it is. 3627 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3628 Expr *E) { 3629 // Don't warn if the operation changed the type. 3630 if (T != E->getType()) 3631 return; 3632 3633 // Now look for array decays. 3634 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3635 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3636 return; 3637 3638 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3639 << ICE->getType() 3640 << ICE->getSubExpr()->getType(); 3641 } 3642 3643 /// \brief Check the constraints on expression operands to unary type expression 3644 /// and type traits. 3645 /// 3646 /// Completes any types necessary and validates the constraints on the operand 3647 /// expression. The logic mostly mirrors the type-based overload, but may modify 3648 /// the expression as it completes the type for that expression through template 3649 /// instantiation, etc. 3650 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3651 UnaryExprOrTypeTrait ExprKind) { 3652 QualType ExprTy = E->getType(); 3653 assert(!ExprTy->isReferenceType()); 3654 3655 if (ExprKind == UETT_VecStep) 3656 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3657 E->getSourceRange()); 3658 3659 // Whitelist some types as extensions 3660 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3661 E->getSourceRange(), ExprKind)) 3662 return false; 3663 3664 // 'alignof' applied to an expression only requires the base element type of 3665 // the expression to be complete. 'sizeof' requires the expression's type to 3666 // be complete (and will attempt to complete it if it's an array of unknown 3667 // bound). 3668 if (ExprKind == UETT_AlignOf) { 3669 if (RequireCompleteType(E->getExprLoc(), 3670 Context.getBaseElementType(E->getType()), 3671 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3672 E->getSourceRange())) 3673 return true; 3674 } else { 3675 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3676 ExprKind, E->getSourceRange())) 3677 return true; 3678 } 3679 3680 // Completing the expression's type may have changed it. 3681 ExprTy = E->getType(); 3682 assert(!ExprTy->isReferenceType()); 3683 3684 if (ExprTy->isFunctionType()) { 3685 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3686 << ExprKind << E->getSourceRange(); 3687 return true; 3688 } 3689 3690 // The operand for sizeof and alignof is in an unevaluated expression context, 3691 // so side effects could result in unintended consequences. 3692 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) && 3693 ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false)) 3694 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3695 3696 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3697 E->getSourceRange(), ExprKind)) 3698 return true; 3699 3700 if (ExprKind == UETT_SizeOf) { 3701 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3702 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3703 QualType OType = PVD->getOriginalType(); 3704 QualType Type = PVD->getType(); 3705 if (Type->isPointerType() && OType->isArrayType()) { 3706 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3707 << Type << OType; 3708 Diag(PVD->getLocation(), diag::note_declared_at); 3709 } 3710 } 3711 } 3712 3713 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3714 // decays into a pointer and returns an unintended result. This is most 3715 // likely a typo for "sizeof(array) op x". 3716 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3717 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3718 BO->getLHS()); 3719 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3720 BO->getRHS()); 3721 } 3722 } 3723 3724 return false; 3725 } 3726 3727 /// \brief Check the constraints on operands to unary expression and type 3728 /// traits. 3729 /// 3730 /// This will complete any types necessary, and validate the various constraints 3731 /// on those operands. 3732 /// 3733 /// The UsualUnaryConversions() function is *not* called by this routine. 3734 /// C99 6.3.2.1p[2-4] all state: 3735 /// Except when it is the operand of the sizeof operator ... 3736 /// 3737 /// C++ [expr.sizeof]p4 3738 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3739 /// standard conversions are not applied to the operand of sizeof. 3740 /// 3741 /// This policy is followed for all of the unary trait expressions. 3742 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3743 SourceLocation OpLoc, 3744 SourceRange ExprRange, 3745 UnaryExprOrTypeTrait ExprKind) { 3746 if (ExprType->isDependentType()) 3747 return false; 3748 3749 // C++ [expr.sizeof]p2: 3750 // When applied to a reference or a reference type, the result 3751 // is the size of the referenced type. 3752 // C++11 [expr.alignof]p3: 3753 // When alignof is applied to a reference type, the result 3754 // shall be the alignment of the referenced type. 3755 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3756 ExprType = Ref->getPointeeType(); 3757 3758 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3759 // When alignof or _Alignof is applied to an array type, the result 3760 // is the alignment of the element type. 3761 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign) 3762 ExprType = Context.getBaseElementType(ExprType); 3763 3764 if (ExprKind == UETT_VecStep) 3765 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3766 3767 // Whitelist some types as extensions 3768 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3769 ExprKind)) 3770 return false; 3771 3772 if (RequireCompleteType(OpLoc, ExprType, 3773 diag::err_sizeof_alignof_incomplete_type, 3774 ExprKind, ExprRange)) 3775 return true; 3776 3777 if (ExprType->isFunctionType()) { 3778 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3779 << ExprKind << ExprRange; 3780 return true; 3781 } 3782 3783 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3784 ExprKind)) 3785 return true; 3786 3787 return false; 3788 } 3789 3790 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3791 E = E->IgnoreParens(); 3792 3793 // Cannot know anything else if the expression is dependent. 3794 if (E->isTypeDependent()) 3795 return false; 3796 3797 if (E->getObjectKind() == OK_BitField) { 3798 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3799 << 1 << E->getSourceRange(); 3800 return true; 3801 } 3802 3803 ValueDecl *D = nullptr; 3804 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3805 D = DRE->getDecl(); 3806 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3807 D = ME->getMemberDecl(); 3808 } 3809 3810 // If it's a field, require the containing struct to have a 3811 // complete definition so that we can compute the layout. 3812 // 3813 // This can happen in C++11 onwards, either by naming the member 3814 // in a way that is not transformed into a member access expression 3815 // (in an unevaluated operand, for instance), or by naming the member 3816 // in a trailing-return-type. 3817 // 3818 // For the record, since __alignof__ on expressions is a GCC 3819 // extension, GCC seems to permit this but always gives the 3820 // nonsensical answer 0. 3821 // 3822 // We don't really need the layout here --- we could instead just 3823 // directly check for all the appropriate alignment-lowing 3824 // attributes --- but that would require duplicating a lot of 3825 // logic that just isn't worth duplicating for such a marginal 3826 // use-case. 3827 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3828 // Fast path this check, since we at least know the record has a 3829 // definition if we can find a member of it. 3830 if (!FD->getParent()->isCompleteDefinition()) { 3831 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3832 << E->getSourceRange(); 3833 return true; 3834 } 3835 3836 // Otherwise, if it's a field, and the field doesn't have 3837 // reference type, then it must have a complete type (or be a 3838 // flexible array member, which we explicitly want to 3839 // white-list anyway), which makes the following checks trivial. 3840 if (!FD->getType()->isReferenceType()) 3841 return false; 3842 } 3843 3844 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3845 } 3846 3847 bool Sema::CheckVecStepExpr(Expr *E) { 3848 E = E->IgnoreParens(); 3849 3850 // Cannot know anything else if the expression is dependent. 3851 if (E->isTypeDependent()) 3852 return false; 3853 3854 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3855 } 3856 3857 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 3858 CapturingScopeInfo *CSI) { 3859 assert(T->isVariablyModifiedType()); 3860 assert(CSI != nullptr); 3861 3862 // We're going to walk down into the type and look for VLA expressions. 3863 do { 3864 const Type *Ty = T.getTypePtr(); 3865 switch (Ty->getTypeClass()) { 3866 #define TYPE(Class, Base) 3867 #define ABSTRACT_TYPE(Class, Base) 3868 #define NON_CANONICAL_TYPE(Class, Base) 3869 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 3870 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 3871 #include "clang/AST/TypeNodes.def" 3872 T = QualType(); 3873 break; 3874 // These types are never variably-modified. 3875 case Type::Builtin: 3876 case Type::Complex: 3877 case Type::Vector: 3878 case Type::ExtVector: 3879 case Type::Record: 3880 case Type::Enum: 3881 case Type::Elaborated: 3882 case Type::TemplateSpecialization: 3883 case Type::ObjCObject: 3884 case Type::ObjCInterface: 3885 case Type::ObjCObjectPointer: 3886 case Type::ObjCTypeParam: 3887 case Type::Pipe: 3888 llvm_unreachable("type class is never variably-modified!"); 3889 case Type::Adjusted: 3890 T = cast<AdjustedType>(Ty)->getOriginalType(); 3891 break; 3892 case Type::Decayed: 3893 T = cast<DecayedType>(Ty)->getPointeeType(); 3894 break; 3895 case Type::Pointer: 3896 T = cast<PointerType>(Ty)->getPointeeType(); 3897 break; 3898 case Type::BlockPointer: 3899 T = cast<BlockPointerType>(Ty)->getPointeeType(); 3900 break; 3901 case Type::LValueReference: 3902 case Type::RValueReference: 3903 T = cast<ReferenceType>(Ty)->getPointeeType(); 3904 break; 3905 case Type::MemberPointer: 3906 T = cast<MemberPointerType>(Ty)->getPointeeType(); 3907 break; 3908 case Type::ConstantArray: 3909 case Type::IncompleteArray: 3910 // Losing element qualification here is fine. 3911 T = cast<ArrayType>(Ty)->getElementType(); 3912 break; 3913 case Type::VariableArray: { 3914 // Losing element qualification here is fine. 3915 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 3916 3917 // Unknown size indication requires no size computation. 3918 // Otherwise, evaluate and record it. 3919 if (auto Size = VAT->getSizeExpr()) { 3920 if (!CSI->isVLATypeCaptured(VAT)) { 3921 RecordDecl *CapRecord = nullptr; 3922 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 3923 CapRecord = LSI->Lambda; 3924 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 3925 CapRecord = CRSI->TheRecordDecl; 3926 } 3927 if (CapRecord) { 3928 auto ExprLoc = Size->getExprLoc(); 3929 auto SizeType = Context.getSizeType(); 3930 // Build the non-static data member. 3931 auto Field = 3932 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc, 3933 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 3934 /*BW*/ nullptr, /*Mutable*/ false, 3935 /*InitStyle*/ ICIS_NoInit); 3936 Field->setImplicit(true); 3937 Field->setAccess(AS_private); 3938 Field->setCapturedVLAType(VAT); 3939 CapRecord->addDecl(Field); 3940 3941 CSI->addVLATypeCapture(ExprLoc, SizeType); 3942 } 3943 } 3944 } 3945 T = VAT->getElementType(); 3946 break; 3947 } 3948 case Type::FunctionProto: 3949 case Type::FunctionNoProto: 3950 T = cast<FunctionType>(Ty)->getReturnType(); 3951 break; 3952 case Type::Paren: 3953 case Type::TypeOf: 3954 case Type::UnaryTransform: 3955 case Type::Attributed: 3956 case Type::SubstTemplateTypeParm: 3957 case Type::PackExpansion: 3958 // Keep walking after single level desugaring. 3959 T = T.getSingleStepDesugaredType(Context); 3960 break; 3961 case Type::Typedef: 3962 T = cast<TypedefType>(Ty)->desugar(); 3963 break; 3964 case Type::Decltype: 3965 T = cast<DecltypeType>(Ty)->desugar(); 3966 break; 3967 case Type::Auto: 3968 T = cast<AutoType>(Ty)->getDeducedType(); 3969 break; 3970 case Type::TypeOfExpr: 3971 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 3972 break; 3973 case Type::Atomic: 3974 T = cast<AtomicType>(Ty)->getValueType(); 3975 break; 3976 } 3977 } while (!T.isNull() && T->isVariablyModifiedType()); 3978 } 3979 3980 /// \brief Build a sizeof or alignof expression given a type operand. 3981 ExprResult 3982 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3983 SourceLocation OpLoc, 3984 UnaryExprOrTypeTrait ExprKind, 3985 SourceRange R) { 3986 if (!TInfo) 3987 return ExprError(); 3988 3989 QualType T = TInfo->getType(); 3990 3991 if (!T->isDependentType() && 3992 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3993 return ExprError(); 3994 3995 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 3996 if (auto *TT = T->getAs<TypedefType>()) { 3997 for (auto I = FunctionScopes.rbegin(), 3998 E = std::prev(FunctionScopes.rend()); 3999 I != E; ++I) { 4000 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4001 if (CSI == nullptr) 4002 break; 4003 DeclContext *DC = nullptr; 4004 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4005 DC = LSI->CallOperator; 4006 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4007 DC = CRSI->TheCapturedDecl; 4008 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4009 DC = BSI->TheDecl; 4010 if (DC) { 4011 if (DC->containsDecl(TT->getDecl())) 4012 break; 4013 captureVariablyModifiedType(Context, T, CSI); 4014 } 4015 } 4016 } 4017 } 4018 4019 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4020 return new (Context) UnaryExprOrTypeTraitExpr( 4021 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4022 } 4023 4024 /// \brief Build a sizeof or alignof expression given an expression 4025 /// operand. 4026 ExprResult 4027 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4028 UnaryExprOrTypeTrait ExprKind) { 4029 ExprResult PE = CheckPlaceholderExpr(E); 4030 if (PE.isInvalid()) 4031 return ExprError(); 4032 4033 E = PE.get(); 4034 4035 // Verify that the operand is valid. 4036 bool isInvalid = false; 4037 if (E->isTypeDependent()) { 4038 // Delay type-checking for type-dependent expressions. 4039 } else if (ExprKind == UETT_AlignOf) { 4040 isInvalid = CheckAlignOfExpr(*this, E); 4041 } else if (ExprKind == UETT_VecStep) { 4042 isInvalid = CheckVecStepExpr(E); 4043 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4044 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4045 isInvalid = true; 4046 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4047 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4048 isInvalid = true; 4049 } else { 4050 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4051 } 4052 4053 if (isInvalid) 4054 return ExprError(); 4055 4056 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4057 PE = TransformToPotentiallyEvaluated(E); 4058 if (PE.isInvalid()) return ExprError(); 4059 E = PE.get(); 4060 } 4061 4062 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4063 return new (Context) UnaryExprOrTypeTraitExpr( 4064 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4065 } 4066 4067 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4068 /// expr and the same for @c alignof and @c __alignof 4069 /// Note that the ArgRange is invalid if isType is false. 4070 ExprResult 4071 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4072 UnaryExprOrTypeTrait ExprKind, bool IsType, 4073 void *TyOrEx, SourceRange ArgRange) { 4074 // If error parsing type, ignore. 4075 if (!TyOrEx) return ExprError(); 4076 4077 if (IsType) { 4078 TypeSourceInfo *TInfo; 4079 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4080 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4081 } 4082 4083 Expr *ArgEx = (Expr *)TyOrEx; 4084 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4085 return Result; 4086 } 4087 4088 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4089 bool IsReal) { 4090 if (V.get()->isTypeDependent()) 4091 return S.Context.DependentTy; 4092 4093 // _Real and _Imag are only l-values for normal l-values. 4094 if (V.get()->getObjectKind() != OK_Ordinary) { 4095 V = S.DefaultLvalueConversion(V.get()); 4096 if (V.isInvalid()) 4097 return QualType(); 4098 } 4099 4100 // These operators return the element type of a complex type. 4101 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4102 return CT->getElementType(); 4103 4104 // Otherwise they pass through real integer and floating point types here. 4105 if (V.get()->getType()->isArithmeticType()) 4106 return V.get()->getType(); 4107 4108 // Test for placeholders. 4109 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4110 if (PR.isInvalid()) return QualType(); 4111 if (PR.get() != V.get()) { 4112 V = PR; 4113 return CheckRealImagOperand(S, V, Loc, IsReal); 4114 } 4115 4116 // Reject anything else. 4117 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4118 << (IsReal ? "__real" : "__imag"); 4119 return QualType(); 4120 } 4121 4122 4123 4124 ExprResult 4125 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4126 tok::TokenKind Kind, Expr *Input) { 4127 UnaryOperatorKind Opc; 4128 switch (Kind) { 4129 default: llvm_unreachable("Unknown unary op!"); 4130 case tok::plusplus: Opc = UO_PostInc; break; 4131 case tok::minusminus: Opc = UO_PostDec; break; 4132 } 4133 4134 // Since this might is a postfix expression, get rid of ParenListExprs. 4135 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4136 if (Result.isInvalid()) return ExprError(); 4137 Input = Result.get(); 4138 4139 return BuildUnaryOp(S, OpLoc, Opc, Input); 4140 } 4141 4142 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 4143 /// 4144 /// \return true on error 4145 static bool checkArithmeticOnObjCPointer(Sema &S, 4146 SourceLocation opLoc, 4147 Expr *op) { 4148 assert(op->getType()->isObjCObjectPointerType()); 4149 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4150 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4151 return false; 4152 4153 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4154 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4155 << op->getSourceRange(); 4156 return true; 4157 } 4158 4159 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4160 auto *BaseNoParens = Base->IgnoreParens(); 4161 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4162 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4163 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4164 } 4165 4166 ExprResult 4167 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4168 Expr *idx, SourceLocation rbLoc) { 4169 if (base && !base->getType().isNull() && 4170 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4171 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4172 /*Length=*/nullptr, rbLoc); 4173 4174 // Since this might be a postfix expression, get rid of ParenListExprs. 4175 if (isa<ParenListExpr>(base)) { 4176 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4177 if (result.isInvalid()) return ExprError(); 4178 base = result.get(); 4179 } 4180 4181 // Handle any non-overload placeholder types in the base and index 4182 // expressions. We can't handle overloads here because the other 4183 // operand might be an overloadable type, in which case the overload 4184 // resolution for the operator overload should get the first crack 4185 // at the overload. 4186 bool IsMSPropertySubscript = false; 4187 if (base->getType()->isNonOverloadPlaceholderType()) { 4188 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4189 if (!IsMSPropertySubscript) { 4190 ExprResult result = CheckPlaceholderExpr(base); 4191 if (result.isInvalid()) 4192 return ExprError(); 4193 base = result.get(); 4194 } 4195 } 4196 if (idx->getType()->isNonOverloadPlaceholderType()) { 4197 ExprResult result = CheckPlaceholderExpr(idx); 4198 if (result.isInvalid()) return ExprError(); 4199 idx = result.get(); 4200 } 4201 4202 // Build an unanalyzed expression if either operand is type-dependent. 4203 if (getLangOpts().CPlusPlus && 4204 (base->isTypeDependent() || idx->isTypeDependent())) { 4205 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4206 VK_LValue, OK_Ordinary, rbLoc); 4207 } 4208 4209 // MSDN, property (C++) 4210 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4211 // This attribute can also be used in the declaration of an empty array in a 4212 // class or structure definition. For example: 4213 // __declspec(property(get=GetX, put=PutX)) int x[]; 4214 // The above statement indicates that x[] can be used with one or more array 4215 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4216 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4217 if (IsMSPropertySubscript) { 4218 // Build MS property subscript expression if base is MS property reference 4219 // or MS property subscript. 4220 return new (Context) MSPropertySubscriptExpr( 4221 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4222 } 4223 4224 // Use C++ overloaded-operator rules if either operand has record 4225 // type. The spec says to do this if either type is *overloadable*, 4226 // but enum types can't declare subscript operators or conversion 4227 // operators, so there's nothing interesting for overload resolution 4228 // to do if there aren't any record types involved. 4229 // 4230 // ObjC pointers have their own subscripting logic that is not tied 4231 // to overload resolution and so should not take this path. 4232 if (getLangOpts().CPlusPlus && 4233 (base->getType()->isRecordType() || 4234 (!base->getType()->isObjCObjectPointerType() && 4235 idx->getType()->isRecordType()))) { 4236 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4237 } 4238 4239 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4240 } 4241 4242 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4243 Expr *LowerBound, 4244 SourceLocation ColonLoc, Expr *Length, 4245 SourceLocation RBLoc) { 4246 if (Base->getType()->isPlaceholderType() && 4247 !Base->getType()->isSpecificPlaceholderType( 4248 BuiltinType::OMPArraySection)) { 4249 ExprResult Result = CheckPlaceholderExpr(Base); 4250 if (Result.isInvalid()) 4251 return ExprError(); 4252 Base = Result.get(); 4253 } 4254 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4255 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4256 if (Result.isInvalid()) 4257 return ExprError(); 4258 Result = DefaultLvalueConversion(Result.get()); 4259 if (Result.isInvalid()) 4260 return ExprError(); 4261 LowerBound = Result.get(); 4262 } 4263 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4264 ExprResult Result = CheckPlaceholderExpr(Length); 4265 if (Result.isInvalid()) 4266 return ExprError(); 4267 Result = DefaultLvalueConversion(Result.get()); 4268 if (Result.isInvalid()) 4269 return ExprError(); 4270 Length = Result.get(); 4271 } 4272 4273 // Build an unanalyzed expression if either operand is type-dependent. 4274 if (Base->isTypeDependent() || 4275 (LowerBound && 4276 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4277 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4278 return new (Context) 4279 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4280 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4281 } 4282 4283 // Perform default conversions. 4284 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4285 QualType ResultTy; 4286 if (OriginalTy->isAnyPointerType()) { 4287 ResultTy = OriginalTy->getPointeeType(); 4288 } else if (OriginalTy->isArrayType()) { 4289 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4290 } else { 4291 return ExprError( 4292 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4293 << Base->getSourceRange()); 4294 } 4295 // C99 6.5.2.1p1 4296 if (LowerBound) { 4297 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4298 LowerBound); 4299 if (Res.isInvalid()) 4300 return ExprError(Diag(LowerBound->getExprLoc(), 4301 diag::err_omp_typecheck_section_not_integer) 4302 << 0 << LowerBound->getSourceRange()); 4303 LowerBound = Res.get(); 4304 4305 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4306 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4307 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4308 << 0 << LowerBound->getSourceRange(); 4309 } 4310 if (Length) { 4311 auto Res = 4312 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4313 if (Res.isInvalid()) 4314 return ExprError(Diag(Length->getExprLoc(), 4315 diag::err_omp_typecheck_section_not_integer) 4316 << 1 << Length->getSourceRange()); 4317 Length = Res.get(); 4318 4319 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4320 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4321 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4322 << 1 << Length->getSourceRange(); 4323 } 4324 4325 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4326 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4327 // type. Note that functions are not objects, and that (in C99 parlance) 4328 // incomplete types are not object types. 4329 if (ResultTy->isFunctionType()) { 4330 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4331 << ResultTy << Base->getSourceRange(); 4332 return ExprError(); 4333 } 4334 4335 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4336 diag::err_omp_section_incomplete_type, Base)) 4337 return ExprError(); 4338 4339 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4340 llvm::APSInt LowerBoundValue; 4341 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) { 4342 // OpenMP 4.5, [2.4 Array Sections] 4343 // The array section must be a subset of the original array. 4344 if (LowerBoundValue.isNegative()) { 4345 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4346 << LowerBound->getSourceRange(); 4347 return ExprError(); 4348 } 4349 } 4350 } 4351 4352 if (Length) { 4353 llvm::APSInt LengthValue; 4354 if (Length->EvaluateAsInt(LengthValue, Context)) { 4355 // OpenMP 4.5, [2.4 Array Sections] 4356 // The length must evaluate to non-negative integers. 4357 if (LengthValue.isNegative()) { 4358 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4359 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4360 << Length->getSourceRange(); 4361 return ExprError(); 4362 } 4363 } 4364 } else if (ColonLoc.isValid() && 4365 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4366 !OriginalTy->isVariableArrayType()))) { 4367 // OpenMP 4.5, [2.4 Array Sections] 4368 // When the size of the array dimension is not known, the length must be 4369 // specified explicitly. 4370 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4371 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4372 return ExprError(); 4373 } 4374 4375 if (!Base->getType()->isSpecificPlaceholderType( 4376 BuiltinType::OMPArraySection)) { 4377 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4378 if (Result.isInvalid()) 4379 return ExprError(); 4380 Base = Result.get(); 4381 } 4382 return new (Context) 4383 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4384 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4385 } 4386 4387 ExprResult 4388 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4389 Expr *Idx, SourceLocation RLoc) { 4390 Expr *LHSExp = Base; 4391 Expr *RHSExp = Idx; 4392 4393 // Perform default conversions. 4394 if (!LHSExp->getType()->getAs<VectorType>()) { 4395 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4396 if (Result.isInvalid()) 4397 return ExprError(); 4398 LHSExp = Result.get(); 4399 } 4400 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4401 if (Result.isInvalid()) 4402 return ExprError(); 4403 RHSExp = Result.get(); 4404 4405 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4406 ExprValueKind VK = VK_LValue; 4407 ExprObjectKind OK = OK_Ordinary; 4408 4409 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4410 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4411 // in the subscript position. As a result, we need to derive the array base 4412 // and index from the expression types. 4413 Expr *BaseExpr, *IndexExpr; 4414 QualType ResultType; 4415 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4416 BaseExpr = LHSExp; 4417 IndexExpr = RHSExp; 4418 ResultType = Context.DependentTy; 4419 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4420 BaseExpr = LHSExp; 4421 IndexExpr = RHSExp; 4422 ResultType = PTy->getPointeeType(); 4423 } else if (const ObjCObjectPointerType *PTy = 4424 LHSTy->getAs<ObjCObjectPointerType>()) { 4425 BaseExpr = LHSExp; 4426 IndexExpr = RHSExp; 4427 4428 // Use custom logic if this should be the pseudo-object subscript 4429 // expression. 4430 if (!LangOpts.isSubscriptPointerArithmetic()) 4431 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4432 nullptr); 4433 4434 ResultType = PTy->getPointeeType(); 4435 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4436 // Handle the uncommon case of "123[Ptr]". 4437 BaseExpr = RHSExp; 4438 IndexExpr = LHSExp; 4439 ResultType = PTy->getPointeeType(); 4440 } else if (const ObjCObjectPointerType *PTy = 4441 RHSTy->getAs<ObjCObjectPointerType>()) { 4442 // Handle the uncommon case of "123[Ptr]". 4443 BaseExpr = RHSExp; 4444 IndexExpr = LHSExp; 4445 ResultType = PTy->getPointeeType(); 4446 if (!LangOpts.isSubscriptPointerArithmetic()) { 4447 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4448 << ResultType << BaseExpr->getSourceRange(); 4449 return ExprError(); 4450 } 4451 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4452 BaseExpr = LHSExp; // vectors: V[123] 4453 IndexExpr = RHSExp; 4454 VK = LHSExp->getValueKind(); 4455 if (VK != VK_RValue) 4456 OK = OK_VectorComponent; 4457 4458 // FIXME: need to deal with const... 4459 ResultType = VTy->getElementType(); 4460 } else if (LHSTy->isArrayType()) { 4461 // If we see an array that wasn't promoted by 4462 // DefaultFunctionArrayLvalueConversion, it must be an array that 4463 // wasn't promoted because of the C90 rule that doesn't 4464 // allow promoting non-lvalue arrays. Warn, then 4465 // force the promotion here. 4466 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4467 LHSExp->getSourceRange(); 4468 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4469 CK_ArrayToPointerDecay).get(); 4470 LHSTy = LHSExp->getType(); 4471 4472 BaseExpr = LHSExp; 4473 IndexExpr = RHSExp; 4474 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4475 } else if (RHSTy->isArrayType()) { 4476 // Same as previous, except for 123[f().a] case 4477 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4478 RHSExp->getSourceRange(); 4479 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4480 CK_ArrayToPointerDecay).get(); 4481 RHSTy = RHSExp->getType(); 4482 4483 BaseExpr = RHSExp; 4484 IndexExpr = LHSExp; 4485 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4486 } else { 4487 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4488 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4489 } 4490 // C99 6.5.2.1p1 4491 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4492 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4493 << IndexExpr->getSourceRange()); 4494 4495 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4496 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4497 && !IndexExpr->isTypeDependent()) 4498 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4499 4500 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4501 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4502 // type. Note that Functions are not objects, and that (in C99 parlance) 4503 // incomplete types are not object types. 4504 if (ResultType->isFunctionType()) { 4505 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 4506 << ResultType << BaseExpr->getSourceRange(); 4507 return ExprError(); 4508 } 4509 4510 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4511 // GNU extension: subscripting on pointer to void 4512 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4513 << BaseExpr->getSourceRange(); 4514 4515 // C forbids expressions of unqualified void type from being l-values. 4516 // See IsCForbiddenLValueType. 4517 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4518 } else if (!ResultType->isDependentType() && 4519 RequireCompleteType(LLoc, ResultType, 4520 diag::err_subscript_incomplete_type, BaseExpr)) 4521 return ExprError(); 4522 4523 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4524 !ResultType.isCForbiddenLValueType()); 4525 4526 return new (Context) 4527 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4528 } 4529 4530 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4531 FunctionDecl *FD, 4532 ParmVarDecl *Param) { 4533 if (Param->hasUnparsedDefaultArg()) { 4534 Diag(CallLoc, 4535 diag::err_use_of_default_argument_to_function_declared_later) << 4536 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4537 Diag(UnparsedDefaultArgLocs[Param], 4538 diag::note_default_argument_declared_here); 4539 return ExprError(); 4540 } 4541 4542 if (Param->hasUninstantiatedDefaultArg()) { 4543 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4544 4545 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated, 4546 Param); 4547 4548 // Instantiate the expression. 4549 MultiLevelTemplateArgumentList MutiLevelArgList 4550 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4551 4552 InstantiatingTemplate Inst(*this, CallLoc, Param, 4553 MutiLevelArgList.getInnermost()); 4554 if (Inst.isInvalid()) 4555 return ExprError(); 4556 if (Inst.isAlreadyInstantiating()) { 4557 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4558 Param->setInvalidDecl(); 4559 return ExprError(); 4560 } 4561 4562 ExprResult Result; 4563 { 4564 // C++ [dcl.fct.default]p5: 4565 // The names in the [default argument] expression are bound, and 4566 // the semantic constraints are checked, at the point where the 4567 // default argument expression appears. 4568 ContextRAII SavedContext(*this, FD); 4569 LocalInstantiationScope Local(*this); 4570 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 4571 /*DirectInit*/false); 4572 } 4573 if (Result.isInvalid()) 4574 return ExprError(); 4575 4576 // Check the expression as an initializer for the parameter. 4577 InitializedEntity Entity 4578 = InitializedEntity::InitializeParameter(Context, Param); 4579 InitializationKind Kind 4580 = InitializationKind::CreateCopy(Param->getLocation(), 4581 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 4582 Expr *ResultE = Result.getAs<Expr>(); 4583 4584 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4585 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4586 if (Result.isInvalid()) 4587 return ExprError(); 4588 4589 Result = ActOnFinishFullExpr(Result.getAs<Expr>(), 4590 Param->getOuterLocStart()); 4591 if (Result.isInvalid()) 4592 return ExprError(); 4593 4594 // Remember the instantiated default argument. 4595 Param->setDefaultArg(Result.getAs<Expr>()); 4596 if (ASTMutationListener *L = getASTMutationListener()) { 4597 L->DefaultArgumentInstantiated(Param); 4598 } 4599 } 4600 4601 // If the default argument expression is not set yet, we are building it now. 4602 if (!Param->hasInit()) { 4603 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4604 Param->setInvalidDecl(); 4605 return ExprError(); 4606 } 4607 4608 // If the default expression creates temporaries, we need to 4609 // push them to the current stack of expression temporaries so they'll 4610 // be properly destroyed. 4611 // FIXME: We should really be rebuilding the default argument with new 4612 // bound temporaries; see the comment in PR5810. 4613 // We don't need to do that with block decls, though, because 4614 // blocks in default argument expression can never capture anything. 4615 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 4616 // Set the "needs cleanups" bit regardless of whether there are 4617 // any explicit objects. 4618 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 4619 4620 // Append all the objects to the cleanup list. Right now, this 4621 // should always be a no-op, because blocks in default argument 4622 // expressions should never be able to capture anything. 4623 assert(!Init->getNumObjects() && 4624 "default argument expression has capturing blocks?"); 4625 } 4626 4627 // We already type-checked the argument, so we know it works. 4628 // Just mark all of the declarations in this potentially-evaluated expression 4629 // as being "referenced". 4630 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4631 /*SkipLocalVariables=*/true); 4632 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4633 } 4634 4635 4636 Sema::VariadicCallType 4637 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4638 Expr *Fn) { 4639 if (Proto && Proto->isVariadic()) { 4640 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4641 return VariadicConstructor; 4642 else if (Fn && Fn->getType()->isBlockPointerType()) 4643 return VariadicBlock; 4644 else if (FDecl) { 4645 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4646 if (Method->isInstance()) 4647 return VariadicMethod; 4648 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4649 return VariadicMethod; 4650 return VariadicFunction; 4651 } 4652 return VariadicDoesNotApply; 4653 } 4654 4655 namespace { 4656 class FunctionCallCCC : public FunctionCallFilterCCC { 4657 public: 4658 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4659 unsigned NumArgs, MemberExpr *ME) 4660 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4661 FunctionName(FuncName) {} 4662 4663 bool ValidateCandidate(const TypoCorrection &candidate) override { 4664 if (!candidate.getCorrectionSpecifier() || 4665 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4666 return false; 4667 } 4668 4669 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4670 } 4671 4672 private: 4673 const IdentifierInfo *const FunctionName; 4674 }; 4675 } 4676 4677 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4678 FunctionDecl *FDecl, 4679 ArrayRef<Expr *> Args) { 4680 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4681 DeclarationName FuncName = FDecl->getDeclName(); 4682 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart(); 4683 4684 if (TypoCorrection Corrected = S.CorrectTypo( 4685 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4686 S.getScopeForContext(S.CurContext), nullptr, 4687 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4688 Args.size(), ME), 4689 Sema::CTK_ErrorRecovery)) { 4690 if (NamedDecl *ND = Corrected.getFoundDecl()) { 4691 if (Corrected.isOverloaded()) { 4692 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4693 OverloadCandidateSet::iterator Best; 4694 for (NamedDecl *CD : Corrected) { 4695 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 4696 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4697 OCS); 4698 } 4699 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4700 case OR_Success: 4701 ND = Best->FoundDecl; 4702 Corrected.setCorrectionDecl(ND); 4703 break; 4704 default: 4705 break; 4706 } 4707 } 4708 ND = ND->getUnderlyingDecl(); 4709 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 4710 return Corrected; 4711 } 4712 } 4713 return TypoCorrection(); 4714 } 4715 4716 /// ConvertArgumentsForCall - Converts the arguments specified in 4717 /// Args/NumArgs to the parameter types of the function FDecl with 4718 /// function prototype Proto. Call is the call expression itself, and 4719 /// Fn is the function expression. For a C++ member function, this 4720 /// routine does not attempt to convert the object argument. Returns 4721 /// true if the call is ill-formed. 4722 bool 4723 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4724 FunctionDecl *FDecl, 4725 const FunctionProtoType *Proto, 4726 ArrayRef<Expr *> Args, 4727 SourceLocation RParenLoc, 4728 bool IsExecConfig) { 4729 // Bail out early if calling a builtin with custom typechecking. 4730 if (FDecl) 4731 if (unsigned ID = FDecl->getBuiltinID()) 4732 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4733 return false; 4734 4735 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4736 // assignment, to the types of the corresponding parameter, ... 4737 unsigned NumParams = Proto->getNumParams(); 4738 bool Invalid = false; 4739 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4740 unsigned FnKind = Fn->getType()->isBlockPointerType() 4741 ? 1 /* block */ 4742 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4743 : 0 /* function */); 4744 4745 // If too few arguments are available (and we don't have default 4746 // arguments for the remaining parameters), don't make the call. 4747 if (Args.size() < NumParams) { 4748 if (Args.size() < MinArgs) { 4749 TypoCorrection TC; 4750 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4751 unsigned diag_id = 4752 MinArgs == NumParams && !Proto->isVariadic() 4753 ? diag::err_typecheck_call_too_few_args_suggest 4754 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4755 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4756 << static_cast<unsigned>(Args.size()) 4757 << TC.getCorrectionRange()); 4758 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4759 Diag(RParenLoc, 4760 MinArgs == NumParams && !Proto->isVariadic() 4761 ? diag::err_typecheck_call_too_few_args_one 4762 : diag::err_typecheck_call_too_few_args_at_least_one) 4763 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4764 else 4765 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4766 ? diag::err_typecheck_call_too_few_args 4767 : diag::err_typecheck_call_too_few_args_at_least) 4768 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4769 << Fn->getSourceRange(); 4770 4771 // Emit the location of the prototype. 4772 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4773 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4774 << FDecl; 4775 4776 return true; 4777 } 4778 Call->setNumArgs(Context, NumParams); 4779 } 4780 4781 // If too many are passed and not variadic, error on the extras and drop 4782 // them. 4783 if (Args.size() > NumParams) { 4784 if (!Proto->isVariadic()) { 4785 TypoCorrection TC; 4786 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4787 unsigned diag_id = 4788 MinArgs == NumParams && !Proto->isVariadic() 4789 ? diag::err_typecheck_call_too_many_args_suggest 4790 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4791 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4792 << static_cast<unsigned>(Args.size()) 4793 << TC.getCorrectionRange()); 4794 } else if (NumParams == 1 && FDecl && 4795 FDecl->getParamDecl(0)->getDeclName()) 4796 Diag(Args[NumParams]->getLocStart(), 4797 MinArgs == NumParams 4798 ? diag::err_typecheck_call_too_many_args_one 4799 : diag::err_typecheck_call_too_many_args_at_most_one) 4800 << FnKind << FDecl->getParamDecl(0) 4801 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4802 << SourceRange(Args[NumParams]->getLocStart(), 4803 Args.back()->getLocEnd()); 4804 else 4805 Diag(Args[NumParams]->getLocStart(), 4806 MinArgs == NumParams 4807 ? diag::err_typecheck_call_too_many_args 4808 : diag::err_typecheck_call_too_many_args_at_most) 4809 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4810 << Fn->getSourceRange() 4811 << SourceRange(Args[NumParams]->getLocStart(), 4812 Args.back()->getLocEnd()); 4813 4814 // Emit the location of the prototype. 4815 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4816 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4817 << FDecl; 4818 4819 // This deletes the extra arguments. 4820 Call->setNumArgs(Context, NumParams); 4821 return true; 4822 } 4823 } 4824 SmallVector<Expr *, 8> AllArgs; 4825 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4826 4827 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4828 Proto, 0, Args, AllArgs, CallType); 4829 if (Invalid) 4830 return true; 4831 unsigned TotalNumArgs = AllArgs.size(); 4832 for (unsigned i = 0; i < TotalNumArgs; ++i) 4833 Call->setArg(i, AllArgs[i]); 4834 4835 return false; 4836 } 4837 4838 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4839 const FunctionProtoType *Proto, 4840 unsigned FirstParam, ArrayRef<Expr *> Args, 4841 SmallVectorImpl<Expr *> &AllArgs, 4842 VariadicCallType CallType, bool AllowExplicit, 4843 bool IsListInitialization) { 4844 unsigned NumParams = Proto->getNumParams(); 4845 bool Invalid = false; 4846 size_t ArgIx = 0; 4847 // Continue to check argument types (even if we have too few/many args). 4848 for (unsigned i = FirstParam; i < NumParams; i++) { 4849 QualType ProtoArgType = Proto->getParamType(i); 4850 4851 Expr *Arg; 4852 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4853 if (ArgIx < Args.size()) { 4854 Arg = Args[ArgIx++]; 4855 4856 if (RequireCompleteType(Arg->getLocStart(), 4857 ProtoArgType, 4858 diag::err_call_incomplete_argument, Arg)) 4859 return true; 4860 4861 // Strip the unbridged-cast placeholder expression off, if applicable. 4862 bool CFAudited = false; 4863 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4864 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4865 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4866 Arg = stripARCUnbridgedCast(Arg); 4867 else if (getLangOpts().ObjCAutoRefCount && 4868 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4869 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4870 CFAudited = true; 4871 4872 InitializedEntity Entity = 4873 Param ? InitializedEntity::InitializeParameter(Context, Param, 4874 ProtoArgType) 4875 : InitializedEntity::InitializeParameter( 4876 Context, ProtoArgType, Proto->isParamConsumed(i)); 4877 4878 // Remember that parameter belongs to a CF audited API. 4879 if (CFAudited) 4880 Entity.setParameterCFAudited(); 4881 4882 ExprResult ArgE = PerformCopyInitialization( 4883 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 4884 if (ArgE.isInvalid()) 4885 return true; 4886 4887 Arg = ArgE.getAs<Expr>(); 4888 } else { 4889 assert(Param && "can't use default arguments without a known callee"); 4890 4891 ExprResult ArgExpr = 4892 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4893 if (ArgExpr.isInvalid()) 4894 return true; 4895 4896 Arg = ArgExpr.getAs<Expr>(); 4897 } 4898 4899 // Check for array bounds violations for each argument to the call. This 4900 // check only triggers warnings when the argument isn't a more complex Expr 4901 // with its own checking, such as a BinaryOperator. 4902 CheckArrayAccess(Arg); 4903 4904 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4905 CheckStaticArrayArgument(CallLoc, Param, Arg); 4906 4907 AllArgs.push_back(Arg); 4908 } 4909 4910 // If this is a variadic call, handle args passed through "...". 4911 if (CallType != VariadicDoesNotApply) { 4912 // Assume that extern "C" functions with variadic arguments that 4913 // return __unknown_anytype aren't *really* variadic. 4914 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4915 FDecl->isExternC()) { 4916 for (Expr *A : Args.slice(ArgIx)) { 4917 QualType paramType; // ignored 4918 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 4919 Invalid |= arg.isInvalid(); 4920 AllArgs.push_back(arg.get()); 4921 } 4922 4923 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4924 } else { 4925 for (Expr *A : Args.slice(ArgIx)) { 4926 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 4927 Invalid |= Arg.isInvalid(); 4928 AllArgs.push_back(Arg.get()); 4929 } 4930 } 4931 4932 // Check for array bounds violations. 4933 for (Expr *A : Args.slice(ArgIx)) 4934 CheckArrayAccess(A); 4935 } 4936 return Invalid; 4937 } 4938 4939 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4940 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4941 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4942 TL = DTL.getOriginalLoc(); 4943 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4944 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4945 << ATL.getLocalSourceRange(); 4946 } 4947 4948 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4949 /// array parameter, check that it is non-null, and that if it is formed by 4950 /// array-to-pointer decay, the underlying array is sufficiently large. 4951 /// 4952 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4953 /// array type derivation, then for each call to the function, the value of the 4954 /// corresponding actual argument shall provide access to the first element of 4955 /// an array with at least as many elements as specified by the size expression. 4956 void 4957 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4958 ParmVarDecl *Param, 4959 const Expr *ArgExpr) { 4960 // Static array parameters are not supported in C++. 4961 if (!Param || getLangOpts().CPlusPlus) 4962 return; 4963 4964 QualType OrigTy = Param->getOriginalType(); 4965 4966 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4967 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4968 return; 4969 4970 if (ArgExpr->isNullPointerConstant(Context, 4971 Expr::NPC_NeverValueDependent)) { 4972 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4973 DiagnoseCalleeStaticArrayParam(*this, Param); 4974 return; 4975 } 4976 4977 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 4978 if (!CAT) 4979 return; 4980 4981 const ConstantArrayType *ArgCAT = 4982 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 4983 if (!ArgCAT) 4984 return; 4985 4986 if (ArgCAT->getSize().ult(CAT->getSize())) { 4987 Diag(CallLoc, diag::warn_static_array_too_small) 4988 << ArgExpr->getSourceRange() 4989 << (unsigned) ArgCAT->getSize().getZExtValue() 4990 << (unsigned) CAT->getSize().getZExtValue(); 4991 DiagnoseCalleeStaticArrayParam(*this, Param); 4992 } 4993 } 4994 4995 /// Given a function expression of unknown-any type, try to rebuild it 4996 /// to have a function type. 4997 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 4998 4999 /// Is the given type a placeholder that we need to lower out 5000 /// immediately during argument processing? 5001 static bool isPlaceholderToRemoveAsArg(QualType type) { 5002 // Placeholders are never sugared. 5003 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 5004 if (!placeholder) return false; 5005 5006 switch (placeholder->getKind()) { 5007 // Ignore all the non-placeholder types. 5008 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 5009 case BuiltinType::Id: 5010 #include "clang/Basic/OpenCLImageTypes.def" 5011 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 5012 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 5013 #include "clang/AST/BuiltinTypes.def" 5014 return false; 5015 5016 // We cannot lower out overload sets; they might validly be resolved 5017 // by the call machinery. 5018 case BuiltinType::Overload: 5019 return false; 5020 5021 // Unbridged casts in ARC can be handled in some call positions and 5022 // should be left in place. 5023 case BuiltinType::ARCUnbridgedCast: 5024 return false; 5025 5026 // Pseudo-objects should be converted as soon as possible. 5027 case BuiltinType::PseudoObject: 5028 return true; 5029 5030 // The debugger mode could theoretically but currently does not try 5031 // to resolve unknown-typed arguments based on known parameter types. 5032 case BuiltinType::UnknownAny: 5033 return true; 5034 5035 // These are always invalid as call arguments and should be reported. 5036 case BuiltinType::BoundMember: 5037 case BuiltinType::BuiltinFn: 5038 case BuiltinType::OMPArraySection: 5039 return true; 5040 5041 } 5042 llvm_unreachable("bad builtin type kind"); 5043 } 5044 5045 /// Check an argument list for placeholders that we won't try to 5046 /// handle later. 5047 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5048 // Apply this processing to all the arguments at once instead of 5049 // dying at the first failure. 5050 bool hasInvalid = false; 5051 for (size_t i = 0, e = args.size(); i != e; i++) { 5052 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5053 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5054 if (result.isInvalid()) hasInvalid = true; 5055 else args[i] = result.get(); 5056 } else if (hasInvalid) { 5057 (void)S.CorrectDelayedTyposInExpr(args[i]); 5058 } 5059 } 5060 return hasInvalid; 5061 } 5062 5063 /// If a builtin function has a pointer argument with no explicit address 5064 /// space, then it should be able to accept a pointer to any address 5065 /// space as input. In order to do this, we need to replace the 5066 /// standard builtin declaration with one that uses the same address space 5067 /// as the call. 5068 /// 5069 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5070 /// it does not contain any pointer arguments without 5071 /// an address space qualifer. Otherwise the rewritten 5072 /// FunctionDecl is returned. 5073 /// TODO: Handle pointer return types. 5074 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5075 const FunctionDecl *FDecl, 5076 MultiExprArg ArgExprs) { 5077 5078 QualType DeclType = FDecl->getType(); 5079 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5080 5081 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 5082 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 5083 return nullptr; 5084 5085 bool NeedsNewDecl = false; 5086 unsigned i = 0; 5087 SmallVector<QualType, 8> OverloadParams; 5088 5089 for (QualType ParamType : FT->param_types()) { 5090 5091 // Convert array arguments to pointer to simplify type lookup. 5092 ExprResult ArgRes = 5093 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5094 if (ArgRes.isInvalid()) 5095 return nullptr; 5096 Expr *Arg = ArgRes.get(); 5097 QualType ArgType = Arg->getType(); 5098 if (!ParamType->isPointerType() || 5099 ParamType.getQualifiers().hasAddressSpace() || 5100 !ArgType->isPointerType() || 5101 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 5102 OverloadParams.push_back(ParamType); 5103 continue; 5104 } 5105 5106 NeedsNewDecl = true; 5107 unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace(); 5108 5109 QualType PointeeType = ParamType->getPointeeType(); 5110 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5111 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5112 } 5113 5114 if (!NeedsNewDecl) 5115 return nullptr; 5116 5117 FunctionProtoType::ExtProtoInfo EPI; 5118 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5119 OverloadParams, EPI); 5120 DeclContext *Parent = Context.getTranslationUnitDecl(); 5121 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5122 FDecl->getLocation(), 5123 FDecl->getLocation(), 5124 FDecl->getIdentifier(), 5125 OverloadTy, 5126 /*TInfo=*/nullptr, 5127 SC_Extern, false, 5128 /*hasPrototype=*/true); 5129 SmallVector<ParmVarDecl*, 16> Params; 5130 FT = cast<FunctionProtoType>(OverloadTy); 5131 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5132 QualType ParamType = FT->getParamType(i); 5133 ParmVarDecl *Parm = 5134 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5135 SourceLocation(), nullptr, ParamType, 5136 /*TInfo=*/nullptr, SC_None, nullptr); 5137 Parm->setScopeInfo(0, i); 5138 Params.push_back(Parm); 5139 } 5140 OverloadDecl->setParams(Params); 5141 return OverloadDecl; 5142 } 5143 5144 static bool isNumberOfArgsValidForCall(Sema &S, const FunctionDecl *Callee, 5145 std::size_t NumArgs) { 5146 if (S.TooManyArguments(Callee->getNumParams(), NumArgs, 5147 /*PartialOverloading=*/false)) 5148 return Callee->isVariadic(); 5149 return Callee->getMinRequiredArguments() <= NumArgs; 5150 } 5151 5152 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 5153 /// This provides the location of the left/right parens and a list of comma 5154 /// locations. 5155 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5156 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5157 Expr *ExecConfig, bool IsExecConfig) { 5158 // Since this might be a postfix expression, get rid of ParenListExprs. 5159 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 5160 if (Result.isInvalid()) return ExprError(); 5161 Fn = Result.get(); 5162 5163 if (checkArgsForPlaceholders(*this, ArgExprs)) 5164 return ExprError(); 5165 5166 if (getLangOpts().CPlusPlus) { 5167 // If this is a pseudo-destructor expression, build the call immediately. 5168 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5169 if (!ArgExprs.empty()) { 5170 // Pseudo-destructor calls should not have any arguments. 5171 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 5172 << FixItHint::CreateRemoval( 5173 SourceRange(ArgExprs.front()->getLocStart(), 5174 ArgExprs.back()->getLocEnd())); 5175 } 5176 5177 return new (Context) 5178 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc); 5179 } 5180 if (Fn->getType() == Context.PseudoObjectTy) { 5181 ExprResult result = CheckPlaceholderExpr(Fn); 5182 if (result.isInvalid()) return ExprError(); 5183 Fn = result.get(); 5184 } 5185 5186 // Determine whether this is a dependent call inside a C++ template, 5187 // in which case we won't do any semantic analysis now. 5188 bool Dependent = false; 5189 if (Fn->isTypeDependent()) 5190 Dependent = true; 5191 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5192 Dependent = true; 5193 5194 if (Dependent) { 5195 if (ExecConfig) { 5196 return new (Context) CUDAKernelCallExpr( 5197 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5198 Context.DependentTy, VK_RValue, RParenLoc); 5199 } else { 5200 return new (Context) CallExpr( 5201 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5202 } 5203 } 5204 5205 // Determine whether this is a call to an object (C++ [over.call.object]). 5206 if (Fn->getType()->isRecordType()) 5207 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 5208 RParenLoc); 5209 5210 if (Fn->getType() == Context.UnknownAnyTy) { 5211 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5212 if (result.isInvalid()) return ExprError(); 5213 Fn = result.get(); 5214 } 5215 5216 if (Fn->getType() == Context.BoundMemberTy) { 5217 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5218 RParenLoc); 5219 } 5220 } 5221 5222 // Check for overloaded calls. This can happen even in C due to extensions. 5223 if (Fn->getType() == Context.OverloadTy) { 5224 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5225 5226 // We aren't supposed to apply this logic for if there'Scope an '&' 5227 // involved. 5228 if (!find.HasFormOfMemberPointer) { 5229 OverloadExpr *ovl = find.Expression; 5230 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5231 return BuildOverloadedCallExpr( 5232 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 5233 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 5234 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5235 RParenLoc); 5236 } 5237 } 5238 5239 // If we're directly calling a function, get the appropriate declaration. 5240 if (Fn->getType() == Context.UnknownAnyTy) { 5241 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5242 if (result.isInvalid()) return ExprError(); 5243 Fn = result.get(); 5244 } 5245 5246 Expr *NakedFn = Fn->IgnoreParens(); 5247 5248 bool CallingNDeclIndirectly = false; 5249 NamedDecl *NDecl = nullptr; 5250 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5251 if (UnOp->getOpcode() == UO_AddrOf) { 5252 CallingNDeclIndirectly = true; 5253 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5254 } 5255 } 5256 5257 if (isa<DeclRefExpr>(NakedFn)) { 5258 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 5259 5260 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5261 if (FDecl && FDecl->getBuiltinID()) { 5262 // Rewrite the function decl for this builtin by replacing parameters 5263 // with no explicit address space with the address space of the arguments 5264 // in ArgExprs. 5265 if ((FDecl = 5266 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5267 NDecl = FDecl; 5268 Fn = DeclRefExpr::Create( 5269 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 5270 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl); 5271 } 5272 } 5273 } else if (isa<MemberExpr>(NakedFn)) 5274 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5275 5276 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5277 if (CallingNDeclIndirectly && 5278 !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 5279 Fn->getLocStart())) 5280 return ExprError(); 5281 5282 // CheckEnableIf assumes that the we're passing in a sane number of args for 5283 // FD, but that doesn't always hold true here. This is because, in some 5284 // cases, we'll emit a diag about an ill-formed function call, but then 5285 // we'll continue on as if the function call wasn't ill-formed. So, if the 5286 // number of args looks incorrect, don't do enable_if checks; we should've 5287 // already emitted an error about the bad call. 5288 if (FD->hasAttr<EnableIfAttr>() && 5289 isNumberOfArgsValidForCall(*this, FD, ArgExprs.size())) { 5290 if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) { 5291 Diag(Fn->getLocStart(), 5292 isa<CXXMethodDecl>(FD) 5293 ? diag::err_ovl_no_viable_member_function_in_call 5294 : diag::err_ovl_no_viable_function_in_call) 5295 << FD << FD->getSourceRange(); 5296 Diag(FD->getLocation(), 5297 diag::note_ovl_candidate_disabled_by_enable_if_attr) 5298 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5299 } 5300 } 5301 } 5302 5303 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5304 ExecConfig, IsExecConfig); 5305 } 5306 5307 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5308 /// 5309 /// __builtin_astype( value, dst type ) 5310 /// 5311 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5312 SourceLocation BuiltinLoc, 5313 SourceLocation RParenLoc) { 5314 ExprValueKind VK = VK_RValue; 5315 ExprObjectKind OK = OK_Ordinary; 5316 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5317 QualType SrcTy = E->getType(); 5318 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5319 return ExprError(Diag(BuiltinLoc, 5320 diag::err_invalid_astype_of_different_size) 5321 << DstTy 5322 << SrcTy 5323 << E->getSourceRange()); 5324 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5325 } 5326 5327 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5328 /// provided arguments. 5329 /// 5330 /// __builtin_convertvector( value, dst type ) 5331 /// 5332 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5333 SourceLocation BuiltinLoc, 5334 SourceLocation RParenLoc) { 5335 TypeSourceInfo *TInfo; 5336 GetTypeFromParser(ParsedDestTy, &TInfo); 5337 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5338 } 5339 5340 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5341 /// i.e. an expression not of \p OverloadTy. The expression should 5342 /// unary-convert to an expression of function-pointer or 5343 /// block-pointer type. 5344 /// 5345 /// \param NDecl the declaration being called, if available 5346 ExprResult 5347 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5348 SourceLocation LParenLoc, 5349 ArrayRef<Expr *> Args, 5350 SourceLocation RParenLoc, 5351 Expr *Config, bool IsExecConfig) { 5352 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5353 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5354 5355 // Functions with 'interrupt' attribute cannot be called directly. 5356 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5357 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5358 return ExprError(); 5359 } 5360 5361 // Promote the function operand. 5362 // We special-case function promotion here because we only allow promoting 5363 // builtin functions to function pointers in the callee of a call. 5364 ExprResult Result; 5365 if (BuiltinID && 5366 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5367 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 5368 CK_BuiltinFnToFnPtr).get(); 5369 } else { 5370 Result = CallExprUnaryConversions(Fn); 5371 } 5372 if (Result.isInvalid()) 5373 return ExprError(); 5374 Fn = Result.get(); 5375 5376 // Make the call expr early, before semantic checks. This guarantees cleanup 5377 // of arguments and function on error. 5378 CallExpr *TheCall; 5379 if (Config) 5380 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 5381 cast<CallExpr>(Config), Args, 5382 Context.BoolTy, VK_RValue, 5383 RParenLoc); 5384 else 5385 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 5386 VK_RValue, RParenLoc); 5387 5388 if (!getLangOpts().CPlusPlus) { 5389 // C cannot always handle TypoExpr nodes in builtin calls and direct 5390 // function calls as their argument checking don't necessarily handle 5391 // dependent types properly, so make sure any TypoExprs have been 5392 // dealt with. 5393 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5394 if (!Result.isUsable()) return ExprError(); 5395 TheCall = dyn_cast<CallExpr>(Result.get()); 5396 if (!TheCall) return Result; 5397 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5398 } 5399 5400 // Bail out early if calling a builtin with custom typechecking. 5401 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5402 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5403 5404 retry: 5405 const FunctionType *FuncT; 5406 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5407 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5408 // have type pointer to function". 5409 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5410 if (!FuncT) 5411 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5412 << Fn->getType() << Fn->getSourceRange()); 5413 } else if (const BlockPointerType *BPT = 5414 Fn->getType()->getAs<BlockPointerType>()) { 5415 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5416 } else { 5417 // Handle calls to expressions of unknown-any type. 5418 if (Fn->getType() == Context.UnknownAnyTy) { 5419 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5420 if (rewrite.isInvalid()) return ExprError(); 5421 Fn = rewrite.get(); 5422 TheCall->setCallee(Fn); 5423 goto retry; 5424 } 5425 5426 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5427 << Fn->getType() << Fn->getSourceRange()); 5428 } 5429 5430 if (getLangOpts().CUDA) { 5431 if (Config) { 5432 // CUDA: Kernel calls must be to global functions 5433 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5434 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5435 << FDecl->getName() << Fn->getSourceRange()); 5436 5437 // CUDA: Kernel function must have 'void' return type 5438 if (!FuncT->getReturnType()->isVoidType()) 5439 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5440 << Fn->getType() << Fn->getSourceRange()); 5441 } else { 5442 // CUDA: Calls to global functions must be configured 5443 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5444 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5445 << FDecl->getName() << Fn->getSourceRange()); 5446 } 5447 } 5448 5449 // Check for a valid return type 5450 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall, 5451 FDecl)) 5452 return ExprError(); 5453 5454 // We know the result type of the call, set it. 5455 TheCall->setType(FuncT->getCallResultType(Context)); 5456 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5457 5458 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 5459 if (Proto) { 5460 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5461 IsExecConfig)) 5462 return ExprError(); 5463 } else { 5464 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5465 5466 if (FDecl) { 5467 // Check if we have too few/too many template arguments, based 5468 // on our knowledge of the function definition. 5469 const FunctionDecl *Def = nullptr; 5470 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5471 Proto = Def->getType()->getAs<FunctionProtoType>(); 5472 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5473 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5474 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5475 } 5476 5477 // If the function we're calling isn't a function prototype, but we have 5478 // a function prototype from a prior declaratiom, use that prototype. 5479 if (!FDecl->hasPrototype()) 5480 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5481 } 5482 5483 // Promote the arguments (C99 6.5.2.2p6). 5484 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5485 Expr *Arg = Args[i]; 5486 5487 if (Proto && i < Proto->getNumParams()) { 5488 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5489 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5490 ExprResult ArgE = 5491 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5492 if (ArgE.isInvalid()) 5493 return true; 5494 5495 Arg = ArgE.getAs<Expr>(); 5496 5497 } else { 5498 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5499 5500 if (ArgE.isInvalid()) 5501 return true; 5502 5503 Arg = ArgE.getAs<Expr>(); 5504 } 5505 5506 if (RequireCompleteType(Arg->getLocStart(), 5507 Arg->getType(), 5508 diag::err_call_incomplete_argument, Arg)) 5509 return ExprError(); 5510 5511 TheCall->setArg(i, Arg); 5512 } 5513 } 5514 5515 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5516 if (!Method->isStatic()) 5517 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5518 << Fn->getSourceRange()); 5519 5520 // Check for sentinels 5521 if (NDecl) 5522 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5523 5524 // Do special checking on direct calls to functions. 5525 if (FDecl) { 5526 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5527 return ExprError(); 5528 5529 if (BuiltinID) 5530 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5531 } else if (NDecl) { 5532 if (CheckPointerCall(NDecl, TheCall, Proto)) 5533 return ExprError(); 5534 } else { 5535 if (CheckOtherCall(TheCall, Proto)) 5536 return ExprError(); 5537 } 5538 5539 return MaybeBindToTemporary(TheCall); 5540 } 5541 5542 ExprResult 5543 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5544 SourceLocation RParenLoc, Expr *InitExpr) { 5545 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5546 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 5547 5548 TypeSourceInfo *TInfo; 5549 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5550 if (!TInfo) 5551 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5552 5553 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5554 } 5555 5556 ExprResult 5557 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5558 SourceLocation RParenLoc, Expr *LiteralExpr) { 5559 QualType literalType = TInfo->getType(); 5560 5561 if (literalType->isArrayType()) { 5562 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5563 diag::err_illegal_decl_array_incomplete_type, 5564 SourceRange(LParenLoc, 5565 LiteralExpr->getSourceRange().getEnd()))) 5566 return ExprError(); 5567 if (literalType->isVariableArrayType()) 5568 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5569 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5570 } else if (!literalType->isDependentType() && 5571 RequireCompleteType(LParenLoc, literalType, 5572 diag::err_typecheck_decl_incomplete_type, 5573 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5574 return ExprError(); 5575 5576 InitializedEntity Entity 5577 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5578 InitializationKind Kind 5579 = InitializationKind::CreateCStyleCast(LParenLoc, 5580 SourceRange(LParenLoc, RParenLoc), 5581 /*InitList=*/true); 5582 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5583 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5584 &literalType); 5585 if (Result.isInvalid()) 5586 return ExprError(); 5587 LiteralExpr = Result.get(); 5588 5589 bool isFileScope = getCurFunctionOrMethodDecl() == nullptr; 5590 if (isFileScope && 5591 !LiteralExpr->isTypeDependent() && 5592 !LiteralExpr->isValueDependent() && 5593 !literalType->isDependentType()) { // 6.5.2.5p3 5594 if (CheckForConstantInitializer(LiteralExpr, literalType)) 5595 return ExprError(); 5596 } 5597 5598 // In C, compound literals are l-values for some reason. 5599 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue; 5600 5601 return MaybeBindToTemporary( 5602 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 5603 VK, LiteralExpr, isFileScope)); 5604 } 5605 5606 ExprResult 5607 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 5608 SourceLocation RBraceLoc) { 5609 // Immediately handle non-overload placeholders. Overloads can be 5610 // resolved contextually, but everything else here can't. 5611 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 5612 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 5613 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 5614 5615 // Ignore failures; dropping the entire initializer list because 5616 // of one failure would be terrible for indexing/etc. 5617 if (result.isInvalid()) continue; 5618 5619 InitArgList[I] = result.get(); 5620 } 5621 } 5622 5623 // Semantic analysis for initializers is done by ActOnDeclarator() and 5624 // CheckInitializer() - it requires knowledge of the object being intialized. 5625 5626 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 5627 RBraceLoc); 5628 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 5629 return E; 5630 } 5631 5632 /// Do an explicit extend of the given block pointer if we're in ARC. 5633 void Sema::maybeExtendBlockObject(ExprResult &E) { 5634 assert(E.get()->getType()->isBlockPointerType()); 5635 assert(E.get()->isRValue()); 5636 5637 // Only do this in an r-value context. 5638 if (!getLangOpts().ObjCAutoRefCount) return; 5639 5640 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 5641 CK_ARCExtendBlockObject, E.get(), 5642 /*base path*/ nullptr, VK_RValue); 5643 Cleanup.setExprNeedsCleanups(true); 5644 } 5645 5646 /// Prepare a conversion of the given expression to an ObjC object 5647 /// pointer type. 5648 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 5649 QualType type = E.get()->getType(); 5650 if (type->isObjCObjectPointerType()) { 5651 return CK_BitCast; 5652 } else if (type->isBlockPointerType()) { 5653 maybeExtendBlockObject(E); 5654 return CK_BlockPointerToObjCPointerCast; 5655 } else { 5656 assert(type->isPointerType()); 5657 return CK_CPointerToObjCPointerCast; 5658 } 5659 } 5660 5661 /// Prepares for a scalar cast, performing all the necessary stages 5662 /// except the final cast and returning the kind required. 5663 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 5664 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 5665 // Also, callers should have filtered out the invalid cases with 5666 // pointers. Everything else should be possible. 5667 5668 QualType SrcTy = Src.get()->getType(); 5669 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 5670 return CK_NoOp; 5671 5672 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 5673 case Type::STK_MemberPointer: 5674 llvm_unreachable("member pointer type in C"); 5675 5676 case Type::STK_CPointer: 5677 case Type::STK_BlockPointer: 5678 case Type::STK_ObjCObjectPointer: 5679 switch (DestTy->getScalarTypeKind()) { 5680 case Type::STK_CPointer: { 5681 unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace(); 5682 unsigned DestAS = DestTy->getPointeeType().getAddressSpace(); 5683 if (SrcAS != DestAS) 5684 return CK_AddressSpaceConversion; 5685 return CK_BitCast; 5686 } 5687 case Type::STK_BlockPointer: 5688 return (SrcKind == Type::STK_BlockPointer 5689 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 5690 case Type::STK_ObjCObjectPointer: 5691 if (SrcKind == Type::STK_ObjCObjectPointer) 5692 return CK_BitCast; 5693 if (SrcKind == Type::STK_CPointer) 5694 return CK_CPointerToObjCPointerCast; 5695 maybeExtendBlockObject(Src); 5696 return CK_BlockPointerToObjCPointerCast; 5697 case Type::STK_Bool: 5698 return CK_PointerToBoolean; 5699 case Type::STK_Integral: 5700 return CK_PointerToIntegral; 5701 case Type::STK_Floating: 5702 case Type::STK_FloatingComplex: 5703 case Type::STK_IntegralComplex: 5704 case Type::STK_MemberPointer: 5705 llvm_unreachable("illegal cast from pointer"); 5706 } 5707 llvm_unreachable("Should have returned before this"); 5708 5709 case Type::STK_Bool: // casting from bool is like casting from an integer 5710 case Type::STK_Integral: 5711 switch (DestTy->getScalarTypeKind()) { 5712 case Type::STK_CPointer: 5713 case Type::STK_ObjCObjectPointer: 5714 case Type::STK_BlockPointer: 5715 if (Src.get()->isNullPointerConstant(Context, 5716 Expr::NPC_ValueDependentIsNull)) 5717 return CK_NullToPointer; 5718 return CK_IntegralToPointer; 5719 case Type::STK_Bool: 5720 return CK_IntegralToBoolean; 5721 case Type::STK_Integral: 5722 return CK_IntegralCast; 5723 case Type::STK_Floating: 5724 return CK_IntegralToFloating; 5725 case Type::STK_IntegralComplex: 5726 Src = ImpCastExprToType(Src.get(), 5727 DestTy->castAs<ComplexType>()->getElementType(), 5728 CK_IntegralCast); 5729 return CK_IntegralRealToComplex; 5730 case Type::STK_FloatingComplex: 5731 Src = ImpCastExprToType(Src.get(), 5732 DestTy->castAs<ComplexType>()->getElementType(), 5733 CK_IntegralToFloating); 5734 return CK_FloatingRealToComplex; 5735 case Type::STK_MemberPointer: 5736 llvm_unreachable("member pointer type in C"); 5737 } 5738 llvm_unreachable("Should have returned before this"); 5739 5740 case Type::STK_Floating: 5741 switch (DestTy->getScalarTypeKind()) { 5742 case Type::STK_Floating: 5743 return CK_FloatingCast; 5744 case Type::STK_Bool: 5745 return CK_FloatingToBoolean; 5746 case Type::STK_Integral: 5747 return CK_FloatingToIntegral; 5748 case Type::STK_FloatingComplex: 5749 Src = ImpCastExprToType(Src.get(), 5750 DestTy->castAs<ComplexType>()->getElementType(), 5751 CK_FloatingCast); 5752 return CK_FloatingRealToComplex; 5753 case Type::STK_IntegralComplex: 5754 Src = ImpCastExprToType(Src.get(), 5755 DestTy->castAs<ComplexType>()->getElementType(), 5756 CK_FloatingToIntegral); 5757 return CK_IntegralRealToComplex; 5758 case Type::STK_CPointer: 5759 case Type::STK_ObjCObjectPointer: 5760 case Type::STK_BlockPointer: 5761 llvm_unreachable("valid float->pointer cast?"); 5762 case Type::STK_MemberPointer: 5763 llvm_unreachable("member pointer type in C"); 5764 } 5765 llvm_unreachable("Should have returned before this"); 5766 5767 case Type::STK_FloatingComplex: 5768 switch (DestTy->getScalarTypeKind()) { 5769 case Type::STK_FloatingComplex: 5770 return CK_FloatingComplexCast; 5771 case Type::STK_IntegralComplex: 5772 return CK_FloatingComplexToIntegralComplex; 5773 case Type::STK_Floating: { 5774 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5775 if (Context.hasSameType(ET, DestTy)) 5776 return CK_FloatingComplexToReal; 5777 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 5778 return CK_FloatingCast; 5779 } 5780 case Type::STK_Bool: 5781 return CK_FloatingComplexToBoolean; 5782 case Type::STK_Integral: 5783 Src = ImpCastExprToType(Src.get(), 5784 SrcTy->castAs<ComplexType>()->getElementType(), 5785 CK_FloatingComplexToReal); 5786 return CK_FloatingToIntegral; 5787 case Type::STK_CPointer: 5788 case Type::STK_ObjCObjectPointer: 5789 case Type::STK_BlockPointer: 5790 llvm_unreachable("valid complex float->pointer cast?"); 5791 case Type::STK_MemberPointer: 5792 llvm_unreachable("member pointer type in C"); 5793 } 5794 llvm_unreachable("Should have returned before this"); 5795 5796 case Type::STK_IntegralComplex: 5797 switch (DestTy->getScalarTypeKind()) { 5798 case Type::STK_FloatingComplex: 5799 return CK_IntegralComplexToFloatingComplex; 5800 case Type::STK_IntegralComplex: 5801 return CK_IntegralComplexCast; 5802 case Type::STK_Integral: { 5803 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5804 if (Context.hasSameType(ET, DestTy)) 5805 return CK_IntegralComplexToReal; 5806 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 5807 return CK_IntegralCast; 5808 } 5809 case Type::STK_Bool: 5810 return CK_IntegralComplexToBoolean; 5811 case Type::STK_Floating: 5812 Src = ImpCastExprToType(Src.get(), 5813 SrcTy->castAs<ComplexType>()->getElementType(), 5814 CK_IntegralComplexToReal); 5815 return CK_IntegralToFloating; 5816 case Type::STK_CPointer: 5817 case Type::STK_ObjCObjectPointer: 5818 case Type::STK_BlockPointer: 5819 llvm_unreachable("valid complex int->pointer cast?"); 5820 case Type::STK_MemberPointer: 5821 llvm_unreachable("member pointer type in C"); 5822 } 5823 llvm_unreachable("Should have returned before this"); 5824 } 5825 5826 llvm_unreachable("Unhandled scalar cast"); 5827 } 5828 5829 static bool breakDownVectorType(QualType type, uint64_t &len, 5830 QualType &eltType) { 5831 // Vectors are simple. 5832 if (const VectorType *vecType = type->getAs<VectorType>()) { 5833 len = vecType->getNumElements(); 5834 eltType = vecType->getElementType(); 5835 assert(eltType->isScalarType()); 5836 return true; 5837 } 5838 5839 // We allow lax conversion to and from non-vector types, but only if 5840 // they're real types (i.e. non-complex, non-pointer scalar types). 5841 if (!type->isRealType()) return false; 5842 5843 len = 1; 5844 eltType = type; 5845 return true; 5846 } 5847 5848 /// Are the two types lax-compatible vector types? That is, given 5849 /// that one of them is a vector, do they have equal storage sizes, 5850 /// where the storage size is the number of elements times the element 5851 /// size? 5852 /// 5853 /// This will also return false if either of the types is neither a 5854 /// vector nor a real type. 5855 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 5856 assert(destTy->isVectorType() || srcTy->isVectorType()); 5857 5858 // Disallow lax conversions between scalars and ExtVectors (these 5859 // conversions are allowed for other vector types because common headers 5860 // depend on them). Most scalar OP ExtVector cases are handled by the 5861 // splat path anyway, which does what we want (convert, not bitcast). 5862 // What this rules out for ExtVectors is crazy things like char4*float. 5863 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 5864 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 5865 5866 uint64_t srcLen, destLen; 5867 QualType srcEltTy, destEltTy; 5868 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 5869 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 5870 5871 // ASTContext::getTypeSize will return the size rounded up to a 5872 // power of 2, so instead of using that, we need to use the raw 5873 // element size multiplied by the element count. 5874 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 5875 uint64_t destEltSize = Context.getTypeSize(destEltTy); 5876 5877 return (srcLen * srcEltSize == destLen * destEltSize); 5878 } 5879 5880 /// Is this a legal conversion between two types, one of which is 5881 /// known to be a vector type? 5882 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 5883 assert(destTy->isVectorType() || srcTy->isVectorType()); 5884 5885 if (!Context.getLangOpts().LaxVectorConversions) 5886 return false; 5887 return areLaxCompatibleVectorTypes(srcTy, destTy); 5888 } 5889 5890 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5891 CastKind &Kind) { 5892 assert(VectorTy->isVectorType() && "Not a vector type!"); 5893 5894 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 5895 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 5896 return Diag(R.getBegin(), 5897 Ty->isVectorType() ? 5898 diag::err_invalid_conversion_between_vectors : 5899 diag::err_invalid_conversion_between_vector_and_integer) 5900 << VectorTy << Ty << R; 5901 } else 5902 return Diag(R.getBegin(), 5903 diag::err_invalid_conversion_between_vector_and_scalar) 5904 << VectorTy << Ty << R; 5905 5906 Kind = CK_BitCast; 5907 return false; 5908 } 5909 5910 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 5911 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 5912 5913 if (DestElemTy == SplattedExpr->getType()) 5914 return SplattedExpr; 5915 5916 assert(DestElemTy->isFloatingType() || 5917 DestElemTy->isIntegralOrEnumerationType()); 5918 5919 CastKind CK; 5920 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 5921 // OpenCL requires that we convert `true` boolean expressions to -1, but 5922 // only when splatting vectors. 5923 if (DestElemTy->isFloatingType()) { 5924 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 5925 // in two steps: boolean to signed integral, then to floating. 5926 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 5927 CK_BooleanToSignedIntegral); 5928 SplattedExpr = CastExprRes.get(); 5929 CK = CK_IntegralToFloating; 5930 } else { 5931 CK = CK_BooleanToSignedIntegral; 5932 } 5933 } else { 5934 ExprResult CastExprRes = SplattedExpr; 5935 CK = PrepareScalarCast(CastExprRes, DestElemTy); 5936 if (CastExprRes.isInvalid()) 5937 return ExprError(); 5938 SplattedExpr = CastExprRes.get(); 5939 } 5940 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 5941 } 5942 5943 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 5944 Expr *CastExpr, CastKind &Kind) { 5945 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 5946 5947 QualType SrcTy = CastExpr->getType(); 5948 5949 // If SrcTy is a VectorType, the total size must match to explicitly cast to 5950 // an ExtVectorType. 5951 // In OpenCL, casts between vectors of different types are not allowed. 5952 // (See OpenCL 6.2). 5953 if (SrcTy->isVectorType()) { 5954 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) 5955 || (getLangOpts().OpenCL && 5956 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 5957 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 5958 << DestTy << SrcTy << R; 5959 return ExprError(); 5960 } 5961 Kind = CK_BitCast; 5962 return CastExpr; 5963 } 5964 5965 // All non-pointer scalars can be cast to ExtVector type. The appropriate 5966 // conversion will take place first from scalar to elt type, and then 5967 // splat from elt type to vector. 5968 if (SrcTy->isPointerType()) 5969 return Diag(R.getBegin(), 5970 diag::err_invalid_conversion_between_vector_and_scalar) 5971 << DestTy << SrcTy << R; 5972 5973 Kind = CK_VectorSplat; 5974 return prepareVectorSplat(DestTy, CastExpr); 5975 } 5976 5977 ExprResult 5978 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 5979 Declarator &D, ParsedType &Ty, 5980 SourceLocation RParenLoc, Expr *CastExpr) { 5981 assert(!D.isInvalidType() && (CastExpr != nullptr) && 5982 "ActOnCastExpr(): missing type or expr"); 5983 5984 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 5985 if (D.isInvalidType()) 5986 return ExprError(); 5987 5988 if (getLangOpts().CPlusPlus) { 5989 // Check that there are no default arguments (C++ only). 5990 CheckExtraCXXDefaultArguments(D); 5991 } else { 5992 // Make sure any TypoExprs have been dealt with. 5993 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 5994 if (!Res.isUsable()) 5995 return ExprError(); 5996 CastExpr = Res.get(); 5997 } 5998 5999 checkUnusedDeclAttributes(D); 6000 6001 QualType castType = castTInfo->getType(); 6002 Ty = CreateParsedType(castType, castTInfo); 6003 6004 bool isVectorLiteral = false; 6005 6006 // Check for an altivec or OpenCL literal, 6007 // i.e. all the elements are integer constants. 6008 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 6009 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 6010 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 6011 && castType->isVectorType() && (PE || PLE)) { 6012 if (PLE && PLE->getNumExprs() == 0) { 6013 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 6014 return ExprError(); 6015 } 6016 if (PE || PLE->getNumExprs() == 1) { 6017 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 6018 if (!E->getType()->isVectorType()) 6019 isVectorLiteral = true; 6020 } 6021 else 6022 isVectorLiteral = true; 6023 } 6024 6025 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 6026 // then handle it as such. 6027 if (isVectorLiteral) 6028 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 6029 6030 // If the Expr being casted is a ParenListExpr, handle it specially. 6031 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 6032 // sequence of BinOp comma operators. 6033 if (isa<ParenListExpr>(CastExpr)) { 6034 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 6035 if (Result.isInvalid()) return ExprError(); 6036 CastExpr = Result.get(); 6037 } 6038 6039 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6040 !getSourceManager().isInSystemMacro(LParenLoc)) 6041 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6042 6043 CheckTollFreeBridgeCast(castType, CastExpr); 6044 6045 CheckObjCBridgeRelatedCast(castType, CastExpr); 6046 6047 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 6048 6049 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6050 } 6051 6052 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6053 SourceLocation RParenLoc, Expr *E, 6054 TypeSourceInfo *TInfo) { 6055 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6056 "Expected paren or paren list expression"); 6057 6058 Expr **exprs; 6059 unsigned numExprs; 6060 Expr *subExpr; 6061 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6062 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6063 LiteralLParenLoc = PE->getLParenLoc(); 6064 LiteralRParenLoc = PE->getRParenLoc(); 6065 exprs = PE->getExprs(); 6066 numExprs = PE->getNumExprs(); 6067 } else { // isa<ParenExpr> by assertion at function entrance 6068 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6069 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6070 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6071 exprs = &subExpr; 6072 numExprs = 1; 6073 } 6074 6075 QualType Ty = TInfo->getType(); 6076 assert(Ty->isVectorType() && "Expected vector type"); 6077 6078 SmallVector<Expr *, 8> initExprs; 6079 const VectorType *VTy = Ty->getAs<VectorType>(); 6080 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 6081 6082 // '(...)' form of vector initialization in AltiVec: the number of 6083 // initializers must be one or must match the size of the vector. 6084 // If a single value is specified in the initializer then it will be 6085 // replicated to all the components of the vector 6086 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6087 // The number of initializers must be one or must match the size of the 6088 // vector. If a single value is specified in the initializer then it will 6089 // be replicated to all the components of the vector 6090 if (numExprs == 1) { 6091 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6092 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6093 if (Literal.isInvalid()) 6094 return ExprError(); 6095 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6096 PrepareScalarCast(Literal, ElemTy)); 6097 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6098 } 6099 else if (numExprs < numElems) { 6100 Diag(E->getExprLoc(), 6101 diag::err_incorrect_number_of_vector_initializers); 6102 return ExprError(); 6103 } 6104 else 6105 initExprs.append(exprs, exprs + numExprs); 6106 } 6107 else { 6108 // For OpenCL, when the number of initializers is a single value, 6109 // it will be replicated to all components of the vector. 6110 if (getLangOpts().OpenCL && 6111 VTy->getVectorKind() == VectorType::GenericVector && 6112 numExprs == 1) { 6113 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6114 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6115 if (Literal.isInvalid()) 6116 return ExprError(); 6117 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6118 PrepareScalarCast(Literal, ElemTy)); 6119 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6120 } 6121 6122 initExprs.append(exprs, exprs + numExprs); 6123 } 6124 // FIXME: This means that pretty-printing the final AST will produce curly 6125 // braces instead of the original commas. 6126 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6127 initExprs, LiteralRParenLoc); 6128 initE->setType(Ty); 6129 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6130 } 6131 6132 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6133 /// the ParenListExpr into a sequence of comma binary operators. 6134 ExprResult 6135 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6136 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6137 if (!E) 6138 return OrigExpr; 6139 6140 ExprResult Result(E->getExpr(0)); 6141 6142 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6143 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6144 E->getExpr(i)); 6145 6146 if (Result.isInvalid()) return ExprError(); 6147 6148 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6149 } 6150 6151 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6152 SourceLocation R, 6153 MultiExprArg Val) { 6154 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 6155 return expr; 6156 } 6157 6158 /// \brief Emit a specialized diagnostic when one expression is a null pointer 6159 /// constant and the other is not a pointer. Returns true if a diagnostic is 6160 /// emitted. 6161 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6162 SourceLocation QuestionLoc) { 6163 Expr *NullExpr = LHSExpr; 6164 Expr *NonPointerExpr = RHSExpr; 6165 Expr::NullPointerConstantKind NullKind = 6166 NullExpr->isNullPointerConstant(Context, 6167 Expr::NPC_ValueDependentIsNotNull); 6168 6169 if (NullKind == Expr::NPCK_NotNull) { 6170 NullExpr = RHSExpr; 6171 NonPointerExpr = LHSExpr; 6172 NullKind = 6173 NullExpr->isNullPointerConstant(Context, 6174 Expr::NPC_ValueDependentIsNotNull); 6175 } 6176 6177 if (NullKind == Expr::NPCK_NotNull) 6178 return false; 6179 6180 if (NullKind == Expr::NPCK_ZeroExpression) 6181 return false; 6182 6183 if (NullKind == Expr::NPCK_ZeroLiteral) { 6184 // In this case, check to make sure that we got here from a "NULL" 6185 // string in the source code. 6186 NullExpr = NullExpr->IgnoreParenImpCasts(); 6187 SourceLocation loc = NullExpr->getExprLoc(); 6188 if (!findMacroSpelling(loc, "NULL")) 6189 return false; 6190 } 6191 6192 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6193 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6194 << NonPointerExpr->getType() << DiagType 6195 << NonPointerExpr->getSourceRange(); 6196 return true; 6197 } 6198 6199 /// \brief Return false if the condition expression is valid, true otherwise. 6200 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6201 QualType CondTy = Cond->getType(); 6202 6203 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6204 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6205 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6206 << CondTy << Cond->getSourceRange(); 6207 return true; 6208 } 6209 6210 // C99 6.5.15p2 6211 if (CondTy->isScalarType()) return false; 6212 6213 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6214 << CondTy << Cond->getSourceRange(); 6215 return true; 6216 } 6217 6218 /// \brief Handle when one or both operands are void type. 6219 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6220 ExprResult &RHS) { 6221 Expr *LHSExpr = LHS.get(); 6222 Expr *RHSExpr = RHS.get(); 6223 6224 if (!LHSExpr->getType()->isVoidType()) 6225 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6226 << RHSExpr->getSourceRange(); 6227 if (!RHSExpr->getType()->isVoidType()) 6228 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6229 << LHSExpr->getSourceRange(); 6230 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6231 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6232 return S.Context.VoidTy; 6233 } 6234 6235 /// \brief Return false if the NullExpr can be promoted to PointerTy, 6236 /// true otherwise. 6237 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6238 QualType PointerTy) { 6239 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6240 !NullExpr.get()->isNullPointerConstant(S.Context, 6241 Expr::NPC_ValueDependentIsNull)) 6242 return true; 6243 6244 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6245 return false; 6246 } 6247 6248 /// \brief Checks compatibility between two pointers and return the resulting 6249 /// type. 6250 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6251 ExprResult &RHS, 6252 SourceLocation Loc) { 6253 QualType LHSTy = LHS.get()->getType(); 6254 QualType RHSTy = RHS.get()->getType(); 6255 6256 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6257 // Two identical pointers types are always compatible. 6258 return LHSTy; 6259 } 6260 6261 QualType lhptee, rhptee; 6262 6263 // Get the pointee types. 6264 bool IsBlockPointer = false; 6265 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6266 lhptee = LHSBTy->getPointeeType(); 6267 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6268 IsBlockPointer = true; 6269 } else { 6270 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6271 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6272 } 6273 6274 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6275 // differently qualified versions of compatible types, the result type is 6276 // a pointer to an appropriately qualified version of the composite 6277 // type. 6278 6279 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6280 // clause doesn't make sense for our extensions. E.g. address space 2 should 6281 // be incompatible with address space 3: they may live on different devices or 6282 // anything. 6283 Qualifiers lhQual = lhptee.getQualifiers(); 6284 Qualifiers rhQual = rhptee.getQualifiers(); 6285 6286 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6287 lhQual.removeCVRQualifiers(); 6288 rhQual.removeCVRQualifiers(); 6289 6290 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 6291 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 6292 6293 // For OpenCL: 6294 // 1. If LHS and RHS types match exactly and: 6295 // (a) AS match => use standard C rules, no bitcast or addrspacecast 6296 // (b) AS overlap => generate addrspacecast 6297 // (c) AS don't overlap => give an error 6298 // 2. if LHS and RHS types don't match: 6299 // (a) AS match => use standard C rules, generate bitcast 6300 // (b) AS overlap => generate addrspacecast instead of bitcast 6301 // (c) AS don't overlap => give an error 6302 6303 // For OpenCL, non-null composite type is returned only for cases 1a and 1b. 6304 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 6305 6306 // OpenCL cases 1c, 2a, 2b, and 2c. 6307 if (CompositeTy.isNull()) { 6308 // In this situation, we assume void* type. No especially good 6309 // reason, but this is what gcc does, and we do have to pick 6310 // to get a consistent AST. 6311 QualType incompatTy; 6312 if (S.getLangOpts().OpenCL) { 6313 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 6314 // spaces is disallowed. 6315 unsigned ResultAddrSpace; 6316 if (lhQual.isAddressSpaceSupersetOf(rhQual)) { 6317 // Cases 2a and 2b. 6318 ResultAddrSpace = lhQual.getAddressSpace(); 6319 } else if (rhQual.isAddressSpaceSupersetOf(lhQual)) { 6320 // Cases 2a and 2b. 6321 ResultAddrSpace = rhQual.getAddressSpace(); 6322 } else { 6323 // Cases 1c and 2c. 6324 S.Diag(Loc, 6325 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 6326 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 6327 << RHS.get()->getSourceRange(); 6328 return QualType(); 6329 } 6330 6331 // Continue handling cases 2a and 2b. 6332 incompatTy = S.Context.getPointerType( 6333 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 6334 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, 6335 (lhQual.getAddressSpace() != ResultAddrSpace) 6336 ? CK_AddressSpaceConversion /* 2b */ 6337 : CK_BitCast /* 2a */); 6338 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, 6339 (rhQual.getAddressSpace() != ResultAddrSpace) 6340 ? CK_AddressSpaceConversion /* 2b */ 6341 : CK_BitCast /* 2a */); 6342 } else { 6343 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 6344 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6345 << RHS.get()->getSourceRange(); 6346 incompatTy = S.Context.getPointerType(S.Context.VoidTy); 6347 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6348 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6349 } 6350 return incompatTy; 6351 } 6352 6353 // The pointer types are compatible. 6354 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual); 6355 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 6356 if (IsBlockPointer) 6357 ResultTy = S.Context.getBlockPointerType(ResultTy); 6358 else { 6359 // Cases 1a and 1b for OpenCL. 6360 auto ResultAddrSpace = ResultTy.getQualifiers().getAddressSpace(); 6361 LHSCastKind = lhQual.getAddressSpace() == ResultAddrSpace 6362 ? CK_BitCast /* 1a */ 6363 : CK_AddressSpaceConversion /* 1b */; 6364 RHSCastKind = rhQual.getAddressSpace() == ResultAddrSpace 6365 ? CK_BitCast /* 1a */ 6366 : CK_AddressSpaceConversion /* 1b */; 6367 ResultTy = S.Context.getPointerType(ResultTy); 6368 } 6369 6370 // For case 1a of OpenCL, S.ImpCastExprToType will not insert bitcast 6371 // if the target type does not change. 6372 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 6373 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 6374 return ResultTy; 6375 } 6376 6377 /// \brief Return the resulting type when the operands are both block pointers. 6378 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 6379 ExprResult &LHS, 6380 ExprResult &RHS, 6381 SourceLocation Loc) { 6382 QualType LHSTy = LHS.get()->getType(); 6383 QualType RHSTy = RHS.get()->getType(); 6384 6385 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 6386 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 6387 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 6388 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6389 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6390 return destType; 6391 } 6392 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 6393 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6394 << RHS.get()->getSourceRange(); 6395 return QualType(); 6396 } 6397 6398 // We have 2 block pointer types. 6399 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6400 } 6401 6402 /// \brief Return the resulting type when the operands are both pointers. 6403 static QualType 6404 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 6405 ExprResult &RHS, 6406 SourceLocation Loc) { 6407 // get the pointer types 6408 QualType LHSTy = LHS.get()->getType(); 6409 QualType RHSTy = RHS.get()->getType(); 6410 6411 // get the "pointed to" types 6412 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6413 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6414 6415 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 6416 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 6417 // Figure out necessary qualifiers (C99 6.5.15p6) 6418 QualType destPointee 6419 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6420 QualType destType = S.Context.getPointerType(destPointee); 6421 // Add qualifiers if necessary. 6422 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6423 // Promote to void*. 6424 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6425 return destType; 6426 } 6427 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 6428 QualType destPointee 6429 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6430 QualType destType = S.Context.getPointerType(destPointee); 6431 // Add qualifiers if necessary. 6432 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6433 // Promote to void*. 6434 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6435 return destType; 6436 } 6437 6438 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6439 } 6440 6441 /// \brief Return false if the first expression is not an integer and the second 6442 /// expression is not a pointer, true otherwise. 6443 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 6444 Expr* PointerExpr, SourceLocation Loc, 6445 bool IsIntFirstExpr) { 6446 if (!PointerExpr->getType()->isPointerType() || 6447 !Int.get()->getType()->isIntegerType()) 6448 return false; 6449 6450 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 6451 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 6452 6453 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 6454 << Expr1->getType() << Expr2->getType() 6455 << Expr1->getSourceRange() << Expr2->getSourceRange(); 6456 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 6457 CK_IntegralToPointer); 6458 return true; 6459 } 6460 6461 /// \brief Simple conversion between integer and floating point types. 6462 /// 6463 /// Used when handling the OpenCL conditional operator where the 6464 /// condition is a vector while the other operands are scalar. 6465 /// 6466 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 6467 /// types are either integer or floating type. Between the two 6468 /// operands, the type with the higher rank is defined as the "result 6469 /// type". The other operand needs to be promoted to the same type. No 6470 /// other type promotion is allowed. We cannot use 6471 /// UsualArithmeticConversions() for this purpose, since it always 6472 /// promotes promotable types. 6473 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 6474 ExprResult &RHS, 6475 SourceLocation QuestionLoc) { 6476 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 6477 if (LHS.isInvalid()) 6478 return QualType(); 6479 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 6480 if (RHS.isInvalid()) 6481 return QualType(); 6482 6483 // For conversion purposes, we ignore any qualifiers. 6484 // For example, "const float" and "float" are equivalent. 6485 QualType LHSType = 6486 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6487 QualType RHSType = 6488 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6489 6490 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 6491 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6492 << LHSType << LHS.get()->getSourceRange(); 6493 return QualType(); 6494 } 6495 6496 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 6497 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6498 << RHSType << RHS.get()->getSourceRange(); 6499 return QualType(); 6500 } 6501 6502 // If both types are identical, no conversion is needed. 6503 if (LHSType == RHSType) 6504 return LHSType; 6505 6506 // Now handle "real" floating types (i.e. float, double, long double). 6507 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 6508 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 6509 /*IsCompAssign = */ false); 6510 6511 // Finally, we have two differing integer types. 6512 return handleIntegerConversion<doIntegralCast, doIntegralCast> 6513 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 6514 } 6515 6516 /// \brief Convert scalar operands to a vector that matches the 6517 /// condition in length. 6518 /// 6519 /// Used when handling the OpenCL conditional operator where the 6520 /// condition is a vector while the other operands are scalar. 6521 /// 6522 /// We first compute the "result type" for the scalar operands 6523 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 6524 /// into a vector of that type where the length matches the condition 6525 /// vector type. s6.11.6 requires that the element types of the result 6526 /// and the condition must have the same number of bits. 6527 static QualType 6528 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 6529 QualType CondTy, SourceLocation QuestionLoc) { 6530 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 6531 if (ResTy.isNull()) return QualType(); 6532 6533 const VectorType *CV = CondTy->getAs<VectorType>(); 6534 assert(CV); 6535 6536 // Determine the vector result type 6537 unsigned NumElements = CV->getNumElements(); 6538 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 6539 6540 // Ensure that all types have the same number of bits 6541 if (S.Context.getTypeSize(CV->getElementType()) 6542 != S.Context.getTypeSize(ResTy)) { 6543 // Since VectorTy is created internally, it does not pretty print 6544 // with an OpenCL name. Instead, we just print a description. 6545 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 6546 SmallString<64> Str; 6547 llvm::raw_svector_ostream OS(Str); 6548 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 6549 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6550 << CondTy << OS.str(); 6551 return QualType(); 6552 } 6553 6554 // Convert operands to the vector result type 6555 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 6556 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 6557 6558 return VectorTy; 6559 } 6560 6561 /// \brief Return false if this is a valid OpenCL condition vector 6562 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 6563 SourceLocation QuestionLoc) { 6564 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 6565 // integral type. 6566 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 6567 assert(CondTy); 6568 QualType EleTy = CondTy->getElementType(); 6569 if (EleTy->isIntegerType()) return false; 6570 6571 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6572 << Cond->getType() << Cond->getSourceRange(); 6573 return true; 6574 } 6575 6576 /// \brief Return false if the vector condition type and the vector 6577 /// result type are compatible. 6578 /// 6579 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 6580 /// number of elements, and their element types have the same number 6581 /// of bits. 6582 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 6583 SourceLocation QuestionLoc) { 6584 const VectorType *CV = CondTy->getAs<VectorType>(); 6585 const VectorType *RV = VecResTy->getAs<VectorType>(); 6586 assert(CV && RV); 6587 6588 if (CV->getNumElements() != RV->getNumElements()) { 6589 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 6590 << CondTy << VecResTy; 6591 return true; 6592 } 6593 6594 QualType CVE = CV->getElementType(); 6595 QualType RVE = RV->getElementType(); 6596 6597 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 6598 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6599 << CondTy << VecResTy; 6600 return true; 6601 } 6602 6603 return false; 6604 } 6605 6606 /// \brief Return the resulting type for the conditional operator in 6607 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 6608 /// s6.3.i) when the condition is a vector type. 6609 static QualType 6610 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 6611 ExprResult &LHS, ExprResult &RHS, 6612 SourceLocation QuestionLoc) { 6613 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 6614 if (Cond.isInvalid()) 6615 return QualType(); 6616 QualType CondTy = Cond.get()->getType(); 6617 6618 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 6619 return QualType(); 6620 6621 // If either operand is a vector then find the vector type of the 6622 // result as specified in OpenCL v1.1 s6.3.i. 6623 if (LHS.get()->getType()->isVectorType() || 6624 RHS.get()->getType()->isVectorType()) { 6625 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 6626 /*isCompAssign*/false, 6627 /*AllowBothBool*/true, 6628 /*AllowBoolConversions*/false); 6629 if (VecResTy.isNull()) return QualType(); 6630 // The result type must match the condition type as specified in 6631 // OpenCL v1.1 s6.11.6. 6632 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 6633 return QualType(); 6634 return VecResTy; 6635 } 6636 6637 // Both operands are scalar. 6638 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 6639 } 6640 6641 /// \brief Return true if the Expr is block type 6642 static bool checkBlockType(Sema &S, const Expr *E) { 6643 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 6644 QualType Ty = CE->getCallee()->getType(); 6645 if (Ty->isBlockPointerType()) { 6646 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 6647 return true; 6648 } 6649 } 6650 return false; 6651 } 6652 6653 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 6654 /// In that case, LHS = cond. 6655 /// C99 6.5.15 6656 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 6657 ExprResult &RHS, ExprValueKind &VK, 6658 ExprObjectKind &OK, 6659 SourceLocation QuestionLoc) { 6660 6661 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 6662 if (!LHSResult.isUsable()) return QualType(); 6663 LHS = LHSResult; 6664 6665 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 6666 if (!RHSResult.isUsable()) return QualType(); 6667 RHS = RHSResult; 6668 6669 // C++ is sufficiently different to merit its own checker. 6670 if (getLangOpts().CPlusPlus) 6671 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 6672 6673 VK = VK_RValue; 6674 OK = OK_Ordinary; 6675 6676 // The OpenCL operator with a vector condition is sufficiently 6677 // different to merit its own checker. 6678 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 6679 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 6680 6681 // First, check the condition. 6682 Cond = UsualUnaryConversions(Cond.get()); 6683 if (Cond.isInvalid()) 6684 return QualType(); 6685 if (checkCondition(*this, Cond.get(), QuestionLoc)) 6686 return QualType(); 6687 6688 // Now check the two expressions. 6689 if (LHS.get()->getType()->isVectorType() || 6690 RHS.get()->getType()->isVectorType()) 6691 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 6692 /*AllowBothBool*/true, 6693 /*AllowBoolConversions*/false); 6694 6695 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 6696 if (LHS.isInvalid() || RHS.isInvalid()) 6697 return QualType(); 6698 6699 QualType LHSTy = LHS.get()->getType(); 6700 QualType RHSTy = RHS.get()->getType(); 6701 6702 // Diagnose attempts to convert between __float128 and long double where 6703 // such conversions currently can't be handled. 6704 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 6705 Diag(QuestionLoc, 6706 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 6707 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6708 return QualType(); 6709 } 6710 6711 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 6712 // selection operator (?:). 6713 if (getLangOpts().OpenCL && 6714 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 6715 return QualType(); 6716 } 6717 6718 // If both operands have arithmetic type, do the usual arithmetic conversions 6719 // to find a common type: C99 6.5.15p3,5. 6720 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 6721 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 6722 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 6723 6724 return ResTy; 6725 } 6726 6727 // If both operands are the same structure or union type, the result is that 6728 // type. 6729 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 6730 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 6731 if (LHSRT->getDecl() == RHSRT->getDecl()) 6732 // "If both the operands have structure or union type, the result has 6733 // that type." This implies that CV qualifiers are dropped. 6734 return LHSTy.getUnqualifiedType(); 6735 // FIXME: Type of conditional expression must be complete in C mode. 6736 } 6737 6738 // C99 6.5.15p5: "If both operands have void type, the result has void type." 6739 // The following || allows only one side to be void (a GCC-ism). 6740 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 6741 return checkConditionalVoidType(*this, LHS, RHS); 6742 } 6743 6744 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 6745 // the type of the other operand." 6746 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 6747 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 6748 6749 // All objective-c pointer type analysis is done here. 6750 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 6751 QuestionLoc); 6752 if (LHS.isInvalid() || RHS.isInvalid()) 6753 return QualType(); 6754 if (!compositeType.isNull()) 6755 return compositeType; 6756 6757 6758 // Handle block pointer types. 6759 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 6760 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 6761 QuestionLoc); 6762 6763 // Check constraints for C object pointers types (C99 6.5.15p3,6). 6764 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 6765 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 6766 QuestionLoc); 6767 6768 // GCC compatibility: soften pointer/integer mismatch. Note that 6769 // null pointers have been filtered out by this point. 6770 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 6771 /*isIntFirstExpr=*/true)) 6772 return RHSTy; 6773 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 6774 /*isIntFirstExpr=*/false)) 6775 return LHSTy; 6776 6777 // Emit a better diagnostic if one of the expressions is a null pointer 6778 // constant and the other is not a pointer type. In this case, the user most 6779 // likely forgot to take the address of the other expression. 6780 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 6781 return QualType(); 6782 6783 // Otherwise, the operands are not compatible. 6784 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 6785 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6786 << RHS.get()->getSourceRange(); 6787 return QualType(); 6788 } 6789 6790 /// FindCompositeObjCPointerType - Helper method to find composite type of 6791 /// two objective-c pointer types of the two input expressions. 6792 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 6793 SourceLocation QuestionLoc) { 6794 QualType LHSTy = LHS.get()->getType(); 6795 QualType RHSTy = RHS.get()->getType(); 6796 6797 // Handle things like Class and struct objc_class*. Here we case the result 6798 // to the pseudo-builtin, because that will be implicitly cast back to the 6799 // redefinition type if an attempt is made to access its fields. 6800 if (LHSTy->isObjCClassType() && 6801 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 6802 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6803 return LHSTy; 6804 } 6805 if (RHSTy->isObjCClassType() && 6806 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 6807 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6808 return RHSTy; 6809 } 6810 // And the same for struct objc_object* / id 6811 if (LHSTy->isObjCIdType() && 6812 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 6813 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6814 return LHSTy; 6815 } 6816 if (RHSTy->isObjCIdType() && 6817 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 6818 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6819 return RHSTy; 6820 } 6821 // And the same for struct objc_selector* / SEL 6822 if (Context.isObjCSelType(LHSTy) && 6823 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 6824 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 6825 return LHSTy; 6826 } 6827 if (Context.isObjCSelType(RHSTy) && 6828 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 6829 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 6830 return RHSTy; 6831 } 6832 // Check constraints for Objective-C object pointers types. 6833 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 6834 6835 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 6836 // Two identical object pointer types are always compatible. 6837 return LHSTy; 6838 } 6839 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 6840 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 6841 QualType compositeType = LHSTy; 6842 6843 // If both operands are interfaces and either operand can be 6844 // assigned to the other, use that type as the composite 6845 // type. This allows 6846 // xxx ? (A*) a : (B*) b 6847 // where B is a subclass of A. 6848 // 6849 // Additionally, as for assignment, if either type is 'id' 6850 // allow silent coercion. Finally, if the types are 6851 // incompatible then make sure to use 'id' as the composite 6852 // type so the result is acceptable for sending messages to. 6853 6854 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 6855 // It could return the composite type. 6856 if (!(compositeType = 6857 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 6858 // Nothing more to do. 6859 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 6860 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 6861 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 6862 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 6863 } else if ((LHSTy->isObjCQualifiedIdType() || 6864 RHSTy->isObjCQualifiedIdType()) && 6865 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 6866 // Need to handle "id<xx>" explicitly. 6867 // GCC allows qualified id and any Objective-C type to devolve to 6868 // id. Currently localizing to here until clear this should be 6869 // part of ObjCQualifiedIdTypesAreCompatible. 6870 compositeType = Context.getObjCIdType(); 6871 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 6872 compositeType = Context.getObjCIdType(); 6873 } else { 6874 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 6875 << LHSTy << RHSTy 6876 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6877 QualType incompatTy = Context.getObjCIdType(); 6878 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6879 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6880 return incompatTy; 6881 } 6882 // The object pointer types are compatible. 6883 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 6884 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 6885 return compositeType; 6886 } 6887 // Check Objective-C object pointer types and 'void *' 6888 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 6889 if (getLangOpts().ObjCAutoRefCount) { 6890 // ARC forbids the implicit conversion of object pointers to 'void *', 6891 // so these types are not compatible. 6892 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6893 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6894 LHS = RHS = true; 6895 return QualType(); 6896 } 6897 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6898 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6899 QualType destPointee 6900 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6901 QualType destType = Context.getPointerType(destPointee); 6902 // Add qualifiers if necessary. 6903 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6904 // Promote to void*. 6905 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6906 return destType; 6907 } 6908 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 6909 if (getLangOpts().ObjCAutoRefCount) { 6910 // ARC forbids the implicit conversion of object pointers to 'void *', 6911 // so these types are not compatible. 6912 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6913 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6914 LHS = RHS = true; 6915 return QualType(); 6916 } 6917 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6918 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6919 QualType destPointee 6920 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6921 QualType destType = Context.getPointerType(destPointee); 6922 // Add qualifiers if necessary. 6923 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6924 // Promote to void*. 6925 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6926 return destType; 6927 } 6928 return QualType(); 6929 } 6930 6931 /// SuggestParentheses - Emit a note with a fixit hint that wraps 6932 /// ParenRange in parentheses. 6933 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 6934 const PartialDiagnostic &Note, 6935 SourceRange ParenRange) { 6936 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 6937 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 6938 EndLoc.isValid()) { 6939 Self.Diag(Loc, Note) 6940 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 6941 << FixItHint::CreateInsertion(EndLoc, ")"); 6942 } else { 6943 // We can't display the parentheses, so just show the bare note. 6944 Self.Diag(Loc, Note) << ParenRange; 6945 } 6946 } 6947 6948 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 6949 return BinaryOperator::isAdditiveOp(Opc) || 6950 BinaryOperator::isMultiplicativeOp(Opc) || 6951 BinaryOperator::isShiftOp(Opc); 6952 } 6953 6954 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 6955 /// expression, either using a built-in or overloaded operator, 6956 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 6957 /// expression. 6958 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 6959 Expr **RHSExprs) { 6960 // Don't strip parenthesis: we should not warn if E is in parenthesis. 6961 E = E->IgnoreImpCasts(); 6962 E = E->IgnoreConversionOperator(); 6963 E = E->IgnoreImpCasts(); 6964 6965 // Built-in binary operator. 6966 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 6967 if (IsArithmeticOp(OP->getOpcode())) { 6968 *Opcode = OP->getOpcode(); 6969 *RHSExprs = OP->getRHS(); 6970 return true; 6971 } 6972 } 6973 6974 // Overloaded operator. 6975 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 6976 if (Call->getNumArgs() != 2) 6977 return false; 6978 6979 // Make sure this is really a binary operator that is safe to pass into 6980 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 6981 OverloadedOperatorKind OO = Call->getOperator(); 6982 if (OO < OO_Plus || OO > OO_Arrow || 6983 OO == OO_PlusPlus || OO == OO_MinusMinus) 6984 return false; 6985 6986 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 6987 if (IsArithmeticOp(OpKind)) { 6988 *Opcode = OpKind; 6989 *RHSExprs = Call->getArg(1); 6990 return true; 6991 } 6992 } 6993 6994 return false; 6995 } 6996 6997 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 6998 /// or is a logical expression such as (x==y) which has int type, but is 6999 /// commonly interpreted as boolean. 7000 static bool ExprLooksBoolean(Expr *E) { 7001 E = E->IgnoreParenImpCasts(); 7002 7003 if (E->getType()->isBooleanType()) 7004 return true; 7005 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 7006 return OP->isComparisonOp() || OP->isLogicalOp(); 7007 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 7008 return OP->getOpcode() == UO_LNot; 7009 if (E->getType()->isPointerType()) 7010 return true; 7011 7012 return false; 7013 } 7014 7015 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 7016 /// and binary operator are mixed in a way that suggests the programmer assumed 7017 /// the conditional operator has higher precedence, for example: 7018 /// "int x = a + someBinaryCondition ? 1 : 2". 7019 static void DiagnoseConditionalPrecedence(Sema &Self, 7020 SourceLocation OpLoc, 7021 Expr *Condition, 7022 Expr *LHSExpr, 7023 Expr *RHSExpr) { 7024 BinaryOperatorKind CondOpcode; 7025 Expr *CondRHS; 7026 7027 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 7028 return; 7029 if (!ExprLooksBoolean(CondRHS)) 7030 return; 7031 7032 // The condition is an arithmetic binary expression, with a right- 7033 // hand side that looks boolean, so warn. 7034 7035 Self.Diag(OpLoc, diag::warn_precedence_conditional) 7036 << Condition->getSourceRange() 7037 << BinaryOperator::getOpcodeStr(CondOpcode); 7038 7039 SuggestParentheses(Self, OpLoc, 7040 Self.PDiag(diag::note_precedence_silence) 7041 << BinaryOperator::getOpcodeStr(CondOpcode), 7042 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 7043 7044 SuggestParentheses(Self, OpLoc, 7045 Self.PDiag(diag::note_precedence_conditional_first), 7046 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 7047 } 7048 7049 /// Compute the nullability of a conditional expression. 7050 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 7051 QualType LHSTy, QualType RHSTy, 7052 ASTContext &Ctx) { 7053 if (!ResTy->isAnyPointerType()) 7054 return ResTy; 7055 7056 auto GetNullability = [&Ctx](QualType Ty) { 7057 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 7058 if (Kind) 7059 return *Kind; 7060 return NullabilityKind::Unspecified; 7061 }; 7062 7063 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 7064 NullabilityKind MergedKind; 7065 7066 // Compute nullability of a binary conditional expression. 7067 if (IsBin) { 7068 if (LHSKind == NullabilityKind::NonNull) 7069 MergedKind = NullabilityKind::NonNull; 7070 else 7071 MergedKind = RHSKind; 7072 // Compute nullability of a normal conditional expression. 7073 } else { 7074 if (LHSKind == NullabilityKind::Nullable || 7075 RHSKind == NullabilityKind::Nullable) 7076 MergedKind = NullabilityKind::Nullable; 7077 else if (LHSKind == NullabilityKind::NonNull) 7078 MergedKind = RHSKind; 7079 else if (RHSKind == NullabilityKind::NonNull) 7080 MergedKind = LHSKind; 7081 else 7082 MergedKind = NullabilityKind::Unspecified; 7083 } 7084 7085 // Return if ResTy already has the correct nullability. 7086 if (GetNullability(ResTy) == MergedKind) 7087 return ResTy; 7088 7089 // Strip all nullability from ResTy. 7090 while (ResTy->getNullability(Ctx)) 7091 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 7092 7093 // Create a new AttributedType with the new nullability kind. 7094 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 7095 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 7096 } 7097 7098 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7099 /// in the case of a the GNU conditional expr extension. 7100 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7101 SourceLocation ColonLoc, 7102 Expr *CondExpr, Expr *LHSExpr, 7103 Expr *RHSExpr) { 7104 if (!getLangOpts().CPlusPlus) { 7105 // C cannot handle TypoExpr nodes in the condition because it 7106 // doesn't handle dependent types properly, so make sure any TypoExprs have 7107 // been dealt with before checking the operands. 7108 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7109 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7110 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7111 7112 if (!CondResult.isUsable()) 7113 return ExprError(); 7114 7115 if (LHSExpr) { 7116 if (!LHSResult.isUsable()) 7117 return ExprError(); 7118 } 7119 7120 if (!RHSResult.isUsable()) 7121 return ExprError(); 7122 7123 CondExpr = CondResult.get(); 7124 LHSExpr = LHSResult.get(); 7125 RHSExpr = RHSResult.get(); 7126 } 7127 7128 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7129 // was the condition. 7130 OpaqueValueExpr *opaqueValue = nullptr; 7131 Expr *commonExpr = nullptr; 7132 if (!LHSExpr) { 7133 commonExpr = CondExpr; 7134 // Lower out placeholder types first. This is important so that we don't 7135 // try to capture a placeholder. This happens in few cases in C++; such 7136 // as Objective-C++'s dictionary subscripting syntax. 7137 if (commonExpr->hasPlaceholderType()) { 7138 ExprResult result = CheckPlaceholderExpr(commonExpr); 7139 if (!result.isUsable()) return ExprError(); 7140 commonExpr = result.get(); 7141 } 7142 // We usually want to apply unary conversions *before* saving, except 7143 // in the special case of a C++ l-value conditional. 7144 if (!(getLangOpts().CPlusPlus 7145 && !commonExpr->isTypeDependent() 7146 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7147 && commonExpr->isGLValue() 7148 && commonExpr->isOrdinaryOrBitFieldObject() 7149 && RHSExpr->isOrdinaryOrBitFieldObject() 7150 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7151 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7152 if (commonRes.isInvalid()) 7153 return ExprError(); 7154 commonExpr = commonRes.get(); 7155 } 7156 7157 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7158 commonExpr->getType(), 7159 commonExpr->getValueKind(), 7160 commonExpr->getObjectKind(), 7161 commonExpr); 7162 LHSExpr = CondExpr = opaqueValue; 7163 } 7164 7165 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 7166 ExprValueKind VK = VK_RValue; 7167 ExprObjectKind OK = OK_Ordinary; 7168 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7169 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7170 VK, OK, QuestionLoc); 7171 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7172 RHS.isInvalid()) 7173 return ExprError(); 7174 7175 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7176 RHS.get()); 7177 7178 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 7179 7180 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 7181 Context); 7182 7183 if (!commonExpr) 7184 return new (Context) 7185 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 7186 RHS.get(), result, VK, OK); 7187 7188 return new (Context) BinaryConditionalOperator( 7189 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 7190 ColonLoc, result, VK, OK); 7191 } 7192 7193 // checkPointerTypesForAssignment - This is a very tricky routine (despite 7194 // being closely modeled after the C99 spec:-). The odd characteristic of this 7195 // routine is it effectively iqnores the qualifiers on the top level pointee. 7196 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 7197 // FIXME: add a couple examples in this comment. 7198 static Sema::AssignConvertType 7199 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 7200 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7201 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7202 7203 // get the "pointed to" type (ignoring qualifiers at the top level) 7204 const Type *lhptee, *rhptee; 7205 Qualifiers lhq, rhq; 7206 std::tie(lhptee, lhq) = 7207 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 7208 std::tie(rhptee, rhq) = 7209 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 7210 7211 Sema::AssignConvertType ConvTy = Sema::Compatible; 7212 7213 // C99 6.5.16.1p1: This following citation is common to constraints 7214 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 7215 // qualifiers of the type *pointed to* by the right; 7216 7217 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 7218 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 7219 lhq.compatiblyIncludesObjCLifetime(rhq)) { 7220 // Ignore lifetime for further calculation. 7221 lhq.removeObjCLifetime(); 7222 rhq.removeObjCLifetime(); 7223 } 7224 7225 if (!lhq.compatiblyIncludes(rhq)) { 7226 // Treat address-space mismatches as fatal. TODO: address subspaces 7227 if (!lhq.isAddressSpaceSupersetOf(rhq)) 7228 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7229 7230 // It's okay to add or remove GC or lifetime qualifiers when converting to 7231 // and from void*. 7232 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 7233 .compatiblyIncludes( 7234 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 7235 && (lhptee->isVoidType() || rhptee->isVoidType())) 7236 ; // keep old 7237 7238 // Treat lifetime mismatches as fatal. 7239 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 7240 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7241 7242 // For GCC/MS compatibility, other qualifier mismatches are treated 7243 // as still compatible in C. 7244 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7245 } 7246 7247 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 7248 // incomplete type and the other is a pointer to a qualified or unqualified 7249 // version of void... 7250 if (lhptee->isVoidType()) { 7251 if (rhptee->isIncompleteOrObjectType()) 7252 return ConvTy; 7253 7254 // As an extension, we allow cast to/from void* to function pointer. 7255 assert(rhptee->isFunctionType()); 7256 return Sema::FunctionVoidPointer; 7257 } 7258 7259 if (rhptee->isVoidType()) { 7260 if (lhptee->isIncompleteOrObjectType()) 7261 return ConvTy; 7262 7263 // As an extension, we allow cast to/from void* to function pointer. 7264 assert(lhptee->isFunctionType()); 7265 return Sema::FunctionVoidPointer; 7266 } 7267 7268 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7269 // unqualified versions of compatible types, ... 7270 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7271 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7272 // Check if the pointee types are compatible ignoring the sign. 7273 // We explicitly check for char so that we catch "char" vs 7274 // "unsigned char" on systems where "char" is unsigned. 7275 if (lhptee->isCharType()) 7276 ltrans = S.Context.UnsignedCharTy; 7277 else if (lhptee->hasSignedIntegerRepresentation()) 7278 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7279 7280 if (rhptee->isCharType()) 7281 rtrans = S.Context.UnsignedCharTy; 7282 else if (rhptee->hasSignedIntegerRepresentation()) 7283 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 7284 7285 if (ltrans == rtrans) { 7286 // Types are compatible ignoring the sign. Qualifier incompatibility 7287 // takes priority over sign incompatibility because the sign 7288 // warning can be disabled. 7289 if (ConvTy != Sema::Compatible) 7290 return ConvTy; 7291 7292 return Sema::IncompatiblePointerSign; 7293 } 7294 7295 // If we are a multi-level pointer, it's possible that our issue is simply 7296 // one of qualification - e.g. char ** -> const char ** is not allowed. If 7297 // the eventual target type is the same and the pointers have the same 7298 // level of indirection, this must be the issue. 7299 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 7300 do { 7301 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 7302 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 7303 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 7304 7305 if (lhptee == rhptee) 7306 return Sema::IncompatibleNestedPointerQualifiers; 7307 } 7308 7309 // General pointer incompatibility takes priority over qualifiers. 7310 return Sema::IncompatiblePointer; 7311 } 7312 if (!S.getLangOpts().CPlusPlus && 7313 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 7314 return Sema::IncompatiblePointer; 7315 return ConvTy; 7316 } 7317 7318 /// checkBlockPointerTypesForAssignment - This routine determines whether two 7319 /// block pointer types are compatible or whether a block and normal pointer 7320 /// are compatible. It is more restrict than comparing two function pointer 7321 // types. 7322 static Sema::AssignConvertType 7323 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 7324 QualType RHSType) { 7325 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7326 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7327 7328 QualType lhptee, rhptee; 7329 7330 // get the "pointed to" type (ignoring qualifiers at the top level) 7331 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 7332 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 7333 7334 // In C++, the types have to match exactly. 7335 if (S.getLangOpts().CPlusPlus) 7336 return Sema::IncompatibleBlockPointer; 7337 7338 Sema::AssignConvertType ConvTy = Sema::Compatible; 7339 7340 // For blocks we enforce that qualifiers are identical. 7341 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers()) 7342 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7343 7344 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 7345 return Sema::IncompatibleBlockPointer; 7346 7347 return ConvTy; 7348 } 7349 7350 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 7351 /// for assignment compatibility. 7352 static Sema::AssignConvertType 7353 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 7354 QualType RHSType) { 7355 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 7356 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 7357 7358 if (LHSType->isObjCBuiltinType()) { 7359 // Class is not compatible with ObjC object pointers. 7360 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 7361 !RHSType->isObjCQualifiedClassType()) 7362 return Sema::IncompatiblePointer; 7363 return Sema::Compatible; 7364 } 7365 if (RHSType->isObjCBuiltinType()) { 7366 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 7367 !LHSType->isObjCQualifiedClassType()) 7368 return Sema::IncompatiblePointer; 7369 return Sema::Compatible; 7370 } 7371 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7372 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7373 7374 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 7375 // make an exception for id<P> 7376 !LHSType->isObjCQualifiedIdType()) 7377 return Sema::CompatiblePointerDiscardsQualifiers; 7378 7379 if (S.Context.typesAreCompatible(LHSType, RHSType)) 7380 return Sema::Compatible; 7381 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 7382 return Sema::IncompatibleObjCQualifiedId; 7383 return Sema::IncompatiblePointer; 7384 } 7385 7386 Sema::AssignConvertType 7387 Sema::CheckAssignmentConstraints(SourceLocation Loc, 7388 QualType LHSType, QualType RHSType) { 7389 // Fake up an opaque expression. We don't actually care about what 7390 // cast operations are required, so if CheckAssignmentConstraints 7391 // adds casts to this they'll be wasted, but fortunately that doesn't 7392 // usually happen on valid code. 7393 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 7394 ExprResult RHSPtr = &RHSExpr; 7395 CastKind K = CK_Invalid; 7396 7397 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 7398 } 7399 7400 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 7401 /// has code to accommodate several GCC extensions when type checking 7402 /// pointers. Here are some objectionable examples that GCC considers warnings: 7403 /// 7404 /// int a, *pint; 7405 /// short *pshort; 7406 /// struct foo *pfoo; 7407 /// 7408 /// pint = pshort; // warning: assignment from incompatible pointer type 7409 /// a = pint; // warning: assignment makes integer from pointer without a cast 7410 /// pint = a; // warning: assignment makes pointer from integer without a cast 7411 /// pint = pfoo; // warning: assignment from incompatible pointer type 7412 /// 7413 /// As a result, the code for dealing with pointers is more complex than the 7414 /// C99 spec dictates. 7415 /// 7416 /// Sets 'Kind' for any result kind except Incompatible. 7417 Sema::AssignConvertType 7418 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 7419 CastKind &Kind, bool ConvertRHS) { 7420 QualType RHSType = RHS.get()->getType(); 7421 QualType OrigLHSType = LHSType; 7422 7423 // Get canonical types. We're not formatting these types, just comparing 7424 // them. 7425 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 7426 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 7427 7428 // Common case: no conversion required. 7429 if (LHSType == RHSType) { 7430 Kind = CK_NoOp; 7431 return Compatible; 7432 } 7433 7434 // If we have an atomic type, try a non-atomic assignment, then just add an 7435 // atomic qualification step. 7436 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 7437 Sema::AssignConvertType result = 7438 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 7439 if (result != Compatible) 7440 return result; 7441 if (Kind != CK_NoOp && ConvertRHS) 7442 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 7443 Kind = CK_NonAtomicToAtomic; 7444 return Compatible; 7445 } 7446 7447 // If the left-hand side is a reference type, then we are in a 7448 // (rare!) case where we've allowed the use of references in C, 7449 // e.g., as a parameter type in a built-in function. In this case, 7450 // just make sure that the type referenced is compatible with the 7451 // right-hand side type. The caller is responsible for adjusting 7452 // LHSType so that the resulting expression does not have reference 7453 // type. 7454 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 7455 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 7456 Kind = CK_LValueBitCast; 7457 return Compatible; 7458 } 7459 return Incompatible; 7460 } 7461 7462 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 7463 // to the same ExtVector type. 7464 if (LHSType->isExtVectorType()) { 7465 if (RHSType->isExtVectorType()) 7466 return Incompatible; 7467 if (RHSType->isArithmeticType()) { 7468 // CK_VectorSplat does T -> vector T, so first cast to the element type. 7469 if (ConvertRHS) 7470 RHS = prepareVectorSplat(LHSType, RHS.get()); 7471 Kind = CK_VectorSplat; 7472 return Compatible; 7473 } 7474 } 7475 7476 // Conversions to or from vector type. 7477 if (LHSType->isVectorType() || RHSType->isVectorType()) { 7478 if (LHSType->isVectorType() && RHSType->isVectorType()) { 7479 // Allow assignments of an AltiVec vector type to an equivalent GCC 7480 // vector type and vice versa 7481 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7482 Kind = CK_BitCast; 7483 return Compatible; 7484 } 7485 7486 // If we are allowing lax vector conversions, and LHS and RHS are both 7487 // vectors, the total size only needs to be the same. This is a bitcast; 7488 // no bits are changed but the result type is different. 7489 if (isLaxVectorConversion(RHSType, LHSType)) { 7490 Kind = CK_BitCast; 7491 return IncompatibleVectors; 7492 } 7493 } 7494 7495 // When the RHS comes from another lax conversion (e.g. binops between 7496 // scalars and vectors) the result is canonicalized as a vector. When the 7497 // LHS is also a vector, the lax is allowed by the condition above. Handle 7498 // the case where LHS is a scalar. 7499 if (LHSType->isScalarType()) { 7500 const VectorType *VecType = RHSType->getAs<VectorType>(); 7501 if (VecType && VecType->getNumElements() == 1 && 7502 isLaxVectorConversion(RHSType, LHSType)) { 7503 ExprResult *VecExpr = &RHS; 7504 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 7505 Kind = CK_BitCast; 7506 return Compatible; 7507 } 7508 } 7509 7510 return Incompatible; 7511 } 7512 7513 // Diagnose attempts to convert between __float128 and long double where 7514 // such conversions currently can't be handled. 7515 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 7516 return Incompatible; 7517 7518 // Arithmetic conversions. 7519 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 7520 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 7521 if (ConvertRHS) 7522 Kind = PrepareScalarCast(RHS, LHSType); 7523 return Compatible; 7524 } 7525 7526 // Conversions to normal pointers. 7527 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 7528 // U* -> T* 7529 if (isa<PointerType>(RHSType)) { 7530 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7531 unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 7532 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7533 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 7534 } 7535 7536 // int -> T* 7537 if (RHSType->isIntegerType()) { 7538 Kind = CK_IntegralToPointer; // FIXME: null? 7539 return IntToPointer; 7540 } 7541 7542 // C pointers are not compatible with ObjC object pointers, 7543 // with two exceptions: 7544 if (isa<ObjCObjectPointerType>(RHSType)) { 7545 // - conversions to void* 7546 if (LHSPointer->getPointeeType()->isVoidType()) { 7547 Kind = CK_BitCast; 7548 return Compatible; 7549 } 7550 7551 // - conversions from 'Class' to the redefinition type 7552 if (RHSType->isObjCClassType() && 7553 Context.hasSameType(LHSType, 7554 Context.getObjCClassRedefinitionType())) { 7555 Kind = CK_BitCast; 7556 return Compatible; 7557 } 7558 7559 Kind = CK_BitCast; 7560 return IncompatiblePointer; 7561 } 7562 7563 // U^ -> void* 7564 if (RHSType->getAs<BlockPointerType>()) { 7565 if (LHSPointer->getPointeeType()->isVoidType()) { 7566 Kind = CK_BitCast; 7567 return Compatible; 7568 } 7569 } 7570 7571 return Incompatible; 7572 } 7573 7574 // Conversions to block pointers. 7575 if (isa<BlockPointerType>(LHSType)) { 7576 // U^ -> T^ 7577 if (RHSType->isBlockPointerType()) { 7578 Kind = CK_BitCast; 7579 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 7580 } 7581 7582 // int or null -> T^ 7583 if (RHSType->isIntegerType()) { 7584 Kind = CK_IntegralToPointer; // FIXME: null 7585 return IntToBlockPointer; 7586 } 7587 7588 // id -> T^ 7589 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 7590 Kind = CK_AnyPointerToBlockPointerCast; 7591 return Compatible; 7592 } 7593 7594 // void* -> T^ 7595 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 7596 if (RHSPT->getPointeeType()->isVoidType()) { 7597 Kind = CK_AnyPointerToBlockPointerCast; 7598 return Compatible; 7599 } 7600 7601 return Incompatible; 7602 } 7603 7604 // Conversions to Objective-C pointers. 7605 if (isa<ObjCObjectPointerType>(LHSType)) { 7606 // A* -> B* 7607 if (RHSType->isObjCObjectPointerType()) { 7608 Kind = CK_BitCast; 7609 Sema::AssignConvertType result = 7610 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 7611 if (getLangOpts().ObjCAutoRefCount && 7612 result == Compatible && 7613 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 7614 result = IncompatibleObjCWeakRef; 7615 return result; 7616 } 7617 7618 // int or null -> A* 7619 if (RHSType->isIntegerType()) { 7620 Kind = CK_IntegralToPointer; // FIXME: null 7621 return IntToPointer; 7622 } 7623 7624 // In general, C pointers are not compatible with ObjC object pointers, 7625 // with two exceptions: 7626 if (isa<PointerType>(RHSType)) { 7627 Kind = CK_CPointerToObjCPointerCast; 7628 7629 // - conversions from 'void*' 7630 if (RHSType->isVoidPointerType()) { 7631 return Compatible; 7632 } 7633 7634 // - conversions to 'Class' from its redefinition type 7635 if (LHSType->isObjCClassType() && 7636 Context.hasSameType(RHSType, 7637 Context.getObjCClassRedefinitionType())) { 7638 return Compatible; 7639 } 7640 7641 return IncompatiblePointer; 7642 } 7643 7644 // Only under strict condition T^ is compatible with an Objective-C pointer. 7645 if (RHSType->isBlockPointerType() && 7646 LHSType->isBlockCompatibleObjCPointerType(Context)) { 7647 if (ConvertRHS) 7648 maybeExtendBlockObject(RHS); 7649 Kind = CK_BlockPointerToObjCPointerCast; 7650 return Compatible; 7651 } 7652 7653 return Incompatible; 7654 } 7655 7656 // Conversions from pointers that are not covered by the above. 7657 if (isa<PointerType>(RHSType)) { 7658 // T* -> _Bool 7659 if (LHSType == Context.BoolTy) { 7660 Kind = CK_PointerToBoolean; 7661 return Compatible; 7662 } 7663 7664 // T* -> int 7665 if (LHSType->isIntegerType()) { 7666 Kind = CK_PointerToIntegral; 7667 return PointerToInt; 7668 } 7669 7670 return Incompatible; 7671 } 7672 7673 // Conversions from Objective-C pointers that are not covered by the above. 7674 if (isa<ObjCObjectPointerType>(RHSType)) { 7675 // T* -> _Bool 7676 if (LHSType == Context.BoolTy) { 7677 Kind = CK_PointerToBoolean; 7678 return Compatible; 7679 } 7680 7681 // T* -> int 7682 if (LHSType->isIntegerType()) { 7683 Kind = CK_PointerToIntegral; 7684 return PointerToInt; 7685 } 7686 7687 return Incompatible; 7688 } 7689 7690 // struct A -> struct B 7691 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 7692 if (Context.typesAreCompatible(LHSType, RHSType)) { 7693 Kind = CK_NoOp; 7694 return Compatible; 7695 } 7696 } 7697 7698 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 7699 Kind = CK_IntToOCLSampler; 7700 return Compatible; 7701 } 7702 7703 return Incompatible; 7704 } 7705 7706 /// \brief Constructs a transparent union from an expression that is 7707 /// used to initialize the transparent union. 7708 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 7709 ExprResult &EResult, QualType UnionType, 7710 FieldDecl *Field) { 7711 // Build an initializer list that designates the appropriate member 7712 // of the transparent union. 7713 Expr *E = EResult.get(); 7714 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 7715 E, SourceLocation()); 7716 Initializer->setType(UnionType); 7717 Initializer->setInitializedFieldInUnion(Field); 7718 7719 // Build a compound literal constructing a value of the transparent 7720 // union type from this initializer list. 7721 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 7722 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 7723 VK_RValue, Initializer, false); 7724 } 7725 7726 Sema::AssignConvertType 7727 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 7728 ExprResult &RHS) { 7729 QualType RHSType = RHS.get()->getType(); 7730 7731 // If the ArgType is a Union type, we want to handle a potential 7732 // transparent_union GCC extension. 7733 const RecordType *UT = ArgType->getAsUnionType(); 7734 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 7735 return Incompatible; 7736 7737 // The field to initialize within the transparent union. 7738 RecordDecl *UD = UT->getDecl(); 7739 FieldDecl *InitField = nullptr; 7740 // It's compatible if the expression matches any of the fields. 7741 for (auto *it : UD->fields()) { 7742 if (it->getType()->isPointerType()) { 7743 // If the transparent union contains a pointer type, we allow: 7744 // 1) void pointer 7745 // 2) null pointer constant 7746 if (RHSType->isPointerType()) 7747 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 7748 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 7749 InitField = it; 7750 break; 7751 } 7752 7753 if (RHS.get()->isNullPointerConstant(Context, 7754 Expr::NPC_ValueDependentIsNull)) { 7755 RHS = ImpCastExprToType(RHS.get(), it->getType(), 7756 CK_NullToPointer); 7757 InitField = it; 7758 break; 7759 } 7760 } 7761 7762 CastKind Kind = CK_Invalid; 7763 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 7764 == Compatible) { 7765 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 7766 InitField = it; 7767 break; 7768 } 7769 } 7770 7771 if (!InitField) 7772 return Incompatible; 7773 7774 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 7775 return Compatible; 7776 } 7777 7778 Sema::AssignConvertType 7779 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 7780 bool Diagnose, 7781 bool DiagnoseCFAudited, 7782 bool ConvertRHS) { 7783 // We need to be able to tell the caller whether we diagnosed a problem, if 7784 // they ask us to issue diagnostics. 7785 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 7786 7787 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 7788 // we can't avoid *all* modifications at the moment, so we need some somewhere 7789 // to put the updated value. 7790 ExprResult LocalRHS = CallerRHS; 7791 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 7792 7793 if (getLangOpts().CPlusPlus) { 7794 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 7795 // C++ 5.17p3: If the left operand is not of class type, the 7796 // expression is implicitly converted (C++ 4) to the 7797 // cv-unqualified type of the left operand. 7798 QualType RHSType = RHS.get()->getType(); 7799 if (Diagnose) { 7800 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7801 AA_Assigning); 7802 } else { 7803 ImplicitConversionSequence ICS = 7804 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7805 /*SuppressUserConversions=*/false, 7806 /*AllowExplicit=*/false, 7807 /*InOverloadResolution=*/false, 7808 /*CStyle=*/false, 7809 /*AllowObjCWritebackConversion=*/false); 7810 if (ICS.isFailure()) 7811 return Incompatible; 7812 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7813 ICS, AA_Assigning); 7814 } 7815 if (RHS.isInvalid()) 7816 return Incompatible; 7817 Sema::AssignConvertType result = Compatible; 7818 if (getLangOpts().ObjCAutoRefCount && 7819 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 7820 result = IncompatibleObjCWeakRef; 7821 return result; 7822 } 7823 7824 // FIXME: Currently, we fall through and treat C++ classes like C 7825 // structures. 7826 // FIXME: We also fall through for atomics; not sure what should 7827 // happen there, though. 7828 } else if (RHS.get()->getType() == Context.OverloadTy) { 7829 // As a set of extensions to C, we support overloading on functions. These 7830 // functions need to be resolved here. 7831 DeclAccessPair DAP; 7832 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 7833 RHS.get(), LHSType, /*Complain=*/false, DAP)) 7834 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 7835 else 7836 return Incompatible; 7837 } 7838 7839 // C99 6.5.16.1p1: the left operand is a pointer and the right is 7840 // a null pointer constant. 7841 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 7842 LHSType->isBlockPointerType()) && 7843 RHS.get()->isNullPointerConstant(Context, 7844 Expr::NPC_ValueDependentIsNull)) { 7845 if (Diagnose || ConvertRHS) { 7846 CastKind Kind; 7847 CXXCastPath Path; 7848 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 7849 /*IgnoreBaseAccess=*/false, Diagnose); 7850 if (ConvertRHS) 7851 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 7852 } 7853 return Compatible; 7854 } 7855 7856 // This check seems unnatural, however it is necessary to ensure the proper 7857 // conversion of functions/arrays. If the conversion were done for all 7858 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 7859 // expressions that suppress this implicit conversion (&, sizeof). 7860 // 7861 // Suppress this for references: C++ 8.5.3p5. 7862 if (!LHSType->isReferenceType()) { 7863 // FIXME: We potentially allocate here even if ConvertRHS is false. 7864 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 7865 if (RHS.isInvalid()) 7866 return Incompatible; 7867 } 7868 7869 Expr *PRE = RHS.get()->IgnoreParenCasts(); 7870 if (Diagnose && isa<ObjCProtocolExpr>(PRE)) { 7871 ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol(); 7872 if (PDecl && !PDecl->hasDefinition()) { 7873 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName(); 7874 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl; 7875 } 7876 } 7877 7878 CastKind Kind = CK_Invalid; 7879 Sema::AssignConvertType result = 7880 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 7881 7882 // C99 6.5.16.1p2: The value of the right operand is converted to the 7883 // type of the assignment expression. 7884 // CheckAssignmentConstraints allows the left-hand side to be a reference, 7885 // so that we can use references in built-in functions even in C. 7886 // The getNonReferenceType() call makes sure that the resulting expression 7887 // does not have reference type. 7888 if (result != Incompatible && RHS.get()->getType() != LHSType) { 7889 QualType Ty = LHSType.getNonLValueExprType(Context); 7890 Expr *E = RHS.get(); 7891 7892 // Check for various Objective-C errors. If we are not reporting 7893 // diagnostics and just checking for errors, e.g., during overload 7894 // resolution, return Incompatible to indicate the failure. 7895 if (getLangOpts().ObjCAutoRefCount && 7896 CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 7897 Diagnose, DiagnoseCFAudited) != ACR_okay) { 7898 if (!Diagnose) 7899 return Incompatible; 7900 } 7901 if (getLangOpts().ObjC1 && 7902 (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType, 7903 E->getType(), E, Diagnose) || 7904 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 7905 if (!Diagnose) 7906 return Incompatible; 7907 // Replace the expression with a corrected version and continue so we 7908 // can find further errors. 7909 RHS = E; 7910 return Compatible; 7911 } 7912 7913 if (ConvertRHS) 7914 RHS = ImpCastExprToType(E, Ty, Kind); 7915 } 7916 return result; 7917 } 7918 7919 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 7920 ExprResult &RHS) { 7921 Diag(Loc, diag::err_typecheck_invalid_operands) 7922 << LHS.get()->getType() << RHS.get()->getType() 7923 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7924 return QualType(); 7925 } 7926 7927 /// Try to convert a value of non-vector type to a vector type by converting 7928 /// the type to the element type of the vector and then performing a splat. 7929 /// If the language is OpenCL, we only use conversions that promote scalar 7930 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 7931 /// for float->int. 7932 /// 7933 /// \param scalar - if non-null, actually perform the conversions 7934 /// \return true if the operation fails (but without diagnosing the failure) 7935 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 7936 QualType scalarTy, 7937 QualType vectorEltTy, 7938 QualType vectorTy) { 7939 // The conversion to apply to the scalar before splatting it, 7940 // if necessary. 7941 CastKind scalarCast = CK_Invalid; 7942 7943 if (vectorEltTy->isIntegralType(S.Context)) { 7944 if (!scalarTy->isIntegralType(S.Context)) 7945 return true; 7946 if (S.getLangOpts().OpenCL && 7947 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0) 7948 return true; 7949 scalarCast = CK_IntegralCast; 7950 } else if (vectorEltTy->isRealFloatingType()) { 7951 if (scalarTy->isRealFloatingType()) { 7952 if (S.getLangOpts().OpenCL && 7953 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) 7954 return true; 7955 scalarCast = CK_FloatingCast; 7956 } 7957 else if (scalarTy->isIntegralType(S.Context)) 7958 scalarCast = CK_IntegralToFloating; 7959 else 7960 return true; 7961 } else { 7962 return true; 7963 } 7964 7965 // Adjust scalar if desired. 7966 if (scalar) { 7967 if (scalarCast != CK_Invalid) 7968 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 7969 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 7970 } 7971 return false; 7972 } 7973 7974 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 7975 SourceLocation Loc, bool IsCompAssign, 7976 bool AllowBothBool, 7977 bool AllowBoolConversions) { 7978 if (!IsCompAssign) { 7979 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 7980 if (LHS.isInvalid()) 7981 return QualType(); 7982 } 7983 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 7984 if (RHS.isInvalid()) 7985 return QualType(); 7986 7987 // For conversion purposes, we ignore any qualifiers. 7988 // For example, "const float" and "float" are equivalent. 7989 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 7990 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 7991 7992 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 7993 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 7994 assert(LHSVecType || RHSVecType); 7995 7996 // AltiVec-style "vector bool op vector bool" combinations are allowed 7997 // for some operators but not others. 7998 if (!AllowBothBool && 7999 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8000 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8001 return InvalidOperands(Loc, LHS, RHS); 8002 8003 // If the vector types are identical, return. 8004 if (Context.hasSameType(LHSType, RHSType)) 8005 return LHSType; 8006 8007 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 8008 if (LHSVecType && RHSVecType && 8009 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8010 if (isa<ExtVectorType>(LHSVecType)) { 8011 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8012 return LHSType; 8013 } 8014 8015 if (!IsCompAssign) 8016 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8017 return RHSType; 8018 } 8019 8020 // AllowBoolConversions says that bool and non-bool AltiVec vectors 8021 // can be mixed, with the result being the non-bool type. The non-bool 8022 // operand must have integer element type. 8023 if (AllowBoolConversions && LHSVecType && RHSVecType && 8024 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 8025 (Context.getTypeSize(LHSVecType->getElementType()) == 8026 Context.getTypeSize(RHSVecType->getElementType()))) { 8027 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 8028 LHSVecType->getElementType()->isIntegerType() && 8029 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 8030 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8031 return LHSType; 8032 } 8033 if (!IsCompAssign && 8034 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8035 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 8036 RHSVecType->getElementType()->isIntegerType()) { 8037 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8038 return RHSType; 8039 } 8040 } 8041 8042 // If there's an ext-vector type and a scalar, try to convert the scalar to 8043 // the vector element type and splat. 8044 // FIXME: this should also work for regular vector types as supported in GCC. 8045 if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) { 8046 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 8047 LHSVecType->getElementType(), LHSType)) 8048 return LHSType; 8049 } 8050 if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) { 8051 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 8052 LHSType, RHSVecType->getElementType(), 8053 RHSType)) 8054 return RHSType; 8055 } 8056 8057 // FIXME: The code below also handles convertion between vectors and 8058 // non-scalars, we should break this down into fine grained specific checks 8059 // and emit proper diagnostics. 8060 QualType VecType = LHSVecType ? LHSType : RHSType; 8061 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 8062 QualType OtherType = LHSVecType ? RHSType : LHSType; 8063 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 8064 if (isLaxVectorConversion(OtherType, VecType)) { 8065 // If we're allowing lax vector conversions, only the total (data) size 8066 // needs to be the same. For non compound assignment, if one of the types is 8067 // scalar, the result is always the vector type. 8068 if (!IsCompAssign) { 8069 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 8070 return VecType; 8071 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 8072 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 8073 // type. Note that this is already done by non-compound assignments in 8074 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 8075 // <1 x T> -> T. The result is also a vector type. 8076 } else if (OtherType->isExtVectorType() || 8077 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 8078 ExprResult *RHSExpr = &RHS; 8079 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 8080 return VecType; 8081 } 8082 } 8083 8084 // Okay, the expression is invalid. 8085 8086 // If there's a non-vector, non-real operand, diagnose that. 8087 if ((!RHSVecType && !RHSType->isRealType()) || 8088 (!LHSVecType && !LHSType->isRealType())) { 8089 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 8090 << LHSType << RHSType 8091 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8092 return QualType(); 8093 } 8094 8095 // OpenCL V1.1 6.2.6.p1: 8096 // If the operands are of more than one vector type, then an error shall 8097 // occur. Implicit conversions between vector types are not permitted, per 8098 // section 6.2.1. 8099 if (getLangOpts().OpenCL && 8100 RHSVecType && isa<ExtVectorType>(RHSVecType) && 8101 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 8102 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 8103 << RHSType; 8104 return QualType(); 8105 } 8106 8107 // Otherwise, use the generic diagnostic. 8108 Diag(Loc, diag::err_typecheck_vector_not_convertable) 8109 << LHSType << RHSType 8110 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8111 return QualType(); 8112 } 8113 8114 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 8115 // expression. These are mainly cases where the null pointer is used as an 8116 // integer instead of a pointer. 8117 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 8118 SourceLocation Loc, bool IsCompare) { 8119 // The canonical way to check for a GNU null is with isNullPointerConstant, 8120 // but we use a bit of a hack here for speed; this is a relatively 8121 // hot path, and isNullPointerConstant is slow. 8122 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 8123 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 8124 8125 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 8126 8127 // Avoid analyzing cases where the result will either be invalid (and 8128 // diagnosed as such) or entirely valid and not something to warn about. 8129 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 8130 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 8131 return; 8132 8133 // Comparison operations would not make sense with a null pointer no matter 8134 // what the other expression is. 8135 if (!IsCompare) { 8136 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 8137 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 8138 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 8139 return; 8140 } 8141 8142 // The rest of the operations only make sense with a null pointer 8143 // if the other expression is a pointer. 8144 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 8145 NonNullType->canDecayToPointerType()) 8146 return; 8147 8148 S.Diag(Loc, diag::warn_null_in_comparison_operation) 8149 << LHSNull /* LHS is NULL */ << NonNullType 8150 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8151 } 8152 8153 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 8154 ExprResult &RHS, 8155 SourceLocation Loc, bool IsDiv) { 8156 // Check for division/remainder by zero. 8157 llvm::APSInt RHSValue; 8158 if (!RHS.get()->isValueDependent() && 8159 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0) 8160 S.DiagRuntimeBehavior(Loc, RHS.get(), 8161 S.PDiag(diag::warn_remainder_division_by_zero) 8162 << IsDiv << RHS.get()->getSourceRange()); 8163 } 8164 8165 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 8166 SourceLocation Loc, 8167 bool IsCompAssign, bool IsDiv) { 8168 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8169 8170 if (LHS.get()->getType()->isVectorType() || 8171 RHS.get()->getType()->isVectorType()) 8172 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8173 /*AllowBothBool*/getLangOpts().AltiVec, 8174 /*AllowBoolConversions*/false); 8175 8176 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8177 if (LHS.isInvalid() || RHS.isInvalid()) 8178 return QualType(); 8179 8180 8181 if (compType.isNull() || !compType->isArithmeticType()) 8182 return InvalidOperands(Loc, LHS, RHS); 8183 if (IsDiv) 8184 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 8185 return compType; 8186 } 8187 8188 QualType Sema::CheckRemainderOperands( 8189 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 8190 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8191 8192 if (LHS.get()->getType()->isVectorType() || 8193 RHS.get()->getType()->isVectorType()) { 8194 if (LHS.get()->getType()->hasIntegerRepresentation() && 8195 RHS.get()->getType()->hasIntegerRepresentation()) 8196 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8197 /*AllowBothBool*/getLangOpts().AltiVec, 8198 /*AllowBoolConversions*/false); 8199 return InvalidOperands(Loc, LHS, RHS); 8200 } 8201 8202 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8203 if (LHS.isInvalid() || RHS.isInvalid()) 8204 return QualType(); 8205 8206 if (compType.isNull() || !compType->isIntegerType()) 8207 return InvalidOperands(Loc, LHS, RHS); 8208 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 8209 return compType; 8210 } 8211 8212 /// \brief Diagnose invalid arithmetic on two void pointers. 8213 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 8214 Expr *LHSExpr, Expr *RHSExpr) { 8215 S.Diag(Loc, S.getLangOpts().CPlusPlus 8216 ? diag::err_typecheck_pointer_arith_void_type 8217 : diag::ext_gnu_void_ptr) 8218 << 1 /* two pointers */ << LHSExpr->getSourceRange() 8219 << RHSExpr->getSourceRange(); 8220 } 8221 8222 /// \brief Diagnose invalid arithmetic on a void pointer. 8223 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 8224 Expr *Pointer) { 8225 S.Diag(Loc, S.getLangOpts().CPlusPlus 8226 ? diag::err_typecheck_pointer_arith_void_type 8227 : diag::ext_gnu_void_ptr) 8228 << 0 /* one pointer */ << Pointer->getSourceRange(); 8229 } 8230 8231 /// \brief Diagnose invalid arithmetic on two function pointers. 8232 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 8233 Expr *LHS, Expr *RHS) { 8234 assert(LHS->getType()->isAnyPointerType()); 8235 assert(RHS->getType()->isAnyPointerType()); 8236 S.Diag(Loc, S.getLangOpts().CPlusPlus 8237 ? diag::err_typecheck_pointer_arith_function_type 8238 : diag::ext_gnu_ptr_func_arith) 8239 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 8240 // We only show the second type if it differs from the first. 8241 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 8242 RHS->getType()) 8243 << RHS->getType()->getPointeeType() 8244 << LHS->getSourceRange() << RHS->getSourceRange(); 8245 } 8246 8247 /// \brief Diagnose invalid arithmetic on a function pointer. 8248 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 8249 Expr *Pointer) { 8250 assert(Pointer->getType()->isAnyPointerType()); 8251 S.Diag(Loc, S.getLangOpts().CPlusPlus 8252 ? diag::err_typecheck_pointer_arith_function_type 8253 : diag::ext_gnu_ptr_func_arith) 8254 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 8255 << 0 /* one pointer, so only one type */ 8256 << Pointer->getSourceRange(); 8257 } 8258 8259 /// \brief Emit error if Operand is incomplete pointer type 8260 /// 8261 /// \returns True if pointer has incomplete type 8262 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 8263 Expr *Operand) { 8264 QualType ResType = Operand->getType(); 8265 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8266 ResType = ResAtomicType->getValueType(); 8267 8268 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 8269 QualType PointeeTy = ResType->getPointeeType(); 8270 return S.RequireCompleteType(Loc, PointeeTy, 8271 diag::err_typecheck_arithmetic_incomplete_type, 8272 PointeeTy, Operand->getSourceRange()); 8273 } 8274 8275 /// \brief Check the validity of an arithmetic pointer operand. 8276 /// 8277 /// If the operand has pointer type, this code will check for pointer types 8278 /// which are invalid in arithmetic operations. These will be diagnosed 8279 /// appropriately, including whether or not the use is supported as an 8280 /// extension. 8281 /// 8282 /// \returns True when the operand is valid to use (even if as an extension). 8283 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 8284 Expr *Operand) { 8285 QualType ResType = Operand->getType(); 8286 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8287 ResType = ResAtomicType->getValueType(); 8288 8289 if (!ResType->isAnyPointerType()) return true; 8290 8291 QualType PointeeTy = ResType->getPointeeType(); 8292 if (PointeeTy->isVoidType()) { 8293 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 8294 return !S.getLangOpts().CPlusPlus; 8295 } 8296 if (PointeeTy->isFunctionType()) { 8297 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 8298 return !S.getLangOpts().CPlusPlus; 8299 } 8300 8301 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 8302 8303 return true; 8304 } 8305 8306 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 8307 /// operands. 8308 /// 8309 /// This routine will diagnose any invalid arithmetic on pointer operands much 8310 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 8311 /// for emitting a single diagnostic even for operations where both LHS and RHS 8312 /// are (potentially problematic) pointers. 8313 /// 8314 /// \returns True when the operand is valid to use (even if as an extension). 8315 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 8316 Expr *LHSExpr, Expr *RHSExpr) { 8317 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 8318 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 8319 if (!isLHSPointer && !isRHSPointer) return true; 8320 8321 QualType LHSPointeeTy, RHSPointeeTy; 8322 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 8323 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 8324 8325 // if both are pointers check if operation is valid wrt address spaces 8326 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 8327 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 8328 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 8329 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 8330 S.Diag(Loc, 8331 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8332 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 8333 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 8334 return false; 8335 } 8336 } 8337 8338 // Check for arithmetic on pointers to incomplete types. 8339 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 8340 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 8341 if (isLHSVoidPtr || isRHSVoidPtr) { 8342 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 8343 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 8344 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 8345 8346 return !S.getLangOpts().CPlusPlus; 8347 } 8348 8349 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 8350 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 8351 if (isLHSFuncPtr || isRHSFuncPtr) { 8352 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 8353 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 8354 RHSExpr); 8355 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 8356 8357 return !S.getLangOpts().CPlusPlus; 8358 } 8359 8360 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 8361 return false; 8362 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 8363 return false; 8364 8365 return true; 8366 } 8367 8368 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 8369 /// literal. 8370 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 8371 Expr *LHSExpr, Expr *RHSExpr) { 8372 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 8373 Expr* IndexExpr = RHSExpr; 8374 if (!StrExpr) { 8375 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 8376 IndexExpr = LHSExpr; 8377 } 8378 8379 bool IsStringPlusInt = StrExpr && 8380 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 8381 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 8382 return; 8383 8384 llvm::APSInt index; 8385 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 8386 unsigned StrLenWithNull = StrExpr->getLength() + 1; 8387 if (index.isNonNegative() && 8388 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 8389 index.isUnsigned())) 8390 return; 8391 } 8392 8393 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8394 Self.Diag(OpLoc, diag::warn_string_plus_int) 8395 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 8396 8397 // Only print a fixit for "str" + int, not for int + "str". 8398 if (IndexExpr == RHSExpr) { 8399 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8400 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8401 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8402 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8403 << FixItHint::CreateInsertion(EndLoc, "]"); 8404 } else 8405 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8406 } 8407 8408 /// \brief Emit a warning when adding a char literal to a string. 8409 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 8410 Expr *LHSExpr, Expr *RHSExpr) { 8411 const Expr *StringRefExpr = LHSExpr; 8412 const CharacterLiteral *CharExpr = 8413 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 8414 8415 if (!CharExpr) { 8416 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 8417 StringRefExpr = RHSExpr; 8418 } 8419 8420 if (!CharExpr || !StringRefExpr) 8421 return; 8422 8423 const QualType StringType = StringRefExpr->getType(); 8424 8425 // Return if not a PointerType. 8426 if (!StringType->isAnyPointerType()) 8427 return; 8428 8429 // Return if not a CharacterType. 8430 if (!StringType->getPointeeType()->isAnyCharacterType()) 8431 return; 8432 8433 ASTContext &Ctx = Self.getASTContext(); 8434 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8435 8436 const QualType CharType = CharExpr->getType(); 8437 if (!CharType->isAnyCharacterType() && 8438 CharType->isIntegerType() && 8439 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 8440 Self.Diag(OpLoc, diag::warn_string_plus_char) 8441 << DiagRange << Ctx.CharTy; 8442 } else { 8443 Self.Diag(OpLoc, diag::warn_string_plus_char) 8444 << DiagRange << CharExpr->getType(); 8445 } 8446 8447 // Only print a fixit for str + char, not for char + str. 8448 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 8449 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8450 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8451 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8452 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8453 << FixItHint::CreateInsertion(EndLoc, "]"); 8454 } else { 8455 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8456 } 8457 } 8458 8459 /// \brief Emit error when two pointers are incompatible. 8460 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 8461 Expr *LHSExpr, Expr *RHSExpr) { 8462 assert(LHSExpr->getType()->isAnyPointerType()); 8463 assert(RHSExpr->getType()->isAnyPointerType()); 8464 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 8465 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 8466 << RHSExpr->getSourceRange(); 8467 } 8468 8469 // C99 6.5.6 8470 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 8471 SourceLocation Loc, BinaryOperatorKind Opc, 8472 QualType* CompLHSTy) { 8473 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8474 8475 if (LHS.get()->getType()->isVectorType() || 8476 RHS.get()->getType()->isVectorType()) { 8477 QualType compType = CheckVectorOperands( 8478 LHS, RHS, Loc, CompLHSTy, 8479 /*AllowBothBool*/getLangOpts().AltiVec, 8480 /*AllowBoolConversions*/getLangOpts().ZVector); 8481 if (CompLHSTy) *CompLHSTy = compType; 8482 return compType; 8483 } 8484 8485 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8486 if (LHS.isInvalid() || RHS.isInvalid()) 8487 return QualType(); 8488 8489 // Diagnose "string literal" '+' int and string '+' "char literal". 8490 if (Opc == BO_Add) { 8491 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 8492 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 8493 } 8494 8495 // handle the common case first (both operands are arithmetic). 8496 if (!compType.isNull() && compType->isArithmeticType()) { 8497 if (CompLHSTy) *CompLHSTy = compType; 8498 return compType; 8499 } 8500 8501 // Type-checking. Ultimately the pointer's going to be in PExp; 8502 // note that we bias towards the LHS being the pointer. 8503 Expr *PExp = LHS.get(), *IExp = RHS.get(); 8504 8505 bool isObjCPointer; 8506 if (PExp->getType()->isPointerType()) { 8507 isObjCPointer = false; 8508 } else if (PExp->getType()->isObjCObjectPointerType()) { 8509 isObjCPointer = true; 8510 } else { 8511 std::swap(PExp, IExp); 8512 if (PExp->getType()->isPointerType()) { 8513 isObjCPointer = false; 8514 } else if (PExp->getType()->isObjCObjectPointerType()) { 8515 isObjCPointer = true; 8516 } else { 8517 return InvalidOperands(Loc, LHS, RHS); 8518 } 8519 } 8520 assert(PExp->getType()->isAnyPointerType()); 8521 8522 if (!IExp->getType()->isIntegerType()) 8523 return InvalidOperands(Loc, LHS, RHS); 8524 8525 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 8526 return QualType(); 8527 8528 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 8529 return QualType(); 8530 8531 // Check array bounds for pointer arithemtic 8532 CheckArrayAccess(PExp, IExp); 8533 8534 if (CompLHSTy) { 8535 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 8536 if (LHSTy.isNull()) { 8537 LHSTy = LHS.get()->getType(); 8538 if (LHSTy->isPromotableIntegerType()) 8539 LHSTy = Context.getPromotedIntegerType(LHSTy); 8540 } 8541 *CompLHSTy = LHSTy; 8542 } 8543 8544 return PExp->getType(); 8545 } 8546 8547 // C99 6.5.6 8548 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 8549 SourceLocation Loc, 8550 QualType* CompLHSTy) { 8551 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8552 8553 if (LHS.get()->getType()->isVectorType() || 8554 RHS.get()->getType()->isVectorType()) { 8555 QualType compType = CheckVectorOperands( 8556 LHS, RHS, Loc, CompLHSTy, 8557 /*AllowBothBool*/getLangOpts().AltiVec, 8558 /*AllowBoolConversions*/getLangOpts().ZVector); 8559 if (CompLHSTy) *CompLHSTy = compType; 8560 return compType; 8561 } 8562 8563 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8564 if (LHS.isInvalid() || RHS.isInvalid()) 8565 return QualType(); 8566 8567 // Enforce type constraints: C99 6.5.6p3. 8568 8569 // Handle the common case first (both operands are arithmetic). 8570 if (!compType.isNull() && compType->isArithmeticType()) { 8571 if (CompLHSTy) *CompLHSTy = compType; 8572 return compType; 8573 } 8574 8575 // Either ptr - int or ptr - ptr. 8576 if (LHS.get()->getType()->isAnyPointerType()) { 8577 QualType lpointee = LHS.get()->getType()->getPointeeType(); 8578 8579 // Diagnose bad cases where we step over interface counts. 8580 if (LHS.get()->getType()->isObjCObjectPointerType() && 8581 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 8582 return QualType(); 8583 8584 // The result type of a pointer-int computation is the pointer type. 8585 if (RHS.get()->getType()->isIntegerType()) { 8586 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 8587 return QualType(); 8588 8589 // Check array bounds for pointer arithemtic 8590 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 8591 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 8592 8593 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8594 return LHS.get()->getType(); 8595 } 8596 8597 // Handle pointer-pointer subtractions. 8598 if (const PointerType *RHSPTy 8599 = RHS.get()->getType()->getAs<PointerType>()) { 8600 QualType rpointee = RHSPTy->getPointeeType(); 8601 8602 if (getLangOpts().CPlusPlus) { 8603 // Pointee types must be the same: C++ [expr.add] 8604 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 8605 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8606 } 8607 } else { 8608 // Pointee types must be compatible C99 6.5.6p3 8609 if (!Context.typesAreCompatible( 8610 Context.getCanonicalType(lpointee).getUnqualifiedType(), 8611 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 8612 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8613 return QualType(); 8614 } 8615 } 8616 8617 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 8618 LHS.get(), RHS.get())) 8619 return QualType(); 8620 8621 // The pointee type may have zero size. As an extension, a structure or 8622 // union may have zero size or an array may have zero length. In this 8623 // case subtraction does not make sense. 8624 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 8625 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 8626 if (ElementSize.isZero()) { 8627 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 8628 << rpointee.getUnqualifiedType() 8629 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8630 } 8631 } 8632 8633 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8634 return Context.getPointerDiffType(); 8635 } 8636 } 8637 8638 return InvalidOperands(Loc, LHS, RHS); 8639 } 8640 8641 static bool isScopedEnumerationType(QualType T) { 8642 if (const EnumType *ET = T->getAs<EnumType>()) 8643 return ET->getDecl()->isScoped(); 8644 return false; 8645 } 8646 8647 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 8648 SourceLocation Loc, BinaryOperatorKind Opc, 8649 QualType LHSType) { 8650 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 8651 // so skip remaining warnings as we don't want to modify values within Sema. 8652 if (S.getLangOpts().OpenCL) 8653 return; 8654 8655 llvm::APSInt Right; 8656 // Check right/shifter operand 8657 if (RHS.get()->isValueDependent() || 8658 !RHS.get()->EvaluateAsInt(Right, S.Context)) 8659 return; 8660 8661 if (Right.isNegative()) { 8662 S.DiagRuntimeBehavior(Loc, RHS.get(), 8663 S.PDiag(diag::warn_shift_negative) 8664 << RHS.get()->getSourceRange()); 8665 return; 8666 } 8667 llvm::APInt LeftBits(Right.getBitWidth(), 8668 S.Context.getTypeSize(LHS.get()->getType())); 8669 if (Right.uge(LeftBits)) { 8670 S.DiagRuntimeBehavior(Loc, RHS.get(), 8671 S.PDiag(diag::warn_shift_gt_typewidth) 8672 << RHS.get()->getSourceRange()); 8673 return; 8674 } 8675 if (Opc != BO_Shl) 8676 return; 8677 8678 // When left shifting an ICE which is signed, we can check for overflow which 8679 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 8680 // integers have defined behavior modulo one more than the maximum value 8681 // representable in the result type, so never warn for those. 8682 llvm::APSInt Left; 8683 if (LHS.get()->isValueDependent() || 8684 LHSType->hasUnsignedIntegerRepresentation() || 8685 !LHS.get()->EvaluateAsInt(Left, S.Context)) 8686 return; 8687 8688 // If LHS does not have a signed type and non-negative value 8689 // then, the behavior is undefined. Warn about it. 8690 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) { 8691 S.DiagRuntimeBehavior(Loc, LHS.get(), 8692 S.PDiag(diag::warn_shift_lhs_negative) 8693 << LHS.get()->getSourceRange()); 8694 return; 8695 } 8696 8697 llvm::APInt ResultBits = 8698 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 8699 if (LeftBits.uge(ResultBits)) 8700 return; 8701 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 8702 Result = Result.shl(Right); 8703 8704 // Print the bit representation of the signed integer as an unsigned 8705 // hexadecimal number. 8706 SmallString<40> HexResult; 8707 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 8708 8709 // If we are only missing a sign bit, this is less likely to result in actual 8710 // bugs -- if the result is cast back to an unsigned type, it will have the 8711 // expected value. Thus we place this behind a different warning that can be 8712 // turned off separately if needed. 8713 if (LeftBits == ResultBits - 1) { 8714 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 8715 << HexResult << LHSType 8716 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8717 return; 8718 } 8719 8720 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 8721 << HexResult.str() << Result.getMinSignedBits() << LHSType 8722 << Left.getBitWidth() << LHS.get()->getSourceRange() 8723 << RHS.get()->getSourceRange(); 8724 } 8725 8726 /// \brief Return the resulting type when a vector is shifted 8727 /// by a scalar or vector shift amount. 8728 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 8729 SourceLocation Loc, bool IsCompAssign) { 8730 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 8731 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 8732 !LHS.get()->getType()->isVectorType()) { 8733 S.Diag(Loc, diag::err_shift_rhs_only_vector) 8734 << RHS.get()->getType() << LHS.get()->getType() 8735 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8736 return QualType(); 8737 } 8738 8739 if (!IsCompAssign) { 8740 LHS = S.UsualUnaryConversions(LHS.get()); 8741 if (LHS.isInvalid()) return QualType(); 8742 } 8743 8744 RHS = S.UsualUnaryConversions(RHS.get()); 8745 if (RHS.isInvalid()) return QualType(); 8746 8747 QualType LHSType = LHS.get()->getType(); 8748 // Note that LHS might be a scalar because the routine calls not only in 8749 // OpenCL case. 8750 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 8751 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 8752 8753 // Note that RHS might not be a vector. 8754 QualType RHSType = RHS.get()->getType(); 8755 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 8756 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 8757 8758 // The operands need to be integers. 8759 if (!LHSEleType->isIntegerType()) { 8760 S.Diag(Loc, diag::err_typecheck_expect_int) 8761 << LHS.get()->getType() << LHS.get()->getSourceRange(); 8762 return QualType(); 8763 } 8764 8765 if (!RHSEleType->isIntegerType()) { 8766 S.Diag(Loc, diag::err_typecheck_expect_int) 8767 << RHS.get()->getType() << RHS.get()->getSourceRange(); 8768 return QualType(); 8769 } 8770 8771 if (!LHSVecTy) { 8772 assert(RHSVecTy); 8773 if (IsCompAssign) 8774 return RHSType; 8775 if (LHSEleType != RHSEleType) { 8776 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 8777 LHSEleType = RHSEleType; 8778 } 8779 QualType VecTy = 8780 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 8781 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 8782 LHSType = VecTy; 8783 } else if (RHSVecTy) { 8784 // OpenCL v1.1 s6.3.j says that for vector types, the operators 8785 // are applied component-wise. So if RHS is a vector, then ensure 8786 // that the number of elements is the same as LHS... 8787 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 8788 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 8789 << LHS.get()->getType() << RHS.get()->getType() 8790 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8791 return QualType(); 8792 } 8793 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 8794 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 8795 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 8796 if (LHSBT != RHSBT && 8797 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 8798 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 8799 << LHS.get()->getType() << RHS.get()->getType() 8800 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8801 } 8802 } 8803 } else { 8804 // ...else expand RHS to match the number of elements in LHS. 8805 QualType VecTy = 8806 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 8807 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 8808 } 8809 8810 return LHSType; 8811 } 8812 8813 // C99 6.5.7 8814 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 8815 SourceLocation Loc, BinaryOperatorKind Opc, 8816 bool IsCompAssign) { 8817 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8818 8819 // Vector shifts promote their scalar inputs to vector type. 8820 if (LHS.get()->getType()->isVectorType() || 8821 RHS.get()->getType()->isVectorType()) { 8822 if (LangOpts.ZVector) { 8823 // The shift operators for the z vector extensions work basically 8824 // like general shifts, except that neither the LHS nor the RHS is 8825 // allowed to be a "vector bool". 8826 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 8827 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 8828 return InvalidOperands(Loc, LHS, RHS); 8829 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 8830 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8831 return InvalidOperands(Loc, LHS, RHS); 8832 } 8833 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 8834 } 8835 8836 // Shifts don't perform usual arithmetic conversions, they just do integer 8837 // promotions on each operand. C99 6.5.7p3 8838 8839 // For the LHS, do usual unary conversions, but then reset them away 8840 // if this is a compound assignment. 8841 ExprResult OldLHS = LHS; 8842 LHS = UsualUnaryConversions(LHS.get()); 8843 if (LHS.isInvalid()) 8844 return QualType(); 8845 QualType LHSType = LHS.get()->getType(); 8846 if (IsCompAssign) LHS = OldLHS; 8847 8848 // The RHS is simpler. 8849 RHS = UsualUnaryConversions(RHS.get()); 8850 if (RHS.isInvalid()) 8851 return QualType(); 8852 QualType RHSType = RHS.get()->getType(); 8853 8854 // C99 6.5.7p2: Each of the operands shall have integer type. 8855 if (!LHSType->hasIntegerRepresentation() || 8856 !RHSType->hasIntegerRepresentation()) 8857 return InvalidOperands(Loc, LHS, RHS); 8858 8859 // C++0x: Don't allow scoped enums. FIXME: Use something better than 8860 // hasIntegerRepresentation() above instead of this. 8861 if (isScopedEnumerationType(LHSType) || 8862 isScopedEnumerationType(RHSType)) { 8863 return InvalidOperands(Loc, LHS, RHS); 8864 } 8865 // Sanity-check shift operands 8866 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 8867 8868 // "The type of the result is that of the promoted left operand." 8869 return LHSType; 8870 } 8871 8872 static bool IsWithinTemplateSpecialization(Decl *D) { 8873 if (DeclContext *DC = D->getDeclContext()) { 8874 if (isa<ClassTemplateSpecializationDecl>(DC)) 8875 return true; 8876 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 8877 return FD->isFunctionTemplateSpecialization(); 8878 } 8879 return false; 8880 } 8881 8882 /// If two different enums are compared, raise a warning. 8883 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 8884 Expr *RHS) { 8885 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 8886 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 8887 8888 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 8889 if (!LHSEnumType) 8890 return; 8891 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 8892 if (!RHSEnumType) 8893 return; 8894 8895 // Ignore anonymous enums. 8896 if (!LHSEnumType->getDecl()->getIdentifier()) 8897 return; 8898 if (!RHSEnumType->getDecl()->getIdentifier()) 8899 return; 8900 8901 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 8902 return; 8903 8904 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 8905 << LHSStrippedType << RHSStrippedType 8906 << LHS->getSourceRange() << RHS->getSourceRange(); 8907 } 8908 8909 /// \brief Diagnose bad pointer comparisons. 8910 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 8911 ExprResult &LHS, ExprResult &RHS, 8912 bool IsError) { 8913 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 8914 : diag::ext_typecheck_comparison_of_distinct_pointers) 8915 << LHS.get()->getType() << RHS.get()->getType() 8916 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8917 } 8918 8919 /// \brief Returns false if the pointers are converted to a composite type, 8920 /// true otherwise. 8921 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 8922 ExprResult &LHS, ExprResult &RHS) { 8923 // C++ [expr.rel]p2: 8924 // [...] Pointer conversions (4.10) and qualification 8925 // conversions (4.4) are performed on pointer operands (or on 8926 // a pointer operand and a null pointer constant) to bring 8927 // them to their composite pointer type. [...] 8928 // 8929 // C++ [expr.eq]p1 uses the same notion for (in)equality 8930 // comparisons of pointers. 8931 8932 // C++ [expr.eq]p2: 8933 // In addition, pointers to members can be compared, or a pointer to 8934 // member and a null pointer constant. Pointer to member conversions 8935 // (4.11) and qualification conversions (4.4) are performed to bring 8936 // them to a common type. If one operand is a null pointer constant, 8937 // the common type is the type of the other operand. Otherwise, the 8938 // common type is a pointer to member type similar (4.4) to the type 8939 // of one of the operands, with a cv-qualification signature (4.4) 8940 // that is the union of the cv-qualification signatures of the operand 8941 // types. 8942 8943 QualType LHSType = LHS.get()->getType(); 8944 QualType RHSType = RHS.get()->getType(); 8945 assert((LHSType->isPointerType() && RHSType->isPointerType()) || 8946 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType())); 8947 8948 bool NonStandardCompositeType = false; 8949 bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType; 8950 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr); 8951 if (T.isNull()) { 8952 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 8953 return true; 8954 } 8955 8956 if (NonStandardCompositeType) 8957 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard) 8958 << LHSType << RHSType << T << LHS.get()->getSourceRange() 8959 << RHS.get()->getSourceRange(); 8960 8961 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 8962 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 8963 return false; 8964 } 8965 8966 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 8967 ExprResult &LHS, 8968 ExprResult &RHS, 8969 bool IsError) { 8970 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 8971 : diag::ext_typecheck_comparison_of_fptr_to_void) 8972 << LHS.get()->getType() << RHS.get()->getType() 8973 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8974 } 8975 8976 static bool isObjCObjectLiteral(ExprResult &E) { 8977 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 8978 case Stmt::ObjCArrayLiteralClass: 8979 case Stmt::ObjCDictionaryLiteralClass: 8980 case Stmt::ObjCStringLiteralClass: 8981 case Stmt::ObjCBoxedExprClass: 8982 return true; 8983 default: 8984 // Note that ObjCBoolLiteral is NOT an object literal! 8985 return false; 8986 } 8987 } 8988 8989 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 8990 const ObjCObjectPointerType *Type = 8991 LHS->getType()->getAs<ObjCObjectPointerType>(); 8992 8993 // If this is not actually an Objective-C object, bail out. 8994 if (!Type) 8995 return false; 8996 8997 // Get the LHS object's interface type. 8998 QualType InterfaceType = Type->getPointeeType(); 8999 9000 // If the RHS isn't an Objective-C object, bail out. 9001 if (!RHS->getType()->isObjCObjectPointerType()) 9002 return false; 9003 9004 // Try to find the -isEqual: method. 9005 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 9006 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 9007 InterfaceType, 9008 /*instance=*/true); 9009 if (!Method) { 9010 if (Type->isObjCIdType()) { 9011 // For 'id', just check the global pool. 9012 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 9013 /*receiverId=*/true); 9014 } else { 9015 // Check protocols. 9016 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 9017 /*instance=*/true); 9018 } 9019 } 9020 9021 if (!Method) 9022 return false; 9023 9024 QualType T = Method->parameters()[0]->getType(); 9025 if (!T->isObjCObjectPointerType()) 9026 return false; 9027 9028 QualType R = Method->getReturnType(); 9029 if (!R->isScalarType()) 9030 return false; 9031 9032 return true; 9033 } 9034 9035 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 9036 FromE = FromE->IgnoreParenImpCasts(); 9037 switch (FromE->getStmtClass()) { 9038 default: 9039 break; 9040 case Stmt::ObjCStringLiteralClass: 9041 // "string literal" 9042 return LK_String; 9043 case Stmt::ObjCArrayLiteralClass: 9044 // "array literal" 9045 return LK_Array; 9046 case Stmt::ObjCDictionaryLiteralClass: 9047 // "dictionary literal" 9048 return LK_Dictionary; 9049 case Stmt::BlockExprClass: 9050 return LK_Block; 9051 case Stmt::ObjCBoxedExprClass: { 9052 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 9053 switch (Inner->getStmtClass()) { 9054 case Stmt::IntegerLiteralClass: 9055 case Stmt::FloatingLiteralClass: 9056 case Stmt::CharacterLiteralClass: 9057 case Stmt::ObjCBoolLiteralExprClass: 9058 case Stmt::CXXBoolLiteralExprClass: 9059 // "numeric literal" 9060 return LK_Numeric; 9061 case Stmt::ImplicitCastExprClass: { 9062 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 9063 // Boolean literals can be represented by implicit casts. 9064 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 9065 return LK_Numeric; 9066 break; 9067 } 9068 default: 9069 break; 9070 } 9071 return LK_Boxed; 9072 } 9073 } 9074 return LK_None; 9075 } 9076 9077 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 9078 ExprResult &LHS, ExprResult &RHS, 9079 BinaryOperator::Opcode Opc){ 9080 Expr *Literal; 9081 Expr *Other; 9082 if (isObjCObjectLiteral(LHS)) { 9083 Literal = LHS.get(); 9084 Other = RHS.get(); 9085 } else { 9086 Literal = RHS.get(); 9087 Other = LHS.get(); 9088 } 9089 9090 // Don't warn on comparisons against nil. 9091 Other = Other->IgnoreParenCasts(); 9092 if (Other->isNullPointerConstant(S.getASTContext(), 9093 Expr::NPC_ValueDependentIsNotNull)) 9094 return; 9095 9096 // This should be kept in sync with warn_objc_literal_comparison. 9097 // LK_String should always be after the other literals, since it has its own 9098 // warning flag. 9099 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 9100 assert(LiteralKind != Sema::LK_Block); 9101 if (LiteralKind == Sema::LK_None) { 9102 llvm_unreachable("Unknown Objective-C object literal kind"); 9103 } 9104 9105 if (LiteralKind == Sema::LK_String) 9106 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 9107 << Literal->getSourceRange(); 9108 else 9109 S.Diag(Loc, diag::warn_objc_literal_comparison) 9110 << LiteralKind << Literal->getSourceRange(); 9111 9112 if (BinaryOperator::isEqualityOp(Opc) && 9113 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 9114 SourceLocation Start = LHS.get()->getLocStart(); 9115 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd()); 9116 CharSourceRange OpRange = 9117 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 9118 9119 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 9120 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 9121 << FixItHint::CreateReplacement(OpRange, " isEqual:") 9122 << FixItHint::CreateInsertion(End, "]"); 9123 } 9124 } 9125 9126 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS, 9127 ExprResult &RHS, 9128 SourceLocation Loc, 9129 BinaryOperatorKind Opc) { 9130 // Check that left hand side is !something. 9131 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 9132 if (!UO || UO->getOpcode() != UO_LNot) return; 9133 9134 // Only check if the right hand side is non-bool arithmetic type. 9135 if (RHS.get()->isKnownToHaveBooleanValue()) return; 9136 9137 // Make sure that the something in !something is not bool. 9138 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 9139 if (SubExpr->isKnownToHaveBooleanValue()) return; 9140 9141 // Emit warning. 9142 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison) 9143 << Loc; 9144 9145 // First note suggest !(x < y) 9146 SourceLocation FirstOpen = SubExpr->getLocStart(); 9147 SourceLocation FirstClose = RHS.get()->getLocEnd(); 9148 FirstClose = S.getLocForEndOfToken(FirstClose); 9149 if (FirstClose.isInvalid()) 9150 FirstOpen = SourceLocation(); 9151 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 9152 << FixItHint::CreateInsertion(FirstOpen, "(") 9153 << FixItHint::CreateInsertion(FirstClose, ")"); 9154 9155 // Second note suggests (!x) < y 9156 SourceLocation SecondOpen = LHS.get()->getLocStart(); 9157 SourceLocation SecondClose = LHS.get()->getLocEnd(); 9158 SecondClose = S.getLocForEndOfToken(SecondClose); 9159 if (SecondClose.isInvalid()) 9160 SecondOpen = SourceLocation(); 9161 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 9162 << FixItHint::CreateInsertion(SecondOpen, "(") 9163 << FixItHint::CreateInsertion(SecondClose, ")"); 9164 } 9165 9166 // Get the decl for a simple expression: a reference to a variable, 9167 // an implicit C++ field reference, or an implicit ObjC ivar reference. 9168 static ValueDecl *getCompareDecl(Expr *E) { 9169 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E)) 9170 return DR->getDecl(); 9171 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 9172 if (Ivar->isFreeIvar()) 9173 return Ivar->getDecl(); 9174 } 9175 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) { 9176 if (Mem->isImplicitAccess()) 9177 return Mem->getMemberDecl(); 9178 } 9179 return nullptr; 9180 } 9181 9182 // C99 6.5.8, C++ [expr.rel] 9183 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 9184 SourceLocation Loc, BinaryOperatorKind Opc, 9185 bool IsRelational) { 9186 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 9187 9188 // Handle vector comparisons separately. 9189 if (LHS.get()->getType()->isVectorType() || 9190 RHS.get()->getType()->isVectorType()) 9191 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 9192 9193 QualType LHSType = LHS.get()->getType(); 9194 QualType RHSType = RHS.get()->getType(); 9195 9196 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 9197 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 9198 9199 checkEnumComparison(*this, Loc, LHS.get(), RHS.get()); 9200 diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, Opc); 9201 9202 if (!LHSType->hasFloatingRepresentation() && 9203 !(LHSType->isBlockPointerType() && IsRelational) && 9204 !LHS.get()->getLocStart().isMacroID() && 9205 !RHS.get()->getLocStart().isMacroID() && 9206 ActiveTemplateInstantiations.empty()) { 9207 // For non-floating point types, check for self-comparisons of the form 9208 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9209 // often indicate logic errors in the program. 9210 // 9211 // NOTE: Don't warn about comparison expressions resulting from macro 9212 // expansion. Also don't warn about comparisons which are only self 9213 // comparisons within a template specialization. The warnings should catch 9214 // obvious cases in the definition of the template anyways. The idea is to 9215 // warn when the typed comparison operator will always evaluate to the same 9216 // result. 9217 ValueDecl *DL = getCompareDecl(LHSStripped); 9218 ValueDecl *DR = getCompareDecl(RHSStripped); 9219 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) { 9220 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 9221 << 0 // self- 9222 << (Opc == BO_EQ 9223 || Opc == BO_LE 9224 || Opc == BO_GE)); 9225 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() && 9226 !DL->getType()->isReferenceType() && 9227 !DR->getType()->isReferenceType()) { 9228 // what is it always going to eval to? 9229 char always_evals_to; 9230 switch(Opc) { 9231 case BO_EQ: // e.g. array1 == array2 9232 always_evals_to = 0; // false 9233 break; 9234 case BO_NE: // e.g. array1 != array2 9235 always_evals_to = 1; // true 9236 break; 9237 default: 9238 // best we can say is 'a constant' 9239 always_evals_to = 2; // e.g. array1 <= array2 9240 break; 9241 } 9242 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 9243 << 1 // array 9244 << always_evals_to); 9245 } 9246 9247 if (isa<CastExpr>(LHSStripped)) 9248 LHSStripped = LHSStripped->IgnoreParenCasts(); 9249 if (isa<CastExpr>(RHSStripped)) 9250 RHSStripped = RHSStripped->IgnoreParenCasts(); 9251 9252 // Warn about comparisons against a string constant (unless the other 9253 // operand is null), the user probably wants strcmp. 9254 Expr *literalString = nullptr; 9255 Expr *literalStringStripped = nullptr; 9256 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 9257 !RHSStripped->isNullPointerConstant(Context, 9258 Expr::NPC_ValueDependentIsNull)) { 9259 literalString = LHS.get(); 9260 literalStringStripped = LHSStripped; 9261 } else if ((isa<StringLiteral>(RHSStripped) || 9262 isa<ObjCEncodeExpr>(RHSStripped)) && 9263 !LHSStripped->isNullPointerConstant(Context, 9264 Expr::NPC_ValueDependentIsNull)) { 9265 literalString = RHS.get(); 9266 literalStringStripped = RHSStripped; 9267 } 9268 9269 if (literalString) { 9270 DiagRuntimeBehavior(Loc, nullptr, 9271 PDiag(diag::warn_stringcompare) 9272 << isa<ObjCEncodeExpr>(literalStringStripped) 9273 << literalString->getSourceRange()); 9274 } 9275 } 9276 9277 // C99 6.5.8p3 / C99 6.5.9p4 9278 UsualArithmeticConversions(LHS, RHS); 9279 if (LHS.isInvalid() || RHS.isInvalid()) 9280 return QualType(); 9281 9282 LHSType = LHS.get()->getType(); 9283 RHSType = RHS.get()->getType(); 9284 9285 // The result of comparisons is 'bool' in C++, 'int' in C. 9286 QualType ResultTy = Context.getLogicalOperationType(); 9287 9288 if (IsRelational) { 9289 if (LHSType->isRealType() && RHSType->isRealType()) 9290 return ResultTy; 9291 } else { 9292 // Check for comparisons of floating point operands using != and ==. 9293 if (LHSType->hasFloatingRepresentation()) 9294 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9295 9296 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 9297 return ResultTy; 9298 } 9299 9300 const Expr::NullPointerConstantKind LHSNullKind = 9301 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9302 const Expr::NullPointerConstantKind RHSNullKind = 9303 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9304 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 9305 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 9306 9307 if (!IsRelational && LHSIsNull != RHSIsNull) { 9308 bool IsEquality = Opc == BO_EQ; 9309 if (RHSIsNull) 9310 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 9311 RHS.get()->getSourceRange()); 9312 else 9313 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 9314 LHS.get()->getSourceRange()); 9315 } 9316 9317 // All of the following pointer-related warnings are GCC extensions, except 9318 // when handling null pointer constants. 9319 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2 9320 QualType LCanPointeeTy = 9321 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9322 QualType RCanPointeeTy = 9323 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9324 9325 if (getLangOpts().CPlusPlus) { 9326 if (LCanPointeeTy == RCanPointeeTy) 9327 return ResultTy; 9328 if (!IsRelational && 9329 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 9330 // Valid unless comparison between non-null pointer and function pointer 9331 // This is a gcc extension compatibility comparison. 9332 // In a SFINAE context, we treat this as a hard error to maintain 9333 // conformance with the C++ standard. 9334 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 9335 && !LHSIsNull && !RHSIsNull) { 9336 diagnoseFunctionPointerToVoidComparison( 9337 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 9338 9339 if (isSFINAEContext()) 9340 return QualType(); 9341 9342 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9343 return ResultTy; 9344 } 9345 } 9346 9347 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9348 return QualType(); 9349 else 9350 return ResultTy; 9351 } 9352 // C99 6.5.9p2 and C99 6.5.8p2 9353 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 9354 RCanPointeeTy.getUnqualifiedType())) { 9355 // Valid unless a relational comparison of function pointers 9356 if (IsRelational && LCanPointeeTy->isFunctionType()) { 9357 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 9358 << LHSType << RHSType << LHS.get()->getSourceRange() 9359 << RHS.get()->getSourceRange(); 9360 } 9361 } else if (!IsRelational && 9362 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 9363 // Valid unless comparison between non-null pointer and function pointer 9364 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 9365 && !LHSIsNull && !RHSIsNull) 9366 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 9367 /*isError*/false); 9368 } else { 9369 // Invalid 9370 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 9371 } 9372 if (LCanPointeeTy != RCanPointeeTy) { 9373 // Treat NULL constant as a special case in OpenCL. 9374 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 9375 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 9376 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 9377 Diag(Loc, 9378 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 9379 << LHSType << RHSType << 0 /* comparison */ 9380 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9381 } 9382 } 9383 unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace(); 9384 unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace(); 9385 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 9386 : CK_BitCast; 9387 if (LHSIsNull && !RHSIsNull) 9388 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 9389 else 9390 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 9391 } 9392 return ResultTy; 9393 } 9394 9395 if (getLangOpts().CPlusPlus) { 9396 // Comparison of nullptr_t with itself. 9397 if (LHSType->isNullPtrType() && RHSType->isNullPtrType()) 9398 return ResultTy; 9399 9400 // Comparison of pointers with null pointer constants and equality 9401 // comparisons of member pointers to null pointer constants. 9402 if (RHSIsNull && 9403 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) || 9404 (!IsRelational && 9405 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) { 9406 RHS = ImpCastExprToType(RHS.get(), LHSType, 9407 LHSType->isMemberPointerType() 9408 ? CK_NullToMemberPointer 9409 : CK_NullToPointer); 9410 return ResultTy; 9411 } 9412 if (LHSIsNull && 9413 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) || 9414 (!IsRelational && 9415 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) { 9416 LHS = ImpCastExprToType(LHS.get(), RHSType, 9417 RHSType->isMemberPointerType() 9418 ? CK_NullToMemberPointer 9419 : CK_NullToPointer); 9420 return ResultTy; 9421 } 9422 9423 // Comparison of member pointers. 9424 if (!IsRelational && 9425 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) { 9426 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9427 return QualType(); 9428 else 9429 return ResultTy; 9430 } 9431 9432 // Handle scoped enumeration types specifically, since they don't promote 9433 // to integers. 9434 if (LHS.get()->getType()->isEnumeralType() && 9435 Context.hasSameUnqualifiedType(LHS.get()->getType(), 9436 RHS.get()->getType())) 9437 return ResultTy; 9438 } 9439 9440 // Handle block pointer types. 9441 if (!IsRelational && LHSType->isBlockPointerType() && 9442 RHSType->isBlockPointerType()) { 9443 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 9444 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 9445 9446 if (!LHSIsNull && !RHSIsNull && 9447 !Context.typesAreCompatible(lpointee, rpointee)) { 9448 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9449 << LHSType << RHSType << LHS.get()->getSourceRange() 9450 << RHS.get()->getSourceRange(); 9451 } 9452 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9453 return ResultTy; 9454 } 9455 9456 // Allow block pointers to be compared with null pointer constants. 9457 if (!IsRelational 9458 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 9459 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 9460 if (!LHSIsNull && !RHSIsNull) { 9461 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 9462 ->getPointeeType()->isVoidType()) 9463 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 9464 ->getPointeeType()->isVoidType()))) 9465 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9466 << LHSType << RHSType << LHS.get()->getSourceRange() 9467 << RHS.get()->getSourceRange(); 9468 } 9469 if (LHSIsNull && !RHSIsNull) 9470 LHS = ImpCastExprToType(LHS.get(), RHSType, 9471 RHSType->isPointerType() ? CK_BitCast 9472 : CK_AnyPointerToBlockPointerCast); 9473 else 9474 RHS = ImpCastExprToType(RHS.get(), LHSType, 9475 LHSType->isPointerType() ? CK_BitCast 9476 : CK_AnyPointerToBlockPointerCast); 9477 return ResultTy; 9478 } 9479 9480 if (LHSType->isObjCObjectPointerType() || 9481 RHSType->isObjCObjectPointerType()) { 9482 const PointerType *LPT = LHSType->getAs<PointerType>(); 9483 const PointerType *RPT = RHSType->getAs<PointerType>(); 9484 if (LPT || RPT) { 9485 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 9486 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 9487 9488 if (!LPtrToVoid && !RPtrToVoid && 9489 !Context.typesAreCompatible(LHSType, RHSType)) { 9490 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9491 /*isError*/false); 9492 } 9493 if (LHSIsNull && !RHSIsNull) { 9494 Expr *E = LHS.get(); 9495 if (getLangOpts().ObjCAutoRefCount) 9496 CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion); 9497 LHS = ImpCastExprToType(E, RHSType, 9498 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9499 } 9500 else { 9501 Expr *E = RHS.get(); 9502 if (getLangOpts().ObjCAutoRefCount) 9503 CheckObjCARCConversion(SourceRange(), LHSType, E, 9504 CCK_ImplicitConversion, /*Diagnose=*/true, 9505 /*DiagnoseCFAudited=*/false, Opc); 9506 RHS = ImpCastExprToType(E, LHSType, 9507 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9508 } 9509 return ResultTy; 9510 } 9511 if (LHSType->isObjCObjectPointerType() && 9512 RHSType->isObjCObjectPointerType()) { 9513 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 9514 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9515 /*isError*/false); 9516 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 9517 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 9518 9519 if (LHSIsNull && !RHSIsNull) 9520 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9521 else 9522 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9523 return ResultTy; 9524 } 9525 } 9526 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 9527 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 9528 unsigned DiagID = 0; 9529 bool isError = false; 9530 if (LangOpts.DebuggerSupport) { 9531 // Under a debugger, allow the comparison of pointers to integers, 9532 // since users tend to want to compare addresses. 9533 } else if ((LHSIsNull && LHSType->isIntegerType()) || 9534 (RHSIsNull && RHSType->isIntegerType())) { 9535 if (IsRelational && !getLangOpts().CPlusPlus) 9536 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 9537 } else if (IsRelational && !getLangOpts().CPlusPlus) 9538 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 9539 else if (getLangOpts().CPlusPlus) { 9540 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 9541 isError = true; 9542 } else 9543 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 9544 9545 if (DiagID) { 9546 Diag(Loc, DiagID) 9547 << LHSType << RHSType << LHS.get()->getSourceRange() 9548 << RHS.get()->getSourceRange(); 9549 if (isError) 9550 return QualType(); 9551 } 9552 9553 if (LHSType->isIntegerType()) 9554 LHS = ImpCastExprToType(LHS.get(), RHSType, 9555 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 9556 else 9557 RHS = ImpCastExprToType(RHS.get(), LHSType, 9558 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 9559 return ResultTy; 9560 } 9561 9562 // Handle block pointers. 9563 if (!IsRelational && RHSIsNull 9564 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 9565 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9566 return ResultTy; 9567 } 9568 if (!IsRelational && LHSIsNull 9569 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 9570 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9571 return ResultTy; 9572 } 9573 9574 return InvalidOperands(Loc, LHS, RHS); 9575 } 9576 9577 9578 // Return a signed type that is of identical size and number of elements. 9579 // For floating point vectors, return an integer type of identical size 9580 // and number of elements. 9581 QualType Sema::GetSignedVectorType(QualType V) { 9582 const VectorType *VTy = V->getAs<VectorType>(); 9583 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 9584 if (TypeSize == Context.getTypeSize(Context.CharTy)) 9585 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 9586 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 9587 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 9588 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 9589 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 9590 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 9591 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 9592 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 9593 "Unhandled vector element size in vector compare"); 9594 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 9595 } 9596 9597 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 9598 /// operates on extended vector types. Instead of producing an IntTy result, 9599 /// like a scalar comparison, a vector comparison produces a vector of integer 9600 /// types. 9601 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 9602 SourceLocation Loc, 9603 bool IsRelational) { 9604 // Check to make sure we're operating on vectors of the same type and width, 9605 // Allowing one side to be a scalar of element type. 9606 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 9607 /*AllowBothBool*/true, 9608 /*AllowBoolConversions*/getLangOpts().ZVector); 9609 if (vType.isNull()) 9610 return vType; 9611 9612 QualType LHSType = LHS.get()->getType(); 9613 9614 // If AltiVec, the comparison results in a numeric type, i.e. 9615 // bool for C++, int for C 9616 if (getLangOpts().AltiVec && 9617 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 9618 return Context.getLogicalOperationType(); 9619 9620 // For non-floating point types, check for self-comparisons of the form 9621 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9622 // often indicate logic errors in the program. 9623 if (!LHSType->hasFloatingRepresentation() && 9624 ActiveTemplateInstantiations.empty()) { 9625 if (DeclRefExpr* DRL 9626 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 9627 if (DeclRefExpr* DRR 9628 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 9629 if (DRL->getDecl() == DRR->getDecl()) 9630 DiagRuntimeBehavior(Loc, nullptr, 9631 PDiag(diag::warn_comparison_always) 9632 << 0 // self- 9633 << 2 // "a constant" 9634 ); 9635 } 9636 9637 // Check for comparisons of floating point operands using != and ==. 9638 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 9639 assert (RHS.get()->getType()->hasFloatingRepresentation()); 9640 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9641 } 9642 9643 // Return a signed type for the vector. 9644 return GetSignedVectorType(vType); 9645 } 9646 9647 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 9648 SourceLocation Loc) { 9649 // Ensure that either both operands are of the same vector type, or 9650 // one operand is of a vector type and the other is of its element type. 9651 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 9652 /*AllowBothBool*/true, 9653 /*AllowBoolConversions*/false); 9654 if (vType.isNull()) 9655 return InvalidOperands(Loc, LHS, RHS); 9656 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 9657 vType->hasFloatingRepresentation()) 9658 return InvalidOperands(Loc, LHS, RHS); 9659 9660 return GetSignedVectorType(LHS.get()->getType()); 9661 } 9662 9663 inline QualType Sema::CheckBitwiseOperands( 9664 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 9665 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9666 9667 if (LHS.get()->getType()->isVectorType() || 9668 RHS.get()->getType()->isVectorType()) { 9669 if (LHS.get()->getType()->hasIntegerRepresentation() && 9670 RHS.get()->getType()->hasIntegerRepresentation()) 9671 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9672 /*AllowBothBool*/true, 9673 /*AllowBoolConversions*/getLangOpts().ZVector); 9674 return InvalidOperands(Loc, LHS, RHS); 9675 } 9676 9677 ExprResult LHSResult = LHS, RHSResult = RHS; 9678 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 9679 IsCompAssign); 9680 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 9681 return QualType(); 9682 LHS = LHSResult.get(); 9683 RHS = RHSResult.get(); 9684 9685 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 9686 return compType; 9687 return InvalidOperands(Loc, LHS, RHS); 9688 } 9689 9690 // C99 6.5.[13,14] 9691 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 9692 SourceLocation Loc, 9693 BinaryOperatorKind Opc) { 9694 // Check vector operands differently. 9695 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 9696 return CheckVectorLogicalOperands(LHS, RHS, Loc); 9697 9698 // Diagnose cases where the user write a logical and/or but probably meant a 9699 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 9700 // is a constant. 9701 if (LHS.get()->getType()->isIntegerType() && 9702 !LHS.get()->getType()->isBooleanType() && 9703 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 9704 // Don't warn in macros or template instantiations. 9705 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) { 9706 // If the RHS can be constant folded, and if it constant folds to something 9707 // that isn't 0 or 1 (which indicate a potential logical operation that 9708 // happened to fold to true/false) then warn. 9709 // Parens on the RHS are ignored. 9710 llvm::APSInt Result; 9711 if (RHS.get()->EvaluateAsInt(Result, Context)) 9712 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 9713 !RHS.get()->getExprLoc().isMacroID()) || 9714 (Result != 0 && Result != 1)) { 9715 Diag(Loc, diag::warn_logical_instead_of_bitwise) 9716 << RHS.get()->getSourceRange() 9717 << (Opc == BO_LAnd ? "&&" : "||"); 9718 // Suggest replacing the logical operator with the bitwise version 9719 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 9720 << (Opc == BO_LAnd ? "&" : "|") 9721 << FixItHint::CreateReplacement(SourceRange( 9722 Loc, getLocForEndOfToken(Loc)), 9723 Opc == BO_LAnd ? "&" : "|"); 9724 if (Opc == BO_LAnd) 9725 // Suggest replacing "Foo() && kNonZero" with "Foo()" 9726 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 9727 << FixItHint::CreateRemoval( 9728 SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()), 9729 RHS.get()->getLocEnd())); 9730 } 9731 } 9732 9733 if (!Context.getLangOpts().CPlusPlus) { 9734 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 9735 // not operate on the built-in scalar and vector float types. 9736 if (Context.getLangOpts().OpenCL && 9737 Context.getLangOpts().OpenCLVersion < 120) { 9738 if (LHS.get()->getType()->isFloatingType() || 9739 RHS.get()->getType()->isFloatingType()) 9740 return InvalidOperands(Loc, LHS, RHS); 9741 } 9742 9743 LHS = UsualUnaryConversions(LHS.get()); 9744 if (LHS.isInvalid()) 9745 return QualType(); 9746 9747 RHS = UsualUnaryConversions(RHS.get()); 9748 if (RHS.isInvalid()) 9749 return QualType(); 9750 9751 if (!LHS.get()->getType()->isScalarType() || 9752 !RHS.get()->getType()->isScalarType()) 9753 return InvalidOperands(Loc, LHS, RHS); 9754 9755 return Context.IntTy; 9756 } 9757 9758 // The following is safe because we only use this method for 9759 // non-overloadable operands. 9760 9761 // C++ [expr.log.and]p1 9762 // C++ [expr.log.or]p1 9763 // The operands are both contextually converted to type bool. 9764 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 9765 if (LHSRes.isInvalid()) 9766 return InvalidOperands(Loc, LHS, RHS); 9767 LHS = LHSRes; 9768 9769 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 9770 if (RHSRes.isInvalid()) 9771 return InvalidOperands(Loc, LHS, RHS); 9772 RHS = RHSRes; 9773 9774 // C++ [expr.log.and]p2 9775 // C++ [expr.log.or]p2 9776 // The result is a bool. 9777 return Context.BoolTy; 9778 } 9779 9780 static bool IsReadonlyMessage(Expr *E, Sema &S) { 9781 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 9782 if (!ME) return false; 9783 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 9784 ObjCMessageExpr *Base = 9785 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts()); 9786 if (!Base) return false; 9787 return Base->getMethodDecl() != nullptr; 9788 } 9789 9790 /// Is the given expression (which must be 'const') a reference to a 9791 /// variable which was originally non-const, but which has become 9792 /// 'const' due to being captured within a block? 9793 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 9794 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 9795 assert(E->isLValue() && E->getType().isConstQualified()); 9796 E = E->IgnoreParens(); 9797 9798 // Must be a reference to a declaration from an enclosing scope. 9799 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 9800 if (!DRE) return NCCK_None; 9801 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 9802 9803 // The declaration must be a variable which is not declared 'const'. 9804 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 9805 if (!var) return NCCK_None; 9806 if (var->getType().isConstQualified()) return NCCK_None; 9807 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 9808 9809 // Decide whether the first capture was for a block or a lambda. 9810 DeclContext *DC = S.CurContext, *Prev = nullptr; 9811 // Decide whether the first capture was for a block or a lambda. 9812 while (DC) { 9813 // For init-capture, it is possible that the variable belongs to the 9814 // template pattern of the current context. 9815 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 9816 if (var->isInitCapture() && 9817 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 9818 break; 9819 if (DC == var->getDeclContext()) 9820 break; 9821 Prev = DC; 9822 DC = DC->getParent(); 9823 } 9824 // Unless we have an init-capture, we've gone one step too far. 9825 if (!var->isInitCapture()) 9826 DC = Prev; 9827 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 9828 } 9829 9830 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 9831 Ty = Ty.getNonReferenceType(); 9832 if (IsDereference && Ty->isPointerType()) 9833 Ty = Ty->getPointeeType(); 9834 return !Ty.isConstQualified(); 9835 } 9836 9837 /// Emit the "read-only variable not assignable" error and print notes to give 9838 /// more information about why the variable is not assignable, such as pointing 9839 /// to the declaration of a const variable, showing that a method is const, or 9840 /// that the function is returning a const reference. 9841 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 9842 SourceLocation Loc) { 9843 // Update err_typecheck_assign_const and note_typecheck_assign_const 9844 // when this enum is changed. 9845 enum { 9846 ConstFunction, 9847 ConstVariable, 9848 ConstMember, 9849 ConstMethod, 9850 ConstUnknown, // Keep as last element 9851 }; 9852 9853 SourceRange ExprRange = E->getSourceRange(); 9854 9855 // Only emit one error on the first const found. All other consts will emit 9856 // a note to the error. 9857 bool DiagnosticEmitted = false; 9858 9859 // Track if the current expression is the result of a derefence, and if the 9860 // next checked expression is the result of a derefence. 9861 bool IsDereference = false; 9862 bool NextIsDereference = false; 9863 9864 // Loop to process MemberExpr chains. 9865 while (true) { 9866 IsDereference = NextIsDereference; 9867 NextIsDereference = false; 9868 9869 E = E->IgnoreParenImpCasts(); 9870 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 9871 NextIsDereference = ME->isArrow(); 9872 const ValueDecl *VD = ME->getMemberDecl(); 9873 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 9874 // Mutable fields can be modified even if the class is const. 9875 if (Field->isMutable()) { 9876 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 9877 break; 9878 } 9879 9880 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 9881 if (!DiagnosticEmitted) { 9882 S.Diag(Loc, diag::err_typecheck_assign_const) 9883 << ExprRange << ConstMember << false /*static*/ << Field 9884 << Field->getType(); 9885 DiagnosticEmitted = true; 9886 } 9887 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9888 << ConstMember << false /*static*/ << Field << Field->getType() 9889 << Field->getSourceRange(); 9890 } 9891 E = ME->getBase(); 9892 continue; 9893 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 9894 if (VDecl->getType().isConstQualified()) { 9895 if (!DiagnosticEmitted) { 9896 S.Diag(Loc, diag::err_typecheck_assign_const) 9897 << ExprRange << ConstMember << true /*static*/ << VDecl 9898 << VDecl->getType(); 9899 DiagnosticEmitted = true; 9900 } 9901 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9902 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 9903 << VDecl->getSourceRange(); 9904 } 9905 // Static fields do not inherit constness from parents. 9906 break; 9907 } 9908 break; 9909 } // End MemberExpr 9910 break; 9911 } 9912 9913 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9914 // Function calls 9915 const FunctionDecl *FD = CE->getDirectCallee(); 9916 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 9917 if (!DiagnosticEmitted) { 9918 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 9919 << ConstFunction << FD; 9920 DiagnosticEmitted = true; 9921 } 9922 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 9923 diag::note_typecheck_assign_const) 9924 << ConstFunction << FD << FD->getReturnType() 9925 << FD->getReturnTypeSourceRange(); 9926 } 9927 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9928 // Point to variable declaration. 9929 if (const ValueDecl *VD = DRE->getDecl()) { 9930 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 9931 if (!DiagnosticEmitted) { 9932 S.Diag(Loc, diag::err_typecheck_assign_const) 9933 << ExprRange << ConstVariable << VD << VD->getType(); 9934 DiagnosticEmitted = true; 9935 } 9936 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9937 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 9938 } 9939 } 9940 } else if (isa<CXXThisExpr>(E)) { 9941 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 9942 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 9943 if (MD->isConst()) { 9944 if (!DiagnosticEmitted) { 9945 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 9946 << ConstMethod << MD; 9947 DiagnosticEmitted = true; 9948 } 9949 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 9950 << ConstMethod << MD << MD->getSourceRange(); 9951 } 9952 } 9953 } 9954 } 9955 9956 if (DiagnosticEmitted) 9957 return; 9958 9959 // Can't determine a more specific message, so display the generic error. 9960 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 9961 } 9962 9963 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 9964 /// emit an error and return true. If so, return false. 9965 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 9966 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 9967 9968 S.CheckShadowingDeclModification(E, Loc); 9969 9970 SourceLocation OrigLoc = Loc; 9971 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 9972 &Loc); 9973 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 9974 IsLV = Expr::MLV_InvalidMessageExpression; 9975 if (IsLV == Expr::MLV_Valid) 9976 return false; 9977 9978 unsigned DiagID = 0; 9979 bool NeedType = false; 9980 switch (IsLV) { // C99 6.5.16p2 9981 case Expr::MLV_ConstQualified: 9982 // Use a specialized diagnostic when we're assigning to an object 9983 // from an enclosing function or block. 9984 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 9985 if (NCCK == NCCK_Block) 9986 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 9987 else 9988 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 9989 break; 9990 } 9991 9992 // In ARC, use some specialized diagnostics for occasions where we 9993 // infer 'const'. These are always pseudo-strong variables. 9994 if (S.getLangOpts().ObjCAutoRefCount) { 9995 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 9996 if (declRef && isa<VarDecl>(declRef->getDecl())) { 9997 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 9998 9999 // Use the normal diagnostic if it's pseudo-__strong but the 10000 // user actually wrote 'const'. 10001 if (var->isARCPseudoStrong() && 10002 (!var->getTypeSourceInfo() || 10003 !var->getTypeSourceInfo()->getType().isConstQualified())) { 10004 // There are two pseudo-strong cases: 10005 // - self 10006 ObjCMethodDecl *method = S.getCurMethodDecl(); 10007 if (method && var == method->getSelfDecl()) 10008 DiagID = method->isClassMethod() 10009 ? diag::err_typecheck_arc_assign_self_class_method 10010 : diag::err_typecheck_arc_assign_self; 10011 10012 // - fast enumeration variables 10013 else 10014 DiagID = diag::err_typecheck_arr_assign_enumeration; 10015 10016 SourceRange Assign; 10017 if (Loc != OrigLoc) 10018 Assign = SourceRange(OrigLoc, OrigLoc); 10019 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10020 // We need to preserve the AST regardless, so migration tool 10021 // can do its job. 10022 return false; 10023 } 10024 } 10025 } 10026 10027 // If none of the special cases above are triggered, then this is a 10028 // simple const assignment. 10029 if (DiagID == 0) { 10030 DiagnoseConstAssignment(S, E, Loc); 10031 return true; 10032 } 10033 10034 break; 10035 case Expr::MLV_ConstAddrSpace: 10036 DiagnoseConstAssignment(S, E, Loc); 10037 return true; 10038 case Expr::MLV_ArrayType: 10039 case Expr::MLV_ArrayTemporary: 10040 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 10041 NeedType = true; 10042 break; 10043 case Expr::MLV_NotObjectType: 10044 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 10045 NeedType = true; 10046 break; 10047 case Expr::MLV_LValueCast: 10048 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 10049 break; 10050 case Expr::MLV_Valid: 10051 llvm_unreachable("did not take early return for MLV_Valid"); 10052 case Expr::MLV_InvalidExpression: 10053 case Expr::MLV_MemberFunction: 10054 case Expr::MLV_ClassTemporary: 10055 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 10056 break; 10057 case Expr::MLV_IncompleteType: 10058 case Expr::MLV_IncompleteVoidType: 10059 return S.RequireCompleteType(Loc, E->getType(), 10060 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 10061 case Expr::MLV_DuplicateVectorComponents: 10062 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 10063 break; 10064 case Expr::MLV_NoSetterProperty: 10065 llvm_unreachable("readonly properties should be processed differently"); 10066 case Expr::MLV_InvalidMessageExpression: 10067 DiagID = diag::error_readonly_message_assignment; 10068 break; 10069 case Expr::MLV_SubObjCPropertySetting: 10070 DiagID = diag::error_no_subobject_property_setting; 10071 break; 10072 } 10073 10074 SourceRange Assign; 10075 if (Loc != OrigLoc) 10076 Assign = SourceRange(OrigLoc, OrigLoc); 10077 if (NeedType) 10078 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 10079 else 10080 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10081 return true; 10082 } 10083 10084 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 10085 SourceLocation Loc, 10086 Sema &Sema) { 10087 // C / C++ fields 10088 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 10089 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 10090 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 10091 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 10092 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 10093 } 10094 10095 // Objective-C instance variables 10096 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 10097 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 10098 if (OL && OR && OL->getDecl() == OR->getDecl()) { 10099 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 10100 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 10101 if (RL && RR && RL->getDecl() == RR->getDecl()) 10102 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 10103 } 10104 } 10105 10106 // C99 6.5.16.1 10107 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 10108 SourceLocation Loc, 10109 QualType CompoundType) { 10110 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 10111 10112 // Verify that LHS is a modifiable lvalue, and emit error if not. 10113 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 10114 return QualType(); 10115 10116 QualType LHSType = LHSExpr->getType(); 10117 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 10118 CompoundType; 10119 // OpenCL v1.2 s6.1.1.1 p2: 10120 // The half data type can only be used to declare a pointer to a buffer that 10121 // contains half values 10122 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 && 10123 LHSType->isHalfType()) { 10124 Diag(Loc, diag::err_opencl_half_load_store) << 1 10125 << LHSType.getUnqualifiedType(); 10126 return QualType(); 10127 } 10128 10129 AssignConvertType ConvTy; 10130 if (CompoundType.isNull()) { 10131 Expr *RHSCheck = RHS.get(); 10132 10133 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 10134 10135 QualType LHSTy(LHSType); 10136 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 10137 if (RHS.isInvalid()) 10138 return QualType(); 10139 // Special case of NSObject attributes on c-style pointer types. 10140 if (ConvTy == IncompatiblePointer && 10141 ((Context.isObjCNSObjectType(LHSType) && 10142 RHSType->isObjCObjectPointerType()) || 10143 (Context.isObjCNSObjectType(RHSType) && 10144 LHSType->isObjCObjectPointerType()))) 10145 ConvTy = Compatible; 10146 10147 if (ConvTy == Compatible && 10148 LHSType->isObjCObjectType()) 10149 Diag(Loc, diag::err_objc_object_assignment) 10150 << LHSType; 10151 10152 // If the RHS is a unary plus or minus, check to see if they = and + are 10153 // right next to each other. If so, the user may have typo'd "x =+ 4" 10154 // instead of "x += 4". 10155 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 10156 RHSCheck = ICE->getSubExpr(); 10157 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 10158 if ((UO->getOpcode() == UO_Plus || 10159 UO->getOpcode() == UO_Minus) && 10160 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 10161 // Only if the two operators are exactly adjacent. 10162 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 10163 // And there is a space or other character before the subexpr of the 10164 // unary +/-. We don't want to warn on "x=-1". 10165 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 10166 UO->getSubExpr()->getLocStart().isFileID()) { 10167 Diag(Loc, diag::warn_not_compound_assign) 10168 << (UO->getOpcode() == UO_Plus ? "+" : "-") 10169 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 10170 } 10171 } 10172 10173 if (ConvTy == Compatible) { 10174 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 10175 // Warn about retain cycles where a block captures the LHS, but 10176 // not if the LHS is a simple variable into which the block is 10177 // being stored...unless that variable can be captured by reference! 10178 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 10179 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 10180 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 10181 checkRetainCycles(LHSExpr, RHS.get()); 10182 10183 // It is safe to assign a weak reference into a strong variable. 10184 // Although this code can still have problems: 10185 // id x = self.weakProp; 10186 // id y = self.weakProp; 10187 // we do not warn to warn spuriously when 'x' and 'y' are on separate 10188 // paths through the function. This should be revisited if 10189 // -Wrepeated-use-of-weak is made flow-sensitive. 10190 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 10191 RHS.get()->getLocStart())) 10192 getCurFunction()->markSafeWeakUse(RHS.get()); 10193 10194 } else if (getLangOpts().ObjCAutoRefCount) { 10195 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 10196 } 10197 } 10198 } else { 10199 // Compound assignment "x += y" 10200 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 10201 } 10202 10203 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 10204 RHS.get(), AA_Assigning)) 10205 return QualType(); 10206 10207 CheckForNullPointerDereference(*this, LHSExpr); 10208 10209 // C99 6.5.16p3: The type of an assignment expression is the type of the 10210 // left operand unless the left operand has qualified type, in which case 10211 // it is the unqualified version of the type of the left operand. 10212 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 10213 // is converted to the type of the assignment expression (above). 10214 // C++ 5.17p1: the type of the assignment expression is that of its left 10215 // operand. 10216 return (getLangOpts().CPlusPlus 10217 ? LHSType : LHSType.getUnqualifiedType()); 10218 } 10219 10220 // Only ignore explicit casts to void. 10221 static bool IgnoreCommaOperand(const Expr *E) { 10222 E = E->IgnoreParens(); 10223 10224 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 10225 if (CE->getCastKind() == CK_ToVoid) { 10226 return true; 10227 } 10228 } 10229 10230 return false; 10231 } 10232 10233 // Look for instances where it is likely the comma operator is confused with 10234 // another operator. There is a whitelist of acceptable expressions for the 10235 // left hand side of the comma operator, otherwise emit a warning. 10236 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 10237 // No warnings in macros 10238 if (Loc.isMacroID()) 10239 return; 10240 10241 // Don't warn in template instantiations. 10242 if (!ActiveTemplateInstantiations.empty()) 10243 return; 10244 10245 // Scope isn't fine-grained enough to whitelist the specific cases, so 10246 // instead, skip more than needed, then call back into here with the 10247 // CommaVisitor in SemaStmt.cpp. 10248 // The whitelisted locations are the initialization and increment portions 10249 // of a for loop. The additional checks are on the condition of 10250 // if statements, do/while loops, and for loops. 10251 const unsigned ForIncrementFlags = 10252 Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope; 10253 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 10254 const unsigned ScopeFlags = getCurScope()->getFlags(); 10255 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 10256 (ScopeFlags & ForInitFlags) == ForInitFlags) 10257 return; 10258 10259 // If there are multiple comma operators used together, get the RHS of the 10260 // of the comma operator as the LHS. 10261 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 10262 if (BO->getOpcode() != BO_Comma) 10263 break; 10264 LHS = BO->getRHS(); 10265 } 10266 10267 // Only allow some expressions on LHS to not warn. 10268 if (IgnoreCommaOperand(LHS)) 10269 return; 10270 10271 Diag(Loc, diag::warn_comma_operator); 10272 Diag(LHS->getLocStart(), diag::note_cast_to_void) 10273 << LHS->getSourceRange() 10274 << FixItHint::CreateInsertion(LHS->getLocStart(), 10275 LangOpts.CPlusPlus ? "static_cast<void>(" 10276 : "(void)(") 10277 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()), 10278 ")"); 10279 } 10280 10281 // C99 6.5.17 10282 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 10283 SourceLocation Loc) { 10284 LHS = S.CheckPlaceholderExpr(LHS.get()); 10285 RHS = S.CheckPlaceholderExpr(RHS.get()); 10286 if (LHS.isInvalid() || RHS.isInvalid()) 10287 return QualType(); 10288 10289 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 10290 // operands, but not unary promotions. 10291 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 10292 10293 // So we treat the LHS as a ignored value, and in C++ we allow the 10294 // containing site to determine what should be done with the RHS. 10295 LHS = S.IgnoredValueConversions(LHS.get()); 10296 if (LHS.isInvalid()) 10297 return QualType(); 10298 10299 S.DiagnoseUnusedExprResult(LHS.get()); 10300 10301 if (!S.getLangOpts().CPlusPlus) { 10302 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 10303 if (RHS.isInvalid()) 10304 return QualType(); 10305 if (!RHS.get()->getType()->isVoidType()) 10306 S.RequireCompleteType(Loc, RHS.get()->getType(), 10307 diag::err_incomplete_type); 10308 } 10309 10310 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 10311 S.DiagnoseCommaOperator(LHS.get(), Loc); 10312 10313 return RHS.get()->getType(); 10314 } 10315 10316 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 10317 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 10318 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 10319 ExprValueKind &VK, 10320 ExprObjectKind &OK, 10321 SourceLocation OpLoc, 10322 bool IsInc, bool IsPrefix) { 10323 if (Op->isTypeDependent()) 10324 return S.Context.DependentTy; 10325 10326 QualType ResType = Op->getType(); 10327 // Atomic types can be used for increment / decrement where the non-atomic 10328 // versions can, so ignore the _Atomic() specifier for the purpose of 10329 // checking. 10330 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10331 ResType = ResAtomicType->getValueType(); 10332 10333 assert(!ResType.isNull() && "no type for increment/decrement expression"); 10334 10335 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 10336 // Decrement of bool is not allowed. 10337 if (!IsInc) { 10338 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 10339 return QualType(); 10340 } 10341 // Increment of bool sets it to true, but is deprecated. 10342 S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool 10343 : diag::warn_increment_bool) 10344 << Op->getSourceRange(); 10345 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 10346 // Error on enum increments and decrements in C++ mode 10347 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 10348 return QualType(); 10349 } else if (ResType->isRealType()) { 10350 // OK! 10351 } else if (ResType->isPointerType()) { 10352 // C99 6.5.2.4p2, 6.5.6p2 10353 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 10354 return QualType(); 10355 } else if (ResType->isObjCObjectPointerType()) { 10356 // On modern runtimes, ObjC pointer arithmetic is forbidden. 10357 // Otherwise, we just need a complete type. 10358 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 10359 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 10360 return QualType(); 10361 } else if (ResType->isAnyComplexType()) { 10362 // C99 does not support ++/-- on complex types, we allow as an extension. 10363 S.Diag(OpLoc, diag::ext_integer_increment_complex) 10364 << ResType << Op->getSourceRange(); 10365 } else if (ResType->isPlaceholderType()) { 10366 ExprResult PR = S.CheckPlaceholderExpr(Op); 10367 if (PR.isInvalid()) return QualType(); 10368 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 10369 IsInc, IsPrefix); 10370 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 10371 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 10372 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 10373 (ResType->getAs<VectorType>()->getVectorKind() != 10374 VectorType::AltiVecBool)) { 10375 // The z vector extensions allow ++ and -- for non-bool vectors. 10376 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 10377 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 10378 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 10379 } else { 10380 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 10381 << ResType << int(IsInc) << Op->getSourceRange(); 10382 return QualType(); 10383 } 10384 // At this point, we know we have a real, complex or pointer type. 10385 // Now make sure the operand is a modifiable lvalue. 10386 if (CheckForModifiableLvalue(Op, OpLoc, S)) 10387 return QualType(); 10388 // In C++, a prefix increment is the same type as the operand. Otherwise 10389 // (in C or with postfix), the increment is the unqualified type of the 10390 // operand. 10391 if (IsPrefix && S.getLangOpts().CPlusPlus) { 10392 VK = VK_LValue; 10393 OK = Op->getObjectKind(); 10394 return ResType; 10395 } else { 10396 VK = VK_RValue; 10397 return ResType.getUnqualifiedType(); 10398 } 10399 } 10400 10401 10402 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 10403 /// This routine allows us to typecheck complex/recursive expressions 10404 /// where the declaration is needed for type checking. We only need to 10405 /// handle cases when the expression references a function designator 10406 /// or is an lvalue. Here are some examples: 10407 /// - &(x) => x 10408 /// - &*****f => f for f a function designator. 10409 /// - &s.xx => s 10410 /// - &s.zz[1].yy -> s, if zz is an array 10411 /// - *(x + 1) -> x, if x is an array 10412 /// - &"123"[2] -> 0 10413 /// - & __real__ x -> x 10414 static ValueDecl *getPrimaryDecl(Expr *E) { 10415 switch (E->getStmtClass()) { 10416 case Stmt::DeclRefExprClass: 10417 return cast<DeclRefExpr>(E)->getDecl(); 10418 case Stmt::MemberExprClass: 10419 // If this is an arrow operator, the address is an offset from 10420 // the base's value, so the object the base refers to is 10421 // irrelevant. 10422 if (cast<MemberExpr>(E)->isArrow()) 10423 return nullptr; 10424 // Otherwise, the expression refers to a part of the base 10425 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 10426 case Stmt::ArraySubscriptExprClass: { 10427 // FIXME: This code shouldn't be necessary! We should catch the implicit 10428 // promotion of register arrays earlier. 10429 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 10430 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 10431 if (ICE->getSubExpr()->getType()->isArrayType()) 10432 return getPrimaryDecl(ICE->getSubExpr()); 10433 } 10434 return nullptr; 10435 } 10436 case Stmt::UnaryOperatorClass: { 10437 UnaryOperator *UO = cast<UnaryOperator>(E); 10438 10439 switch(UO->getOpcode()) { 10440 case UO_Real: 10441 case UO_Imag: 10442 case UO_Extension: 10443 return getPrimaryDecl(UO->getSubExpr()); 10444 default: 10445 return nullptr; 10446 } 10447 } 10448 case Stmt::ParenExprClass: 10449 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 10450 case Stmt::ImplicitCastExprClass: 10451 // If the result of an implicit cast is an l-value, we care about 10452 // the sub-expression; otherwise, the result here doesn't matter. 10453 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 10454 default: 10455 return nullptr; 10456 } 10457 } 10458 10459 namespace { 10460 enum { 10461 AO_Bit_Field = 0, 10462 AO_Vector_Element = 1, 10463 AO_Property_Expansion = 2, 10464 AO_Register_Variable = 3, 10465 AO_No_Error = 4 10466 }; 10467 } 10468 /// \brief Diagnose invalid operand for address of operations. 10469 /// 10470 /// \param Type The type of operand which cannot have its address taken. 10471 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 10472 Expr *E, unsigned Type) { 10473 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 10474 } 10475 10476 /// CheckAddressOfOperand - The operand of & must be either a function 10477 /// designator or an lvalue designating an object. If it is an lvalue, the 10478 /// object cannot be declared with storage class register or be a bit field. 10479 /// Note: The usual conversions are *not* applied to the operand of the & 10480 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 10481 /// In C++, the operand might be an overloaded function name, in which case 10482 /// we allow the '&' but retain the overloaded-function type. 10483 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 10484 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 10485 if (PTy->getKind() == BuiltinType::Overload) { 10486 Expr *E = OrigOp.get()->IgnoreParens(); 10487 if (!isa<OverloadExpr>(E)) { 10488 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 10489 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 10490 << OrigOp.get()->getSourceRange(); 10491 return QualType(); 10492 } 10493 10494 OverloadExpr *Ovl = cast<OverloadExpr>(E); 10495 if (isa<UnresolvedMemberExpr>(Ovl)) 10496 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 10497 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10498 << OrigOp.get()->getSourceRange(); 10499 return QualType(); 10500 } 10501 10502 return Context.OverloadTy; 10503 } 10504 10505 if (PTy->getKind() == BuiltinType::UnknownAny) 10506 return Context.UnknownAnyTy; 10507 10508 if (PTy->getKind() == BuiltinType::BoundMember) { 10509 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10510 << OrigOp.get()->getSourceRange(); 10511 return QualType(); 10512 } 10513 10514 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 10515 if (OrigOp.isInvalid()) return QualType(); 10516 } 10517 10518 if (OrigOp.get()->isTypeDependent()) 10519 return Context.DependentTy; 10520 10521 assert(!OrigOp.get()->getType()->isPlaceholderType()); 10522 10523 // Make sure to ignore parentheses in subsequent checks 10524 Expr *op = OrigOp.get()->IgnoreParens(); 10525 10526 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 10527 if (LangOpts.OpenCL && op->getType()->isFunctionType()) { 10528 Diag(op->getExprLoc(), diag::err_opencl_taking_function_address); 10529 return QualType(); 10530 } 10531 10532 if (getLangOpts().C99) { 10533 // Implement C99-only parts of addressof rules. 10534 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 10535 if (uOp->getOpcode() == UO_Deref) 10536 // Per C99 6.5.3.2, the address of a deref always returns a valid result 10537 // (assuming the deref expression is valid). 10538 return uOp->getSubExpr()->getType(); 10539 } 10540 // Technically, there should be a check for array subscript 10541 // expressions here, but the result of one is always an lvalue anyway. 10542 } 10543 ValueDecl *dcl = getPrimaryDecl(op); 10544 10545 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 10546 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 10547 op->getLocStart())) 10548 return QualType(); 10549 10550 Expr::LValueClassification lval = op->ClassifyLValue(Context); 10551 unsigned AddressOfError = AO_No_Error; 10552 10553 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 10554 bool sfinae = (bool)isSFINAEContext(); 10555 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 10556 : diag::ext_typecheck_addrof_temporary) 10557 << op->getType() << op->getSourceRange(); 10558 if (sfinae) 10559 return QualType(); 10560 // Materialize the temporary as an lvalue so that we can take its address. 10561 OrigOp = op = 10562 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 10563 } else if (isa<ObjCSelectorExpr>(op)) { 10564 return Context.getPointerType(op->getType()); 10565 } else if (lval == Expr::LV_MemberFunction) { 10566 // If it's an instance method, make a member pointer. 10567 // The expression must have exactly the form &A::foo. 10568 10569 // If the underlying expression isn't a decl ref, give up. 10570 if (!isa<DeclRefExpr>(op)) { 10571 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10572 << OrigOp.get()->getSourceRange(); 10573 return QualType(); 10574 } 10575 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 10576 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 10577 10578 // The id-expression was parenthesized. 10579 if (OrigOp.get() != DRE) { 10580 Diag(OpLoc, diag::err_parens_pointer_member_function) 10581 << OrigOp.get()->getSourceRange(); 10582 10583 // The method was named without a qualifier. 10584 } else if (!DRE->getQualifier()) { 10585 if (MD->getParent()->getName().empty()) 10586 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 10587 << op->getSourceRange(); 10588 else { 10589 SmallString<32> Str; 10590 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 10591 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 10592 << op->getSourceRange() 10593 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 10594 } 10595 } 10596 10597 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 10598 if (isa<CXXDestructorDecl>(MD)) 10599 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 10600 10601 QualType MPTy = Context.getMemberPointerType( 10602 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 10603 // Under the MS ABI, lock down the inheritance model now. 10604 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 10605 (void)isCompleteType(OpLoc, MPTy); 10606 return MPTy; 10607 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 10608 // C99 6.5.3.2p1 10609 // The operand must be either an l-value or a function designator 10610 if (!op->getType()->isFunctionType()) { 10611 // Use a special diagnostic for loads from property references. 10612 if (isa<PseudoObjectExpr>(op)) { 10613 AddressOfError = AO_Property_Expansion; 10614 } else { 10615 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 10616 << op->getType() << op->getSourceRange(); 10617 return QualType(); 10618 } 10619 } 10620 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 10621 // The operand cannot be a bit-field 10622 AddressOfError = AO_Bit_Field; 10623 } else if (op->getObjectKind() == OK_VectorComponent) { 10624 // The operand cannot be an element of a vector 10625 AddressOfError = AO_Vector_Element; 10626 } else if (dcl) { // C99 6.5.3.2p1 10627 // We have an lvalue with a decl. Make sure the decl is not declared 10628 // with the register storage-class specifier. 10629 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 10630 // in C++ it is not error to take address of a register 10631 // variable (c++03 7.1.1P3) 10632 if (vd->getStorageClass() == SC_Register && 10633 !getLangOpts().CPlusPlus) { 10634 AddressOfError = AO_Register_Variable; 10635 } 10636 } else if (isa<MSPropertyDecl>(dcl)) { 10637 AddressOfError = AO_Property_Expansion; 10638 } else if (isa<FunctionTemplateDecl>(dcl)) { 10639 return Context.OverloadTy; 10640 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 10641 // Okay: we can take the address of a field. 10642 // Could be a pointer to member, though, if there is an explicit 10643 // scope qualifier for the class. 10644 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 10645 DeclContext *Ctx = dcl->getDeclContext(); 10646 if (Ctx && Ctx->isRecord()) { 10647 if (dcl->getType()->isReferenceType()) { 10648 Diag(OpLoc, 10649 diag::err_cannot_form_pointer_to_member_of_reference_type) 10650 << dcl->getDeclName() << dcl->getType(); 10651 return QualType(); 10652 } 10653 10654 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 10655 Ctx = Ctx->getParent(); 10656 10657 QualType MPTy = Context.getMemberPointerType( 10658 op->getType(), 10659 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 10660 // Under the MS ABI, lock down the inheritance model now. 10661 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 10662 (void)isCompleteType(OpLoc, MPTy); 10663 return MPTy; 10664 } 10665 } 10666 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 10667 !isa<BindingDecl>(dcl)) 10668 llvm_unreachable("Unknown/unexpected decl type"); 10669 } 10670 10671 if (AddressOfError != AO_No_Error) { 10672 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 10673 return QualType(); 10674 } 10675 10676 if (lval == Expr::LV_IncompleteVoidType) { 10677 // Taking the address of a void variable is technically illegal, but we 10678 // allow it in cases which are otherwise valid. 10679 // Example: "extern void x; void* y = &x;". 10680 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 10681 } 10682 10683 // If the operand has type "type", the result has type "pointer to type". 10684 if (op->getType()->isObjCObjectType()) 10685 return Context.getObjCObjectPointerType(op->getType()); 10686 10687 CheckAddressOfPackedMember(op); 10688 10689 return Context.getPointerType(op->getType()); 10690 } 10691 10692 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 10693 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 10694 if (!DRE) 10695 return; 10696 const Decl *D = DRE->getDecl(); 10697 if (!D) 10698 return; 10699 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 10700 if (!Param) 10701 return; 10702 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 10703 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 10704 return; 10705 if (FunctionScopeInfo *FD = S.getCurFunction()) 10706 if (!FD->ModifiedNonNullParams.count(Param)) 10707 FD->ModifiedNonNullParams.insert(Param); 10708 } 10709 10710 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 10711 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 10712 SourceLocation OpLoc) { 10713 if (Op->isTypeDependent()) 10714 return S.Context.DependentTy; 10715 10716 ExprResult ConvResult = S.UsualUnaryConversions(Op); 10717 if (ConvResult.isInvalid()) 10718 return QualType(); 10719 Op = ConvResult.get(); 10720 QualType OpTy = Op->getType(); 10721 QualType Result; 10722 10723 if (isa<CXXReinterpretCastExpr>(Op)) { 10724 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 10725 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 10726 Op->getSourceRange()); 10727 } 10728 10729 if (const PointerType *PT = OpTy->getAs<PointerType>()) 10730 { 10731 Result = PT->getPointeeType(); 10732 } 10733 else if (const ObjCObjectPointerType *OPT = 10734 OpTy->getAs<ObjCObjectPointerType>()) 10735 Result = OPT->getPointeeType(); 10736 else { 10737 ExprResult PR = S.CheckPlaceholderExpr(Op); 10738 if (PR.isInvalid()) return QualType(); 10739 if (PR.get() != Op) 10740 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 10741 } 10742 10743 if (Result.isNull()) { 10744 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 10745 << OpTy << Op->getSourceRange(); 10746 return QualType(); 10747 } 10748 10749 // Note that per both C89 and C99, indirection is always legal, even if Result 10750 // is an incomplete type or void. It would be possible to warn about 10751 // dereferencing a void pointer, but it's completely well-defined, and such a 10752 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 10753 // for pointers to 'void' but is fine for any other pointer type: 10754 // 10755 // C++ [expr.unary.op]p1: 10756 // [...] the expression to which [the unary * operator] is applied shall 10757 // be a pointer to an object type, or a pointer to a function type 10758 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 10759 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 10760 << OpTy << Op->getSourceRange(); 10761 10762 // Dereferences are usually l-values... 10763 VK = VK_LValue; 10764 10765 // ...except that certain expressions are never l-values in C. 10766 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 10767 VK = VK_RValue; 10768 10769 return Result; 10770 } 10771 10772 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 10773 BinaryOperatorKind Opc; 10774 switch (Kind) { 10775 default: llvm_unreachable("Unknown binop!"); 10776 case tok::periodstar: Opc = BO_PtrMemD; break; 10777 case tok::arrowstar: Opc = BO_PtrMemI; break; 10778 case tok::star: Opc = BO_Mul; break; 10779 case tok::slash: Opc = BO_Div; break; 10780 case tok::percent: Opc = BO_Rem; break; 10781 case tok::plus: Opc = BO_Add; break; 10782 case tok::minus: Opc = BO_Sub; break; 10783 case tok::lessless: Opc = BO_Shl; break; 10784 case tok::greatergreater: Opc = BO_Shr; break; 10785 case tok::lessequal: Opc = BO_LE; break; 10786 case tok::less: Opc = BO_LT; break; 10787 case tok::greaterequal: Opc = BO_GE; break; 10788 case tok::greater: Opc = BO_GT; break; 10789 case tok::exclaimequal: Opc = BO_NE; break; 10790 case tok::equalequal: Opc = BO_EQ; break; 10791 case tok::amp: Opc = BO_And; break; 10792 case tok::caret: Opc = BO_Xor; break; 10793 case tok::pipe: Opc = BO_Or; break; 10794 case tok::ampamp: Opc = BO_LAnd; break; 10795 case tok::pipepipe: Opc = BO_LOr; break; 10796 case tok::equal: Opc = BO_Assign; break; 10797 case tok::starequal: Opc = BO_MulAssign; break; 10798 case tok::slashequal: Opc = BO_DivAssign; break; 10799 case tok::percentequal: Opc = BO_RemAssign; break; 10800 case tok::plusequal: Opc = BO_AddAssign; break; 10801 case tok::minusequal: Opc = BO_SubAssign; break; 10802 case tok::lesslessequal: Opc = BO_ShlAssign; break; 10803 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 10804 case tok::ampequal: Opc = BO_AndAssign; break; 10805 case tok::caretequal: Opc = BO_XorAssign; break; 10806 case tok::pipeequal: Opc = BO_OrAssign; break; 10807 case tok::comma: Opc = BO_Comma; break; 10808 } 10809 return Opc; 10810 } 10811 10812 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 10813 tok::TokenKind Kind) { 10814 UnaryOperatorKind Opc; 10815 switch (Kind) { 10816 default: llvm_unreachable("Unknown unary op!"); 10817 case tok::plusplus: Opc = UO_PreInc; break; 10818 case tok::minusminus: Opc = UO_PreDec; break; 10819 case tok::amp: Opc = UO_AddrOf; break; 10820 case tok::star: Opc = UO_Deref; break; 10821 case tok::plus: Opc = UO_Plus; break; 10822 case tok::minus: Opc = UO_Minus; break; 10823 case tok::tilde: Opc = UO_Not; break; 10824 case tok::exclaim: Opc = UO_LNot; break; 10825 case tok::kw___real: Opc = UO_Real; break; 10826 case tok::kw___imag: Opc = UO_Imag; break; 10827 case tok::kw___extension__: Opc = UO_Extension; break; 10828 } 10829 return Opc; 10830 } 10831 10832 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 10833 /// This warning is only emitted for builtin assignment operations. It is also 10834 /// suppressed in the event of macro expansions. 10835 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 10836 SourceLocation OpLoc) { 10837 if (!S.ActiveTemplateInstantiations.empty()) 10838 return; 10839 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 10840 return; 10841 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 10842 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 10843 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 10844 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 10845 if (!LHSDeclRef || !RHSDeclRef || 10846 LHSDeclRef->getLocation().isMacroID() || 10847 RHSDeclRef->getLocation().isMacroID()) 10848 return; 10849 const ValueDecl *LHSDecl = 10850 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 10851 const ValueDecl *RHSDecl = 10852 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 10853 if (LHSDecl != RHSDecl) 10854 return; 10855 if (LHSDecl->getType().isVolatileQualified()) 10856 return; 10857 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 10858 if (RefTy->getPointeeType().isVolatileQualified()) 10859 return; 10860 10861 S.Diag(OpLoc, diag::warn_self_assignment) 10862 << LHSDeclRef->getType() 10863 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10864 } 10865 10866 /// Check if a bitwise-& is performed on an Objective-C pointer. This 10867 /// is usually indicative of introspection within the Objective-C pointer. 10868 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 10869 SourceLocation OpLoc) { 10870 if (!S.getLangOpts().ObjC1) 10871 return; 10872 10873 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 10874 const Expr *LHS = L.get(); 10875 const Expr *RHS = R.get(); 10876 10877 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 10878 ObjCPointerExpr = LHS; 10879 OtherExpr = RHS; 10880 } 10881 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 10882 ObjCPointerExpr = RHS; 10883 OtherExpr = LHS; 10884 } 10885 10886 // This warning is deliberately made very specific to reduce false 10887 // positives with logic that uses '&' for hashing. This logic mainly 10888 // looks for code trying to introspect into tagged pointers, which 10889 // code should generally never do. 10890 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 10891 unsigned Diag = diag::warn_objc_pointer_masking; 10892 // Determine if we are introspecting the result of performSelectorXXX. 10893 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 10894 // Special case messages to -performSelector and friends, which 10895 // can return non-pointer values boxed in a pointer value. 10896 // Some clients may wish to silence warnings in this subcase. 10897 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 10898 Selector S = ME->getSelector(); 10899 StringRef SelArg0 = S.getNameForSlot(0); 10900 if (SelArg0.startswith("performSelector")) 10901 Diag = diag::warn_objc_pointer_masking_performSelector; 10902 } 10903 10904 S.Diag(OpLoc, Diag) 10905 << ObjCPointerExpr->getSourceRange(); 10906 } 10907 } 10908 10909 static NamedDecl *getDeclFromExpr(Expr *E) { 10910 if (!E) 10911 return nullptr; 10912 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 10913 return DRE->getDecl(); 10914 if (auto *ME = dyn_cast<MemberExpr>(E)) 10915 return ME->getMemberDecl(); 10916 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 10917 return IRE->getDecl(); 10918 return nullptr; 10919 } 10920 10921 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 10922 /// operator @p Opc at location @c TokLoc. This routine only supports 10923 /// built-in operations; ActOnBinOp handles overloaded operators. 10924 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 10925 BinaryOperatorKind Opc, 10926 Expr *LHSExpr, Expr *RHSExpr) { 10927 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 10928 // The syntax only allows initializer lists on the RHS of assignment, 10929 // so we don't need to worry about accepting invalid code for 10930 // non-assignment operators. 10931 // C++11 5.17p9: 10932 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 10933 // of x = {} is x = T(). 10934 InitializationKind Kind = 10935 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 10936 InitializedEntity Entity = 10937 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 10938 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 10939 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 10940 if (Init.isInvalid()) 10941 return Init; 10942 RHSExpr = Init.get(); 10943 } 10944 10945 ExprResult LHS = LHSExpr, RHS = RHSExpr; 10946 QualType ResultTy; // Result type of the binary operator. 10947 // The following two variables are used for compound assignment operators 10948 QualType CompLHSTy; // Type of LHS after promotions for computation 10949 QualType CompResultTy; // Type of computation result 10950 ExprValueKind VK = VK_RValue; 10951 ExprObjectKind OK = OK_Ordinary; 10952 10953 if (!getLangOpts().CPlusPlus) { 10954 // C cannot handle TypoExpr nodes on either side of a binop because it 10955 // doesn't handle dependent types properly, so make sure any TypoExprs have 10956 // been dealt with before checking the operands. 10957 LHS = CorrectDelayedTyposInExpr(LHSExpr); 10958 RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) { 10959 if (Opc != BO_Assign) 10960 return ExprResult(E); 10961 // Avoid correcting the RHS to the same Expr as the LHS. 10962 Decl *D = getDeclFromExpr(E); 10963 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 10964 }); 10965 if (!LHS.isUsable() || !RHS.isUsable()) 10966 return ExprError(); 10967 } 10968 10969 if (getLangOpts().OpenCL) { 10970 QualType LHSTy = LHSExpr->getType(); 10971 QualType RHSTy = RHSExpr->getType(); 10972 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 10973 // the ATOMIC_VAR_INIT macro. 10974 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 10975 SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 10976 if (BO_Assign == Opc) 10977 Diag(OpLoc, diag::err_atomic_init_constant) << SR; 10978 else 10979 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 10980 return ExprError(); 10981 } 10982 10983 // OpenCL special types - image, sampler, pipe, and blocks are to be used 10984 // only with a builtin functions and therefore should be disallowed here. 10985 if (LHSTy->isImageType() || RHSTy->isImageType() || 10986 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 10987 LHSTy->isPipeType() || RHSTy->isPipeType() || 10988 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 10989 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 10990 return ExprError(); 10991 } 10992 } 10993 10994 switch (Opc) { 10995 case BO_Assign: 10996 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 10997 if (getLangOpts().CPlusPlus && 10998 LHS.get()->getObjectKind() != OK_ObjCProperty) { 10999 VK = LHS.get()->getValueKind(); 11000 OK = LHS.get()->getObjectKind(); 11001 } 11002 if (!ResultTy.isNull()) { 11003 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 11004 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 11005 } 11006 RecordModifiableNonNullParam(*this, LHS.get()); 11007 break; 11008 case BO_PtrMemD: 11009 case BO_PtrMemI: 11010 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 11011 Opc == BO_PtrMemI); 11012 break; 11013 case BO_Mul: 11014 case BO_Div: 11015 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 11016 Opc == BO_Div); 11017 break; 11018 case BO_Rem: 11019 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 11020 break; 11021 case BO_Add: 11022 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 11023 break; 11024 case BO_Sub: 11025 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 11026 break; 11027 case BO_Shl: 11028 case BO_Shr: 11029 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 11030 break; 11031 case BO_LE: 11032 case BO_LT: 11033 case BO_GE: 11034 case BO_GT: 11035 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 11036 break; 11037 case BO_EQ: 11038 case BO_NE: 11039 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 11040 break; 11041 case BO_And: 11042 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 11043 case BO_Xor: 11044 case BO_Or: 11045 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc); 11046 break; 11047 case BO_LAnd: 11048 case BO_LOr: 11049 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 11050 break; 11051 case BO_MulAssign: 11052 case BO_DivAssign: 11053 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 11054 Opc == BO_DivAssign); 11055 CompLHSTy = CompResultTy; 11056 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11057 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11058 break; 11059 case BO_RemAssign: 11060 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 11061 CompLHSTy = CompResultTy; 11062 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11063 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11064 break; 11065 case BO_AddAssign: 11066 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 11067 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11068 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11069 break; 11070 case BO_SubAssign: 11071 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 11072 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11073 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11074 break; 11075 case BO_ShlAssign: 11076 case BO_ShrAssign: 11077 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 11078 CompLHSTy = CompResultTy; 11079 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11080 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11081 break; 11082 case BO_AndAssign: 11083 case BO_OrAssign: // fallthrough 11084 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 11085 case BO_XorAssign: 11086 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true); 11087 CompLHSTy = CompResultTy; 11088 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11089 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11090 break; 11091 case BO_Comma: 11092 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 11093 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 11094 VK = RHS.get()->getValueKind(); 11095 OK = RHS.get()->getObjectKind(); 11096 } 11097 break; 11098 } 11099 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 11100 return ExprError(); 11101 11102 // Check for array bounds violations for both sides of the BinaryOperator 11103 CheckArrayAccess(LHS.get()); 11104 CheckArrayAccess(RHS.get()); 11105 11106 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 11107 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 11108 &Context.Idents.get("object_setClass"), 11109 SourceLocation(), LookupOrdinaryName); 11110 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 11111 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd()); 11112 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 11113 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 11114 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 11115 FixItHint::CreateInsertion(RHSLocEnd, ")"); 11116 } 11117 else 11118 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 11119 } 11120 else if (const ObjCIvarRefExpr *OIRE = 11121 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 11122 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 11123 11124 if (CompResultTy.isNull()) 11125 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 11126 OK, OpLoc, FPFeatures.fp_contract); 11127 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 11128 OK_ObjCProperty) { 11129 VK = VK_LValue; 11130 OK = LHS.get()->getObjectKind(); 11131 } 11132 return new (Context) CompoundAssignOperator( 11133 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 11134 OpLoc, FPFeatures.fp_contract); 11135 } 11136 11137 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 11138 /// operators are mixed in a way that suggests that the programmer forgot that 11139 /// comparison operators have higher precedence. The most typical example of 11140 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 11141 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 11142 SourceLocation OpLoc, Expr *LHSExpr, 11143 Expr *RHSExpr) { 11144 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 11145 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 11146 11147 // Check that one of the sides is a comparison operator and the other isn't. 11148 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 11149 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 11150 if (isLeftComp == isRightComp) 11151 return; 11152 11153 // Bitwise operations are sometimes used as eager logical ops. 11154 // Don't diagnose this. 11155 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 11156 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 11157 if (isLeftBitwise || isRightBitwise) 11158 return; 11159 11160 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 11161 OpLoc) 11162 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 11163 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 11164 SourceRange ParensRange = isLeftComp ? 11165 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 11166 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd()); 11167 11168 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 11169 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 11170 SuggestParentheses(Self, OpLoc, 11171 Self.PDiag(diag::note_precedence_silence) << OpStr, 11172 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 11173 SuggestParentheses(Self, OpLoc, 11174 Self.PDiag(diag::note_precedence_bitwise_first) 11175 << BinaryOperator::getOpcodeStr(Opc), 11176 ParensRange); 11177 } 11178 11179 /// \brief It accepts a '&&' expr that is inside a '||' one. 11180 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 11181 /// in parentheses. 11182 static void 11183 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 11184 BinaryOperator *Bop) { 11185 assert(Bop->getOpcode() == BO_LAnd); 11186 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 11187 << Bop->getSourceRange() << OpLoc; 11188 SuggestParentheses(Self, Bop->getOperatorLoc(), 11189 Self.PDiag(diag::note_precedence_silence) 11190 << Bop->getOpcodeStr(), 11191 Bop->getSourceRange()); 11192 } 11193 11194 /// \brief Returns true if the given expression can be evaluated as a constant 11195 /// 'true'. 11196 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 11197 bool Res; 11198 return !E->isValueDependent() && 11199 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 11200 } 11201 11202 /// \brief Returns true if the given expression can be evaluated as a constant 11203 /// 'false'. 11204 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 11205 bool Res; 11206 return !E->isValueDependent() && 11207 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 11208 } 11209 11210 /// \brief Look for '&&' in the left hand of a '||' expr. 11211 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 11212 Expr *LHSExpr, Expr *RHSExpr) { 11213 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 11214 if (Bop->getOpcode() == BO_LAnd) { 11215 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 11216 if (EvaluatesAsFalse(S, RHSExpr)) 11217 return; 11218 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 11219 if (!EvaluatesAsTrue(S, Bop->getLHS())) 11220 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11221 } else if (Bop->getOpcode() == BO_LOr) { 11222 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 11223 // If it's "a || b && 1 || c" we didn't warn earlier for 11224 // "a || b && 1", but warn now. 11225 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 11226 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 11227 } 11228 } 11229 } 11230 } 11231 11232 /// \brief Look for '&&' in the right hand of a '||' expr. 11233 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 11234 Expr *LHSExpr, Expr *RHSExpr) { 11235 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 11236 if (Bop->getOpcode() == BO_LAnd) { 11237 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 11238 if (EvaluatesAsFalse(S, LHSExpr)) 11239 return; 11240 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 11241 if (!EvaluatesAsTrue(S, Bop->getRHS())) 11242 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11243 } 11244 } 11245 } 11246 11247 /// \brief Look for bitwise op in the left or right hand of a bitwise op with 11248 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 11249 /// the '&' expression in parentheses. 11250 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 11251 SourceLocation OpLoc, Expr *SubExpr) { 11252 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11253 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 11254 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 11255 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 11256 << Bop->getSourceRange() << OpLoc; 11257 SuggestParentheses(S, Bop->getOperatorLoc(), 11258 S.PDiag(diag::note_precedence_silence) 11259 << Bop->getOpcodeStr(), 11260 Bop->getSourceRange()); 11261 } 11262 } 11263 } 11264 11265 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 11266 Expr *SubExpr, StringRef Shift) { 11267 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11268 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 11269 StringRef Op = Bop->getOpcodeStr(); 11270 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 11271 << Bop->getSourceRange() << OpLoc << Shift << Op; 11272 SuggestParentheses(S, Bop->getOperatorLoc(), 11273 S.PDiag(diag::note_precedence_silence) << Op, 11274 Bop->getSourceRange()); 11275 } 11276 } 11277 } 11278 11279 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 11280 Expr *LHSExpr, Expr *RHSExpr) { 11281 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 11282 if (!OCE) 11283 return; 11284 11285 FunctionDecl *FD = OCE->getDirectCallee(); 11286 if (!FD || !FD->isOverloadedOperator()) 11287 return; 11288 11289 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 11290 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 11291 return; 11292 11293 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 11294 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 11295 << (Kind == OO_LessLess); 11296 SuggestParentheses(S, OCE->getOperatorLoc(), 11297 S.PDiag(diag::note_precedence_silence) 11298 << (Kind == OO_LessLess ? "<<" : ">>"), 11299 OCE->getSourceRange()); 11300 SuggestParentheses(S, OpLoc, 11301 S.PDiag(diag::note_evaluate_comparison_first), 11302 SourceRange(OCE->getArg(1)->getLocStart(), 11303 RHSExpr->getLocEnd())); 11304 } 11305 11306 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 11307 /// precedence. 11308 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 11309 SourceLocation OpLoc, Expr *LHSExpr, 11310 Expr *RHSExpr){ 11311 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 11312 if (BinaryOperator::isBitwiseOp(Opc)) 11313 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 11314 11315 // Diagnose "arg1 & arg2 | arg3" 11316 if ((Opc == BO_Or || Opc == BO_Xor) && 11317 !OpLoc.isMacroID()/* Don't warn in macros. */) { 11318 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 11319 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 11320 } 11321 11322 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 11323 // We don't warn for 'assert(a || b && "bad")' since this is safe. 11324 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 11325 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 11326 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 11327 } 11328 11329 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 11330 || Opc == BO_Shr) { 11331 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 11332 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 11333 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 11334 } 11335 11336 // Warn on overloaded shift operators and comparisons, such as: 11337 // cout << 5 == 4; 11338 if (BinaryOperator::isComparisonOp(Opc)) 11339 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 11340 } 11341 11342 // Binary Operators. 'Tok' is the token for the operator. 11343 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 11344 tok::TokenKind Kind, 11345 Expr *LHSExpr, Expr *RHSExpr) { 11346 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 11347 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 11348 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 11349 11350 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 11351 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 11352 11353 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 11354 } 11355 11356 /// Build an overloaded binary operator expression in the given scope. 11357 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 11358 BinaryOperatorKind Opc, 11359 Expr *LHS, Expr *RHS) { 11360 // Find all of the overloaded operators visible from this 11361 // point. We perform both an operator-name lookup from the local 11362 // scope and an argument-dependent lookup based on the types of 11363 // the arguments. 11364 UnresolvedSet<16> Functions; 11365 OverloadedOperatorKind OverOp 11366 = BinaryOperator::getOverloadedOperator(Opc); 11367 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 11368 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 11369 RHS->getType(), Functions); 11370 11371 // Build the (potentially-overloaded, potentially-dependent) 11372 // binary operation. 11373 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 11374 } 11375 11376 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 11377 BinaryOperatorKind Opc, 11378 Expr *LHSExpr, Expr *RHSExpr) { 11379 // We want to end up calling one of checkPseudoObjectAssignment 11380 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 11381 // both expressions are overloadable or either is type-dependent), 11382 // or CreateBuiltinBinOp (in any other case). We also want to get 11383 // any placeholder types out of the way. 11384 11385 // Handle pseudo-objects in the LHS. 11386 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 11387 // Assignments with a pseudo-object l-value need special analysis. 11388 if (pty->getKind() == BuiltinType::PseudoObject && 11389 BinaryOperator::isAssignmentOp(Opc)) 11390 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 11391 11392 // Don't resolve overloads if the other type is overloadable. 11393 if (pty->getKind() == BuiltinType::Overload) { 11394 // We can't actually test that if we still have a placeholder, 11395 // though. Fortunately, none of the exceptions we see in that 11396 // code below are valid when the LHS is an overload set. Note 11397 // that an overload set can be dependently-typed, but it never 11398 // instantiates to having an overloadable type. 11399 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 11400 if (resolvedRHS.isInvalid()) return ExprError(); 11401 RHSExpr = resolvedRHS.get(); 11402 11403 if (RHSExpr->isTypeDependent() || 11404 RHSExpr->getType()->isOverloadableType()) 11405 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11406 } 11407 11408 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 11409 if (LHS.isInvalid()) return ExprError(); 11410 LHSExpr = LHS.get(); 11411 } 11412 11413 // Handle pseudo-objects in the RHS. 11414 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 11415 // An overload in the RHS can potentially be resolved by the type 11416 // being assigned to. 11417 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 11418 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 11419 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11420 11421 if (LHSExpr->getType()->isOverloadableType()) 11422 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11423 11424 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 11425 } 11426 11427 // Don't resolve overloads if the other type is overloadable. 11428 if (pty->getKind() == BuiltinType::Overload && 11429 LHSExpr->getType()->isOverloadableType()) 11430 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11431 11432 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 11433 if (!resolvedRHS.isUsable()) return ExprError(); 11434 RHSExpr = resolvedRHS.get(); 11435 } 11436 11437 if (getLangOpts().CPlusPlus) { 11438 // If either expression is type-dependent, always build an 11439 // overloaded op. 11440 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 11441 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11442 11443 // Otherwise, build an overloaded op if either expression has an 11444 // overloadable type. 11445 if (LHSExpr->getType()->isOverloadableType() || 11446 RHSExpr->getType()->isOverloadableType()) 11447 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11448 } 11449 11450 // Build a built-in binary operation. 11451 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 11452 } 11453 11454 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 11455 UnaryOperatorKind Opc, 11456 Expr *InputExpr) { 11457 ExprResult Input = InputExpr; 11458 ExprValueKind VK = VK_RValue; 11459 ExprObjectKind OK = OK_Ordinary; 11460 QualType resultType; 11461 if (getLangOpts().OpenCL) { 11462 QualType Ty = InputExpr->getType(); 11463 // The only legal unary operation for atomics is '&'. 11464 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 11465 // OpenCL special types - image, sampler, pipe, and blocks are to be used 11466 // only with a builtin functions and therefore should be disallowed here. 11467 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 11468 || Ty->isBlockPointerType())) { 11469 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11470 << InputExpr->getType() 11471 << Input.get()->getSourceRange()); 11472 } 11473 } 11474 switch (Opc) { 11475 case UO_PreInc: 11476 case UO_PreDec: 11477 case UO_PostInc: 11478 case UO_PostDec: 11479 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 11480 OpLoc, 11481 Opc == UO_PreInc || 11482 Opc == UO_PostInc, 11483 Opc == UO_PreInc || 11484 Opc == UO_PreDec); 11485 break; 11486 case UO_AddrOf: 11487 resultType = CheckAddressOfOperand(Input, OpLoc); 11488 RecordModifiableNonNullParam(*this, InputExpr); 11489 break; 11490 case UO_Deref: { 11491 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 11492 if (Input.isInvalid()) return ExprError(); 11493 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 11494 break; 11495 } 11496 case UO_Plus: 11497 case UO_Minus: 11498 Input = UsualUnaryConversions(Input.get()); 11499 if (Input.isInvalid()) return ExprError(); 11500 resultType = Input.get()->getType(); 11501 if (resultType->isDependentType()) 11502 break; 11503 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 11504 break; 11505 else if (resultType->isVectorType() && 11506 // The z vector extensions don't allow + or - with bool vectors. 11507 (!Context.getLangOpts().ZVector || 11508 resultType->getAs<VectorType>()->getVectorKind() != 11509 VectorType::AltiVecBool)) 11510 break; 11511 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 11512 Opc == UO_Plus && 11513 resultType->isPointerType()) 11514 break; 11515 11516 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11517 << resultType << Input.get()->getSourceRange()); 11518 11519 case UO_Not: // bitwise complement 11520 Input = UsualUnaryConversions(Input.get()); 11521 if (Input.isInvalid()) 11522 return ExprError(); 11523 resultType = Input.get()->getType(); 11524 if (resultType->isDependentType()) 11525 break; 11526 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 11527 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 11528 // C99 does not support '~' for complex conjugation. 11529 Diag(OpLoc, diag::ext_integer_complement_complex) 11530 << resultType << Input.get()->getSourceRange(); 11531 else if (resultType->hasIntegerRepresentation()) 11532 break; 11533 else if (resultType->isExtVectorType()) { 11534 if (Context.getLangOpts().OpenCL) { 11535 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 11536 // on vector float types. 11537 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 11538 if (!T->isIntegerType()) 11539 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11540 << resultType << Input.get()->getSourceRange()); 11541 } 11542 break; 11543 } else { 11544 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11545 << resultType << Input.get()->getSourceRange()); 11546 } 11547 break; 11548 11549 case UO_LNot: // logical negation 11550 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 11551 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 11552 if (Input.isInvalid()) return ExprError(); 11553 resultType = Input.get()->getType(); 11554 11555 // Though we still have to promote half FP to float... 11556 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 11557 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 11558 resultType = Context.FloatTy; 11559 } 11560 11561 if (resultType->isDependentType()) 11562 break; 11563 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 11564 // C99 6.5.3.3p1: ok, fallthrough; 11565 if (Context.getLangOpts().CPlusPlus) { 11566 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 11567 // operand contextually converted to bool. 11568 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 11569 ScalarTypeToBooleanCastKind(resultType)); 11570 } else if (Context.getLangOpts().OpenCL && 11571 Context.getLangOpts().OpenCLVersion < 120) { 11572 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 11573 // operate on scalar float types. 11574 if (!resultType->isIntegerType()) 11575 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11576 << resultType << Input.get()->getSourceRange()); 11577 } 11578 } else if (resultType->isExtVectorType()) { 11579 if (Context.getLangOpts().OpenCL && 11580 Context.getLangOpts().OpenCLVersion < 120) { 11581 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 11582 // operate on vector float types. 11583 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 11584 if (!T->isIntegerType()) 11585 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11586 << resultType << Input.get()->getSourceRange()); 11587 } 11588 // Vector logical not returns the signed variant of the operand type. 11589 resultType = GetSignedVectorType(resultType); 11590 break; 11591 } else { 11592 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11593 << resultType << Input.get()->getSourceRange()); 11594 } 11595 11596 // LNot always has type int. C99 6.5.3.3p5. 11597 // In C++, it's bool. C++ 5.3.1p8 11598 resultType = Context.getLogicalOperationType(); 11599 break; 11600 case UO_Real: 11601 case UO_Imag: 11602 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 11603 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 11604 // complex l-values to ordinary l-values and all other values to r-values. 11605 if (Input.isInvalid()) return ExprError(); 11606 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 11607 if (Input.get()->getValueKind() != VK_RValue && 11608 Input.get()->getObjectKind() == OK_Ordinary) 11609 VK = Input.get()->getValueKind(); 11610 } else if (!getLangOpts().CPlusPlus) { 11611 // In C, a volatile scalar is read by __imag. In C++, it is not. 11612 Input = DefaultLvalueConversion(Input.get()); 11613 } 11614 break; 11615 case UO_Extension: 11616 case UO_Coawait: 11617 resultType = Input.get()->getType(); 11618 VK = Input.get()->getValueKind(); 11619 OK = Input.get()->getObjectKind(); 11620 break; 11621 } 11622 if (resultType.isNull() || Input.isInvalid()) 11623 return ExprError(); 11624 11625 // Check for array bounds violations in the operand of the UnaryOperator, 11626 // except for the '*' and '&' operators that have to be handled specially 11627 // by CheckArrayAccess (as there are special cases like &array[arraysize] 11628 // that are explicitly defined as valid by the standard). 11629 if (Opc != UO_AddrOf && Opc != UO_Deref) 11630 CheckArrayAccess(Input.get()); 11631 11632 return new (Context) 11633 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc); 11634 } 11635 11636 /// \brief Determine whether the given expression is a qualified member 11637 /// access expression, of a form that could be turned into a pointer to member 11638 /// with the address-of operator. 11639 static bool isQualifiedMemberAccess(Expr *E) { 11640 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11641 if (!DRE->getQualifier()) 11642 return false; 11643 11644 ValueDecl *VD = DRE->getDecl(); 11645 if (!VD->isCXXClassMember()) 11646 return false; 11647 11648 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 11649 return true; 11650 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 11651 return Method->isInstance(); 11652 11653 return false; 11654 } 11655 11656 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 11657 if (!ULE->getQualifier()) 11658 return false; 11659 11660 for (NamedDecl *D : ULE->decls()) { 11661 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 11662 if (Method->isInstance()) 11663 return true; 11664 } else { 11665 // Overload set does not contain methods. 11666 break; 11667 } 11668 } 11669 11670 return false; 11671 } 11672 11673 return false; 11674 } 11675 11676 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 11677 UnaryOperatorKind Opc, Expr *Input) { 11678 // First things first: handle placeholders so that the 11679 // overloaded-operator check considers the right type. 11680 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 11681 // Increment and decrement of pseudo-object references. 11682 if (pty->getKind() == BuiltinType::PseudoObject && 11683 UnaryOperator::isIncrementDecrementOp(Opc)) 11684 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 11685 11686 // extension is always a builtin operator. 11687 if (Opc == UO_Extension) 11688 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11689 11690 // & gets special logic for several kinds of placeholder. 11691 // The builtin code knows what to do. 11692 if (Opc == UO_AddrOf && 11693 (pty->getKind() == BuiltinType::Overload || 11694 pty->getKind() == BuiltinType::UnknownAny || 11695 pty->getKind() == BuiltinType::BoundMember)) 11696 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11697 11698 // Anything else needs to be handled now. 11699 ExprResult Result = CheckPlaceholderExpr(Input); 11700 if (Result.isInvalid()) return ExprError(); 11701 Input = Result.get(); 11702 } 11703 11704 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 11705 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 11706 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 11707 // Find all of the overloaded operators visible from this 11708 // point. We perform both an operator-name lookup from the local 11709 // scope and an argument-dependent lookup based on the types of 11710 // the arguments. 11711 UnresolvedSet<16> Functions; 11712 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 11713 if (S && OverOp != OO_None) 11714 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 11715 Functions); 11716 11717 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 11718 } 11719 11720 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11721 } 11722 11723 // Unary Operators. 'Tok' is the token for the operator. 11724 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 11725 tok::TokenKind Op, Expr *Input) { 11726 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 11727 } 11728 11729 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 11730 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 11731 LabelDecl *TheDecl) { 11732 TheDecl->markUsed(Context); 11733 // Create the AST node. The address of a label always has type 'void*'. 11734 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 11735 Context.getPointerType(Context.VoidTy)); 11736 } 11737 11738 /// Given the last statement in a statement-expression, check whether 11739 /// the result is a producing expression (like a call to an 11740 /// ns_returns_retained function) and, if so, rebuild it to hoist the 11741 /// release out of the full-expression. Otherwise, return null. 11742 /// Cannot fail. 11743 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 11744 // Should always be wrapped with one of these. 11745 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 11746 if (!cleanups) return nullptr; 11747 11748 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 11749 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 11750 return nullptr; 11751 11752 // Splice out the cast. This shouldn't modify any interesting 11753 // features of the statement. 11754 Expr *producer = cast->getSubExpr(); 11755 assert(producer->getType() == cast->getType()); 11756 assert(producer->getValueKind() == cast->getValueKind()); 11757 cleanups->setSubExpr(producer); 11758 return cleanups; 11759 } 11760 11761 void Sema::ActOnStartStmtExpr() { 11762 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 11763 } 11764 11765 void Sema::ActOnStmtExprError() { 11766 // Note that function is also called by TreeTransform when leaving a 11767 // StmtExpr scope without rebuilding anything. 11768 11769 DiscardCleanupsInEvaluationContext(); 11770 PopExpressionEvaluationContext(); 11771 } 11772 11773 ExprResult 11774 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 11775 SourceLocation RPLoc) { // "({..})" 11776 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 11777 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 11778 11779 if (hasAnyUnrecoverableErrorsInThisFunction()) 11780 DiscardCleanupsInEvaluationContext(); 11781 assert(!Cleanup.exprNeedsCleanups() && 11782 "cleanups within StmtExpr not correctly bound!"); 11783 PopExpressionEvaluationContext(); 11784 11785 // FIXME: there are a variety of strange constraints to enforce here, for 11786 // example, it is not possible to goto into a stmt expression apparently. 11787 // More semantic analysis is needed. 11788 11789 // If there are sub-stmts in the compound stmt, take the type of the last one 11790 // as the type of the stmtexpr. 11791 QualType Ty = Context.VoidTy; 11792 bool StmtExprMayBindToTemp = false; 11793 if (!Compound->body_empty()) { 11794 Stmt *LastStmt = Compound->body_back(); 11795 LabelStmt *LastLabelStmt = nullptr; 11796 // If LastStmt is a label, skip down through into the body. 11797 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 11798 LastLabelStmt = Label; 11799 LastStmt = Label->getSubStmt(); 11800 } 11801 11802 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 11803 // Do function/array conversion on the last expression, but not 11804 // lvalue-to-rvalue. However, initialize an unqualified type. 11805 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 11806 if (LastExpr.isInvalid()) 11807 return ExprError(); 11808 Ty = LastExpr.get()->getType().getUnqualifiedType(); 11809 11810 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 11811 // In ARC, if the final expression ends in a consume, splice 11812 // the consume out and bind it later. In the alternate case 11813 // (when dealing with a retainable type), the result 11814 // initialization will create a produce. In both cases the 11815 // result will be +1, and we'll need to balance that out with 11816 // a bind. 11817 if (Expr *rebuiltLastStmt 11818 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 11819 LastExpr = rebuiltLastStmt; 11820 } else { 11821 LastExpr = PerformCopyInitialization( 11822 InitializedEntity::InitializeResult(LPLoc, 11823 Ty, 11824 false), 11825 SourceLocation(), 11826 LastExpr); 11827 } 11828 11829 if (LastExpr.isInvalid()) 11830 return ExprError(); 11831 if (LastExpr.get() != nullptr) { 11832 if (!LastLabelStmt) 11833 Compound->setLastStmt(LastExpr.get()); 11834 else 11835 LastLabelStmt->setSubStmt(LastExpr.get()); 11836 StmtExprMayBindToTemp = true; 11837 } 11838 } 11839 } 11840 } 11841 11842 // FIXME: Check that expression type is complete/non-abstract; statement 11843 // expressions are not lvalues. 11844 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 11845 if (StmtExprMayBindToTemp) 11846 return MaybeBindToTemporary(ResStmtExpr); 11847 return ResStmtExpr; 11848 } 11849 11850 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 11851 TypeSourceInfo *TInfo, 11852 ArrayRef<OffsetOfComponent> Components, 11853 SourceLocation RParenLoc) { 11854 QualType ArgTy = TInfo->getType(); 11855 bool Dependent = ArgTy->isDependentType(); 11856 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 11857 11858 // We must have at least one component that refers to the type, and the first 11859 // one is known to be a field designator. Verify that the ArgTy represents 11860 // a struct/union/class. 11861 if (!Dependent && !ArgTy->isRecordType()) 11862 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 11863 << ArgTy << TypeRange); 11864 11865 // Type must be complete per C99 7.17p3 because a declaring a variable 11866 // with an incomplete type would be ill-formed. 11867 if (!Dependent 11868 && RequireCompleteType(BuiltinLoc, ArgTy, 11869 diag::err_offsetof_incomplete_type, TypeRange)) 11870 return ExprError(); 11871 11872 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 11873 // GCC extension, diagnose them. 11874 // FIXME: This diagnostic isn't actually visible because the location is in 11875 // a system header! 11876 if (Components.size() != 1) 11877 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 11878 << SourceRange(Components[1].LocStart, Components.back().LocEnd); 11879 11880 bool DidWarnAboutNonPOD = false; 11881 QualType CurrentType = ArgTy; 11882 SmallVector<OffsetOfNode, 4> Comps; 11883 SmallVector<Expr*, 4> Exprs; 11884 for (const OffsetOfComponent &OC : Components) { 11885 if (OC.isBrackets) { 11886 // Offset of an array sub-field. TODO: Should we allow vector elements? 11887 if (!CurrentType->isDependentType()) { 11888 const ArrayType *AT = Context.getAsArrayType(CurrentType); 11889 if(!AT) 11890 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 11891 << CurrentType); 11892 CurrentType = AT->getElementType(); 11893 } else 11894 CurrentType = Context.DependentTy; 11895 11896 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 11897 if (IdxRval.isInvalid()) 11898 return ExprError(); 11899 Expr *Idx = IdxRval.get(); 11900 11901 // The expression must be an integral expression. 11902 // FIXME: An integral constant expression? 11903 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 11904 !Idx->getType()->isIntegerType()) 11905 return ExprError(Diag(Idx->getLocStart(), 11906 diag::err_typecheck_subscript_not_integer) 11907 << Idx->getSourceRange()); 11908 11909 // Record this array index. 11910 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 11911 Exprs.push_back(Idx); 11912 continue; 11913 } 11914 11915 // Offset of a field. 11916 if (CurrentType->isDependentType()) { 11917 // We have the offset of a field, but we can't look into the dependent 11918 // type. Just record the identifier of the field. 11919 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 11920 CurrentType = Context.DependentTy; 11921 continue; 11922 } 11923 11924 // We need to have a complete type to look into. 11925 if (RequireCompleteType(OC.LocStart, CurrentType, 11926 diag::err_offsetof_incomplete_type)) 11927 return ExprError(); 11928 11929 // Look for the designated field. 11930 const RecordType *RC = CurrentType->getAs<RecordType>(); 11931 if (!RC) 11932 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 11933 << CurrentType); 11934 RecordDecl *RD = RC->getDecl(); 11935 11936 // C++ [lib.support.types]p5: 11937 // The macro offsetof accepts a restricted set of type arguments in this 11938 // International Standard. type shall be a POD structure or a POD union 11939 // (clause 9). 11940 // C++11 [support.types]p4: 11941 // If type is not a standard-layout class (Clause 9), the results are 11942 // undefined. 11943 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 11944 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 11945 unsigned DiagID = 11946 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 11947 : diag::ext_offsetof_non_pod_type; 11948 11949 if (!IsSafe && !DidWarnAboutNonPOD && 11950 DiagRuntimeBehavior(BuiltinLoc, nullptr, 11951 PDiag(DiagID) 11952 << SourceRange(Components[0].LocStart, OC.LocEnd) 11953 << CurrentType)) 11954 DidWarnAboutNonPOD = true; 11955 } 11956 11957 // Look for the field. 11958 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 11959 LookupQualifiedName(R, RD); 11960 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 11961 IndirectFieldDecl *IndirectMemberDecl = nullptr; 11962 if (!MemberDecl) { 11963 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 11964 MemberDecl = IndirectMemberDecl->getAnonField(); 11965 } 11966 11967 if (!MemberDecl) 11968 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 11969 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 11970 OC.LocEnd)); 11971 11972 // C99 7.17p3: 11973 // (If the specified member is a bit-field, the behavior is undefined.) 11974 // 11975 // We diagnose this as an error. 11976 if (MemberDecl->isBitField()) { 11977 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 11978 << MemberDecl->getDeclName() 11979 << SourceRange(BuiltinLoc, RParenLoc); 11980 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 11981 return ExprError(); 11982 } 11983 11984 RecordDecl *Parent = MemberDecl->getParent(); 11985 if (IndirectMemberDecl) 11986 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 11987 11988 // If the member was found in a base class, introduce OffsetOfNodes for 11989 // the base class indirections. 11990 CXXBasePaths Paths; 11991 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 11992 Paths)) { 11993 if (Paths.getDetectedVirtual()) { 11994 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 11995 << MemberDecl->getDeclName() 11996 << SourceRange(BuiltinLoc, RParenLoc); 11997 return ExprError(); 11998 } 11999 12000 CXXBasePath &Path = Paths.front(); 12001 for (const CXXBasePathElement &B : Path) 12002 Comps.push_back(OffsetOfNode(B.Base)); 12003 } 12004 12005 if (IndirectMemberDecl) { 12006 for (auto *FI : IndirectMemberDecl->chain()) { 12007 assert(isa<FieldDecl>(FI)); 12008 Comps.push_back(OffsetOfNode(OC.LocStart, 12009 cast<FieldDecl>(FI), OC.LocEnd)); 12010 } 12011 } else 12012 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 12013 12014 CurrentType = MemberDecl->getType().getNonReferenceType(); 12015 } 12016 12017 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 12018 Comps, Exprs, RParenLoc); 12019 } 12020 12021 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 12022 SourceLocation BuiltinLoc, 12023 SourceLocation TypeLoc, 12024 ParsedType ParsedArgTy, 12025 ArrayRef<OffsetOfComponent> Components, 12026 SourceLocation RParenLoc) { 12027 12028 TypeSourceInfo *ArgTInfo; 12029 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 12030 if (ArgTy.isNull()) 12031 return ExprError(); 12032 12033 if (!ArgTInfo) 12034 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 12035 12036 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 12037 } 12038 12039 12040 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 12041 Expr *CondExpr, 12042 Expr *LHSExpr, Expr *RHSExpr, 12043 SourceLocation RPLoc) { 12044 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 12045 12046 ExprValueKind VK = VK_RValue; 12047 ExprObjectKind OK = OK_Ordinary; 12048 QualType resType; 12049 bool ValueDependent = false; 12050 bool CondIsTrue = false; 12051 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 12052 resType = Context.DependentTy; 12053 ValueDependent = true; 12054 } else { 12055 // The conditional expression is required to be a constant expression. 12056 llvm::APSInt condEval(32); 12057 ExprResult CondICE 12058 = VerifyIntegerConstantExpression(CondExpr, &condEval, 12059 diag::err_typecheck_choose_expr_requires_constant, false); 12060 if (CondICE.isInvalid()) 12061 return ExprError(); 12062 CondExpr = CondICE.get(); 12063 CondIsTrue = condEval.getZExtValue(); 12064 12065 // If the condition is > zero, then the AST type is the same as the LSHExpr. 12066 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 12067 12068 resType = ActiveExpr->getType(); 12069 ValueDependent = ActiveExpr->isValueDependent(); 12070 VK = ActiveExpr->getValueKind(); 12071 OK = ActiveExpr->getObjectKind(); 12072 } 12073 12074 return new (Context) 12075 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 12076 CondIsTrue, resType->isDependentType(), ValueDependent); 12077 } 12078 12079 //===----------------------------------------------------------------------===// 12080 // Clang Extensions. 12081 //===----------------------------------------------------------------------===// 12082 12083 /// ActOnBlockStart - This callback is invoked when a block literal is started. 12084 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 12085 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 12086 12087 if (LangOpts.CPlusPlus) { 12088 Decl *ManglingContextDecl; 12089 if (MangleNumberingContext *MCtx = 12090 getCurrentMangleNumberContext(Block->getDeclContext(), 12091 ManglingContextDecl)) { 12092 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 12093 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 12094 } 12095 } 12096 12097 PushBlockScope(CurScope, Block); 12098 CurContext->addDecl(Block); 12099 if (CurScope) 12100 PushDeclContext(CurScope, Block); 12101 else 12102 CurContext = Block; 12103 12104 getCurBlock()->HasImplicitReturnType = true; 12105 12106 // Enter a new evaluation context to insulate the block from any 12107 // cleanups from the enclosing full-expression. 12108 PushExpressionEvaluationContext(PotentiallyEvaluated); 12109 } 12110 12111 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 12112 Scope *CurScope) { 12113 assert(ParamInfo.getIdentifier() == nullptr && 12114 "block-id should have no identifier!"); 12115 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 12116 BlockScopeInfo *CurBlock = getCurBlock(); 12117 12118 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 12119 QualType T = Sig->getType(); 12120 12121 // FIXME: We should allow unexpanded parameter packs here, but that would, 12122 // in turn, make the block expression contain unexpanded parameter packs. 12123 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 12124 // Drop the parameters. 12125 FunctionProtoType::ExtProtoInfo EPI; 12126 EPI.HasTrailingReturn = false; 12127 EPI.TypeQuals |= DeclSpec::TQ_const; 12128 T = Context.getFunctionType(Context.DependentTy, None, EPI); 12129 Sig = Context.getTrivialTypeSourceInfo(T); 12130 } 12131 12132 // GetTypeForDeclarator always produces a function type for a block 12133 // literal signature. Furthermore, it is always a FunctionProtoType 12134 // unless the function was written with a typedef. 12135 assert(T->isFunctionType() && 12136 "GetTypeForDeclarator made a non-function block signature"); 12137 12138 // Look for an explicit signature in that function type. 12139 FunctionProtoTypeLoc ExplicitSignature; 12140 12141 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 12142 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) { 12143 12144 // Check whether that explicit signature was synthesized by 12145 // GetTypeForDeclarator. If so, don't save that as part of the 12146 // written signature. 12147 if (ExplicitSignature.getLocalRangeBegin() == 12148 ExplicitSignature.getLocalRangeEnd()) { 12149 // This would be much cheaper if we stored TypeLocs instead of 12150 // TypeSourceInfos. 12151 TypeLoc Result = ExplicitSignature.getReturnLoc(); 12152 unsigned Size = Result.getFullDataSize(); 12153 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 12154 Sig->getTypeLoc().initializeFullCopy(Result, Size); 12155 12156 ExplicitSignature = FunctionProtoTypeLoc(); 12157 } 12158 } 12159 12160 CurBlock->TheDecl->setSignatureAsWritten(Sig); 12161 CurBlock->FunctionType = T; 12162 12163 const FunctionType *Fn = T->getAs<FunctionType>(); 12164 QualType RetTy = Fn->getReturnType(); 12165 bool isVariadic = 12166 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 12167 12168 CurBlock->TheDecl->setIsVariadic(isVariadic); 12169 12170 // Context.DependentTy is used as a placeholder for a missing block 12171 // return type. TODO: what should we do with declarators like: 12172 // ^ * { ... } 12173 // If the answer is "apply template argument deduction".... 12174 if (RetTy != Context.DependentTy) { 12175 CurBlock->ReturnType = RetTy; 12176 CurBlock->TheDecl->setBlockMissingReturnType(false); 12177 CurBlock->HasImplicitReturnType = false; 12178 } 12179 12180 // Push block parameters from the declarator if we had them. 12181 SmallVector<ParmVarDecl*, 8> Params; 12182 if (ExplicitSignature) { 12183 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 12184 ParmVarDecl *Param = ExplicitSignature.getParam(I); 12185 if (Param->getIdentifier() == nullptr && 12186 !Param->isImplicit() && 12187 !Param->isInvalidDecl() && 12188 !getLangOpts().CPlusPlus) 12189 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 12190 Params.push_back(Param); 12191 } 12192 12193 // Fake up parameter variables if we have a typedef, like 12194 // ^ fntype { ... } 12195 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 12196 for (const auto &I : Fn->param_types()) { 12197 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 12198 CurBlock->TheDecl, ParamInfo.getLocStart(), I); 12199 Params.push_back(Param); 12200 } 12201 } 12202 12203 // Set the parameters on the block decl. 12204 if (!Params.empty()) { 12205 CurBlock->TheDecl->setParams(Params); 12206 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 12207 /*CheckParameterNames=*/false); 12208 } 12209 12210 // Finally we can process decl attributes. 12211 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 12212 12213 // Put the parameter variables in scope. 12214 for (auto AI : CurBlock->TheDecl->parameters()) { 12215 AI->setOwningFunction(CurBlock->TheDecl); 12216 12217 // If this has an identifier, add it to the scope stack. 12218 if (AI->getIdentifier()) { 12219 CheckShadow(CurBlock->TheScope, AI); 12220 12221 PushOnScopeChains(AI, CurBlock->TheScope); 12222 } 12223 } 12224 } 12225 12226 /// ActOnBlockError - If there is an error parsing a block, this callback 12227 /// is invoked to pop the information about the block from the action impl. 12228 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 12229 // Leave the expression-evaluation context. 12230 DiscardCleanupsInEvaluationContext(); 12231 PopExpressionEvaluationContext(); 12232 12233 // Pop off CurBlock, handle nested blocks. 12234 PopDeclContext(); 12235 PopFunctionScopeInfo(); 12236 } 12237 12238 /// ActOnBlockStmtExpr - This is called when the body of a block statement 12239 /// literal was successfully completed. ^(int x){...} 12240 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 12241 Stmt *Body, Scope *CurScope) { 12242 // If blocks are disabled, emit an error. 12243 if (!LangOpts.Blocks) 12244 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 12245 12246 // Leave the expression-evaluation context. 12247 if (hasAnyUnrecoverableErrorsInThisFunction()) 12248 DiscardCleanupsInEvaluationContext(); 12249 assert(!Cleanup.exprNeedsCleanups() && 12250 "cleanups within block not correctly bound!"); 12251 PopExpressionEvaluationContext(); 12252 12253 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 12254 12255 if (BSI->HasImplicitReturnType) 12256 deduceClosureReturnType(*BSI); 12257 12258 PopDeclContext(); 12259 12260 QualType RetTy = Context.VoidTy; 12261 if (!BSI->ReturnType.isNull()) 12262 RetTy = BSI->ReturnType; 12263 12264 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 12265 QualType BlockTy; 12266 12267 // Set the captured variables on the block. 12268 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 12269 SmallVector<BlockDecl::Capture, 4> Captures; 12270 for (CapturingScopeInfo::Capture &Cap : BSI->Captures) { 12271 if (Cap.isThisCapture()) 12272 continue; 12273 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 12274 Cap.isNested(), Cap.getInitExpr()); 12275 Captures.push_back(NewCap); 12276 } 12277 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 12278 12279 // If the user wrote a function type in some form, try to use that. 12280 if (!BSI->FunctionType.isNull()) { 12281 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 12282 12283 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 12284 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 12285 12286 // Turn protoless block types into nullary block types. 12287 if (isa<FunctionNoProtoType>(FTy)) { 12288 FunctionProtoType::ExtProtoInfo EPI; 12289 EPI.ExtInfo = Ext; 12290 BlockTy = Context.getFunctionType(RetTy, None, EPI); 12291 12292 // Otherwise, if we don't need to change anything about the function type, 12293 // preserve its sugar structure. 12294 } else if (FTy->getReturnType() == RetTy && 12295 (!NoReturn || FTy->getNoReturnAttr())) { 12296 BlockTy = BSI->FunctionType; 12297 12298 // Otherwise, make the minimal modifications to the function type. 12299 } else { 12300 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 12301 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 12302 EPI.TypeQuals = 0; // FIXME: silently? 12303 EPI.ExtInfo = Ext; 12304 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 12305 } 12306 12307 // If we don't have a function type, just build one from nothing. 12308 } else { 12309 FunctionProtoType::ExtProtoInfo EPI; 12310 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 12311 BlockTy = Context.getFunctionType(RetTy, None, EPI); 12312 } 12313 12314 DiagnoseUnusedParameters(BSI->TheDecl->parameters()); 12315 BlockTy = Context.getBlockPointerType(BlockTy); 12316 12317 // If needed, diagnose invalid gotos and switches in the block. 12318 if (getCurFunction()->NeedsScopeChecking() && 12319 !PP.isCodeCompletionEnabled()) 12320 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 12321 12322 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 12323 12324 // Try to apply the named return value optimization. We have to check again 12325 // if we can do this, though, because blocks keep return statements around 12326 // to deduce an implicit return type. 12327 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 12328 !BSI->TheDecl->isDependentContext()) 12329 computeNRVO(Body, BSI); 12330 12331 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 12332 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 12333 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 12334 12335 // If the block isn't obviously global, i.e. it captures anything at 12336 // all, then we need to do a few things in the surrounding context: 12337 if (Result->getBlockDecl()->hasCaptures()) { 12338 // First, this expression has a new cleanup object. 12339 ExprCleanupObjects.push_back(Result->getBlockDecl()); 12340 Cleanup.setExprNeedsCleanups(true); 12341 12342 // It also gets a branch-protected scope if any of the captured 12343 // variables needs destruction. 12344 for (const auto &CI : Result->getBlockDecl()->captures()) { 12345 const VarDecl *var = CI.getVariable(); 12346 if (var->getType().isDestructedType() != QualType::DK_none) { 12347 getCurFunction()->setHasBranchProtectedScope(); 12348 break; 12349 } 12350 } 12351 } 12352 12353 return Result; 12354 } 12355 12356 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 12357 SourceLocation RPLoc) { 12358 TypeSourceInfo *TInfo; 12359 GetTypeFromParser(Ty, &TInfo); 12360 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 12361 } 12362 12363 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 12364 Expr *E, TypeSourceInfo *TInfo, 12365 SourceLocation RPLoc) { 12366 Expr *OrigExpr = E; 12367 bool IsMS = false; 12368 12369 // CUDA device code does not support varargs. 12370 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 12371 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 12372 CUDAFunctionTarget T = IdentifyCUDATarget(F); 12373 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 12374 return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device)); 12375 } 12376 } 12377 12378 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 12379 // as Microsoft ABI on an actual Microsoft platform, where 12380 // __builtin_ms_va_list and __builtin_va_list are the same.) 12381 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 12382 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 12383 QualType MSVaListType = Context.getBuiltinMSVaListType(); 12384 if (Context.hasSameType(MSVaListType, E->getType())) { 12385 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 12386 return ExprError(); 12387 IsMS = true; 12388 } 12389 } 12390 12391 // Get the va_list type 12392 QualType VaListType = Context.getBuiltinVaListType(); 12393 if (!IsMS) { 12394 if (VaListType->isArrayType()) { 12395 // Deal with implicit array decay; for example, on x86-64, 12396 // va_list is an array, but it's supposed to decay to 12397 // a pointer for va_arg. 12398 VaListType = Context.getArrayDecayedType(VaListType); 12399 // Make sure the input expression also decays appropriately. 12400 ExprResult Result = UsualUnaryConversions(E); 12401 if (Result.isInvalid()) 12402 return ExprError(); 12403 E = Result.get(); 12404 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 12405 // If va_list is a record type and we are compiling in C++ mode, 12406 // check the argument using reference binding. 12407 InitializedEntity Entity = InitializedEntity::InitializeParameter( 12408 Context, Context.getLValueReferenceType(VaListType), false); 12409 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 12410 if (Init.isInvalid()) 12411 return ExprError(); 12412 E = Init.getAs<Expr>(); 12413 } else { 12414 // Otherwise, the va_list argument must be an l-value because 12415 // it is modified by va_arg. 12416 if (!E->isTypeDependent() && 12417 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 12418 return ExprError(); 12419 } 12420 } 12421 12422 if (!IsMS && !E->isTypeDependent() && 12423 !Context.hasSameType(VaListType, E->getType())) 12424 return ExprError(Diag(E->getLocStart(), 12425 diag::err_first_argument_to_va_arg_not_of_type_va_list) 12426 << OrigExpr->getType() << E->getSourceRange()); 12427 12428 if (!TInfo->getType()->isDependentType()) { 12429 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 12430 diag::err_second_parameter_to_va_arg_incomplete, 12431 TInfo->getTypeLoc())) 12432 return ExprError(); 12433 12434 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 12435 TInfo->getType(), 12436 diag::err_second_parameter_to_va_arg_abstract, 12437 TInfo->getTypeLoc())) 12438 return ExprError(); 12439 12440 if (!TInfo->getType().isPODType(Context)) { 12441 Diag(TInfo->getTypeLoc().getBeginLoc(), 12442 TInfo->getType()->isObjCLifetimeType() 12443 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 12444 : diag::warn_second_parameter_to_va_arg_not_pod) 12445 << TInfo->getType() 12446 << TInfo->getTypeLoc().getSourceRange(); 12447 } 12448 12449 // Check for va_arg where arguments of the given type will be promoted 12450 // (i.e. this va_arg is guaranteed to have undefined behavior). 12451 QualType PromoteType; 12452 if (TInfo->getType()->isPromotableIntegerType()) { 12453 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 12454 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 12455 PromoteType = QualType(); 12456 } 12457 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 12458 PromoteType = Context.DoubleTy; 12459 if (!PromoteType.isNull()) 12460 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 12461 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 12462 << TInfo->getType() 12463 << PromoteType 12464 << TInfo->getTypeLoc().getSourceRange()); 12465 } 12466 12467 QualType T = TInfo->getType().getNonLValueExprType(Context); 12468 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 12469 } 12470 12471 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 12472 // The type of __null will be int or long, depending on the size of 12473 // pointers on the target. 12474 QualType Ty; 12475 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 12476 if (pw == Context.getTargetInfo().getIntWidth()) 12477 Ty = Context.IntTy; 12478 else if (pw == Context.getTargetInfo().getLongWidth()) 12479 Ty = Context.LongTy; 12480 else if (pw == Context.getTargetInfo().getLongLongWidth()) 12481 Ty = Context.LongLongTy; 12482 else { 12483 llvm_unreachable("I don't know size of pointer!"); 12484 } 12485 12486 return new (Context) GNUNullExpr(Ty, TokenLoc); 12487 } 12488 12489 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 12490 bool Diagnose) { 12491 if (!getLangOpts().ObjC1) 12492 return false; 12493 12494 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 12495 if (!PT) 12496 return false; 12497 12498 if (!PT->isObjCIdType()) { 12499 // Check if the destination is the 'NSString' interface. 12500 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 12501 if (!ID || !ID->getIdentifier()->isStr("NSString")) 12502 return false; 12503 } 12504 12505 // Ignore any parens, implicit casts (should only be 12506 // array-to-pointer decays), and not-so-opaque values. The last is 12507 // important for making this trigger for property assignments. 12508 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 12509 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 12510 if (OV->getSourceExpr()) 12511 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 12512 12513 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 12514 if (!SL || !SL->isAscii()) 12515 return false; 12516 if (Diagnose) { 12517 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix) 12518 << FixItHint::CreateInsertion(SL->getLocStart(), "@"); 12519 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get(); 12520 } 12521 return true; 12522 } 12523 12524 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 12525 const Expr *SrcExpr) { 12526 if (!DstType->isFunctionPointerType() || 12527 !SrcExpr->getType()->isFunctionType()) 12528 return false; 12529 12530 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 12531 if (!DRE) 12532 return false; 12533 12534 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 12535 if (!FD) 12536 return false; 12537 12538 return !S.checkAddressOfFunctionIsAvailable(FD, 12539 /*Complain=*/true, 12540 SrcExpr->getLocStart()); 12541 } 12542 12543 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 12544 SourceLocation Loc, 12545 QualType DstType, QualType SrcType, 12546 Expr *SrcExpr, AssignmentAction Action, 12547 bool *Complained) { 12548 if (Complained) 12549 *Complained = false; 12550 12551 // Decode the result (notice that AST's are still created for extensions). 12552 bool CheckInferredResultType = false; 12553 bool isInvalid = false; 12554 unsigned DiagKind = 0; 12555 FixItHint Hint; 12556 ConversionFixItGenerator ConvHints; 12557 bool MayHaveConvFixit = false; 12558 bool MayHaveFunctionDiff = false; 12559 const ObjCInterfaceDecl *IFace = nullptr; 12560 const ObjCProtocolDecl *PDecl = nullptr; 12561 12562 switch (ConvTy) { 12563 case Compatible: 12564 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 12565 return false; 12566 12567 case PointerToInt: 12568 DiagKind = diag::ext_typecheck_convert_pointer_int; 12569 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12570 MayHaveConvFixit = true; 12571 break; 12572 case IntToPointer: 12573 DiagKind = diag::ext_typecheck_convert_int_pointer; 12574 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12575 MayHaveConvFixit = true; 12576 break; 12577 case IncompatiblePointer: 12578 if (Action == AA_Passing_CFAudited) 12579 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 12580 else if (SrcType->isFunctionPointerType() && 12581 DstType->isFunctionPointerType()) 12582 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 12583 else 12584 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 12585 12586 CheckInferredResultType = DstType->isObjCObjectPointerType() && 12587 SrcType->isObjCObjectPointerType(); 12588 if (Hint.isNull() && !CheckInferredResultType) { 12589 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12590 } 12591 else if (CheckInferredResultType) { 12592 SrcType = SrcType.getUnqualifiedType(); 12593 DstType = DstType.getUnqualifiedType(); 12594 } 12595 MayHaveConvFixit = true; 12596 break; 12597 case IncompatiblePointerSign: 12598 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 12599 break; 12600 case FunctionVoidPointer: 12601 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 12602 break; 12603 case IncompatiblePointerDiscardsQualifiers: { 12604 // Perform array-to-pointer decay if necessary. 12605 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 12606 12607 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 12608 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 12609 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 12610 DiagKind = diag::err_typecheck_incompatible_address_space; 12611 break; 12612 12613 12614 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 12615 DiagKind = diag::err_typecheck_incompatible_ownership; 12616 break; 12617 } 12618 12619 llvm_unreachable("unknown error case for discarding qualifiers!"); 12620 // fallthrough 12621 } 12622 case CompatiblePointerDiscardsQualifiers: 12623 // If the qualifiers lost were because we were applying the 12624 // (deprecated) C++ conversion from a string literal to a char* 12625 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 12626 // Ideally, this check would be performed in 12627 // checkPointerTypesForAssignment. However, that would require a 12628 // bit of refactoring (so that the second argument is an 12629 // expression, rather than a type), which should be done as part 12630 // of a larger effort to fix checkPointerTypesForAssignment for 12631 // C++ semantics. 12632 if (getLangOpts().CPlusPlus && 12633 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 12634 return false; 12635 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 12636 break; 12637 case IncompatibleNestedPointerQualifiers: 12638 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 12639 break; 12640 case IntToBlockPointer: 12641 DiagKind = diag::err_int_to_block_pointer; 12642 break; 12643 case IncompatibleBlockPointer: 12644 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 12645 break; 12646 case IncompatibleObjCQualifiedId: { 12647 if (SrcType->isObjCQualifiedIdType()) { 12648 const ObjCObjectPointerType *srcOPT = 12649 SrcType->getAs<ObjCObjectPointerType>(); 12650 for (auto *srcProto : srcOPT->quals()) { 12651 PDecl = srcProto; 12652 break; 12653 } 12654 if (const ObjCInterfaceType *IFaceT = 12655 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 12656 IFace = IFaceT->getDecl(); 12657 } 12658 else if (DstType->isObjCQualifiedIdType()) { 12659 const ObjCObjectPointerType *dstOPT = 12660 DstType->getAs<ObjCObjectPointerType>(); 12661 for (auto *dstProto : dstOPT->quals()) { 12662 PDecl = dstProto; 12663 break; 12664 } 12665 if (const ObjCInterfaceType *IFaceT = 12666 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 12667 IFace = IFaceT->getDecl(); 12668 } 12669 DiagKind = diag::warn_incompatible_qualified_id; 12670 break; 12671 } 12672 case IncompatibleVectors: 12673 DiagKind = diag::warn_incompatible_vectors; 12674 break; 12675 case IncompatibleObjCWeakRef: 12676 DiagKind = diag::err_arc_weak_unavailable_assign; 12677 break; 12678 case Incompatible: 12679 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 12680 if (Complained) 12681 *Complained = true; 12682 return true; 12683 } 12684 12685 DiagKind = diag::err_typecheck_convert_incompatible; 12686 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12687 MayHaveConvFixit = true; 12688 isInvalid = true; 12689 MayHaveFunctionDiff = true; 12690 break; 12691 } 12692 12693 QualType FirstType, SecondType; 12694 switch (Action) { 12695 case AA_Assigning: 12696 case AA_Initializing: 12697 // The destination type comes first. 12698 FirstType = DstType; 12699 SecondType = SrcType; 12700 break; 12701 12702 case AA_Returning: 12703 case AA_Passing: 12704 case AA_Passing_CFAudited: 12705 case AA_Converting: 12706 case AA_Sending: 12707 case AA_Casting: 12708 // The source type comes first. 12709 FirstType = SrcType; 12710 SecondType = DstType; 12711 break; 12712 } 12713 12714 PartialDiagnostic FDiag = PDiag(DiagKind); 12715 if (Action == AA_Passing_CFAudited) 12716 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 12717 else 12718 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 12719 12720 // If we can fix the conversion, suggest the FixIts. 12721 assert(ConvHints.isNull() || Hint.isNull()); 12722 if (!ConvHints.isNull()) { 12723 for (FixItHint &H : ConvHints.Hints) 12724 FDiag << H; 12725 } else { 12726 FDiag << Hint; 12727 } 12728 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 12729 12730 if (MayHaveFunctionDiff) 12731 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 12732 12733 Diag(Loc, FDiag); 12734 if (DiagKind == diag::warn_incompatible_qualified_id && 12735 PDecl && IFace && !IFace->hasDefinition()) 12736 Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id) 12737 << IFace->getName() << PDecl->getName(); 12738 12739 if (SecondType == Context.OverloadTy) 12740 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 12741 FirstType, /*TakingAddress=*/true); 12742 12743 if (CheckInferredResultType) 12744 EmitRelatedResultTypeNote(SrcExpr); 12745 12746 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 12747 EmitRelatedResultTypeNoteForReturn(DstType); 12748 12749 if (Complained) 12750 *Complained = true; 12751 return isInvalid; 12752 } 12753 12754 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12755 llvm::APSInt *Result) { 12756 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 12757 public: 12758 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12759 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 12760 } 12761 } Diagnoser; 12762 12763 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 12764 } 12765 12766 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12767 llvm::APSInt *Result, 12768 unsigned DiagID, 12769 bool AllowFold) { 12770 class IDDiagnoser : public VerifyICEDiagnoser { 12771 unsigned DiagID; 12772 12773 public: 12774 IDDiagnoser(unsigned DiagID) 12775 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 12776 12777 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12778 S.Diag(Loc, DiagID) << SR; 12779 } 12780 } Diagnoser(DiagID); 12781 12782 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 12783 } 12784 12785 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 12786 SourceRange SR) { 12787 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 12788 } 12789 12790 ExprResult 12791 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 12792 VerifyICEDiagnoser &Diagnoser, 12793 bool AllowFold) { 12794 SourceLocation DiagLoc = E->getLocStart(); 12795 12796 if (getLangOpts().CPlusPlus11) { 12797 // C++11 [expr.const]p5: 12798 // If an expression of literal class type is used in a context where an 12799 // integral constant expression is required, then that class type shall 12800 // have a single non-explicit conversion function to an integral or 12801 // unscoped enumeration type 12802 ExprResult Converted; 12803 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 12804 public: 12805 CXX11ConvertDiagnoser(bool Silent) 12806 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 12807 Silent, true) {} 12808 12809 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 12810 QualType T) override { 12811 return S.Diag(Loc, diag::err_ice_not_integral) << T; 12812 } 12813 12814 SemaDiagnosticBuilder diagnoseIncomplete( 12815 Sema &S, SourceLocation Loc, QualType T) override { 12816 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 12817 } 12818 12819 SemaDiagnosticBuilder diagnoseExplicitConv( 12820 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12821 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 12822 } 12823 12824 SemaDiagnosticBuilder noteExplicitConv( 12825 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12826 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12827 << ConvTy->isEnumeralType() << ConvTy; 12828 } 12829 12830 SemaDiagnosticBuilder diagnoseAmbiguous( 12831 Sema &S, SourceLocation Loc, QualType T) override { 12832 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 12833 } 12834 12835 SemaDiagnosticBuilder noteAmbiguous( 12836 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12837 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12838 << ConvTy->isEnumeralType() << ConvTy; 12839 } 12840 12841 SemaDiagnosticBuilder diagnoseConversion( 12842 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12843 llvm_unreachable("conversion functions are permitted"); 12844 } 12845 } ConvertDiagnoser(Diagnoser.Suppress); 12846 12847 Converted = PerformContextualImplicitConversion(DiagLoc, E, 12848 ConvertDiagnoser); 12849 if (Converted.isInvalid()) 12850 return Converted; 12851 E = Converted.get(); 12852 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 12853 return ExprError(); 12854 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 12855 // An ICE must be of integral or unscoped enumeration type. 12856 if (!Diagnoser.Suppress) 12857 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 12858 return ExprError(); 12859 } 12860 12861 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 12862 // in the non-ICE case. 12863 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 12864 if (Result) 12865 *Result = E->EvaluateKnownConstInt(Context); 12866 return E; 12867 } 12868 12869 Expr::EvalResult EvalResult; 12870 SmallVector<PartialDiagnosticAt, 8> Notes; 12871 EvalResult.Diag = &Notes; 12872 12873 // Try to evaluate the expression, and produce diagnostics explaining why it's 12874 // not a constant expression as a side-effect. 12875 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 12876 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 12877 12878 // In C++11, we can rely on diagnostics being produced for any expression 12879 // which is not a constant expression. If no diagnostics were produced, then 12880 // this is a constant expression. 12881 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 12882 if (Result) 12883 *Result = EvalResult.Val.getInt(); 12884 return E; 12885 } 12886 12887 // If our only note is the usual "invalid subexpression" note, just point 12888 // the caret at its location rather than producing an essentially 12889 // redundant note. 12890 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 12891 diag::note_invalid_subexpr_in_const_expr) { 12892 DiagLoc = Notes[0].first; 12893 Notes.clear(); 12894 } 12895 12896 if (!Folded || !AllowFold) { 12897 if (!Diagnoser.Suppress) { 12898 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 12899 for (const PartialDiagnosticAt &Note : Notes) 12900 Diag(Note.first, Note.second); 12901 } 12902 12903 return ExprError(); 12904 } 12905 12906 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 12907 for (const PartialDiagnosticAt &Note : Notes) 12908 Diag(Note.first, Note.second); 12909 12910 if (Result) 12911 *Result = EvalResult.Val.getInt(); 12912 return E; 12913 } 12914 12915 namespace { 12916 // Handle the case where we conclude a expression which we speculatively 12917 // considered to be unevaluated is actually evaluated. 12918 class TransformToPE : public TreeTransform<TransformToPE> { 12919 typedef TreeTransform<TransformToPE> BaseTransform; 12920 12921 public: 12922 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 12923 12924 // Make sure we redo semantic analysis 12925 bool AlwaysRebuild() { return true; } 12926 12927 // Make sure we handle LabelStmts correctly. 12928 // FIXME: This does the right thing, but maybe we need a more general 12929 // fix to TreeTransform? 12930 StmtResult TransformLabelStmt(LabelStmt *S) { 12931 S->getDecl()->setStmt(nullptr); 12932 return BaseTransform::TransformLabelStmt(S); 12933 } 12934 12935 // We need to special-case DeclRefExprs referring to FieldDecls which 12936 // are not part of a member pointer formation; normal TreeTransforming 12937 // doesn't catch this case because of the way we represent them in the AST. 12938 // FIXME: This is a bit ugly; is it really the best way to handle this 12939 // case? 12940 // 12941 // Error on DeclRefExprs referring to FieldDecls. 12942 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 12943 if (isa<FieldDecl>(E->getDecl()) && 12944 !SemaRef.isUnevaluatedContext()) 12945 return SemaRef.Diag(E->getLocation(), 12946 diag::err_invalid_non_static_member_use) 12947 << E->getDecl() << E->getSourceRange(); 12948 12949 return BaseTransform::TransformDeclRefExpr(E); 12950 } 12951 12952 // Exception: filter out member pointer formation 12953 ExprResult TransformUnaryOperator(UnaryOperator *E) { 12954 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 12955 return E; 12956 12957 return BaseTransform::TransformUnaryOperator(E); 12958 } 12959 12960 ExprResult TransformLambdaExpr(LambdaExpr *E) { 12961 // Lambdas never need to be transformed. 12962 return E; 12963 } 12964 }; 12965 } 12966 12967 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 12968 assert(isUnevaluatedContext() && 12969 "Should only transform unevaluated expressions"); 12970 ExprEvalContexts.back().Context = 12971 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 12972 if (isUnevaluatedContext()) 12973 return E; 12974 return TransformToPE(*this).TransformExpr(E); 12975 } 12976 12977 void 12978 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 12979 Decl *LambdaContextDecl, 12980 bool IsDecltype) { 12981 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 12982 LambdaContextDecl, IsDecltype); 12983 Cleanup.reset(); 12984 if (!MaybeODRUseExprs.empty()) 12985 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 12986 } 12987 12988 void 12989 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 12990 ReuseLambdaContextDecl_t, 12991 bool IsDecltype) { 12992 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 12993 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 12994 } 12995 12996 void Sema::PopExpressionEvaluationContext() { 12997 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 12998 unsigned NumTypos = Rec.NumTypos; 12999 13000 if (!Rec.Lambdas.empty()) { 13001 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 13002 unsigned D; 13003 if (Rec.isUnevaluated()) { 13004 // C++11 [expr.prim.lambda]p2: 13005 // A lambda-expression shall not appear in an unevaluated operand 13006 // (Clause 5). 13007 D = diag::err_lambda_unevaluated_operand; 13008 } else { 13009 // C++1y [expr.const]p2: 13010 // A conditional-expression e is a core constant expression unless the 13011 // evaluation of e, following the rules of the abstract machine, would 13012 // evaluate [...] a lambda-expression. 13013 D = diag::err_lambda_in_constant_expression; 13014 } 13015 for (const auto *L : Rec.Lambdas) 13016 Diag(L->getLocStart(), D); 13017 } else { 13018 // Mark the capture expressions odr-used. This was deferred 13019 // during lambda expression creation. 13020 for (auto *Lambda : Rec.Lambdas) { 13021 for (auto *C : Lambda->capture_inits()) 13022 MarkDeclarationsReferencedInExpr(C); 13023 } 13024 } 13025 } 13026 13027 // When are coming out of an unevaluated context, clear out any 13028 // temporaries that we may have created as part of the evaluation of 13029 // the expression in that context: they aren't relevant because they 13030 // will never be constructed. 13031 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 13032 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 13033 ExprCleanupObjects.end()); 13034 Cleanup = Rec.ParentCleanup; 13035 CleanupVarDeclMarking(); 13036 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 13037 // Otherwise, merge the contexts together. 13038 } else { 13039 Cleanup.mergeFrom(Rec.ParentCleanup); 13040 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 13041 Rec.SavedMaybeODRUseExprs.end()); 13042 } 13043 13044 // Pop the current expression evaluation context off the stack. 13045 ExprEvalContexts.pop_back(); 13046 13047 if (!ExprEvalContexts.empty()) 13048 ExprEvalContexts.back().NumTypos += NumTypos; 13049 else 13050 assert(NumTypos == 0 && "There are outstanding typos after popping the " 13051 "last ExpressionEvaluationContextRecord"); 13052 } 13053 13054 void Sema::DiscardCleanupsInEvaluationContext() { 13055 ExprCleanupObjects.erase( 13056 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 13057 ExprCleanupObjects.end()); 13058 Cleanup.reset(); 13059 MaybeODRUseExprs.clear(); 13060 } 13061 13062 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 13063 if (!E->getType()->isVariablyModifiedType()) 13064 return E; 13065 return TransformToPotentiallyEvaluated(E); 13066 } 13067 13068 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) { 13069 // Do not mark anything as "used" within a dependent context; wait for 13070 // an instantiation. 13071 if (SemaRef.CurContext->isDependentContext()) 13072 return false; 13073 13074 switch (SemaRef.ExprEvalContexts.back().Context) { 13075 case Sema::Unevaluated: 13076 case Sema::UnevaluatedAbstract: 13077 // We are in an expression that is not potentially evaluated; do nothing. 13078 // (Depending on how you read the standard, we actually do need to do 13079 // something here for null pointer constants, but the standard's 13080 // definition of a null pointer constant is completely crazy.) 13081 return false; 13082 13083 case Sema::DiscardedStatement: 13084 // These are technically a potentially evaluated but they have the effect 13085 // of suppressing use marking. 13086 return false; 13087 13088 case Sema::ConstantEvaluated: 13089 case Sema::PotentiallyEvaluated: 13090 // We are in a potentially evaluated expression (or a constant-expression 13091 // in C++03); we need to do implicit template instantiation, implicitly 13092 // define class members, and mark most declarations as used. 13093 return true; 13094 13095 case Sema::PotentiallyEvaluatedIfUsed: 13096 // Referenced declarations will only be used if the construct in the 13097 // containing expression is used. 13098 return false; 13099 } 13100 llvm_unreachable("Invalid context"); 13101 } 13102 13103 /// \brief Mark a function referenced, and check whether it is odr-used 13104 /// (C++ [basic.def.odr]p2, C99 6.9p3) 13105 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 13106 bool MightBeOdrUse) { 13107 assert(Func && "No function?"); 13108 13109 Func->setReferenced(); 13110 13111 // C++11 [basic.def.odr]p3: 13112 // A function whose name appears as a potentially-evaluated expression is 13113 // odr-used if it is the unique lookup result or the selected member of a 13114 // set of overloaded functions [...]. 13115 // 13116 // We (incorrectly) mark overload resolution as an unevaluated context, so we 13117 // can just check that here. 13118 bool OdrUse = MightBeOdrUse && IsPotentiallyEvaluatedContext(*this); 13119 13120 // Determine whether we require a function definition to exist, per 13121 // C++11 [temp.inst]p3: 13122 // Unless a function template specialization has been explicitly 13123 // instantiated or explicitly specialized, the function template 13124 // specialization is implicitly instantiated when the specialization is 13125 // referenced in a context that requires a function definition to exist. 13126 // 13127 // We consider constexpr function templates to be referenced in a context 13128 // that requires a definition to exist whenever they are referenced. 13129 // 13130 // FIXME: This instantiates constexpr functions too frequently. If this is 13131 // really an unevaluated context (and we're not just in the definition of a 13132 // function template or overload resolution or other cases which we 13133 // incorrectly consider to be unevaluated contexts), and we're not in a 13134 // subexpression which we actually need to evaluate (for instance, a 13135 // template argument, array bound or an expression in a braced-init-list), 13136 // we are not permitted to instantiate this constexpr function definition. 13137 // 13138 // FIXME: This also implicitly defines special members too frequently. They 13139 // are only supposed to be implicitly defined if they are odr-used, but they 13140 // are not odr-used from constant expressions in unevaluated contexts. 13141 // However, they cannot be referenced if they are deleted, and they are 13142 // deleted whenever the implicit definition of the special member would 13143 // fail (with very few exceptions). 13144 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 13145 bool NeedDefinition = 13146 OdrUse || (Func->isConstexpr() && (Func->isImplicitlyInstantiable() || 13147 (MD && !MD->isUserProvided()))); 13148 13149 // C++14 [temp.expl.spec]p6: 13150 // If a template [...] is explicitly specialized then that specialization 13151 // shall be declared before the first use of that specialization that would 13152 // cause an implicit instantiation to take place, in every translation unit 13153 // in which such a use occurs 13154 if (NeedDefinition && 13155 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 13156 Func->getMemberSpecializationInfo())) 13157 checkSpecializationVisibility(Loc, Func); 13158 13159 // C++14 [except.spec]p17: 13160 // An exception-specification is considered to be needed when: 13161 // - the function is odr-used or, if it appears in an unevaluated operand, 13162 // would be odr-used if the expression were potentially-evaluated; 13163 // 13164 // Note, we do this even if MightBeOdrUse is false. That indicates that the 13165 // function is a pure virtual function we're calling, and in that case the 13166 // function was selected by overload resolution and we need to resolve its 13167 // exception specification for a different reason. 13168 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 13169 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 13170 ResolveExceptionSpec(Loc, FPT); 13171 13172 // If we don't need to mark the function as used, and we don't need to 13173 // try to provide a definition, there's nothing more to do. 13174 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) && 13175 (!NeedDefinition || Func->getBody())) 13176 return; 13177 13178 // Note that this declaration has been used. 13179 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 13180 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 13181 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 13182 if (Constructor->isDefaultConstructor()) { 13183 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 13184 return; 13185 DefineImplicitDefaultConstructor(Loc, Constructor); 13186 } else if (Constructor->isCopyConstructor()) { 13187 DefineImplicitCopyConstructor(Loc, Constructor); 13188 } else if (Constructor->isMoveConstructor()) { 13189 DefineImplicitMoveConstructor(Loc, Constructor); 13190 } 13191 } else if (Constructor->getInheritedConstructor()) { 13192 DefineInheritingConstructor(Loc, Constructor); 13193 } 13194 } else if (CXXDestructorDecl *Destructor = 13195 dyn_cast<CXXDestructorDecl>(Func)) { 13196 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 13197 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 13198 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 13199 return; 13200 DefineImplicitDestructor(Loc, Destructor); 13201 } 13202 if (Destructor->isVirtual() && getLangOpts().AppleKext) 13203 MarkVTableUsed(Loc, Destructor->getParent()); 13204 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 13205 if (MethodDecl->isOverloadedOperator() && 13206 MethodDecl->getOverloadedOperator() == OO_Equal) { 13207 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 13208 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 13209 if (MethodDecl->isCopyAssignmentOperator()) 13210 DefineImplicitCopyAssignment(Loc, MethodDecl); 13211 else if (MethodDecl->isMoveAssignmentOperator()) 13212 DefineImplicitMoveAssignment(Loc, MethodDecl); 13213 } 13214 } else if (isa<CXXConversionDecl>(MethodDecl) && 13215 MethodDecl->getParent()->isLambda()) { 13216 CXXConversionDecl *Conversion = 13217 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 13218 if (Conversion->isLambdaToBlockPointerConversion()) 13219 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 13220 else 13221 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 13222 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 13223 MarkVTableUsed(Loc, MethodDecl->getParent()); 13224 } 13225 13226 // Recursive functions should be marked when used from another function. 13227 // FIXME: Is this really right? 13228 if (CurContext == Func) return; 13229 13230 // Implicit instantiation of function templates and member functions of 13231 // class templates. 13232 if (Func->isImplicitlyInstantiable()) { 13233 bool AlreadyInstantiated = false; 13234 SourceLocation PointOfInstantiation = Loc; 13235 if (FunctionTemplateSpecializationInfo *SpecInfo 13236 = Func->getTemplateSpecializationInfo()) { 13237 if (SpecInfo->getPointOfInstantiation().isInvalid()) 13238 SpecInfo->setPointOfInstantiation(Loc); 13239 else if (SpecInfo->getTemplateSpecializationKind() 13240 == TSK_ImplicitInstantiation) { 13241 AlreadyInstantiated = true; 13242 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 13243 } 13244 } else if (MemberSpecializationInfo *MSInfo 13245 = Func->getMemberSpecializationInfo()) { 13246 if (MSInfo->getPointOfInstantiation().isInvalid()) 13247 MSInfo->setPointOfInstantiation(Loc); 13248 else if (MSInfo->getTemplateSpecializationKind() 13249 == TSK_ImplicitInstantiation) { 13250 AlreadyInstantiated = true; 13251 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 13252 } 13253 } 13254 13255 if (!AlreadyInstantiated || Func->isConstexpr()) { 13256 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 13257 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 13258 ActiveTemplateInstantiations.size()) 13259 PendingLocalImplicitInstantiations.push_back( 13260 std::make_pair(Func, PointOfInstantiation)); 13261 else if (Func->isConstexpr()) 13262 // Do not defer instantiations of constexpr functions, to avoid the 13263 // expression evaluator needing to call back into Sema if it sees a 13264 // call to such a function. 13265 InstantiateFunctionDefinition(PointOfInstantiation, Func); 13266 else { 13267 PendingInstantiations.push_back(std::make_pair(Func, 13268 PointOfInstantiation)); 13269 // Notify the consumer that a function was implicitly instantiated. 13270 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 13271 } 13272 } 13273 } else { 13274 // Walk redefinitions, as some of them may be instantiable. 13275 for (auto i : Func->redecls()) { 13276 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 13277 MarkFunctionReferenced(Loc, i, OdrUse); 13278 } 13279 } 13280 13281 if (!OdrUse) return; 13282 13283 // Keep track of used but undefined functions. 13284 if (!Func->isDefined()) { 13285 if (mightHaveNonExternalLinkage(Func)) 13286 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 13287 else if (Func->getMostRecentDecl()->isInlined() && 13288 !LangOpts.GNUInline && 13289 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 13290 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 13291 } 13292 13293 Func->markUsed(Context); 13294 } 13295 13296 static void 13297 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 13298 ValueDecl *var, DeclContext *DC) { 13299 DeclContext *VarDC = var->getDeclContext(); 13300 13301 // If the parameter still belongs to the translation unit, then 13302 // we're actually just using one parameter in the declaration of 13303 // the next. 13304 if (isa<ParmVarDecl>(var) && 13305 isa<TranslationUnitDecl>(VarDC)) 13306 return; 13307 13308 // For C code, don't diagnose about capture if we're not actually in code 13309 // right now; it's impossible to write a non-constant expression outside of 13310 // function context, so we'll get other (more useful) diagnostics later. 13311 // 13312 // For C++, things get a bit more nasty... it would be nice to suppress this 13313 // diagnostic for certain cases like using a local variable in an array bound 13314 // for a member of a local class, but the correct predicate is not obvious. 13315 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 13316 return; 13317 13318 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 13319 unsigned ContextKind = 3; // unknown 13320 if (isa<CXXMethodDecl>(VarDC) && 13321 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 13322 ContextKind = 2; 13323 } else if (isa<FunctionDecl>(VarDC)) { 13324 ContextKind = 0; 13325 } else if (isa<BlockDecl>(VarDC)) { 13326 ContextKind = 1; 13327 } 13328 13329 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 13330 << var << ValueKind << ContextKind << VarDC; 13331 S.Diag(var->getLocation(), diag::note_entity_declared_at) 13332 << var; 13333 13334 // FIXME: Add additional diagnostic info about class etc. which prevents 13335 // capture. 13336 } 13337 13338 13339 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 13340 bool &SubCapturesAreNested, 13341 QualType &CaptureType, 13342 QualType &DeclRefType) { 13343 // Check whether we've already captured it. 13344 if (CSI->CaptureMap.count(Var)) { 13345 // If we found a capture, any subcaptures are nested. 13346 SubCapturesAreNested = true; 13347 13348 // Retrieve the capture type for this variable. 13349 CaptureType = CSI->getCapture(Var).getCaptureType(); 13350 13351 // Compute the type of an expression that refers to this variable. 13352 DeclRefType = CaptureType.getNonReferenceType(); 13353 13354 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 13355 // are mutable in the sense that user can change their value - they are 13356 // private instances of the captured declarations. 13357 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 13358 if (Cap.isCopyCapture() && 13359 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 13360 !(isa<CapturedRegionScopeInfo>(CSI) && 13361 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 13362 DeclRefType.addConst(); 13363 return true; 13364 } 13365 return false; 13366 } 13367 13368 // Only block literals, captured statements, and lambda expressions can 13369 // capture; other scopes don't work. 13370 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 13371 SourceLocation Loc, 13372 const bool Diagnose, Sema &S) { 13373 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 13374 return getLambdaAwareParentOfDeclContext(DC); 13375 else if (Var->hasLocalStorage()) { 13376 if (Diagnose) 13377 diagnoseUncapturableValueReference(S, Loc, Var, DC); 13378 } 13379 return nullptr; 13380 } 13381 13382 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 13383 // certain types of variables (unnamed, variably modified types etc.) 13384 // so check for eligibility. 13385 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 13386 SourceLocation Loc, 13387 const bool Diagnose, Sema &S) { 13388 13389 bool IsBlock = isa<BlockScopeInfo>(CSI); 13390 bool IsLambda = isa<LambdaScopeInfo>(CSI); 13391 13392 // Lambdas are not allowed to capture unnamed variables 13393 // (e.g. anonymous unions). 13394 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 13395 // assuming that's the intent. 13396 if (IsLambda && !Var->getDeclName()) { 13397 if (Diagnose) { 13398 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 13399 S.Diag(Var->getLocation(), diag::note_declared_at); 13400 } 13401 return false; 13402 } 13403 13404 // Prohibit variably-modified types in blocks; they're difficult to deal with. 13405 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 13406 if (Diagnose) { 13407 S.Diag(Loc, diag::err_ref_vm_type); 13408 S.Diag(Var->getLocation(), diag::note_previous_decl) 13409 << Var->getDeclName(); 13410 } 13411 return false; 13412 } 13413 // Prohibit structs with flexible array members too. 13414 // We cannot capture what is in the tail end of the struct. 13415 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 13416 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 13417 if (Diagnose) { 13418 if (IsBlock) 13419 S.Diag(Loc, diag::err_ref_flexarray_type); 13420 else 13421 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 13422 << Var->getDeclName(); 13423 S.Diag(Var->getLocation(), diag::note_previous_decl) 13424 << Var->getDeclName(); 13425 } 13426 return false; 13427 } 13428 } 13429 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 13430 // Lambdas and captured statements are not allowed to capture __block 13431 // variables; they don't support the expected semantics. 13432 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 13433 if (Diagnose) { 13434 S.Diag(Loc, diag::err_capture_block_variable) 13435 << Var->getDeclName() << !IsLambda; 13436 S.Diag(Var->getLocation(), diag::note_previous_decl) 13437 << Var->getDeclName(); 13438 } 13439 return false; 13440 } 13441 13442 return true; 13443 } 13444 13445 // Returns true if the capture by block was successful. 13446 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 13447 SourceLocation Loc, 13448 const bool BuildAndDiagnose, 13449 QualType &CaptureType, 13450 QualType &DeclRefType, 13451 const bool Nested, 13452 Sema &S) { 13453 Expr *CopyExpr = nullptr; 13454 bool ByRef = false; 13455 13456 // Blocks are not allowed to capture arrays. 13457 if (CaptureType->isArrayType()) { 13458 if (BuildAndDiagnose) { 13459 S.Diag(Loc, diag::err_ref_array_type); 13460 S.Diag(Var->getLocation(), diag::note_previous_decl) 13461 << Var->getDeclName(); 13462 } 13463 return false; 13464 } 13465 13466 // Forbid the block-capture of autoreleasing variables. 13467 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 13468 if (BuildAndDiagnose) { 13469 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 13470 << /*block*/ 0; 13471 S.Diag(Var->getLocation(), diag::note_previous_decl) 13472 << Var->getDeclName(); 13473 } 13474 return false; 13475 } 13476 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 13477 if (HasBlocksAttr || CaptureType->isReferenceType() || 13478 (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) { 13479 // Block capture by reference does not change the capture or 13480 // declaration reference types. 13481 ByRef = true; 13482 } else { 13483 // Block capture by copy introduces 'const'. 13484 CaptureType = CaptureType.getNonReferenceType().withConst(); 13485 DeclRefType = CaptureType; 13486 13487 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 13488 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 13489 // The capture logic needs the destructor, so make sure we mark it. 13490 // Usually this is unnecessary because most local variables have 13491 // their destructors marked at declaration time, but parameters are 13492 // an exception because it's technically only the call site that 13493 // actually requires the destructor. 13494 if (isa<ParmVarDecl>(Var)) 13495 S.FinalizeVarWithDestructor(Var, Record); 13496 13497 // Enter a new evaluation context to insulate the copy 13498 // full-expression. 13499 EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated); 13500 13501 // According to the blocks spec, the capture of a variable from 13502 // the stack requires a const copy constructor. This is not true 13503 // of the copy/move done to move a __block variable to the heap. 13504 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 13505 DeclRefType.withConst(), 13506 VK_LValue, Loc); 13507 13508 ExprResult Result 13509 = S.PerformCopyInitialization( 13510 InitializedEntity::InitializeBlock(Var->getLocation(), 13511 CaptureType, false), 13512 Loc, DeclRef); 13513 13514 // Build a full-expression copy expression if initialization 13515 // succeeded and used a non-trivial constructor. Recover from 13516 // errors by pretending that the copy isn't necessary. 13517 if (!Result.isInvalid() && 13518 !cast<CXXConstructExpr>(Result.get())->getConstructor() 13519 ->isTrivial()) { 13520 Result = S.MaybeCreateExprWithCleanups(Result); 13521 CopyExpr = Result.get(); 13522 } 13523 } 13524 } 13525 } 13526 13527 // Actually capture the variable. 13528 if (BuildAndDiagnose) 13529 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 13530 SourceLocation(), CaptureType, CopyExpr); 13531 13532 return true; 13533 13534 } 13535 13536 13537 /// \brief Capture the given variable in the captured region. 13538 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 13539 VarDecl *Var, 13540 SourceLocation Loc, 13541 const bool BuildAndDiagnose, 13542 QualType &CaptureType, 13543 QualType &DeclRefType, 13544 const bool RefersToCapturedVariable, 13545 Sema &S) { 13546 // By default, capture variables by reference. 13547 bool ByRef = true; 13548 // Using an LValue reference type is consistent with Lambdas (see below). 13549 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 13550 if (S.IsOpenMPCapturedDecl(Var)) 13551 DeclRefType = DeclRefType.getUnqualifiedType(); 13552 ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel); 13553 } 13554 13555 if (ByRef) 13556 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 13557 else 13558 CaptureType = DeclRefType; 13559 13560 Expr *CopyExpr = nullptr; 13561 if (BuildAndDiagnose) { 13562 // The current implementation assumes that all variables are captured 13563 // by references. Since there is no capture by copy, no expression 13564 // evaluation will be needed. 13565 RecordDecl *RD = RSI->TheRecordDecl; 13566 13567 FieldDecl *Field 13568 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 13569 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 13570 nullptr, false, ICIS_NoInit); 13571 Field->setImplicit(true); 13572 Field->setAccess(AS_private); 13573 RD->addDecl(Field); 13574 13575 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, 13576 DeclRefType, VK_LValue, Loc); 13577 Var->setReferenced(true); 13578 Var->markUsed(S.Context); 13579 } 13580 13581 // Actually capture the variable. 13582 if (BuildAndDiagnose) 13583 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 13584 SourceLocation(), CaptureType, CopyExpr); 13585 13586 13587 return true; 13588 } 13589 13590 /// \brief Create a field within the lambda class for the variable 13591 /// being captured. 13592 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, 13593 QualType FieldType, QualType DeclRefType, 13594 SourceLocation Loc, 13595 bool RefersToCapturedVariable) { 13596 CXXRecordDecl *Lambda = LSI->Lambda; 13597 13598 // Build the non-static data member. 13599 FieldDecl *Field 13600 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 13601 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 13602 nullptr, false, ICIS_NoInit); 13603 Field->setImplicit(true); 13604 Field->setAccess(AS_private); 13605 Lambda->addDecl(Field); 13606 } 13607 13608 /// \brief Capture the given variable in the lambda. 13609 static bool captureInLambda(LambdaScopeInfo *LSI, 13610 VarDecl *Var, 13611 SourceLocation Loc, 13612 const bool BuildAndDiagnose, 13613 QualType &CaptureType, 13614 QualType &DeclRefType, 13615 const bool RefersToCapturedVariable, 13616 const Sema::TryCaptureKind Kind, 13617 SourceLocation EllipsisLoc, 13618 const bool IsTopScope, 13619 Sema &S) { 13620 13621 // Determine whether we are capturing by reference or by value. 13622 bool ByRef = false; 13623 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 13624 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 13625 } else { 13626 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 13627 } 13628 13629 // Compute the type of the field that will capture this variable. 13630 if (ByRef) { 13631 // C++11 [expr.prim.lambda]p15: 13632 // An entity is captured by reference if it is implicitly or 13633 // explicitly captured but not captured by copy. It is 13634 // unspecified whether additional unnamed non-static data 13635 // members are declared in the closure type for entities 13636 // captured by reference. 13637 // 13638 // FIXME: It is not clear whether we want to build an lvalue reference 13639 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 13640 // to do the former, while EDG does the latter. Core issue 1249 will 13641 // clarify, but for now we follow GCC because it's a more permissive and 13642 // easily defensible position. 13643 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 13644 } else { 13645 // C++11 [expr.prim.lambda]p14: 13646 // For each entity captured by copy, an unnamed non-static 13647 // data member is declared in the closure type. The 13648 // declaration order of these members is unspecified. The type 13649 // of such a data member is the type of the corresponding 13650 // captured entity if the entity is not a reference to an 13651 // object, or the referenced type otherwise. [Note: If the 13652 // captured entity is a reference to a function, the 13653 // corresponding data member is also a reference to a 13654 // function. - end note ] 13655 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 13656 if (!RefType->getPointeeType()->isFunctionType()) 13657 CaptureType = RefType->getPointeeType(); 13658 } 13659 13660 // Forbid the lambda copy-capture of autoreleasing variables. 13661 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 13662 if (BuildAndDiagnose) { 13663 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 13664 S.Diag(Var->getLocation(), diag::note_previous_decl) 13665 << Var->getDeclName(); 13666 } 13667 return false; 13668 } 13669 13670 // Make sure that by-copy captures are of a complete and non-abstract type. 13671 if (BuildAndDiagnose) { 13672 if (!CaptureType->isDependentType() && 13673 S.RequireCompleteType(Loc, CaptureType, 13674 diag::err_capture_of_incomplete_type, 13675 Var->getDeclName())) 13676 return false; 13677 13678 if (S.RequireNonAbstractType(Loc, CaptureType, 13679 diag::err_capture_of_abstract_type)) 13680 return false; 13681 } 13682 } 13683 13684 // Capture this variable in the lambda. 13685 if (BuildAndDiagnose) 13686 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc, 13687 RefersToCapturedVariable); 13688 13689 // Compute the type of a reference to this captured variable. 13690 if (ByRef) 13691 DeclRefType = CaptureType.getNonReferenceType(); 13692 else { 13693 // C++ [expr.prim.lambda]p5: 13694 // The closure type for a lambda-expression has a public inline 13695 // function call operator [...]. This function call operator is 13696 // declared const (9.3.1) if and only if the lambda-expression's 13697 // parameter-declaration-clause is not followed by mutable. 13698 DeclRefType = CaptureType.getNonReferenceType(); 13699 if (!LSI->Mutable && !CaptureType->isReferenceType()) 13700 DeclRefType.addConst(); 13701 } 13702 13703 // Add the capture. 13704 if (BuildAndDiagnose) 13705 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 13706 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 13707 13708 return true; 13709 } 13710 13711 bool Sema::tryCaptureVariable( 13712 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 13713 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 13714 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 13715 // An init-capture is notionally from the context surrounding its 13716 // declaration, but its parent DC is the lambda class. 13717 DeclContext *VarDC = Var->getDeclContext(); 13718 if (Var->isInitCapture()) 13719 VarDC = VarDC->getParent(); 13720 13721 DeclContext *DC = CurContext; 13722 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 13723 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 13724 // We need to sync up the Declaration Context with the 13725 // FunctionScopeIndexToStopAt 13726 if (FunctionScopeIndexToStopAt) { 13727 unsigned FSIndex = FunctionScopes.size() - 1; 13728 while (FSIndex != MaxFunctionScopesIndex) { 13729 DC = getLambdaAwareParentOfDeclContext(DC); 13730 --FSIndex; 13731 } 13732 } 13733 13734 13735 // If the variable is declared in the current context, there is no need to 13736 // capture it. 13737 if (VarDC == DC) return true; 13738 13739 // Capture global variables if it is required to use private copy of this 13740 // variable. 13741 bool IsGlobal = !Var->hasLocalStorage(); 13742 if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var))) 13743 return true; 13744 13745 // Walk up the stack to determine whether we can capture the variable, 13746 // performing the "simple" checks that don't depend on type. We stop when 13747 // we've either hit the declared scope of the variable or find an existing 13748 // capture of that variable. We start from the innermost capturing-entity 13749 // (the DC) and ensure that all intervening capturing-entities 13750 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 13751 // declcontext can either capture the variable or have already captured 13752 // the variable. 13753 CaptureType = Var->getType(); 13754 DeclRefType = CaptureType.getNonReferenceType(); 13755 bool Nested = false; 13756 bool Explicit = (Kind != TryCapture_Implicit); 13757 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 13758 do { 13759 // Only block literals, captured statements, and lambda expressions can 13760 // capture; other scopes don't work. 13761 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 13762 ExprLoc, 13763 BuildAndDiagnose, 13764 *this); 13765 // We need to check for the parent *first* because, if we *have* 13766 // private-captured a global variable, we need to recursively capture it in 13767 // intermediate blocks, lambdas, etc. 13768 if (!ParentDC) { 13769 if (IsGlobal) { 13770 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 13771 break; 13772 } 13773 return true; 13774 } 13775 13776 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 13777 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 13778 13779 13780 // Check whether we've already captured it. 13781 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 13782 DeclRefType)) 13783 break; 13784 // If we are instantiating a generic lambda call operator body, 13785 // we do not want to capture new variables. What was captured 13786 // during either a lambdas transformation or initial parsing 13787 // should be used. 13788 if (isGenericLambdaCallOperatorSpecialization(DC)) { 13789 if (BuildAndDiagnose) { 13790 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 13791 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 13792 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 13793 Diag(Var->getLocation(), diag::note_previous_decl) 13794 << Var->getDeclName(); 13795 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); 13796 } else 13797 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 13798 } 13799 return true; 13800 } 13801 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 13802 // certain types of variables (unnamed, variably modified types etc.) 13803 // so check for eligibility. 13804 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 13805 return true; 13806 13807 // Try to capture variable-length arrays types. 13808 if (Var->getType()->isVariablyModifiedType()) { 13809 // We're going to walk down into the type and look for VLA 13810 // expressions. 13811 QualType QTy = Var->getType(); 13812 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 13813 QTy = PVD->getOriginalType(); 13814 captureVariablyModifiedType(Context, QTy, CSI); 13815 } 13816 13817 if (getLangOpts().OpenMP) { 13818 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13819 // OpenMP private variables should not be captured in outer scope, so 13820 // just break here. Similarly, global variables that are captured in a 13821 // target region should not be captured outside the scope of the region. 13822 if (RSI->CapRegionKind == CR_OpenMP) { 13823 auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 13824 // When we detect target captures we are looking from inside the 13825 // target region, therefore we need to propagate the capture from the 13826 // enclosing region. Therefore, the capture is not initially nested. 13827 if (IsTargetCap) 13828 FunctionScopesIndex--; 13829 13830 if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) { 13831 Nested = !IsTargetCap; 13832 DeclRefType = DeclRefType.getUnqualifiedType(); 13833 CaptureType = Context.getLValueReferenceType(DeclRefType); 13834 break; 13835 } 13836 } 13837 } 13838 } 13839 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 13840 // No capture-default, and this is not an explicit capture 13841 // so cannot capture this variable. 13842 if (BuildAndDiagnose) { 13843 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 13844 Diag(Var->getLocation(), diag::note_previous_decl) 13845 << Var->getDeclName(); 13846 if (cast<LambdaScopeInfo>(CSI)->Lambda) 13847 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 13848 diag::note_lambda_decl); 13849 // FIXME: If we error out because an outer lambda can not implicitly 13850 // capture a variable that an inner lambda explicitly captures, we 13851 // should have the inner lambda do the explicit capture - because 13852 // it makes for cleaner diagnostics later. This would purely be done 13853 // so that the diagnostic does not misleadingly claim that a variable 13854 // can not be captured by a lambda implicitly even though it is captured 13855 // explicitly. Suggestion: 13856 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 13857 // at the function head 13858 // - cache the StartingDeclContext - this must be a lambda 13859 // - captureInLambda in the innermost lambda the variable. 13860 } 13861 return true; 13862 } 13863 13864 FunctionScopesIndex--; 13865 DC = ParentDC; 13866 Explicit = false; 13867 } while (!VarDC->Equals(DC)); 13868 13869 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 13870 // computing the type of the capture at each step, checking type-specific 13871 // requirements, and adding captures if requested. 13872 // If the variable had already been captured previously, we start capturing 13873 // at the lambda nested within that one. 13874 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 13875 ++I) { 13876 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 13877 13878 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 13879 if (!captureInBlock(BSI, Var, ExprLoc, 13880 BuildAndDiagnose, CaptureType, 13881 DeclRefType, Nested, *this)) 13882 return true; 13883 Nested = true; 13884 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13885 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 13886 BuildAndDiagnose, CaptureType, 13887 DeclRefType, Nested, *this)) 13888 return true; 13889 Nested = true; 13890 } else { 13891 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 13892 if (!captureInLambda(LSI, Var, ExprLoc, 13893 BuildAndDiagnose, CaptureType, 13894 DeclRefType, Nested, Kind, EllipsisLoc, 13895 /*IsTopScope*/I == N - 1, *this)) 13896 return true; 13897 Nested = true; 13898 } 13899 } 13900 return false; 13901 } 13902 13903 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 13904 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 13905 QualType CaptureType; 13906 QualType DeclRefType; 13907 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 13908 /*BuildAndDiagnose=*/true, CaptureType, 13909 DeclRefType, nullptr); 13910 } 13911 13912 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 13913 QualType CaptureType; 13914 QualType DeclRefType; 13915 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 13916 /*BuildAndDiagnose=*/false, CaptureType, 13917 DeclRefType, nullptr); 13918 } 13919 13920 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 13921 QualType CaptureType; 13922 QualType DeclRefType; 13923 13924 // Determine whether we can capture this variable. 13925 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 13926 /*BuildAndDiagnose=*/false, CaptureType, 13927 DeclRefType, nullptr)) 13928 return QualType(); 13929 13930 return DeclRefType; 13931 } 13932 13933 13934 13935 // If either the type of the variable or the initializer is dependent, 13936 // return false. Otherwise, determine whether the variable is a constant 13937 // expression. Use this if you need to know if a variable that might or 13938 // might not be dependent is truly a constant expression. 13939 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 13940 ASTContext &Context) { 13941 13942 if (Var->getType()->isDependentType()) 13943 return false; 13944 const VarDecl *DefVD = nullptr; 13945 Var->getAnyInitializer(DefVD); 13946 if (!DefVD) 13947 return false; 13948 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 13949 Expr *Init = cast<Expr>(Eval->Value); 13950 if (Init->isValueDependent()) 13951 return false; 13952 return IsVariableAConstantExpression(Var, Context); 13953 } 13954 13955 13956 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 13957 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 13958 // an object that satisfies the requirements for appearing in a 13959 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 13960 // is immediately applied." This function handles the lvalue-to-rvalue 13961 // conversion part. 13962 MaybeODRUseExprs.erase(E->IgnoreParens()); 13963 13964 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 13965 // to a variable that is a constant expression, and if so, identify it as 13966 // a reference to a variable that does not involve an odr-use of that 13967 // variable. 13968 if (LambdaScopeInfo *LSI = getCurLambda()) { 13969 Expr *SansParensExpr = E->IgnoreParens(); 13970 VarDecl *Var = nullptr; 13971 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 13972 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 13973 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 13974 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 13975 13976 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 13977 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 13978 } 13979 } 13980 13981 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 13982 Res = CorrectDelayedTyposInExpr(Res); 13983 13984 if (!Res.isUsable()) 13985 return Res; 13986 13987 // If a constant-expression is a reference to a variable where we delay 13988 // deciding whether it is an odr-use, just assume we will apply the 13989 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 13990 // (a non-type template argument), we have special handling anyway. 13991 UpdateMarkingForLValueToRValue(Res.get()); 13992 return Res; 13993 } 13994 13995 void Sema::CleanupVarDeclMarking() { 13996 for (Expr *E : MaybeODRUseExprs) { 13997 VarDecl *Var; 13998 SourceLocation Loc; 13999 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 14000 Var = cast<VarDecl>(DRE->getDecl()); 14001 Loc = DRE->getLocation(); 14002 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 14003 Var = cast<VarDecl>(ME->getMemberDecl()); 14004 Loc = ME->getMemberLoc(); 14005 } else { 14006 llvm_unreachable("Unexpected expression"); 14007 } 14008 14009 MarkVarDeclODRUsed(Var, Loc, *this, 14010 /*MaxFunctionScopeIndex Pointer*/ nullptr); 14011 } 14012 14013 MaybeODRUseExprs.clear(); 14014 } 14015 14016 14017 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 14018 VarDecl *Var, Expr *E) { 14019 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 14020 "Invalid Expr argument to DoMarkVarDeclReferenced"); 14021 Var->setReferenced(); 14022 14023 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 14024 bool MarkODRUsed = true; 14025 14026 // If the context is not potentially evaluated, this is not an odr-use and 14027 // does not trigger instantiation. 14028 if (!IsPotentiallyEvaluatedContext(SemaRef)) { 14029 if (SemaRef.isUnevaluatedContext()) 14030 return; 14031 14032 // If we don't yet know whether this context is going to end up being an 14033 // evaluated context, and we're referencing a variable from an enclosing 14034 // scope, add a potential capture. 14035 // 14036 // FIXME: Is this necessary? These contexts are only used for default 14037 // arguments, where local variables can't be used. 14038 const bool RefersToEnclosingScope = 14039 (SemaRef.CurContext != Var->getDeclContext() && 14040 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 14041 if (RefersToEnclosingScope) { 14042 if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) { 14043 // If a variable could potentially be odr-used, defer marking it so 14044 // until we finish analyzing the full expression for any 14045 // lvalue-to-rvalue 14046 // or discarded value conversions that would obviate odr-use. 14047 // Add it to the list of potential captures that will be analyzed 14048 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 14049 // unless the variable is a reference that was initialized by a constant 14050 // expression (this will never need to be captured or odr-used). 14051 assert(E && "Capture variable should be used in an expression."); 14052 if (!Var->getType()->isReferenceType() || 14053 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 14054 LSI->addPotentialCapture(E->IgnoreParens()); 14055 } 14056 } 14057 14058 if (!isTemplateInstantiation(TSK)) 14059 return; 14060 14061 // Instantiate, but do not mark as odr-used, variable templates. 14062 MarkODRUsed = false; 14063 } 14064 14065 VarTemplateSpecializationDecl *VarSpec = 14066 dyn_cast<VarTemplateSpecializationDecl>(Var); 14067 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 14068 "Can't instantiate a partial template specialization."); 14069 14070 // If this might be a member specialization of a static data member, check 14071 // the specialization is visible. We already did the checks for variable 14072 // template specializations when we created them. 14073 if (TSK != TSK_Undeclared && !isa<VarTemplateSpecializationDecl>(Var)) 14074 SemaRef.checkSpecializationVisibility(Loc, Var); 14075 14076 // Perform implicit instantiation of static data members, static data member 14077 // templates of class templates, and variable template specializations. Delay 14078 // instantiations of variable templates, except for those that could be used 14079 // in a constant expression. 14080 if (isTemplateInstantiation(TSK)) { 14081 bool TryInstantiating = TSK == TSK_ImplicitInstantiation; 14082 14083 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) { 14084 if (Var->getPointOfInstantiation().isInvalid()) { 14085 // This is a modification of an existing AST node. Notify listeners. 14086 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 14087 L->StaticDataMemberInstantiated(Var); 14088 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context)) 14089 // Don't bother trying to instantiate it again, unless we might need 14090 // its initializer before we get to the end of the TU. 14091 TryInstantiating = false; 14092 } 14093 14094 if (Var->getPointOfInstantiation().isInvalid()) 14095 Var->setTemplateSpecializationKind(TSK, Loc); 14096 14097 if (TryInstantiating) { 14098 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 14099 bool InstantiationDependent = false; 14100 bool IsNonDependent = 14101 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 14102 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 14103 : true; 14104 14105 // Do not instantiate specializations that are still type-dependent. 14106 if (IsNonDependent) { 14107 if (Var->isUsableInConstantExpressions(SemaRef.Context)) { 14108 // Do not defer instantiations of variables which could be used in a 14109 // constant expression. 14110 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 14111 } else { 14112 SemaRef.PendingInstantiations 14113 .push_back(std::make_pair(Var, PointOfInstantiation)); 14114 } 14115 } 14116 } 14117 } 14118 14119 if (!MarkODRUsed) 14120 return; 14121 14122 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 14123 // the requirements for appearing in a constant expression (5.19) and, if 14124 // it is an object, the lvalue-to-rvalue conversion (4.1) 14125 // is immediately applied." We check the first part here, and 14126 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 14127 // Note that we use the C++11 definition everywhere because nothing in 14128 // C++03 depends on whether we get the C++03 version correct. The second 14129 // part does not apply to references, since they are not objects. 14130 if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) { 14131 // A reference initialized by a constant expression can never be 14132 // odr-used, so simply ignore it. 14133 if (!Var->getType()->isReferenceType()) 14134 SemaRef.MaybeODRUseExprs.insert(E); 14135 } else 14136 MarkVarDeclODRUsed(Var, Loc, SemaRef, 14137 /*MaxFunctionScopeIndex ptr*/ nullptr); 14138 } 14139 14140 /// \brief Mark a variable referenced, and check whether it is odr-used 14141 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 14142 /// used directly for normal expressions referring to VarDecl. 14143 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 14144 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 14145 } 14146 14147 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 14148 Decl *D, Expr *E, bool MightBeOdrUse) { 14149 if (SemaRef.isInOpenMPDeclareTargetContext()) 14150 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 14151 14152 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 14153 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 14154 return; 14155 } 14156 14157 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 14158 14159 // If this is a call to a method via a cast, also mark the method in the 14160 // derived class used in case codegen can devirtualize the call. 14161 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 14162 if (!ME) 14163 return; 14164 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 14165 if (!MD) 14166 return; 14167 // Only attempt to devirtualize if this is truly a virtual call. 14168 bool IsVirtualCall = MD->isVirtual() && 14169 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 14170 if (!IsVirtualCall) 14171 return; 14172 const Expr *Base = ME->getBase(); 14173 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType(); 14174 if (!MostDerivedClassDecl) 14175 return; 14176 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl); 14177 if (!DM || DM->isPure()) 14178 return; 14179 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 14180 } 14181 14182 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 14183 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) { 14184 // TODO: update this with DR# once a defect report is filed. 14185 // C++11 defect. The address of a pure member should not be an ODR use, even 14186 // if it's a qualified reference. 14187 bool OdrUse = true; 14188 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 14189 if (Method->isVirtual()) 14190 OdrUse = false; 14191 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 14192 } 14193 14194 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 14195 void Sema::MarkMemberReferenced(MemberExpr *E) { 14196 // C++11 [basic.def.odr]p2: 14197 // A non-overloaded function whose name appears as a potentially-evaluated 14198 // expression or a member of a set of candidate functions, if selected by 14199 // overload resolution when referred to from a potentially-evaluated 14200 // expression, is odr-used, unless it is a pure virtual function and its 14201 // name is not explicitly qualified. 14202 bool MightBeOdrUse = true; 14203 if (E->performsVirtualDispatch(getLangOpts())) { 14204 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 14205 if (Method->isPure()) 14206 MightBeOdrUse = false; 14207 } 14208 SourceLocation Loc = E->getMemberLoc().isValid() ? 14209 E->getMemberLoc() : E->getLocStart(); 14210 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 14211 } 14212 14213 /// \brief Perform marking for a reference to an arbitrary declaration. It 14214 /// marks the declaration referenced, and performs odr-use checking for 14215 /// functions and variables. This method should not be used when building a 14216 /// normal expression which refers to a variable. 14217 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 14218 bool MightBeOdrUse) { 14219 if (MightBeOdrUse) { 14220 if (auto *VD = dyn_cast<VarDecl>(D)) { 14221 MarkVariableReferenced(Loc, VD); 14222 return; 14223 } 14224 } 14225 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 14226 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 14227 return; 14228 } 14229 D->setReferenced(); 14230 } 14231 14232 namespace { 14233 // Mark all of the declarations referenced 14234 // FIXME: Not fully implemented yet! We need to have a better understanding 14235 // of when we're entering 14236 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 14237 Sema &S; 14238 SourceLocation Loc; 14239 14240 public: 14241 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 14242 14243 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 14244 14245 bool TraverseTemplateArgument(const TemplateArgument &Arg); 14246 bool TraverseRecordType(RecordType *T); 14247 }; 14248 } 14249 14250 bool MarkReferencedDecls::TraverseTemplateArgument( 14251 const TemplateArgument &Arg) { 14252 if (Arg.getKind() == TemplateArgument::Declaration) { 14253 if (Decl *D = Arg.getAsDecl()) 14254 S.MarkAnyDeclReferenced(Loc, D, true); 14255 } 14256 14257 return Inherited::TraverseTemplateArgument(Arg); 14258 } 14259 14260 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) { 14261 if (ClassTemplateSpecializationDecl *Spec 14262 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) { 14263 const TemplateArgumentList &Args = Spec->getTemplateArgs(); 14264 return TraverseTemplateArguments(Args.data(), Args.size()); 14265 } 14266 14267 return true; 14268 } 14269 14270 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 14271 MarkReferencedDecls Marker(*this, Loc); 14272 Marker.TraverseType(Context.getCanonicalType(T)); 14273 } 14274 14275 namespace { 14276 /// \brief Helper class that marks all of the declarations referenced by 14277 /// potentially-evaluated subexpressions as "referenced". 14278 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 14279 Sema &S; 14280 bool SkipLocalVariables; 14281 14282 public: 14283 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 14284 14285 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 14286 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 14287 14288 void VisitDeclRefExpr(DeclRefExpr *E) { 14289 // If we were asked not to visit local variables, don't. 14290 if (SkipLocalVariables) { 14291 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 14292 if (VD->hasLocalStorage()) 14293 return; 14294 } 14295 14296 S.MarkDeclRefReferenced(E); 14297 } 14298 14299 void VisitMemberExpr(MemberExpr *E) { 14300 S.MarkMemberReferenced(E); 14301 Inherited::VisitMemberExpr(E); 14302 } 14303 14304 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 14305 S.MarkFunctionReferenced(E->getLocStart(), 14306 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 14307 Visit(E->getSubExpr()); 14308 } 14309 14310 void VisitCXXNewExpr(CXXNewExpr *E) { 14311 if (E->getOperatorNew()) 14312 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 14313 if (E->getOperatorDelete()) 14314 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 14315 Inherited::VisitCXXNewExpr(E); 14316 } 14317 14318 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 14319 if (E->getOperatorDelete()) 14320 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 14321 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 14322 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 14323 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 14324 S.MarkFunctionReferenced(E->getLocStart(), 14325 S.LookupDestructor(Record)); 14326 } 14327 14328 Inherited::VisitCXXDeleteExpr(E); 14329 } 14330 14331 void VisitCXXConstructExpr(CXXConstructExpr *E) { 14332 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 14333 Inherited::VisitCXXConstructExpr(E); 14334 } 14335 14336 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 14337 Visit(E->getExpr()); 14338 } 14339 14340 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 14341 Inherited::VisitImplicitCastExpr(E); 14342 14343 if (E->getCastKind() == CK_LValueToRValue) 14344 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 14345 } 14346 }; 14347 } 14348 14349 /// \brief Mark any declarations that appear within this expression or any 14350 /// potentially-evaluated subexpressions as "referenced". 14351 /// 14352 /// \param SkipLocalVariables If true, don't mark local variables as 14353 /// 'referenced'. 14354 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 14355 bool SkipLocalVariables) { 14356 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 14357 } 14358 14359 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 14360 /// of the program being compiled. 14361 /// 14362 /// This routine emits the given diagnostic when the code currently being 14363 /// type-checked is "potentially evaluated", meaning that there is a 14364 /// possibility that the code will actually be executable. Code in sizeof() 14365 /// expressions, code used only during overload resolution, etc., are not 14366 /// potentially evaluated. This routine will suppress such diagnostics or, 14367 /// in the absolutely nutty case of potentially potentially evaluated 14368 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 14369 /// later. 14370 /// 14371 /// This routine should be used for all diagnostics that describe the run-time 14372 /// behavior of a program, such as passing a non-POD value through an ellipsis. 14373 /// Failure to do so will likely result in spurious diagnostics or failures 14374 /// during overload resolution or within sizeof/alignof/typeof/typeid. 14375 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 14376 const PartialDiagnostic &PD) { 14377 switch (ExprEvalContexts.back().Context) { 14378 case Unevaluated: 14379 case UnevaluatedAbstract: 14380 case DiscardedStatement: 14381 // The argument will never be evaluated, so don't complain. 14382 break; 14383 14384 case ConstantEvaluated: 14385 // Relevant diagnostics should be produced by constant evaluation. 14386 break; 14387 14388 case PotentiallyEvaluated: 14389 case PotentiallyEvaluatedIfUsed: 14390 if (Statement && getCurFunctionOrMethodDecl()) { 14391 FunctionScopes.back()->PossiblyUnreachableDiags. 14392 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 14393 } 14394 else 14395 Diag(Loc, PD); 14396 14397 return true; 14398 } 14399 14400 return false; 14401 } 14402 14403 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 14404 CallExpr *CE, FunctionDecl *FD) { 14405 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 14406 return false; 14407 14408 // If we're inside a decltype's expression, don't check for a valid return 14409 // type or construct temporaries until we know whether this is the last call. 14410 if (ExprEvalContexts.back().IsDecltype) { 14411 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 14412 return false; 14413 } 14414 14415 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 14416 FunctionDecl *FD; 14417 CallExpr *CE; 14418 14419 public: 14420 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 14421 : FD(FD), CE(CE) { } 14422 14423 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 14424 if (!FD) { 14425 S.Diag(Loc, diag::err_call_incomplete_return) 14426 << T << CE->getSourceRange(); 14427 return; 14428 } 14429 14430 S.Diag(Loc, diag::err_call_function_incomplete_return) 14431 << CE->getSourceRange() << FD->getDeclName() << T; 14432 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 14433 << FD->getDeclName(); 14434 } 14435 } Diagnoser(FD, CE); 14436 14437 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 14438 return true; 14439 14440 return false; 14441 } 14442 14443 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 14444 // will prevent this condition from triggering, which is what we want. 14445 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 14446 SourceLocation Loc; 14447 14448 unsigned diagnostic = diag::warn_condition_is_assignment; 14449 bool IsOrAssign = false; 14450 14451 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 14452 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 14453 return; 14454 14455 IsOrAssign = Op->getOpcode() == BO_OrAssign; 14456 14457 // Greylist some idioms by putting them into a warning subcategory. 14458 if (ObjCMessageExpr *ME 14459 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 14460 Selector Sel = ME->getSelector(); 14461 14462 // self = [<foo> init...] 14463 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 14464 diagnostic = diag::warn_condition_is_idiomatic_assignment; 14465 14466 // <foo> = [<bar> nextObject] 14467 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 14468 diagnostic = diag::warn_condition_is_idiomatic_assignment; 14469 } 14470 14471 Loc = Op->getOperatorLoc(); 14472 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 14473 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 14474 return; 14475 14476 IsOrAssign = Op->getOperator() == OO_PipeEqual; 14477 Loc = Op->getOperatorLoc(); 14478 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 14479 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 14480 else { 14481 // Not an assignment. 14482 return; 14483 } 14484 14485 Diag(Loc, diagnostic) << E->getSourceRange(); 14486 14487 SourceLocation Open = E->getLocStart(); 14488 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 14489 Diag(Loc, diag::note_condition_assign_silence) 14490 << FixItHint::CreateInsertion(Open, "(") 14491 << FixItHint::CreateInsertion(Close, ")"); 14492 14493 if (IsOrAssign) 14494 Diag(Loc, diag::note_condition_or_assign_to_comparison) 14495 << FixItHint::CreateReplacement(Loc, "!="); 14496 else 14497 Diag(Loc, diag::note_condition_assign_to_comparison) 14498 << FixItHint::CreateReplacement(Loc, "=="); 14499 } 14500 14501 /// \brief Redundant parentheses over an equality comparison can indicate 14502 /// that the user intended an assignment used as condition. 14503 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 14504 // Don't warn if the parens came from a macro. 14505 SourceLocation parenLoc = ParenE->getLocStart(); 14506 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 14507 return; 14508 // Don't warn for dependent expressions. 14509 if (ParenE->isTypeDependent()) 14510 return; 14511 14512 Expr *E = ParenE->IgnoreParens(); 14513 14514 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 14515 if (opE->getOpcode() == BO_EQ && 14516 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 14517 == Expr::MLV_Valid) { 14518 SourceLocation Loc = opE->getOperatorLoc(); 14519 14520 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 14521 SourceRange ParenERange = ParenE->getSourceRange(); 14522 Diag(Loc, diag::note_equality_comparison_silence) 14523 << FixItHint::CreateRemoval(ParenERange.getBegin()) 14524 << FixItHint::CreateRemoval(ParenERange.getEnd()); 14525 Diag(Loc, diag::note_equality_comparison_to_assign) 14526 << FixItHint::CreateReplacement(Loc, "="); 14527 } 14528 } 14529 14530 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 14531 bool IsConstexpr) { 14532 DiagnoseAssignmentAsCondition(E); 14533 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 14534 DiagnoseEqualityWithExtraParens(parenE); 14535 14536 ExprResult result = CheckPlaceholderExpr(E); 14537 if (result.isInvalid()) return ExprError(); 14538 E = result.get(); 14539 14540 if (!E->isTypeDependent()) { 14541 if (getLangOpts().CPlusPlus) 14542 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 14543 14544 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 14545 if (ERes.isInvalid()) 14546 return ExprError(); 14547 E = ERes.get(); 14548 14549 QualType T = E->getType(); 14550 if (!T->isScalarType()) { // C99 6.8.4.1p1 14551 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 14552 << T << E->getSourceRange(); 14553 return ExprError(); 14554 } 14555 CheckBoolLikeConversion(E, Loc); 14556 } 14557 14558 return E; 14559 } 14560 14561 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 14562 Expr *SubExpr, ConditionKind CK) { 14563 // Empty conditions are valid in for-statements. 14564 if (!SubExpr) 14565 return ConditionResult(); 14566 14567 ExprResult Cond; 14568 switch (CK) { 14569 case ConditionKind::Boolean: 14570 Cond = CheckBooleanCondition(Loc, SubExpr); 14571 break; 14572 14573 case ConditionKind::ConstexprIf: 14574 Cond = CheckBooleanCondition(Loc, SubExpr, true); 14575 break; 14576 14577 case ConditionKind::Switch: 14578 Cond = CheckSwitchCondition(Loc, SubExpr); 14579 break; 14580 } 14581 if (Cond.isInvalid()) 14582 return ConditionError(); 14583 14584 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 14585 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 14586 if (!FullExpr.get()) 14587 return ConditionError(); 14588 14589 return ConditionResult(*this, nullptr, FullExpr, 14590 CK == ConditionKind::ConstexprIf); 14591 } 14592 14593 namespace { 14594 /// A visitor for rebuilding a call to an __unknown_any expression 14595 /// to have an appropriate type. 14596 struct RebuildUnknownAnyFunction 14597 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 14598 14599 Sema &S; 14600 14601 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 14602 14603 ExprResult VisitStmt(Stmt *S) { 14604 llvm_unreachable("unexpected statement!"); 14605 } 14606 14607 ExprResult VisitExpr(Expr *E) { 14608 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 14609 << E->getSourceRange(); 14610 return ExprError(); 14611 } 14612 14613 /// Rebuild an expression which simply semantically wraps another 14614 /// expression which it shares the type and value kind of. 14615 template <class T> ExprResult rebuildSugarExpr(T *E) { 14616 ExprResult SubResult = Visit(E->getSubExpr()); 14617 if (SubResult.isInvalid()) return ExprError(); 14618 14619 Expr *SubExpr = SubResult.get(); 14620 E->setSubExpr(SubExpr); 14621 E->setType(SubExpr->getType()); 14622 E->setValueKind(SubExpr->getValueKind()); 14623 assert(E->getObjectKind() == OK_Ordinary); 14624 return E; 14625 } 14626 14627 ExprResult VisitParenExpr(ParenExpr *E) { 14628 return rebuildSugarExpr(E); 14629 } 14630 14631 ExprResult VisitUnaryExtension(UnaryOperator *E) { 14632 return rebuildSugarExpr(E); 14633 } 14634 14635 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 14636 ExprResult SubResult = Visit(E->getSubExpr()); 14637 if (SubResult.isInvalid()) return ExprError(); 14638 14639 Expr *SubExpr = SubResult.get(); 14640 E->setSubExpr(SubExpr); 14641 E->setType(S.Context.getPointerType(SubExpr->getType())); 14642 assert(E->getValueKind() == VK_RValue); 14643 assert(E->getObjectKind() == OK_Ordinary); 14644 return E; 14645 } 14646 14647 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 14648 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 14649 14650 E->setType(VD->getType()); 14651 14652 assert(E->getValueKind() == VK_RValue); 14653 if (S.getLangOpts().CPlusPlus && 14654 !(isa<CXXMethodDecl>(VD) && 14655 cast<CXXMethodDecl>(VD)->isInstance())) 14656 E->setValueKind(VK_LValue); 14657 14658 return E; 14659 } 14660 14661 ExprResult VisitMemberExpr(MemberExpr *E) { 14662 return resolveDecl(E, E->getMemberDecl()); 14663 } 14664 14665 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 14666 return resolveDecl(E, E->getDecl()); 14667 } 14668 }; 14669 } 14670 14671 /// Given a function expression of unknown-any type, try to rebuild it 14672 /// to have a function type. 14673 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 14674 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 14675 if (Result.isInvalid()) return ExprError(); 14676 return S.DefaultFunctionArrayConversion(Result.get()); 14677 } 14678 14679 namespace { 14680 /// A visitor for rebuilding an expression of type __unknown_anytype 14681 /// into one which resolves the type directly on the referring 14682 /// expression. Strict preservation of the original source 14683 /// structure is not a goal. 14684 struct RebuildUnknownAnyExpr 14685 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 14686 14687 Sema &S; 14688 14689 /// The current destination type. 14690 QualType DestType; 14691 14692 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 14693 : S(S), DestType(CastType) {} 14694 14695 ExprResult VisitStmt(Stmt *S) { 14696 llvm_unreachable("unexpected statement!"); 14697 } 14698 14699 ExprResult VisitExpr(Expr *E) { 14700 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 14701 << E->getSourceRange(); 14702 return ExprError(); 14703 } 14704 14705 ExprResult VisitCallExpr(CallExpr *E); 14706 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 14707 14708 /// Rebuild an expression which simply semantically wraps another 14709 /// expression which it shares the type and value kind of. 14710 template <class T> ExprResult rebuildSugarExpr(T *E) { 14711 ExprResult SubResult = Visit(E->getSubExpr()); 14712 if (SubResult.isInvalid()) return ExprError(); 14713 Expr *SubExpr = SubResult.get(); 14714 E->setSubExpr(SubExpr); 14715 E->setType(SubExpr->getType()); 14716 E->setValueKind(SubExpr->getValueKind()); 14717 assert(E->getObjectKind() == OK_Ordinary); 14718 return E; 14719 } 14720 14721 ExprResult VisitParenExpr(ParenExpr *E) { 14722 return rebuildSugarExpr(E); 14723 } 14724 14725 ExprResult VisitUnaryExtension(UnaryOperator *E) { 14726 return rebuildSugarExpr(E); 14727 } 14728 14729 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 14730 const PointerType *Ptr = DestType->getAs<PointerType>(); 14731 if (!Ptr) { 14732 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 14733 << E->getSourceRange(); 14734 return ExprError(); 14735 } 14736 assert(E->getValueKind() == VK_RValue); 14737 assert(E->getObjectKind() == OK_Ordinary); 14738 E->setType(DestType); 14739 14740 // Build the sub-expression as if it were an object of the pointee type. 14741 DestType = Ptr->getPointeeType(); 14742 ExprResult SubResult = Visit(E->getSubExpr()); 14743 if (SubResult.isInvalid()) return ExprError(); 14744 E->setSubExpr(SubResult.get()); 14745 return E; 14746 } 14747 14748 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 14749 14750 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 14751 14752 ExprResult VisitMemberExpr(MemberExpr *E) { 14753 return resolveDecl(E, E->getMemberDecl()); 14754 } 14755 14756 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 14757 return resolveDecl(E, E->getDecl()); 14758 } 14759 }; 14760 } 14761 14762 /// Rebuilds a call expression which yielded __unknown_anytype. 14763 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 14764 Expr *CalleeExpr = E->getCallee(); 14765 14766 enum FnKind { 14767 FK_MemberFunction, 14768 FK_FunctionPointer, 14769 FK_BlockPointer 14770 }; 14771 14772 FnKind Kind; 14773 QualType CalleeType = CalleeExpr->getType(); 14774 if (CalleeType == S.Context.BoundMemberTy) { 14775 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 14776 Kind = FK_MemberFunction; 14777 CalleeType = Expr::findBoundMemberType(CalleeExpr); 14778 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 14779 CalleeType = Ptr->getPointeeType(); 14780 Kind = FK_FunctionPointer; 14781 } else { 14782 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 14783 Kind = FK_BlockPointer; 14784 } 14785 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 14786 14787 // Verify that this is a legal result type of a function. 14788 if (DestType->isArrayType() || DestType->isFunctionType()) { 14789 unsigned diagID = diag::err_func_returning_array_function; 14790 if (Kind == FK_BlockPointer) 14791 diagID = diag::err_block_returning_array_function; 14792 14793 S.Diag(E->getExprLoc(), diagID) 14794 << DestType->isFunctionType() << DestType; 14795 return ExprError(); 14796 } 14797 14798 // Otherwise, go ahead and set DestType as the call's result. 14799 E->setType(DestType.getNonLValueExprType(S.Context)); 14800 E->setValueKind(Expr::getValueKindForType(DestType)); 14801 assert(E->getObjectKind() == OK_Ordinary); 14802 14803 // Rebuild the function type, replacing the result type with DestType. 14804 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 14805 if (Proto) { 14806 // __unknown_anytype(...) is a special case used by the debugger when 14807 // it has no idea what a function's signature is. 14808 // 14809 // We want to build this call essentially under the K&R 14810 // unprototyped rules, but making a FunctionNoProtoType in C++ 14811 // would foul up all sorts of assumptions. However, we cannot 14812 // simply pass all arguments as variadic arguments, nor can we 14813 // portably just call the function under a non-variadic type; see 14814 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 14815 // However, it turns out that in practice it is generally safe to 14816 // call a function declared as "A foo(B,C,D);" under the prototype 14817 // "A foo(B,C,D,...);". The only known exception is with the 14818 // Windows ABI, where any variadic function is implicitly cdecl 14819 // regardless of its normal CC. Therefore we change the parameter 14820 // types to match the types of the arguments. 14821 // 14822 // This is a hack, but it is far superior to moving the 14823 // corresponding target-specific code from IR-gen to Sema/AST. 14824 14825 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 14826 SmallVector<QualType, 8> ArgTypes; 14827 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 14828 ArgTypes.reserve(E->getNumArgs()); 14829 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 14830 Expr *Arg = E->getArg(i); 14831 QualType ArgType = Arg->getType(); 14832 if (E->isLValue()) { 14833 ArgType = S.Context.getLValueReferenceType(ArgType); 14834 } else if (E->isXValue()) { 14835 ArgType = S.Context.getRValueReferenceType(ArgType); 14836 } 14837 ArgTypes.push_back(ArgType); 14838 } 14839 ParamTypes = ArgTypes; 14840 } 14841 DestType = S.Context.getFunctionType(DestType, ParamTypes, 14842 Proto->getExtProtoInfo()); 14843 } else { 14844 DestType = S.Context.getFunctionNoProtoType(DestType, 14845 FnType->getExtInfo()); 14846 } 14847 14848 // Rebuild the appropriate pointer-to-function type. 14849 switch (Kind) { 14850 case FK_MemberFunction: 14851 // Nothing to do. 14852 break; 14853 14854 case FK_FunctionPointer: 14855 DestType = S.Context.getPointerType(DestType); 14856 break; 14857 14858 case FK_BlockPointer: 14859 DestType = S.Context.getBlockPointerType(DestType); 14860 break; 14861 } 14862 14863 // Finally, we can recurse. 14864 ExprResult CalleeResult = Visit(CalleeExpr); 14865 if (!CalleeResult.isUsable()) return ExprError(); 14866 E->setCallee(CalleeResult.get()); 14867 14868 // Bind a temporary if necessary. 14869 return S.MaybeBindToTemporary(E); 14870 } 14871 14872 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 14873 // Verify that this is a legal result type of a call. 14874 if (DestType->isArrayType() || DestType->isFunctionType()) { 14875 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 14876 << DestType->isFunctionType() << DestType; 14877 return ExprError(); 14878 } 14879 14880 // Rewrite the method result type if available. 14881 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 14882 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 14883 Method->setReturnType(DestType); 14884 } 14885 14886 // Change the type of the message. 14887 E->setType(DestType.getNonReferenceType()); 14888 E->setValueKind(Expr::getValueKindForType(DestType)); 14889 14890 return S.MaybeBindToTemporary(E); 14891 } 14892 14893 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 14894 // The only case we should ever see here is a function-to-pointer decay. 14895 if (E->getCastKind() == CK_FunctionToPointerDecay) { 14896 assert(E->getValueKind() == VK_RValue); 14897 assert(E->getObjectKind() == OK_Ordinary); 14898 14899 E->setType(DestType); 14900 14901 // Rebuild the sub-expression as the pointee (function) type. 14902 DestType = DestType->castAs<PointerType>()->getPointeeType(); 14903 14904 ExprResult Result = Visit(E->getSubExpr()); 14905 if (!Result.isUsable()) return ExprError(); 14906 14907 E->setSubExpr(Result.get()); 14908 return E; 14909 } else if (E->getCastKind() == CK_LValueToRValue) { 14910 assert(E->getValueKind() == VK_RValue); 14911 assert(E->getObjectKind() == OK_Ordinary); 14912 14913 assert(isa<BlockPointerType>(E->getType())); 14914 14915 E->setType(DestType); 14916 14917 // The sub-expression has to be a lvalue reference, so rebuild it as such. 14918 DestType = S.Context.getLValueReferenceType(DestType); 14919 14920 ExprResult Result = Visit(E->getSubExpr()); 14921 if (!Result.isUsable()) return ExprError(); 14922 14923 E->setSubExpr(Result.get()); 14924 return E; 14925 } else { 14926 llvm_unreachable("Unhandled cast type!"); 14927 } 14928 } 14929 14930 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 14931 ExprValueKind ValueKind = VK_LValue; 14932 QualType Type = DestType; 14933 14934 // We know how to make this work for certain kinds of decls: 14935 14936 // - functions 14937 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 14938 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 14939 DestType = Ptr->getPointeeType(); 14940 ExprResult Result = resolveDecl(E, VD); 14941 if (Result.isInvalid()) return ExprError(); 14942 return S.ImpCastExprToType(Result.get(), Type, 14943 CK_FunctionToPointerDecay, VK_RValue); 14944 } 14945 14946 if (!Type->isFunctionType()) { 14947 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 14948 << VD << E->getSourceRange(); 14949 return ExprError(); 14950 } 14951 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 14952 // We must match the FunctionDecl's type to the hack introduced in 14953 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 14954 // type. See the lengthy commentary in that routine. 14955 QualType FDT = FD->getType(); 14956 const FunctionType *FnType = FDT->castAs<FunctionType>(); 14957 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 14958 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 14959 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 14960 SourceLocation Loc = FD->getLocation(); 14961 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(), 14962 FD->getDeclContext(), 14963 Loc, Loc, FD->getNameInfo().getName(), 14964 DestType, FD->getTypeSourceInfo(), 14965 SC_None, false/*isInlineSpecified*/, 14966 FD->hasPrototype(), 14967 false/*isConstexprSpecified*/); 14968 14969 if (FD->getQualifier()) 14970 NewFD->setQualifierInfo(FD->getQualifierLoc()); 14971 14972 SmallVector<ParmVarDecl*, 16> Params; 14973 for (const auto &AI : FT->param_types()) { 14974 ParmVarDecl *Param = 14975 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 14976 Param->setScopeInfo(0, Params.size()); 14977 Params.push_back(Param); 14978 } 14979 NewFD->setParams(Params); 14980 DRE->setDecl(NewFD); 14981 VD = DRE->getDecl(); 14982 } 14983 } 14984 14985 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 14986 if (MD->isInstance()) { 14987 ValueKind = VK_RValue; 14988 Type = S.Context.BoundMemberTy; 14989 } 14990 14991 // Function references aren't l-values in C. 14992 if (!S.getLangOpts().CPlusPlus) 14993 ValueKind = VK_RValue; 14994 14995 // - variables 14996 } else if (isa<VarDecl>(VD)) { 14997 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 14998 Type = RefTy->getPointeeType(); 14999 } else if (Type->isFunctionType()) { 15000 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 15001 << VD << E->getSourceRange(); 15002 return ExprError(); 15003 } 15004 15005 // - nothing else 15006 } else { 15007 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 15008 << VD << E->getSourceRange(); 15009 return ExprError(); 15010 } 15011 15012 // Modifying the declaration like this is friendly to IR-gen but 15013 // also really dangerous. 15014 VD->setType(DestType); 15015 E->setType(Type); 15016 E->setValueKind(ValueKind); 15017 return E; 15018 } 15019 15020 /// Check a cast of an unknown-any type. We intentionally only 15021 /// trigger this for C-style casts. 15022 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 15023 Expr *CastExpr, CastKind &CastKind, 15024 ExprValueKind &VK, CXXCastPath &Path) { 15025 // The type we're casting to must be either void or complete. 15026 if (!CastType->isVoidType() && 15027 RequireCompleteType(TypeRange.getBegin(), CastType, 15028 diag::err_typecheck_cast_to_incomplete)) 15029 return ExprError(); 15030 15031 // Rewrite the casted expression from scratch. 15032 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 15033 if (!result.isUsable()) return ExprError(); 15034 15035 CastExpr = result.get(); 15036 VK = CastExpr->getValueKind(); 15037 CastKind = CK_NoOp; 15038 15039 return CastExpr; 15040 } 15041 15042 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 15043 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 15044 } 15045 15046 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 15047 Expr *arg, QualType ¶mType) { 15048 // If the syntactic form of the argument is not an explicit cast of 15049 // any sort, just do default argument promotion. 15050 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 15051 if (!castArg) { 15052 ExprResult result = DefaultArgumentPromotion(arg); 15053 if (result.isInvalid()) return ExprError(); 15054 paramType = result.get()->getType(); 15055 return result; 15056 } 15057 15058 // Otherwise, use the type that was written in the explicit cast. 15059 assert(!arg->hasPlaceholderType()); 15060 paramType = castArg->getTypeAsWritten(); 15061 15062 // Copy-initialize a parameter of that type. 15063 InitializedEntity entity = 15064 InitializedEntity::InitializeParameter(Context, paramType, 15065 /*consumed*/ false); 15066 return PerformCopyInitialization(entity, callLoc, arg); 15067 } 15068 15069 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 15070 Expr *orig = E; 15071 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 15072 while (true) { 15073 E = E->IgnoreParenImpCasts(); 15074 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 15075 E = call->getCallee(); 15076 diagID = diag::err_uncasted_call_of_unknown_any; 15077 } else { 15078 break; 15079 } 15080 } 15081 15082 SourceLocation loc; 15083 NamedDecl *d; 15084 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 15085 loc = ref->getLocation(); 15086 d = ref->getDecl(); 15087 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 15088 loc = mem->getMemberLoc(); 15089 d = mem->getMemberDecl(); 15090 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 15091 diagID = diag::err_uncasted_call_of_unknown_any; 15092 loc = msg->getSelectorStartLoc(); 15093 d = msg->getMethodDecl(); 15094 if (!d) { 15095 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 15096 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 15097 << orig->getSourceRange(); 15098 return ExprError(); 15099 } 15100 } else { 15101 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 15102 << E->getSourceRange(); 15103 return ExprError(); 15104 } 15105 15106 S.Diag(loc, diagID) << d << orig->getSourceRange(); 15107 15108 // Never recoverable. 15109 return ExprError(); 15110 } 15111 15112 /// Check for operands with placeholder types and complain if found. 15113 /// Returns true if there was an error and no recovery was possible. 15114 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 15115 if (!getLangOpts().CPlusPlus) { 15116 // C cannot handle TypoExpr nodes on either side of a binop because it 15117 // doesn't handle dependent types properly, so make sure any TypoExprs have 15118 // been dealt with before checking the operands. 15119 ExprResult Result = CorrectDelayedTyposInExpr(E); 15120 if (!Result.isUsable()) return ExprError(); 15121 E = Result.get(); 15122 } 15123 15124 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 15125 if (!placeholderType) return E; 15126 15127 switch (placeholderType->getKind()) { 15128 15129 // Overloaded expressions. 15130 case BuiltinType::Overload: { 15131 // Try to resolve a single function template specialization. 15132 // This is obligatory. 15133 ExprResult Result = E; 15134 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 15135 return Result; 15136 15137 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 15138 // leaves Result unchanged on failure. 15139 Result = E; 15140 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) 15141 return Result; 15142 15143 // If that failed, try to recover with a call. 15144 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 15145 /*complain*/ true); 15146 return Result; 15147 } 15148 15149 // Bound member functions. 15150 case BuiltinType::BoundMember: { 15151 ExprResult result = E; 15152 const Expr *BME = E->IgnoreParens(); 15153 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 15154 // Try to give a nicer diagnostic if it is a bound member that we recognize. 15155 if (isa<CXXPseudoDestructorExpr>(BME)) { 15156 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 15157 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 15158 if (ME->getMemberNameInfo().getName().getNameKind() == 15159 DeclarationName::CXXDestructorName) 15160 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 15161 } 15162 tryToRecoverWithCall(result, PD, 15163 /*complain*/ true); 15164 return result; 15165 } 15166 15167 // ARC unbridged casts. 15168 case BuiltinType::ARCUnbridgedCast: { 15169 Expr *realCast = stripARCUnbridgedCast(E); 15170 diagnoseARCUnbridgedCast(realCast); 15171 return realCast; 15172 } 15173 15174 // Expressions of unknown type. 15175 case BuiltinType::UnknownAny: 15176 return diagnoseUnknownAnyExpr(*this, E); 15177 15178 // Pseudo-objects. 15179 case BuiltinType::PseudoObject: 15180 return checkPseudoObjectRValue(E); 15181 15182 case BuiltinType::BuiltinFn: { 15183 // Accept __noop without parens by implicitly converting it to a call expr. 15184 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 15185 if (DRE) { 15186 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 15187 if (FD->getBuiltinID() == Builtin::BI__noop) { 15188 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 15189 CK_BuiltinFnToFnPtr).get(); 15190 return new (Context) CallExpr(Context, E, None, Context.IntTy, 15191 VK_RValue, SourceLocation()); 15192 } 15193 } 15194 15195 Diag(E->getLocStart(), diag::err_builtin_fn_use); 15196 return ExprError(); 15197 } 15198 15199 // Expressions of unknown type. 15200 case BuiltinType::OMPArraySection: 15201 Diag(E->getLocStart(), diag::err_omp_array_section_use); 15202 return ExprError(); 15203 15204 // Everything else should be impossible. 15205 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 15206 case BuiltinType::Id: 15207 #include "clang/Basic/OpenCLImageTypes.def" 15208 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 15209 #define PLACEHOLDER_TYPE(Id, SingletonId) 15210 #include "clang/AST/BuiltinTypes.def" 15211 break; 15212 } 15213 15214 llvm_unreachable("invalid placeholder type!"); 15215 } 15216 15217 bool Sema::CheckCaseExpression(Expr *E) { 15218 if (E->isTypeDependent()) 15219 return true; 15220 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 15221 return E->getType()->isIntegralOrEnumerationType(); 15222 return false; 15223 } 15224 15225 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 15226 ExprResult 15227 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 15228 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 15229 "Unknown Objective-C Boolean value!"); 15230 QualType BoolT = Context.ObjCBuiltinBoolTy; 15231 if (!Context.getBOOLDecl()) { 15232 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 15233 Sema::LookupOrdinaryName); 15234 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 15235 NamedDecl *ND = Result.getFoundDecl(); 15236 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 15237 Context.setBOOLDecl(TD); 15238 } 15239 } 15240 if (Context.getBOOLDecl()) 15241 BoolT = Context.getBOOLType(); 15242 return new (Context) 15243 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 15244 } 15245 15246 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 15247 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 15248 SourceLocation RParen) { 15249 15250 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 15251 15252 auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(), 15253 [&](const AvailabilitySpec &Spec) { 15254 return Spec.getPlatform() == Platform; 15255 }); 15256 15257 VersionTuple Version; 15258 if (Spec != AvailSpecs.end()) 15259 Version = Spec->getVersion(); 15260 15261 return new (Context) 15262 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 15263 } 15264